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/api/org/openmrs/module/ModuleClassLoader.java b/src/api/org/openmrs/module/ModuleClassLoader.java
index 55f2cbf9..698e8afe 100644
--- a/src/api/org/openmrs/module/ModuleClassLoader.java
+++ b/src/api/org/openmrs/module/ModuleClassLoader.java
@@ -1,907 +1,907 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*
* Code adapted from the Java Plug-in Framework (JPF) - LGPL - Copyright (C)
* 2004-2006 Dmitry Olshansky
*/
package org.openmrs.module;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.util.OpenmrsClassLoader;
import org.openmrs.util.OpenmrsUtil;
/**
* Standard implementation of module class loader.
*/
public class ModuleClassLoader extends URLClassLoader {
static Log log = LogFactory.getLog(ModuleClassLoader.class);
private final Module module;
private Module[] requiredModules;
private Map<URL, File> libraryCache;
private boolean probeParentLoaderLast = true;
/**
* @param module Module
* @param urls resources "managed" by this class loader
* @param parent parent class loader
* @param factory URL stream handler factory
* @see URLClassLoader#URLClassLoader(java.net.URL[], java.lang.ClassLoader,
* java.net.URLStreamHandlerFactory)
*/
protected ModuleClassLoader(final Module module, final List<URL> urls,
final ClassLoader parent, final URLStreamHandlerFactory factory) {
super(urls.toArray(new URL[urls.size()]), parent, factory);
if (log.isDebugEnabled())
log.debug("URLs length: " + urls.size());
this.module = module;
collectRequiredModuleImports();
collectFilters();
libraryCache = new WeakHashMap<URL, File>();
}
/**
* @param descr plug-in module
* @param urls resources "managed" by this class loader
* @param parent parent class loader
* @see URLClassLoader#URLClassLoader(java.net.URL[], java.lang.ClassLoader)
*/
protected ModuleClassLoader(final Module module, final List<URL> urls,
final ClassLoader parent) {
this(module, urls, parent, null);
}
/**
* @param aManager plug-in manager
* @param descr plug-in module
* @param urls resources "managed" by this class loader
* @see URLClassLoader#URLClassLoader(java.net.URL[])
*/
protected ModuleClassLoader(final Module module, final List<URL> urls) {
this(module, urls, null);
}
/**
* Creates class instance configured to load classes and resources for
* given module.
* @param aManager module manager instance
* @param descr module module
* @param parent parent class loader, usually this is the application class loader
*/
public ModuleClassLoader(final Module module, final ClassLoader parent) {
this(module, getUrls(module), parent);
}
/**
* @return returns this classloader's module
*/
public Module getModule() {
return module;
}
/**
* Get the base class url of the given <code>cls</code>. Used for checking
* against system class loads vs classloader loads
*
* @param cls Class name
* @return URL to the class
*/
private static URL getClassBaseUrl(final Class<?> cls) {
ProtectionDomain pd = cls.getProtectionDomain();
if (pd != null) {
CodeSource cs = pd.getCodeSource();
if (cs != null) {
return cs.getLocation();
}
}
return null;
}
/**
* Get all urls for all files in the given <code>module</code>
*
* @param module Module in which to look
* @return List<URL> of all urls found (and cached) in the module
*/
private static List<URL> getUrls(final Module module) {
List<URL> result = new LinkedList<URL>();
File tmpModuleDir = getLibCacheFolderForModule(module);
File tmpModuleJar = new File(tmpModuleDir, module.getModuleId() + ".jar");
if (!tmpModuleJar.exists()) {
try {
tmpModuleJar.createNewFile();
}
catch (IOException io) {
log.warn("Unable to create tmpModuleFile", io);
}
}
// copy the module jar into that temporary folder
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(module.getFile());
out = new FileOutputStream(tmpModuleJar);
OpenmrsUtil.copyFile(in, out);
}
catch (IOException io) {
log.warn("Unable to copy tmpModuleFile", io);
}
finally {
try { in.close(); } catch (Exception e) { /* pass */ }
try { out.close();} catch (Exception e) { /* pass */ }
}
// add the module jar as a url in the classpath of the classloader
URL moduleFileURL = null;
try {
moduleFileURL = ModuleUtil.file2url(tmpModuleJar);
result.add(moduleFileURL);
}
catch (MalformedURLException e) {
log.warn("Unable to add files from module to URL list: " + module.getModuleId(), e);
}
// add each defined jar in the /lib folder, add as a url in the classpath of the classloader
try {
if (log.isDebugEnabled())
log.debug("Expanding /lib folder in module");
ModuleUtil.expandJar(module.getFile(), tmpModuleDir, "lib", true);
File libdir = new File(tmpModuleDir, "lib");
if (libdir != null && libdir.exists())
for (File file : libdir.listFiles()) {
if (log.isDebugEnabled())
log.debug("Adding file to results: " + file.getAbsolutePath());
result.add(ModuleUtil.file2url(file));
}
}
catch (MalformedURLException e) {
log.warn("Error while adding module 'lib' folder to URL result list");
}
catch (IOException io) {
log.warn("Error while expanding lib folder", io);
}
// add each xml document to the url list
return result;
}
/**
* Get the library cache folder for the given module. Each module has a
* different cache folder to ease cleanup when unloading a module while
* openmrs is running
*
* @param module Module which the cache will be used for
* @return File directory where the files will be placed
*/
public static File getLibCacheFolderForModule(Module module) {
File tmpModuleDir = new File(OpenmrsClassLoader.getLibCacheFolder(), module.getModuleId());
// each module gets its own folder named /moduleId/
if (!tmpModuleDir.exists()) {
tmpModuleDir.mkdir();
tmpModuleDir.deleteOnExit();
}
return tmpModuleDir;
}
/**
* Get all urls for the given <code>module</code> that are not already in the
* <code>existingUrls</code>
*
* @param module Module in which to get urls
* @param existingUrls Array of URLs to skip
* @return List<URL> of new unique urls
*
* @see #getUrls(Module)
*/
private static List<URL> getUrls(final Module module, final URL[] existingUrls) {
List<URL> urls = Arrays.asList(existingUrls);
List<URL> result = new LinkedList<URL>();
for (URL url : getUrls(module)) {
if (!urls.contains(url)) {
result.add(url);
}
}
return result;
}
/**
* Get and cache the imports for this module. The imports should just be
* the modules that set as "required" by this module
*/
protected void collectRequiredModuleImports() {
// collect imported modules (exclude duplicates)
Map<String, Module> publicImportsMap = new WeakHashMap<String, Module>(); //<module ID, Module>
for (String requiredPackage : getModule().getRequiredModules()) {
Module requiredModule = ModuleFactory.getModuleByPackage(requiredPackage);
if (ModuleFactory.isModuleStarted(requiredModule)) {
publicImportsMap.put(requiredModule.getModuleId(), requiredModule);
}
}
requiredModules = (Module[]) publicImportsMap.values().toArray(
new Module[publicImportsMap.size()]);
}
/**
* Get and cache the filters for this module
*
* (not currently implemented)
*/
protected void collectFilters() {
// if (resourceFilters == null) {
// resourceFilters = new WeakHashMap<URL, ResourceFilter>();
// } else {
// resourceFilters.clear();
// }
// TODO even need to iterate over libraries here?
//for (Library lib : getModule().getLibraries()) {
//resourceFilters.put(
// ModuleFactory.getPathResolver().resolvePath(lib,
// lib.getPath()), new ResourceFilter(lib));
//}
}
/**
* @see org.openmrs.module.ModuleClassLoader#modulesSetChanged()
*/
protected void modulesSetChanged() {
List<URL> newUrls = getUrls(getModule(), getURLs());
for (URL u : newUrls) {
addURL(u);
}
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("New code URL's populated for module "
+ getModule() + ":\r\n");
for (URL u : newUrls) {
buf.append("\t");
buf.append(u);
buf.append("\r\n");
}
log.debug(buf.toString());
}
collectRequiredModuleImports();
// repopulate resource URLs
//resourceLoader = ModuleResourceLoader.get(getModule());
collectFilters();
for (Iterator<Map.Entry<URL, File>> it = libraryCache.entrySet().iterator(); it.hasNext();) {
if (it.next().getValue() == null) {
it.remove();
}
}
}
/**
* @see org.openmrs.module.ModuleFactory#stopModule(Module,boolean)
*/
public void dispose() {
if (log.isDebugEnabled())
log.debug("Disposing of ModuleClassLoader: " + this);
for (Iterator<File> it = libraryCache.values().iterator(); it.hasNext();) {
it.next().delete();
}
libraryCache.clear();
//resourceFilters.clear();
requiredModules = null;
//resourceLoader = null;
}
/**
* Allow the probe parent loader last variable to be set. Usually this is set
* to true to allow modules to override and create their own classes
*
* @param value boolean true/false whether or not to look at the parent classloader last
*/
protected void setProbeParentLoaderLast(final boolean value) {
probeParentLoaderLast = value;
}
/**
* @see java.lang.ClassLoader#loadClass(java.lang.String, boolean)
*/
protected Class<?> loadClass(final String name, final boolean resolve)
throws ClassNotFoundException {
Class<?> result = null;
if (probeParentLoaderLast) {
try {
result = loadClass(name, resolve, this, null);
} catch (ClassNotFoundException cnfe) {
if (getParent() != null)
result = getParent().loadClass(name);
} catch (NullPointerException e) {
log.debug("Error while attempting to load class: " + name + " from: " + this.toString());
}
if (result == null) {
if (getParent() != null)
result = getParent().loadClass(name);
}
} else {
try {
if (getParent() != null)
result = getParent().loadClass(name);
} catch (ClassNotFoundException cnfe) {
result = loadClass(name, resolve, this, null);
}
}
if (result != null)
return result;
throw new ClassNotFoundException(name);
}
/**
* Custom loadClass implementation to allow for loading from a given
* ModuleClassLoader and skip the modules that have been tried already
*
* @param name String path and name of the class to load
* @param resolve boolean whether or not to resolve this class before returning
* @param requestor ModuleClassLoader with which to try loading
* @param seenModules Set<String> moduleIds that have been tried already
* @return Class that has been loaded or null if none
* @throws ClassNotFoundException if no class found
*/
protected Class<?> loadClass(final String name, final boolean resolve,
final ModuleClassLoader requestor, Set<String> seenModules)
throws ClassNotFoundException {
- if (log.isDebugEnabled()) {
- log.warn("loading " + name + " " + getModule() + " seenModules: " + seenModules + " requestor: " + requestor + " resolve? " + resolve);
+ if (log.isTraceEnabled()) {
+ log.trace("loading " + name + " " + getModule() + " seenModules: " + seenModules + " requestor: " + requestor + " resolve? " + resolve);
StringBuilder output = new StringBuilder();
for(StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getClassName().contains("openmrs"))
output.append("+ ");
output.append(element);
output.append("\n");
}
- log.warn("stacktrace: " + output.toString());
+ log.trace("stacktrace: " + output.toString());
}
if ((seenModules != null) && seenModules.contains(getModule().getModuleId())) {
return null;
}
// make sure the module is started
if ((this != requestor)
&& !ModuleFactory.isModuleStarted(getModule())) {
String msg = "can't load class " + name + ", module "
+ getModule() + " is not started yet";
log.warn(msg);
throw new ClassNotFoundException(msg);
}
// the class ultimately returned (if found)
Class<?> result = null;
synchronized (this) {
result = findLoadedClass(name);
if (result != null) {
checkClassVisibility(result, requestor);
/*if (resolve) {
resolveClass(result);
}*/
// found an already loaded class in this moduleclassloader
return result;
}
// we have to look in the requiredModules list before doing a "findClass"
// so that the class is loaded by the correct ModuleClassLoader
for (Module reqMod : requiredModules) {
if (name.startsWith(reqMod.getPackageName())) {
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(reqMod);
result = mcl.loadClass(name, resolve, requestor, seenModules);
if (result != null)
return result;
}
}
// we didn't find a loaded class and this isn't a class
// from another module
try {
synchronized (getClass()) {
result = findClass(name);
}
} catch (LinkageError le) {
throw le;
} catch (ClassNotFoundException cnfe) {
// ignore
}
// we were able to "find" a class
if (result != null) {
checkClassVisibility(result, requestor);
if (resolve) {
resolveClass(result);
}
return result; // found class in this module
}
}
// initialize the array if need be
if (seenModules == null)
seenModules = new HashSet<String>();
// add this module to the list of modules we've tried already
seenModules.add(getModule().getModuleId());
// look through this module's imports to see if it the class
// can be loaded from them
for (Module publicImport : requiredModules) {
if (seenModules.contains(publicImport.getModuleId()))
continue;
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(publicImport);
result = mcl.loadClass(name, resolve, requestor, seenModules);
if (result != null) {
/*if (resolve) {
resolveClass(result);
}*/
break; // found class in publicly imported module
}
}
return result;
}
/**
* Checking the given class's visibility in this module
*
* @param cls Class to check
* @param requestor ModuleClassLoader to check against
* @throws ClassNotFoundException
*/
protected void checkClassVisibility(final Class<?> cls,
final ModuleClassLoader requestor)
throws ClassNotFoundException {
if (this == requestor)
return;
URL lib = getClassBaseUrl(cls);
if (lib == null)
return; // cls is a system class
ClassLoader loader = cls.getClassLoader();
if (!(loader instanceof ModuleClassLoader))
return;
if (loader != this) {
((ModuleClassLoader) loader).checkClassVisibility(cls,
requestor);
}
else {
// ResourceFilter filter = (ResourceFilter) resourceFilters.get(lib);
// if (filter == null) {
// log.warn("class not visible, no class filter found, lib=" + lib
// + ", class=" + cls + ", this=" + this
// + ", requestor=" + requestor);
// throw new ClassNotFoundException("class "
// + cls.getName() + " is not visible for module "
// + requestor.getModule().getModuleId()
// + ", no filter found for library " + lib);
// }
// if (!filter.isClassVisible(cls.getName())) {
// log.warn("class not visible, lib=" + lib
// + ", class=" + cls + ", this=" + this
// + ", requestor=" + requestor);
// throw new ClassNotFoundException("class "
// + cls.getName() + " is not visible for module "
// + requestor.getModule().getModuleId());
// }
}
}
/**
* @see java.lang.ClassLoader#findLibrary(java.lang.String)
*/
protected String findLibrary(final String name) {
if ((name == null) || "".equals(name.trim()))
return null;
if (log.isDebugEnabled()) {
log.debug("findLibrary(String): name=" + name
+ ", this=" + this);
}
String libname = System.mapLibraryName(name);
String result = null;
//TODO
//PathResolver pathResolver = ModuleFactory.getPathResolver();
// for (Library lib : getModule().getLibraries()) {
// if (lib.isCodeLibrary()) {
// continue;
// }
// URL libUrl = null; //pathResolver.resolvePath(lib, lib.getPath() + libname);
// if (log.isDebugEnabled()) {
// log.debug("findLibrary(String): trying URL " + libUrl);
// }
// File libFile = OpenmrsUtil.url2file(libUrl);
// if (libFile != null) {
// if (log.isDebugEnabled()) {
// log.debug("findLibrary(String): URL " + libUrl
// + " resolved as local file " + libFile);
// }
// if (libFile.isFile()) {
// result = libFile.getAbsolutePath();
// break;
// }
// continue;
// }
// // we have some kind of non-local URL
// // try to copy it to local temporary file
// libFile = (File) libraryCache.get(libUrl);
// if (libFile != null) {
// if (libFile.isFile()) {
// result = libFile.getAbsolutePath();
// break;
// }
// libraryCache.remove(libUrl);
// }
// if (libraryCache.containsKey(libUrl)) {
// // already tried to cache this library
// break;
// }
// libFile = cacheLibrary(libUrl, libname);
// if (libFile != null) {
// result = libFile.getAbsolutePath();
// break;
// }
// }
if (log.isDebugEnabled()) {
log.debug("findLibrary(String): name=" + name
+ ", libname=" + libname
+ ", result=" + result
+ ", this=" + this);
}
return result;
}
/**
* Saves the given library in the openmrs cache. This prevents locking of jars/files by servlet
* container
*
* @param libUrl URL to the library/jar file
* @param libname name of the
* @return
*/
protected File cacheLibrary(final URL libUrl,
final String libname) {
File cacheFolder = OpenmrsClassLoader.getLibCacheFolder();
if (libraryCache.containsKey(libUrl)) {
return (File) libraryCache.get(libUrl);
}
File result = null;
try {
if (cacheFolder == null) {
throw new IOException(
"can't initialize libraries cache folder");
}
// create the directory to hold the jar's files
File libCacheModuleFolder = new File(cacheFolder,
getModule().getModuleId());
// error while creating the file
if (!libCacheModuleFolder.exists()
&& !libCacheModuleFolder.mkdirs()) {
throw new IOException("can't create cache folder "
+ libCacheModuleFolder);
}
// directory within the specific folder within the cache
result = new File(libCacheModuleFolder, libname);
// copy the file over to the cache
InputStream in = OpenmrsUtil.getResourceInputStream(libUrl);
try {
FileOutputStream fileOut = new FileOutputStream(result);
OutputStream out = new BufferedOutputStream(fileOut);
try {
OpenmrsUtil.copyFile(in, out);
} finally {
try { out.close(); } catch (Exception e) { /* pass */ }
try { fileOut.close(); } catch (Exception e) { }
}
} finally {
try { in.close(); } catch (Exception e) { /* pass */ }
}
// save a link to the cached file
libraryCache.put(libUrl, result);
if (log.isDebugEnabled()) {
log.debug("library " + libname
+ " successfully cached from URL " + libUrl
+ " and saved to local file " + result);
}
} catch (IOException ioe) {
log.error("can't cache library " + libname
+ " from URL " + libUrl, ioe);
libraryCache.put(libUrl, null);
result = null;
}
return result;
}
/**
* If a resource is found within a jar, that jar URL is converted to
* a temporary file and a URL to that is returned
* @see java.lang.ClassLoader#findResource(java.lang.String)
*/
public URL findResource(final String name) {
URL result = findResource(name, this, null);
return expandIfNecessary(result);
}
/**
* @see java.lang.ClassLoader#findResources(java.lang.String)
*/
@Override
public Enumeration<URL> findResources(final String name) throws IOException {
List<URL> result = new LinkedList<URL>();
findResources(result, name, this, null);
// expand all of the "jar" urls
for (URL url : result) {
url = expandIfNecessary(url);
}
return Collections.enumeration(result);
}
/**
* Find a resource (image, file, etc) in the module structure
*
* @param name String path and name of the file
* @param requestor ModuleClassLoader in which to look
* @param seenModules Set<String> modules that have been checked already
* @return URL to resource
*
* @see #findResource(String)
*/
protected URL findResource(final String name,
final ModuleClassLoader requestor, Set<String> seenModules) {
if (log.isDebugEnabled()) {
if (name != null && name.contains("starter")) {
if (seenModules != null) log.debug("seenModules.size: " + seenModules.size());
log.debug("name: " + name);
for (URL url : getURLs()) {
log.debug("url: " + url);
}
}
}
if ((seenModules != null) && seenModules.contains(getModule().getModuleId()))
return null;
URL result = super.findResource(name);
if (result != null) { // found resource in this module class path
if (isResourceVisible(name, result, requestor)) {
return result;
}
log.debug("Resource is not visible");
return null;
}
// if (resourceLoader != null) {
// result = resourceLoader.findResource(name);
// log.debug("Result from resourceLoader: " + result);
// if (result != null) { // found resource in this module resource libraries
// if (isResourceVisible(name, result, requestor)) {
// return result;
// }
// log.debug("result from resourceLoader is not visible");
// return null;
// }
// }
if (seenModules == null)
seenModules = new HashSet<String>();
seenModules.add(getModule().getModuleId());
for (Module publicImport : requiredModules) {
if (seenModules.contains(publicImport.getModuleId()))
continue;
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(publicImport);
result = mcl.findResource(name, requestor, seenModules);
if (result != null) {
break; // found resource in publicly imported module
}
}
return result;
}
/**
* Find all occurrences of a resource (image, file, etc) in the module structure
*
* @param result URL of the file found
* @param name String path and name of the file to find
* @param requestor ModuleClassLoader in which to start
* @param seenModules Set<String> moduleIds that have been checked already
* @throws IOException
*
* @see {@link #findResources(String)}
* @see {@link #findResource(String, ModuleClassLoader, Set)}
*/
protected void findResources(final List<URL> result, final String name,
final ModuleClassLoader requestor, Set<String> seenModules)
throws IOException {
if ((seenModules != null) && seenModules.contains(getModule().getModuleId())) {
return;
}
for (Enumeration<URL> enm = super.findResources(name);
enm.hasMoreElements();) {
URL url = enm.nextElement();
if (isResourceVisible(name, url, requestor)) {
result.add(url);
}
}
// if (resourceLoader != null) {
// for (Enumeration enm = resourceLoader.findResources(name);
// enm.hasMoreElements();) {
// URL url = (URL) enm.nextElement();
// if (isResourceVisible(name, url, requestor)) {
// result.add(url);
// }
// }
// }
if (seenModules == null) {
seenModules = new HashSet<String>();
}
seenModules.add(getModule().getModuleId());
for (Module publicImport : requiredModules) {
if (seenModules.contains(publicImport.getModuleId()))
continue;
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(publicImport);
mcl.findResources(result, name, requestor, seenModules);
}
}
/**
* Check if the given resource (image, file, etc) is visible by this classloader
*
* @param name String path and name to check
* @param url URL of the library file
* @param requestor ModuleClassLoader in which to look
* @return true/false whether this resource is visibile by this classloader
*/
protected boolean isResourceVisible(final String name, final URL url,
final ModuleClassLoader requestor) {
/*log.debug("isResourceVisible(URL, ModuleClassLoader): URL=" + url
+ ", requestor=" + requestor);*/
if (this == requestor) {
return true;
}
@SuppressWarnings("unused")
URL lib;
try {
String file = url.getFile();
lib = new URL(url.getProtocol(), url.getHost(),
file.substring(0, file.length() - name.length()));
} catch (MalformedURLException mue) {
log.error("can't get resource library URL", mue);
return false;
}
// ResourceFilter filter = (ResourceFilter) resourceFilters.get(lib);
// if (filter == null) {
// log.warn("no resource filter found for library "
// + lib + ", name=" + name
// + ", URL=" + url + ", this=" + this
// + ", requestor=" + requestor);
// return false;
// }
// if (!filter.isResourceVisible(name)) {
// log.warn("resource not visible, name=" + name
// + ", URL=" + url + ", this=" + this
// + ", requestor=" + requestor);
// return false;
// }
return true;
}
/**
* Expands the URL into the temporary folder if the URL points to a
* resource inside of a jar file
*
* @param result
* @return URL to the expanded result or null if an error occurred
*/
private URL expandIfNecessary(URL result) {
if (result == null || !"jar".equals(result.getProtocol()))
return result;
File tmpFolder = getLibCacheFolderForModule(module);
return OpenmrsClassLoader.expandURL(result, tmpFolder);
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return "{ModuleClassLoader: uid="
+ System.identityHashCode(this) + "; "
+ module + "}";
}
}
| false | true | protected Class<?> loadClass(final String name, final boolean resolve,
final ModuleClassLoader requestor, Set<String> seenModules)
throws ClassNotFoundException {
if (log.isDebugEnabled()) {
log.warn("loading " + name + " " + getModule() + " seenModules: " + seenModules + " requestor: " + requestor + " resolve? " + resolve);
StringBuilder output = new StringBuilder();
for(StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getClassName().contains("openmrs"))
output.append("+ ");
output.append(element);
output.append("\n");
}
log.warn("stacktrace: " + output.toString());
}
if ((seenModules != null) && seenModules.contains(getModule().getModuleId())) {
return null;
}
// make sure the module is started
if ((this != requestor)
&& !ModuleFactory.isModuleStarted(getModule())) {
String msg = "can't load class " + name + ", module "
+ getModule() + " is not started yet";
log.warn(msg);
throw new ClassNotFoundException(msg);
}
// the class ultimately returned (if found)
Class<?> result = null;
synchronized (this) {
result = findLoadedClass(name);
if (result != null) {
checkClassVisibility(result, requestor);
/*if (resolve) {
resolveClass(result);
}*/
// found an already loaded class in this moduleclassloader
return result;
}
// we have to look in the requiredModules list before doing a "findClass"
// so that the class is loaded by the correct ModuleClassLoader
for (Module reqMod : requiredModules) {
if (name.startsWith(reqMod.getPackageName())) {
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(reqMod);
result = mcl.loadClass(name, resolve, requestor, seenModules);
if (result != null)
return result;
}
}
// we didn't find a loaded class and this isn't a class
// from another module
try {
synchronized (getClass()) {
result = findClass(name);
}
} catch (LinkageError le) {
throw le;
} catch (ClassNotFoundException cnfe) {
// ignore
}
// we were able to "find" a class
if (result != null) {
checkClassVisibility(result, requestor);
if (resolve) {
resolveClass(result);
}
return result; // found class in this module
}
}
| protected Class<?> loadClass(final String name, final boolean resolve,
final ModuleClassLoader requestor, Set<String> seenModules)
throws ClassNotFoundException {
if (log.isTraceEnabled()) {
log.trace("loading " + name + " " + getModule() + " seenModules: " + seenModules + " requestor: " + requestor + " resolve? " + resolve);
StringBuilder output = new StringBuilder();
for(StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getClassName().contains("openmrs"))
output.append("+ ");
output.append(element);
output.append("\n");
}
log.trace("stacktrace: " + output.toString());
}
if ((seenModules != null) && seenModules.contains(getModule().getModuleId())) {
return null;
}
// make sure the module is started
if ((this != requestor)
&& !ModuleFactory.isModuleStarted(getModule())) {
String msg = "can't load class " + name + ", module "
+ getModule() + " is not started yet";
log.warn(msg);
throw new ClassNotFoundException(msg);
}
// the class ultimately returned (if found)
Class<?> result = null;
synchronized (this) {
result = findLoadedClass(name);
if (result != null) {
checkClassVisibility(result, requestor);
/*if (resolve) {
resolveClass(result);
}*/
// found an already loaded class in this moduleclassloader
return result;
}
// we have to look in the requiredModules list before doing a "findClass"
// so that the class is loaded by the correct ModuleClassLoader
for (Module reqMod : requiredModules) {
if (name.startsWith(reqMod.getPackageName())) {
ModuleClassLoader mcl = ModuleFactory.getModuleClassLoader(reqMod);
result = mcl.loadClass(name, resolve, requestor, seenModules);
if (result != null)
return result;
}
}
// we didn't find a loaded class and this isn't a class
// from another module
try {
synchronized (getClass()) {
result = findClass(name);
}
} catch (LinkageError le) {
throw le;
} catch (ClassNotFoundException cnfe) {
// ignore
}
// we were able to "find" a class
if (result != null) {
checkClassVisibility(result, requestor);
if (resolve) {
resolveClass(result);
}
return result; // found class in this module
}
}
|
diff --git a/crypto/jdk1.3/org/bouncycastle/cms/CMSSignedData.java b/crypto/jdk1.3/org/bouncycastle/cms/CMSSignedData.java
index fe6df1a6..260ce625 100644
--- a/crypto/jdk1.3/org/bouncycastle/cms/CMSSignedData.java
+++ b/crypto/jdk1.3/org/bouncycastle/cms/CMSSignedData.java
@@ -1,528 +1,528 @@
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.cms.SignerInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.x509.NoSuchStoreException;
import org.bouncycastle.x509.X509Store;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.bouncycastle.jce.cert.CertStore;
import org.bouncycastle.jce.cert.CertStoreException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* general class for handling a pkcs7-signature message.
*
* A simple example of usage - note, in the example below the validity of
* the certificate isn't verified, just the fact that one of the certs
* matches the given signer...
*
* <pre>
* CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
* SignerInformationStore signers = s.getSignerInfos();
* Collection c = signers.getSigners();
* Iterator it = c.iterator();
*
* while (it.hasNext())
* {
* SignerInformation signer = (SignerInformation)it.next();
* Collection certCollection = certs.getCertificates(signer.getSID());
*
* Iterator certIt = certCollection.iterator();
* X509Certificate cert = (X509Certificate)certIt.next();
*
* if (signer.verify(cert.getPublicKey()))
* {
* verified++;
* }
* }
* </pre>
*/
public class CMSSignedData
{
private static CMSSignedHelper HELPER = CMSSignedHelper.INSTANCE;
SignedData signedData;
ContentInfo contentInfo;
CMSProcessable signedContent;
CertStore certStore;
SignerInformationStore signerInfoStore;
X509Store attributeStore;
X509Store certificateStore;
X509Store crlStore;
private Map hashes;
private CMSSignedData(
CMSSignedData c)
{
this.signedData = c.signedData;
this.contentInfo = c.contentInfo;
this.signedContent = c.signedContent;
this.certStore = c.certStore;
this.signerInfoStore = c.signerInfoStore;
}
public CMSSignedData(
byte[] sigBlock)
throws CMSException
{
this(CMSUtils.readContentInfo(sigBlock));
}
public CMSSignedData(
CMSProcessable signedContent,
byte[] sigBlock)
throws CMSException
{
this(signedContent, CMSUtils.readContentInfo(sigBlock));
}
/**
* Content with detached signature, digests precomputed
*
* @param hashes a map of precomputed digests for content indexed by name of hash.
* @param sigBlock the signature object.
*/
public CMSSignedData(
Map hashes,
byte[] sigBlock)
throws CMSException
{
this(hashes, CMSUtils.readContentInfo(sigBlock));
}
/**
* base constructor - content with detached signature.
*
* @param signedContent the content that was signed.
* @param sigData the signature object.
*/
public CMSSignedData(
CMSProcessable signedContent,
InputStream sigData)
throws CMSException
{
this(signedContent, CMSUtils.readContentInfo(new ASN1InputStream(sigData)));
}
/**
* base constructor - with encapsulated content
*/
public CMSSignedData(
InputStream sigData)
throws CMSException
{
this(CMSUtils.readContentInfo(sigData));
}
public CMSSignedData(
CMSProcessable signedContent,
ContentInfo sigData)
{
this.signedContent = signedContent;
this.contentInfo = sigData;
this.signedData = SignedData.getInstance(contentInfo.getContent());
}
public CMSSignedData(
Map hashes,
ContentInfo sigData)
{
this.hashes = hashes;
this.contentInfo = sigData;
this.signedData = SignedData.getInstance(contentInfo.getContent());
}
public CMSSignedData(
ContentInfo sigData)
{
this.contentInfo = sigData;
this.signedData = SignedData.getInstance(contentInfo.getContent());
//
// this can happen if the signed message is sent simply to send a
// certificate chain.
//
if (signedData.getEncapContentInfo().getContent() != null)
{
this.signedContent = new CMSProcessableByteArray(
((ASN1OctetString)(signedData.getEncapContentInfo()
.getContent())).getOctets());
}
else
{
this.signedContent = null;
}
}
/**
* Return the version number for this object
*/
public int getVersion()
{
return signedData.getVersion().getValue().intValue();
}
/**
* return the collection of signers that are associated with the
* signatures for the message.
*/
public SignerInformationStore getSignerInfos()
{
if (signerInfoStore == null)
{
ASN1Set s = signedData.getSignerInfos();
List signerInfos = new ArrayList();
for (int i = 0; i != s.size(); i++)
{
if (hashes == null)
{
signerInfos.add(new SignerInformation(SignerInfo.getInstance(s.getObjectAt(i)), signedData.getEncapContentInfo().getContentType(), signedContent, null));
}
else
{
SignerInfo info = SignerInfo.getInstance(s.getObjectAt(i));
byte[] hash = (byte[])hashes.get(info.getDigestAlgorithm().getObjectId().getId());
signerInfos.add(new SignerInformation(info, signedData.getEncapContentInfo().getContentType(), null, hash));
}
}
signerInfoStore = new SignerInformationStore(signerInfos);
}
return signerInfoStore;
}
/**
* return a X509Store containing the attribute certificates, if any, contained
* in this message.
*
* @param type type of store to create
* @param provider provider to use
* @return a store of attribute certificates
* @exception NoSuchProviderException if the provider requested isn't available.
* @exception NoSuchStoreException if the store type isn't available.
* @exception CMSException if a general exception prevents creation of the X509Store
*/
public X509Store getAttributeCertificates(
String type,
String provider)
throws NoSuchStoreException, NoSuchProviderException, CMSException
{
if (attributeStore == null)
{
attributeStore = HELPER.createAttributeStore(type, provider, signedData.getCertificates());
}
return attributeStore;
}
/**
* return a X509Store containing the public key certificates, if any, contained
* in this message.
*
* @param type type of store to create
* @param provider provider to use
* @return a store of public key certificates
* @exception NoSuchProviderException if the provider requested isn't available.
* @exception NoSuchStoreException if the store type isn't available.
* @exception CMSException if a general exception prevents creation of the X509Store
*/
public X509Store getCertificates(
String type,
String provider)
throws NoSuchStoreException, NoSuchProviderException, CMSException
{
if (certificateStore == null)
{
certificateStore = HELPER.createCertificateStore(type, provider, signedData.getCertificates());
}
return certificateStore;
}
/**
* return a X509Store containing CRLs, if any, contained
* in this message.
*
* @param type type of store to create
* @param provider provider to use
* @return a store of CRLs
* @exception NoSuchProviderException if the provider requested isn't available.
* @exception NoSuchStoreException if the store type isn't available.
* @exception CMSException if a general exception prevents creation of the X509Store
*/
public X509Store getCRLs(
String type,
String provider)
throws NoSuchStoreException, NoSuchProviderException, CMSException
{
if (crlStore == null)
{
crlStore = HELPER.createCRLsStore(type, provider, signedData.getCRLs());
}
return crlStore;
}
/**
* return a CertStore containing the certificates and CRLs associated with
* this message.
*
* @exception NoSuchProviderException if the provider requested isn't available.
* @exception NoSuchAlgorithmException if the cert store isn't available.
* @exception CMSException if a general exception prevents creation of the CertStore
*/
public CertStore getCertificatesAndCRLs(
String type,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException, CMSException
{
if (certStore == null)
{
ASN1Set certSet = signedData.getCertificates();
ASN1Set crlSet = signedData.getCRLs();
certStore = HELPER.createCertStore(type, provider, certSet, crlSet);
}
return certStore;
}
/**
* Return the a string representation of the OID associated with the
* encapsulated content info structure carried in the signed data.
*
* @return the OID for the content type.
*/
public String getSignedContentTypeOID()
{
return signedData.getEncapContentInfo().getContentType().getId();
}
public CMSProcessable getSignedContent()
{
return signedContent;
}
/**
* return the ASN.1 encoded representation of this object.
*/
public byte[] getEncoded()
throws IOException
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(contentInfo);
return bOut.toByteArray();
}
/**
* Replace the signerinformation store associated with this
* CMSSignedData object with the new one passed in. You would
* probably only want to do this if you wanted to change the unsigned
* attributes associated with a signer, or perhaps delete one.
*
* @param signedData the signed data object to be used as a base.
* @param signerInformationStore the new signer information store to use.
* @return a new signed data object.
*/
public static CMSSignedData replaceSigners(
CMSSignedData signedData,
SignerInformationStore signerInformationStore)
{
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the store
//
cms.signerInfoStore = signerInformationStore;
//
// replace the signers in the SignedData object
//
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector vec = new ASN1EncodableVector();
Iterator it = signerInformationStore.getSigners().iterator();
while (it.hasNext())
{
SignerInformation signer = (SignerInformation)it.next();
AlgorithmIdentifier digAlgId;
try
{
digAlgId = makeAlgId(signer.getDigestAlgOID(),
signer.getDigestAlgParams());
}
catch (IOException e)
{
- throw new RuntimeException("encoding error.", e);
+ throw new RuntimeException("encoding error:" + e);
}
digestAlgs.add(digAlgId);
vec.add(signer.toSignerInfo());
}
ASN1Set digests = new DERSet(digestAlgs);
ASN1Set signers = new DERSet(vec);
ASN1Sequence sD = (ASN1Sequence)signedData.signedData.getDERObject();
vec = new ASN1EncodableVector();
//
// signers are the last item in the sequence.
//
vec.add(sD.getObjectAt(0)); // version
vec.add(digests);
for (int i = 2; i != sD.size() - 1; i++)
{
vec.add(sD.getObjectAt(i));
}
vec.add(signers);
cms.signedData = SignedData.getInstance(new BERSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
/**
* Replace the certificate and CRL information associated with this
* CMSSignedData object with the new one passed in.
*
* @param signedData the signed data object to be used as a base.
* @param certsAndCrls the new certificates and CRLs to be used.
* @return a new signed data object.
* @exception CMSException if there is an error processing the CertStore
*/
public static CMSSignedData replaceCertificatesAndCRLs(
CMSSignedData signedData,
CertStore certsAndCrls)
throws CMSException
{
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the store
//
cms.certStore = certsAndCrls;
//
// replace the certs and crls in the SignedData object
//
ASN1Set certs = null;
ASN1Set crls = null;
try
{
ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCertificatesFromStore(certsAndCrls));
if (set.size() != 0)
{
certs = set;
}
}
catch (CertStoreException e)
{
throw new CMSException("error getting certs from certStore", e);
}
try
{
ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(certsAndCrls));
if (set.size() != 0)
{
crls = set;
}
}
catch (CertStoreException e)
{
throw new CMSException("error getting crls from certStore", e);
}
//
// replace the CMS structure.
//
cms.signedData = new SignedData(signedData.signedData.getDigestAlgorithms(),
signedData.signedData.getEncapContentInfo(),
certs,
crls,
signedData.signedData.getSignerInfos());
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
private static DERObject makeObj(
byte[] encoding)
throws IOException
{
if (encoding == null)
{
return null;
}
ASN1InputStream aIn = new ASN1InputStream(encoding);
return aIn.readObject();
}
private static AlgorithmIdentifier makeAlgId(
String oid,
byte[] params)
throws IOException
{
if (params != null)
{
return new AlgorithmIdentifier(
new DERObjectIdentifier(oid), makeObj(params));
}
else
{
return new AlgorithmIdentifier(
new DERObjectIdentifier(oid), new DERNull());
}
}
}
| true | true | public static CMSSignedData replaceSigners(
CMSSignedData signedData,
SignerInformationStore signerInformationStore)
{
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the store
//
cms.signerInfoStore = signerInformationStore;
//
// replace the signers in the SignedData object
//
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector vec = new ASN1EncodableVector();
Iterator it = signerInformationStore.getSigners().iterator();
while (it.hasNext())
{
SignerInformation signer = (SignerInformation)it.next();
AlgorithmIdentifier digAlgId;
try
{
digAlgId = makeAlgId(signer.getDigestAlgOID(),
signer.getDigestAlgParams());
}
catch (IOException e)
{
throw new RuntimeException("encoding error.", e);
}
digestAlgs.add(digAlgId);
vec.add(signer.toSignerInfo());
}
ASN1Set digests = new DERSet(digestAlgs);
ASN1Set signers = new DERSet(vec);
ASN1Sequence sD = (ASN1Sequence)signedData.signedData.getDERObject();
vec = new ASN1EncodableVector();
//
// signers are the last item in the sequence.
//
vec.add(sD.getObjectAt(0)); // version
vec.add(digests);
for (int i = 2; i != sD.size() - 1; i++)
{
vec.add(sD.getObjectAt(i));
}
vec.add(signers);
cms.signedData = SignedData.getInstance(new BERSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
| public static CMSSignedData replaceSigners(
CMSSignedData signedData,
SignerInformationStore signerInformationStore)
{
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the store
//
cms.signerInfoStore = signerInformationStore;
//
// replace the signers in the SignedData object
//
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector vec = new ASN1EncodableVector();
Iterator it = signerInformationStore.getSigners().iterator();
while (it.hasNext())
{
SignerInformation signer = (SignerInformation)it.next();
AlgorithmIdentifier digAlgId;
try
{
digAlgId = makeAlgId(signer.getDigestAlgOID(),
signer.getDigestAlgParams());
}
catch (IOException e)
{
throw new RuntimeException("encoding error:" + e);
}
digestAlgs.add(digAlgId);
vec.add(signer.toSignerInfo());
}
ASN1Set digests = new DERSet(digestAlgs);
ASN1Set signers = new DERSet(vec);
ASN1Sequence sD = (ASN1Sequence)signedData.signedData.getDERObject();
vec = new ASN1EncodableVector();
//
// signers are the last item in the sequence.
//
vec.add(sD.getObjectAt(0)); // version
vec.add(digests);
for (int i = 2; i != sD.size() - 1; i++)
{
vec.add(sD.getObjectAt(i));
}
vec.add(signers);
cms.signedData = SignedData.getInstance(new BERSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
|
diff --git a/src/eu/icecraft/iceauth/IceAuth.java b/src/eu/icecraft/iceauth/IceAuth.java
index ea6b010..050dc81 100644
--- a/src/eu/icecraft/iceauth/IceAuth.java
+++ b/src/eu/icecraft/iceauth/IceAuth.java
@@ -1,694 +1,694 @@
package eu.icecraft.iceauth;
import java.io.File;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
//import java.util.Set;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.inventory.ItemStack;
//import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import com.alta189.sqlLibrary.MySQL.mysqlCore;
import com.alta189.sqlLibrary.SQLite.sqlCore;
//import com.nijikokun.bukkit.Permissions.Permissions;
public class IceAuth extends JavaPlugin {
public String logPrefix = "[IceAuth] ";
public Logger log = Logger.getLogger("Minecraft");
public mysqlCore manageMySQL;
public sqlCore manageSQLite;
public Boolean MySQL = false;
public String dbHost = null;
public String dbUser = null;
public String dbPass = null;
public String dbDatabase = null;
public String tableName;
public ArrayList<String> playersLoggedIn = new ArrayList<String>();
public ArrayList<String> notRegistered = new ArrayList<String>();
public Map<String, NLIData> notLoggedIn = new HashMap<String, NLIData>();
//private boolean useSpout;
//private Permissions perm;
//private boolean UseOP;
private Thread thread;
private String userField;
private String passField;
private MessageDigest md5;
private NLICacheHandler nch;
@Override
public void onDisable() {
try {
thread.interrupt();
thread.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println(this.getDescription().getName() + " " + this.getDescription().getVersion() + " was disabled!");
}
@Override
public void onEnable() {
PluginManager pm = getServer().getPluginManager();
// TODO: Permissions
/*
Plugin perms = pm.getPlugin("Permissions");
if (perms != null) {
if (!pm.isPluginEnabled(perms)) {
pm.enablePlugin(perms);
}
perm = (Permissions) perms;
} else {
UseOP = true;
}
*/
/*
Plugin spLoaded = pm.getPlugin("Spout");
if (spLoaded != null && pm.isPluginEnabled(spLoaded)) {
System.out.println("[IceAuth] Found Spout, using inventory events.");
useSpout = true;
} else {
System.out.println("[IceAuth] WARNING! Spout not found, inventories are unprotected!");
}
*/
if(!this.getDataFolder().exists()) this.getDataFolder().mkdir();
File confFile = new File(this.getDataFolder(), "config.yml");
Configuration conf = new Configuration(confFile);
if(!confFile.exists()) {
conf.setProperty("mysql.use", false);
conf.setProperty("mysql.dbHost", "localhost");
conf.setProperty("mysql.dbUser", "root");
conf.setProperty("mysql.dbPass", "");
conf.setProperty("mysql.database", "minecraft");
conf.setProperty("mysql.tableName", "auth");
conf.setProperty("mysql.userField", "username");
conf.setProperty("mysql.passField", "password");
conf.save();
}
conf.load();
this.MySQL = conf.getBoolean("mysql.use", false);
this.dbHost = conf.getString("mysql.dbHost");
this.dbUser = conf.getString("mysql.dbUser");
this.dbPass = conf.getString("mysql.dbPass");
this.dbDatabase = conf.getString("mysql.database");
this.tableName = conf.getString("mysql.tableName");
this.userField = conf.getString("mysql.userField");
this.passField = conf.getString("mysql.passField");
if (this.MySQL) {
if (this.dbHost.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but host is not defined, defaulting to SQLite"); }
if (this.dbUser.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but username is not defined, defaulting to SQLite"); }
if (this.dbPass.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but password is not defined, defaulting to SQLite"); }
if (this.dbDatabase.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but database is not defined, defaulting to SQLite"); }
}
if (this.MySQL) {
this.manageMySQL = new mysqlCore(this.log, this.logPrefix, this.dbHost, this.dbDatabase, this.dbUser, this.dbPass);
this.log.info(this.logPrefix + "MySQL Initializing");
this.manageMySQL.initialize();
try {
if (this.manageMySQL.checkConnection()) {
this.log.info(this.logPrefix + "MySQL connection successful");
if (!this.manageMySQL.checkTable(tableName)) {
this.MySQL = false;
}
} else {
this.log.severe(this.logPrefix + "MySQL connection failed. Defaulting to SQLite");
this.MySQL = false;
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
this.log.info(this.logPrefix + "SQLite Initializing");
this.manageSQLite = new sqlCore(this.log, this.logPrefix, "IceAuth", this.getDataFolder().getPath());
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
this.manageSQLite.initialize();
if (!this.manageSQLite.checkTable(tableName)) {
this.manageSQLite.createTable("CREATE TABLE auth (id INT AUTO_INCREMENT PRIMARY_KEY, username VARCHAR(30), password VARCHAR(50));");
}
}
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
nch = new NLICacheHandler(this);
IceAuthPlayerListener playerListener = new IceAuthPlayerListener(this);
IceAuthBlockListener blockListener = new IceAuthBlockListener(this);
IceAuthEntityListener entityListener = new IceAuthEntityListener(this);
/*
if(useSpout) {
IceAuthSpoutListener spoutListener = new IceAuthSpoutListener(this);
pm.registerEvent(Event.Type.CUSTOM_EVENT, spoutListener, Priority.Highest, this);
}
*/
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
pm.registerEvent(Event.Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
- pm.registerEvent(Event.Type.PLAYER_KICK, playerListener, Priority.High, this);
+ pm.registerEvent(Event.Type.PLAYER_KICK, playerListener, Priority.Monitor, this); // sorry! :(
pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Lowest, this);
thread = new Thread(new PlayerThread(this));
thread.start();
System.out.println("IceAuth v1.0 has been enabled. Forked thread: "+thread.getName());
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("register")) {
if(!(sender instanceof Player)) {
return false;
}
Player player = (Player) sender;
if(!checkUnReg(player)) {
player.sendMessage(ChatColor.RED + "Already registered.");
return false;
}
if(args.length != 1) {
player.sendMessage("Usage: /register <password>");
return false;
}
String password = args[0];
if(!register(player.getName(), password)) {
player.sendMessage(ChatColor.RED + "Something failed?");
return false;
}
player.sendMessage(ChatColor.GREEN + "Registered successfully! Use /login <password>");
return true;
}
if(commandLabel.equalsIgnoreCase("login") || commandLabel.equalsIgnoreCase("l")) {
if(!(sender instanceof Player)) {
return false;
}
Player player = (Player) sender;
if(args.length != 1) {
player.sendMessage("Usage: /login <password>");
return false;
}
String playername = player.getName();
String password = args[0];
if(checkUnReg(player)) {
player.sendMessage(ChatColor.RED + "You need to register first!");
return false;
}
if(checkAuth(player)) {
player.sendMessage(ChatColor.RED + "Already logged in!");
return false;
}
if(checkLogin(playername, password)) {
player.sendMessage(ChatColor.GREEN + "Logged in successfully");
restoreInv(player);
delPlayerNotLoggedIn(player);
addAuthPlayer(player);
return true;
} else {
player.sendMessage(ChatColor.RED + "Wrong password!");
System.out.println("[IceAuth] Player "+player.getName()+" tried logging in with a wrong password!");
return false;
}
}
if(commandLabel.equalsIgnoreCase("changepassword")) {
if(!(sender instanceof Player)) {
return false;
}
Player player = (Player) sender;
if(checkUnReg(player)) {
player.sendMessage(ChatColor.RED + "You aren't registered!");
return false;
}
if(!checkAuth(player)) {
player.sendMessage(ChatColor.RED + "You aren't logged in!");
return false;
}
if(args.length != 2) {
player.sendMessage("Usage: /changepassword <oldpassword> <newpassword>");
return false;
}
changePassword(args[0], args[1], player);
return true;
}
return false;
}
public void addAuthPlayer(Player player) {
playersLoggedIn.add(player.getName());
}
public boolean checkAuth(Player player) {
return playersLoggedIn.contains(player.getName());
}
public boolean checkUnReg(Player player) {
return notRegistered.contains(player.getName());
}
public void removePlayerCache(Player player) {
String pName = player.getName();
if(!checkAuth(player)) restoreInv(player); else saveInventory(player);
playersLoggedIn.remove(pName);
notLoggedIn.remove(pName);
notRegistered.remove(pName);
}
public void addPlayerNotLoggedIn(Player player, Location loc, Boolean registered) {
NLIData nli = new NLIData(loc, (int) (System.currentTimeMillis() / 1000L), player.getInventory().getContents(), player.getInventory().getArmorContents());
notLoggedIn.put(player.getName(), nli);
if(!registered) notRegistered.add(player.getName());
}
public void saveInventory(Player player) {
NLIData nli = new NLIData(player.getInventory().getContents(), player.getInventory().getArmorContents());
nch.createCache(player.getName(), nli);
}
public void delPlayerNotLoggedIn(Player player) {
notLoggedIn.remove(player.getName());
notRegistered.remove(player.getName());
}
public void msgPlayerLogin(Player player) {
if(checkUnReg(player)) {
player.sendMessage(ChatColor.RED + "Use /register <password> to register!");
} else {
player.sendMessage(ChatColor.RED + "Use /login <password> to log in!");
}
}
public boolean checkInvEmpty(ItemStack[] invstack) {
for (int i = 0; i < invstack.length; i++) {
if (invstack[i] != null) {
if(invstack[i].getTypeId() > 0) return false;
}
}
return true;
}
public boolean isInvCacheEmpty(String pName) {
NLIData nli = nch.readCache(pName);
ItemStack[] inv = nli.getInventory();
if(checkInvEmpty(inv)) return true;
return false;
}
public void restoreInv(Player player) {
restoreInv(player, false);
}
public void restoreInv(Player player, boolean useCache) {
NLIData nli = null;
if(useCache) {
nli = nch.readCache(player.getName());
} else {
nli = notLoggedIn.get(player.getName());
}
ItemStack[] invstackbackup = null;
ItemStack[] armStackBackup = null;
try {
invstackbackup = nli.getInventory();
armStackBackup = nli.getArmour();
} catch(Exception e) {
System.out.println("[IceAuth] Restoring inventory failed");
e.printStackTrace();
}
if(invstackbackup != null) {
player.getInventory().setContents(invstackbackup);
}
if(armStackBackup[3] != null) {
if(armStackBackup[3].getAmount() != 0) {
player.getInventory().setHelmet(armStackBackup[3]);
}
}
if(armStackBackup[2] != null) {
if(armStackBackup[2].getAmount() != 0) {
player.getInventory().setChestplate(armStackBackup[2]);
}
}
if(armStackBackup[1] != null) {
if(armStackBackup[1].getAmount() != 0) {
player.getInventory().setLeggings(armStackBackup[1]);
}
}
if(armStackBackup[0] != null) {
if(armStackBackup[0].getAmount() != 0) {
player.getInventory().setBoots(armStackBackup[0]);
}
}
}
public String getMD5(String message) {
byte[] digest;
md5.reset();
md5.update(message.getBytes());
digest = md5.digest();
return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1,
digest));
}
public boolean isRegistered(String name) {
ResultSet result = null;
Connection connection = null;
if (this.MySQL) {
try {
connection = this.manageMySQL.getConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
connection = this.manageSQLite.getConnection();
}
try {
PreparedStatement regQ = connection.prepareStatement("SELECT COUNT(*) AS c FROM "+tableName+" WHERE " + userField + " = ?");
regQ.setString(1, name);
result = regQ.executeQuery();
while(result.next()) {
if(result.getInt("c") > 0) {
return true;
} else {
return false;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public boolean checkLogin(String name, String password) { // fails at sqlite (or register, not tested)
ResultSet result = null;
Connection connection = null;
if (this.MySQL) {
try {
connection = this.manageMySQL.getConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
connection = this.manageSQLite.getConnection();
}
try {
PreparedStatement regQ = connection.prepareStatement("SELECT COUNT(*) AS c FROM "+tableName+" WHERE " + userField + " = ? && "+passField+" = ?");
regQ.setString(1, name);
regQ.setString(2, getMD5(password));
result = regQ.executeQuery();
while(result.next()) {
if(result.getInt("c") > 0) {
return true;
} else {
return false;
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public boolean register(String name, String password) {
Connection connection = null;
if (this.MySQL) {
try {
connection = this.manageMySQL.getConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
connection = this.manageSQLite.getConnection();
}
try {
PreparedStatement regQ = connection.prepareStatement("INSERT INTO "+tableName+" ("+userField+", "+passField+") VALUES(?,?)");
regQ.setString(1, name);
regQ.setString(2, getMD5(password));
regQ.executeUpdate();
System.out.println("[IceAuth] Player "+name+" registered sucessfully.");
notRegistered.remove(name);
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean changePassword(String oldpass, String password, Player player) {
if(checkLogin(player.getName(), oldpass)) {
Connection connection = null;
if (this.MySQL) {
try {
connection = this.manageMySQL.getConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
connection = this.manageSQLite.getConnection();
}
try {
PreparedStatement regQ = connection.prepareStatement("UPDATE "+tableName+" SET " + passField + " = ? WHERE " + userField + " = ?");
regQ.setString(1, getMD5(password));
regQ.setString(2, player.getName());
regQ.executeUpdate();
player.sendMessage(ChatColor.GREEN + "Password updated sucessfully!");
System.out.println("[IceAuth] Player "+player.getName()+" changed his password!");
return true;
} catch (SQLException e) {
e.printStackTrace();
}
} else {
player.sendMessage(ChatColor.RED + "Wrong password!");
System.out.println("[IceAuth] Player "+player.getName()+" tried changepassword with a wrong password!");
return true;
}
return false;
}
public void tpPlayers(boolean msgLogin) {
//Set<String> ks = notLoggedIn.keySet();
//for (String playerName : ks) {
for (Player player : this.getServer().getOnlinePlayers()) {
if(!checkAuth(player)) {
try {
//Player player = this.getServer().getPlayer(playerName);
String playerName = player.getName();
NLIData nli = notLoggedIn.get(playerName);
Location pos = nli.getLoc();
if((int) (System.currentTimeMillis() / 1000L) - nli.getLoggedSecs() > 60) {
player.kickPlayer("Took too long to log in");
System.out.println("[IceAuth] Player "+playerName+" took too long to log in");
continue;
}
player.teleport(pos);
if(msgLogin) {
msgPlayerLogin(player);
}
} catch(Exception ex) {
System.out.println("[IceAuth] Exception in thread caught, Player: "+player.getName()); // strange npe
ex.printStackTrace();
}
}
}
}
// Data structures
public class NLIData {
private int loggedSecs;
private Location loc;
private ItemStack[] inventory;
private ItemStack[] armour;
public NLIData(ItemStack[] inventory, ItemStack[] armour) {
this.inventory = inventory;
this.armour = armour;
}
public NLIData(Location loc, int loggedSecs, ItemStack[] inventory, ItemStack[] armour) {
this.inventory = inventory;
this.armour = armour;
this.loc = loc;
this.loggedSecs = loggedSecs;
}
public Location getLoc() {
return this.loc;
}
public int getLoggedSecs() {
return this.loggedSecs;
}
public ItemStack[] getInventory() {
return inventory;
}
public ItemStack[] getArmour() {
return armour;
}
}
}
| true | true | public void onEnable() {
PluginManager pm = getServer().getPluginManager();
// TODO: Permissions
/*
Plugin perms = pm.getPlugin("Permissions");
if (perms != null) {
if (!pm.isPluginEnabled(perms)) {
pm.enablePlugin(perms);
}
perm = (Permissions) perms;
} else {
UseOP = true;
}
*/
/*
Plugin spLoaded = pm.getPlugin("Spout");
if (spLoaded != null && pm.isPluginEnabled(spLoaded)) {
System.out.println("[IceAuth] Found Spout, using inventory events.");
useSpout = true;
} else {
System.out.println("[IceAuth] WARNING! Spout not found, inventories are unprotected!");
}
*/
if(!this.getDataFolder().exists()) this.getDataFolder().mkdir();
File confFile = new File(this.getDataFolder(), "config.yml");
Configuration conf = new Configuration(confFile);
if(!confFile.exists()) {
conf.setProperty("mysql.use", false);
conf.setProperty("mysql.dbHost", "localhost");
conf.setProperty("mysql.dbUser", "root");
conf.setProperty("mysql.dbPass", "");
conf.setProperty("mysql.database", "minecraft");
conf.setProperty("mysql.tableName", "auth");
conf.setProperty("mysql.userField", "username");
conf.setProperty("mysql.passField", "password");
conf.save();
}
conf.load();
this.MySQL = conf.getBoolean("mysql.use", false);
this.dbHost = conf.getString("mysql.dbHost");
this.dbUser = conf.getString("mysql.dbUser");
this.dbPass = conf.getString("mysql.dbPass");
this.dbDatabase = conf.getString("mysql.database");
this.tableName = conf.getString("mysql.tableName");
this.userField = conf.getString("mysql.userField");
this.passField = conf.getString("mysql.passField");
if (this.MySQL) {
if (this.dbHost.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but host is not defined, defaulting to SQLite"); }
if (this.dbUser.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but username is not defined, defaulting to SQLite"); }
if (this.dbPass.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but password is not defined, defaulting to SQLite"); }
if (this.dbDatabase.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but database is not defined, defaulting to SQLite"); }
}
if (this.MySQL) {
this.manageMySQL = new mysqlCore(this.log, this.logPrefix, this.dbHost, this.dbDatabase, this.dbUser, this.dbPass);
this.log.info(this.logPrefix + "MySQL Initializing");
this.manageMySQL.initialize();
try {
if (this.manageMySQL.checkConnection()) {
this.log.info(this.logPrefix + "MySQL connection successful");
if (!this.manageMySQL.checkTable(tableName)) {
this.MySQL = false;
}
} else {
this.log.severe(this.logPrefix + "MySQL connection failed. Defaulting to SQLite");
this.MySQL = false;
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
this.log.info(this.logPrefix + "SQLite Initializing");
this.manageSQLite = new sqlCore(this.log, this.logPrefix, "IceAuth", this.getDataFolder().getPath());
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
this.manageSQLite.initialize();
if (!this.manageSQLite.checkTable(tableName)) {
this.manageSQLite.createTable("CREATE TABLE auth (id INT AUTO_INCREMENT PRIMARY_KEY, username VARCHAR(30), password VARCHAR(50));");
}
}
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
nch = new NLICacheHandler(this);
IceAuthPlayerListener playerListener = new IceAuthPlayerListener(this);
IceAuthBlockListener blockListener = new IceAuthBlockListener(this);
IceAuthEntityListener entityListener = new IceAuthEntityListener(this);
/*
if(useSpout) {
IceAuthSpoutListener spoutListener = new IceAuthSpoutListener(this);
pm.registerEvent(Event.Type.CUSTOM_EVENT, spoutListener, Priority.Highest, this);
}
*/
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
pm.registerEvent(Event.Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Event.Type.PLAYER_KICK, playerListener, Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Lowest, this);
thread = new Thread(new PlayerThread(this));
thread.start();
System.out.println("IceAuth v1.0 has been enabled. Forked thread: "+thread.getName());
}
| public void onEnable() {
PluginManager pm = getServer().getPluginManager();
// TODO: Permissions
/*
Plugin perms = pm.getPlugin("Permissions");
if (perms != null) {
if (!pm.isPluginEnabled(perms)) {
pm.enablePlugin(perms);
}
perm = (Permissions) perms;
} else {
UseOP = true;
}
*/
/*
Plugin spLoaded = pm.getPlugin("Spout");
if (spLoaded != null && pm.isPluginEnabled(spLoaded)) {
System.out.println("[IceAuth] Found Spout, using inventory events.");
useSpout = true;
} else {
System.out.println("[IceAuth] WARNING! Spout not found, inventories are unprotected!");
}
*/
if(!this.getDataFolder().exists()) this.getDataFolder().mkdir();
File confFile = new File(this.getDataFolder(), "config.yml");
Configuration conf = new Configuration(confFile);
if(!confFile.exists()) {
conf.setProperty("mysql.use", false);
conf.setProperty("mysql.dbHost", "localhost");
conf.setProperty("mysql.dbUser", "root");
conf.setProperty("mysql.dbPass", "");
conf.setProperty("mysql.database", "minecraft");
conf.setProperty("mysql.tableName", "auth");
conf.setProperty("mysql.userField", "username");
conf.setProperty("mysql.passField", "password");
conf.save();
}
conf.load();
this.MySQL = conf.getBoolean("mysql.use", false);
this.dbHost = conf.getString("mysql.dbHost");
this.dbUser = conf.getString("mysql.dbUser");
this.dbPass = conf.getString("mysql.dbPass");
this.dbDatabase = conf.getString("mysql.database");
this.tableName = conf.getString("mysql.tableName");
this.userField = conf.getString("mysql.userField");
this.passField = conf.getString("mysql.passField");
if (this.MySQL) {
if (this.dbHost.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but host is not defined, defaulting to SQLite"); }
if (this.dbUser.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but username is not defined, defaulting to SQLite"); }
if (this.dbPass.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but password is not defined, defaulting to SQLite"); }
if (this.dbDatabase.equals(null)) { this.MySQL = false; this.log.severe(this.logPrefix + "MySQL is on, but database is not defined, defaulting to SQLite"); }
}
if (this.MySQL) {
this.manageMySQL = new mysqlCore(this.log, this.logPrefix, this.dbHost, this.dbDatabase, this.dbUser, this.dbPass);
this.log.info(this.logPrefix + "MySQL Initializing");
this.manageMySQL.initialize();
try {
if (this.manageMySQL.checkConnection()) {
this.log.info(this.logPrefix + "MySQL connection successful");
if (!this.manageMySQL.checkTable(tableName)) {
this.MySQL = false;
}
} else {
this.log.severe(this.logPrefix + "MySQL connection failed. Defaulting to SQLite");
this.MySQL = false;
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
this.log.info(this.logPrefix + "SQLite Initializing");
this.manageSQLite = new sqlCore(this.log, this.logPrefix, "IceAuth", this.getDataFolder().getPath());
this.tableName = "auth";
this.userField = "username";
this.passField = "password";
this.manageSQLite.initialize();
if (!this.manageSQLite.checkTable(tableName)) {
this.manageSQLite.createTable("CREATE TABLE auth (id INT AUTO_INCREMENT PRIMARY_KEY, username VARCHAR(30), password VARCHAR(50));");
}
}
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
nch = new NLICacheHandler(this);
IceAuthPlayerListener playerListener = new IceAuthPlayerListener(this);
IceAuthBlockListener blockListener = new IceAuthBlockListener(this);
IceAuthEntityListener entityListener = new IceAuthEntityListener(this);
/*
if(useSpout) {
IceAuthSpoutListener spoutListener = new IceAuthSpoutListener(this);
pm.registerEvent(Event.Type.CUSTOM_EVENT, spoutListener, Priority.Highest, this);
}
*/
pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
pm.registerEvent(Event.Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Event.Type.PLAYER_KICK, playerListener, Priority.Monitor, this); // sorry! :(
pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, playerListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Lowest, this);
thread = new Thread(new PlayerThread(this));
thread.start();
System.out.println("IceAuth v1.0 has been enabled. Forked thread: "+thread.getName());
}
|
diff --git a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Overlays/DrawableMarker.java b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Overlays/DrawableMarker.java
index e0b79b4..8d00297 100644
--- a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Overlays/DrawableMarker.java
+++ b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/UI/Overlays/DrawableMarker.java
@@ -1,97 +1,95 @@
package de.uni.stuttgart.informatik.ToureNPlaner.UI.Overlays;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import org.mapsforge.android.maps.GeoPoint;
import org.mapsforge.android.maps.MapView;
public class DrawableMarker extends Drawable {
private MapView mapView;
private GeoPoint gp;
private int color = Color.BLACK;
private int index = 1;
private Boolean isDrawText = true;
private double bound;
private final Paint circle;
private final Paint circleLine;
private final Paint textPaint;
private final DrawFilter drawFilter;
private final Point point;
public DrawableMarker(MapView mapview, GeoPoint gp, Boolean isDrawText) {
this.mapView = mapview;
this.gp = gp;
this.isDrawText = isDrawText;
circle = new Paint();
circleLine = new Paint();
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(16);
textPaint.setTextAlign(Paint.Align.CENTER);
circleLine.setColor(Color.BLACK);
// draw line with antialiasing
drawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG);
point = new Point();
}
public void setGp(GeoPoint gp) {
this.gp = gp;
}
@Override
public void draw(Canvas canvas) {
int radiusFactor = 1;
// Transfrom geoposition to Point on canvas
mapView.getProjection().toPixels(gp, point);
canvas.setDrawFilter(drawFilter);
- // Workaround for http://code.google.com/p/skia/issues/detail?id=387
- canvas.setMatrix(canvas.getMatrix());
circle.setColor(color);
//add a line for the circle
canvas.drawCircle(point.x, point.y, (float) ((mapView.getZoomLevel()) * radiusFactor) + 1, circleLine);
bound = mapView.getZoomLevel() * radiusFactor + 1;
// add a factor to customize the standard radius
canvas.drawCircle(point.x, point.y, (float) (mapView.getZoomLevel()) * radiusFactor, circle);
// draw Text on the circle
// x position depending on amount of numbers
if (isDrawText) {
canvas.drawText(String.valueOf(index), point.x, point.y + 6f, textPaint);
}
}
public double getBound() {
return bound;
}
public void SetIndex(Integer index) {
this.index = index;
}
public void setColor(int color) {
this.color = color;
}
@Override
public int getOpacity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setAlpha(int alpha) {
// TODO Auto-generated method stub
}
@Override
public void setColorFilter(ColorFilter cf) {
// TODO Auto-generated method stub
}
}
| true | true | public void draw(Canvas canvas) {
int radiusFactor = 1;
// Transfrom geoposition to Point on canvas
mapView.getProjection().toPixels(gp, point);
canvas.setDrawFilter(drawFilter);
// Workaround for http://code.google.com/p/skia/issues/detail?id=387
canvas.setMatrix(canvas.getMatrix());
circle.setColor(color);
//add a line for the circle
canvas.drawCircle(point.x, point.y, (float) ((mapView.getZoomLevel()) * radiusFactor) + 1, circleLine);
bound = mapView.getZoomLevel() * radiusFactor + 1;
// add a factor to customize the standard radius
canvas.drawCircle(point.x, point.y, (float) (mapView.getZoomLevel()) * radiusFactor, circle);
// draw Text on the circle
// x position depending on amount of numbers
if (isDrawText) {
canvas.drawText(String.valueOf(index), point.x, point.y + 6f, textPaint);
}
}
| public void draw(Canvas canvas) {
int radiusFactor = 1;
// Transfrom geoposition to Point on canvas
mapView.getProjection().toPixels(gp, point);
canvas.setDrawFilter(drawFilter);
circle.setColor(color);
//add a line for the circle
canvas.drawCircle(point.x, point.y, (float) ((mapView.getZoomLevel()) * radiusFactor) + 1, circleLine);
bound = mapView.getZoomLevel() * radiusFactor + 1;
// add a factor to customize the standard radius
canvas.drawCircle(point.x, point.y, (float) (mapView.getZoomLevel()) * radiusFactor, circle);
// draw Text on the circle
// x position depending on amount of numbers
if (isDrawText) {
canvas.drawText(String.valueOf(index), point.x, point.y + 6f, textPaint);
}
}
|
diff --git a/src/gameEngine/GameEngine.java b/src/gameEngine/GameEngine.java
index 8f9a53c..6493799 100644
--- a/src/gameEngine/GameEngine.java
+++ b/src/gameEngine/GameEngine.java
@@ -1,640 +1,640 @@
package gameEngine;
import java.util.*;
import gui.MainInterface;
import participant.Chips;
import participant.Player;
import table.Table;
import game.*;
import game.Observable;
import game.Observer;
import cards.*;
public class GameEngine implements Observable {
private Blackjack myGame;
private Table gameTable;
private ArrayList<Observer> observerList = new ArrayList<Observer>();
private BlackjackHand dealerHand = new BlackjackHand();
private HashMap<Player, ArrayList<BlackjackHand>> playersAndHands;
private HashMap<Player, Chips> playersAndChips;
private final int MUST_HIT = 16;
private final int STARTING_CHIPS = 500;
private final int DEALER_WON = 1;
private final int PLAYER_WON = -1;
private final int DRAW = 0;
private final int WIN_CONSTANT = 2;
private final int BLACKJACK_PAYOUT_CONSTANT = 3;
private final int MIN_BET = 0;
private final int MAX_BET = 500;
public GameEngine(Player player) {
gameTable = new Table(player);
}
/* Currently, storage/blackjackStorage can only save and load one hand for each player
* so players.size() must equal to hand.size() */
public GameEngine(ArrayList<Player> players, ArrayList<Hand> hand, Deck deck) {
ArrayList<BlackjackHand> bh = new ArrayList<BlackjackHand>();
for (int i=0; i<players.size(); i++) {
bh.add((BlackjackHand) hand.get(i));
playersAndHands.put(players.get(i), bh);
bh.clear();
}
}
public void reset() {
myGame = new Blackjack();
playersAndHands = new HashMap<Player, ArrayList<BlackjackHand>>();
playersAndChips = new HashMap<Player, Chips>();
dealerHand = new BlackjackHand();
this.notifyObservers();
}
public void resetKeepPlayers() {
myGame = new Blackjack();
this.notifyObservers();
}
public HashMap<Player, ArrayList<BlackjackHand>> getPlayersAndHands() {
return this.playersAndHands;
}
public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
/*
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
*/
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + ", you have " + players.get(i).getChips() + " chips.");
System.out.println("how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips() || a < MIN_BET || a > MAX_BET) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i)).getChips() + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
// ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(players.get(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(players.get(i).getUsername() + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
// System.out.println(gameTable.getPlayer(i).getUsername()+": ");
System.out.println(players.get(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
// String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
String s = keyboard.next();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
- else if (s.equals("double down")){
- if (playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(i).getBet())==false) {
+ else if (s.equals("doubledown")){
+ if (playersAndChips.get(players.get(i)).getChips() < 2*playersAndChips.get(players.get(i)).getBet()) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
/**
* Returns the current game's Deck object
* @return Deck object
*/
public Deck getDeck() {
return myGame.getDeck();
}
/**
* Returns the current game's Table object
* @return Table object
*/
public Table getTable() {
return gameTable;
}
public void addPlayer(Player player) {
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
gameTable.requestJoin(player);
}
@Override
public void notifyObservers()
{
if (!observerList.isEmpty()){
for (Observer ob : observerList) {
ob.handleEvent();
}
}
}
@Override
public void addObservers(Observer obsToAdd)
{
observerList.add(obsToAdd);
}
@Override
public void removeObservers(Observer obsToRemove)
{
observerList.remove(obsToRemove);
}
public void resetObservers() {
observerList = new ArrayList<Observer>();
}
public void loadTable(Table table) {
gameTable = table;
}
public void loadPlayers() {
for ( int i = 0 ; i < getPlayers().size() ; i++ ) {
Player tmpPlayer = getPlayers().get(i);
if (!playersAndHands.containsKey(tmpPlayer)) {
playersAndHands.put(tmpPlayer, new ArrayList<BlackjackHand>());
}
}
}
public ArrayList<Player> getPlayers() {
return gameTable.getAllPlayers();
}
public void loadHands() {
}
public void loadChips() {
for ( int i = 0 ; i < getPlayers().size() ; i++ ) {
Player tmpPlayer = getPlayers().get(i);
if (!playersAndChips.containsKey(tmpPlayer)) {
playersAndChips.put(tmpPlayer, new Chips(STARTING_CHIPS));
}
}
}
public ArrayList<BlackjackHand> getPlayerHand(Player player) {
return playersAndHands.get(player);
}
/**
* Returns winner between hands of dealer and player
* @param hand BlackjackHand to compare
* @return 1 if dealer won, 0 if no winner, -1 if player won
*/
public int processWinner(BlackjackHand hand) {
if ((hand.isBust()) && !(dealerHand.isBust()))
return DEALER_WON;
if (!(hand.isBust()) && !(dealerHand.isBust()) && (dealerHand.getBlackjackValue() > hand.getBlackjackValue()))
return DEALER_WON;
if (!(hand.isBust()) && (dealerHand.isBust()))
return PLAYER_WON;
if (!(hand.isBust()) && !(dealerHand.isBust()) && dealerHand.getBlackjackValue() < hand.getBlackjackValue()) {
return PLAYER_WON;
}
return DRAW;
}
// public void resetKeepPlayers() {
// myGame = new Blackjack();
// winner = null;
//
// HashMap<Player, Hand> tmpPlayers = new HashMap<Player, Hand>();
// for (int i = 0 ; i < gameTable.getAllPlayers().size() ; i++) {
// Player tmpPlayer = gameTable.getPlayer(i);
// tmpPlayers.put(tmpPlayer, new Hand());
// }
// playersHands = tmpPlayers;
//
// }
public int getNumberOfPlayers() {
return playersAndHands.size();
}
//
// public void playDoubleDown() {
// if ( hasSufficientChips(player, chipCount)) {
// player.chips -= chipCount;
// chipCount += chipCount;
//
// }
/**
* Checks if there is sufficient specified amount of chips
* @param amount The amount to be checked
* @return True if there is sufficient chips, false otherwise
*/
// public boolean hasSufficientChips(Player player, int amount) {
// if ( player.getChips() < amount ) {
// return false;
// }
// return true;
// }
/**
*
* @param
* @return
*/
// public void bet(Player player, int amount) {
// if ( hasSufficientChips(player,amount) ) {
// chipCount += amount;
// player.getChips() -= amount;
// }
// }
public void doHit(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.isBust()==true){
System.out.println("cannot hit, the hand is bust");
}else if(hand.checkBlackjack()==true){
System.out.println("cannot hit, the hand is blackjack");
}else{
myGame.hit(hand);
}
}
}
}
}
public void doStand(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
if(hand.isBust()==true){
System.out.println("cannot stand, the hand is bust");
}else if(hand.checkBlackjack()==true){
System.out.println("cannot stand, the hand is blackjack");
}else{
myGame.stand(hand);
hand.setDone();
}
}
}
}
public void doSplit(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.checkBlackjack()==true){
System.out.println("cannot split, the hand is blackjack");
}else{
myGame.split(hand);
}
}
}
}
}
public void doDoubleDown(){
ArrayList<Player> allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.checkBlackjack()==true){
System.out.println("cannot double down, the hand is blackjack");
}else{
myGame.doubleDown(hand);
}
}
}
}
}
}
| true | true | public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
/*
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
*/
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + ", you have " + players.get(i).getChips() + " chips.");
System.out.println("how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips() || a < MIN_BET || a > MAX_BET) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i)).getChips() + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
// ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(players.get(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(players.get(i).getUsername() + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
// System.out.println(gameTable.getPlayer(i).getUsername()+": ");
System.out.println(players.get(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
// String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
String s = keyboard.next();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
else if (s.equals("double down")){
if (playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(i).getBet())==false) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
| public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
/*
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
*/
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + ", you have " + players.get(i).getChips() + " chips.");
System.out.println("how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips() || a < MIN_BET || a > MAX_BET) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i)).getChips() + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
// ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(players.get(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(players.get(i).getUsername() + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
// System.out.println(gameTable.getPlayer(i).getUsername()+": ");
System.out.println(players.get(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
// String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
String s = keyboard.next();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
else if (s.equals("doubledown")){
if (playersAndChips.get(players.get(i)).getChips() < 2*playersAndChips.get(players.get(i)).getBet()) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1) {
players.get(i).addChips(playersAndChips.get(players.get(i)).getBet());
players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet());
System.out.println("Dealer wins!");
}
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet());
// playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
|
diff --git a/java/de/hattrickorganizer/gui/model/UserColumnFactory.java b/java/de/hattrickorganizer/gui/model/UserColumnFactory.java
index 783afba5..71cf820f 100644
--- a/java/de/hattrickorganizer/gui/model/UserColumnFactory.java
+++ b/java/de/hattrickorganizer/gui/model/UserColumnFactory.java
@@ -1,674 +1,674 @@
package de.hattrickorganizer.gui.model;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.table.TableColumn;
import plugins.IEPVData;
import plugins.IMatchKurzInfo;
import plugins.ISpieler;
import plugins.ISpielerPosition;
import de.hattrickorganizer.gui.playeroverview.SpielerStatusLabelEntry;
import de.hattrickorganizer.gui.templates.ColorLabelEntry;
import de.hattrickorganizer.gui.templates.DoppelLabelEntry;
import de.hattrickorganizer.gui.templates.RatingTableEntry;
import de.hattrickorganizer.gui.templates.SpielerLabelEntry;
import de.hattrickorganizer.gui.templates.TableEntry;
import de.hattrickorganizer.model.HOModel;
import de.hattrickorganizer.model.HOVerwaltung;
import de.hattrickorganizer.model.Spieler;
import de.hattrickorganizer.model.SpielerPosition;
import de.hattrickorganizer.model.matches.MatchKurzInfo;
import de.hattrickorganizer.model.matches.Matchdetails;
import de.hattrickorganizer.tools.Helper;
import de.hattrickorganizer.tools.HelperWrapper;
import de.hattrickorganizer.tools.PlayerHelper;
/**
* Create the userColumns
* @author Thorsten Dietz
*
*/
final public class UserColumnFactory {
//~ Static fields/initializers -----------------------------------------------------------------
/** id from the column NAME **/
public static final int NAME = 1;
/** id from the column BEST_POSITION **/
public static final int BEST_POSITION = 40;
/** id from the column LINUP **/
public static final int LINUP = 50;
/** id from the column GROUP **/
public static final int GROUP = 60;
/** id from the column ID **/
public static final int ID = 440;
/** id from the column DATUM **/
public static final int DATUM = 450;
/** id from the column RATING **/
public static final int RATING = 435;
/** id from the column DATUM **/
public static final int AUTO_LINEUP = 510;
/**
*
* @return PlayerCBItem[]
*/
protected static PlayerCBItem[] createPlayerCBItemArray(){
final PlayerCBItem[] playerCBItemArray = new PlayerCBItem[4];
playerCBItemArray[0] = new PlayerCBItem(590,"Stimmung"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getStimmung(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
playerCBItemArray[1] = new PlayerCBItem(600,"Selbstvertrauen"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getSelbstvertrauen(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
playerCBItemArray[2] = new PlayerCBItem(601,"Position"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
ColorLabelEntry colorLabelEntry = new ColorLabelEntry(Helper
.getImage4Position(SpielerPosition
.getHTPosidForHOPosition4Image((byte) spielerCBItem
.getPosition()),
(byte) 0, 0),
-SpielerPosition.getSortId((byte) spielerCBItem
.getPosition(), false),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
colorLabelEntry.setText(SpielerPosition.getNameForPosition((byte) spielerCBItem
.getPosition())
+ " ("
+ spielerCBItem.getSpieler().calcPosValue((byte) spielerCBItem
.getPosition(),
true) + ")");
return colorLabelEntry;
}
};
playerCBItemArray[3] = new PlayerCBItem(RATING,"Bewertung"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new RatingTableEntry(spielerCBItem.getRating(), false);
}
};
return playerCBItemArray;
}
/**
*
* @return MatchDetailsColumn[]
*/
protected static MatchDetailsColumn[] createMatchDetailsColumnsArray(){
final MatchDetailsColumn[] matchDetailsColumnsArray = new MatchDetailsColumn[4];
matchDetailsColumnsArray[0] = new MatchDetailsColumn(550,"Wetter",30){
public TableEntry getTableEntry(Matchdetails matchdetails){
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Wetter(matchdetails.getWetterId()),
matchdetails.getWetterId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.RIGHT);
}
};// Wetter
matchDetailsColumnsArray[1] = new MatchDetailsColumn(560,"Einstellung"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int einstellung = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeEinstellung():matchdetails.getGuestEinstellung();
return new ColorLabelEntry(Matchdetails.getNameForEinstellung(einstellung), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
matchDetailsColumnsArray[2] = new MatchDetailsColumn(570,"Taktik"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int tactic = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeTacticType():matchdetails.getGuestTacticType();
return new ColorLabelEntry(Matchdetails.getNameForTaktik(tactic), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
matchDetailsColumnsArray[3] = new MatchDetailsColumn(580,"Taktikstaerke"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int tacticSkill = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeTacticSkill():matchdetails.getGuestTacticSkill();
return new ColorLabelEntry(PlayerHelper.getNameForSkill(tacticSkill), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
return matchDetailsColumnsArray;
}
/**
*
* @return PlayerColumn[]
*/
protected static PlayerColumn[] createGoalsColumnsArray(){
final PlayerColumn[] playerGoalsArray = new PlayerColumn[4];
playerGoalsArray[0] = new PlayerColumn(380,"TG","ToreGesamt",20){
public int getValue(Spieler player){
return player.getToreGesamt();
}
};
playerGoalsArray[1] = new PlayerColumn(390,"TF","ToreFreund",20){
public int getValue(Spieler player){
return player.getToreFreund();
}
};
playerGoalsArray[2] = new PlayerColumn(400,"TL","ToreLiga",20){
public int getValue(Spieler player){
return player.getToreLiga();
}
};
playerGoalsArray[3] = new PlayerColumn(410,"TP","TorePokal",20){
public int getValue(Spieler player){
return player.getTorePokal();
}
};
return playerGoalsArray;
}
/**
*
* @return PlayerSkillColumn []
*/
protected static PlayerSkillColumn[] createPlayerSkillArray(){
final PlayerSkillColumn[] playerSkillArray = new PlayerSkillColumn[11];
playerSkillArray[0] = new PlayerSkillColumn( 80, "FUE", "Fuehrung", ISpieler.SKILL_LEADERSHIP);
playerSkillArray[1] = new PlayerSkillColumn( 90, "ER", "Erfahrung", ISpieler.SKILL_EXPIERIENCE);
playerSkillArray[2] = new PlayerSkillColumn( 100, "FO", "Form", ISpieler.SKILL_FORM);
playerSkillArray[3] = new PlayerSkillColumn( 110, "KO", "Kondition", ISpieler.SKILL_KONDITION);
playerSkillArray[4] = new PlayerSkillColumn( 120, "TW", "Torwart", ISpieler.SKILL_TORWART);
playerSkillArray[5] = new PlayerSkillColumn( 130, "VE", "Verteidigung", ISpieler.SKILL_VERTEIDIGUNG);
playerSkillArray[6] = new PlayerSkillColumn( 140, "SA", "Spielaufbau", ISpieler.SKILL_SPIELAUFBAU);
playerSkillArray[7] = new PlayerSkillColumn( 150, "PS", "Passpiel", ISpieler.SKILL_PASSSPIEL);
playerSkillArray[8] = new PlayerSkillColumn( 160, "FL", "Fluegelspiel", ISpieler.SKILL_FLUEGEL);
playerSkillArray[9] = new PlayerSkillColumn( 170, "TS", "Torschuss", ISpieler.SKILL_TORSCHUSS);
playerSkillArray[10] = new PlayerSkillColumn( 180, "ST", "Standards", ISpieler.SKILL_STANDARDS);
return playerSkillArray;
}
/**
*
* @return PlayerColumn []
*/
protected static PlayerColumn[] createPlayerBasicArray(){
final PlayerColumn[] playerBasicArray = new PlayerColumn[2];
playerBasicArray[0] = new PlayerColumn(NAME,"Name",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new SpielerLabelEntry(player,
HOVerwaltung.instance().getModel()
.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
0f, false, false);
}
public boolean isEditable(){
return false;
}
};
playerBasicArray[1] = new PlayerColumn(ID,"ID",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(player.getSpielerID(),
player.getSpielerID() + "",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.RIGHT);
}
public boolean isEditable(){
return false;
}
public void setSize(TableColumn column){
column.setMinWidth(0);
column.setPreferredWidth(0);
}
};
return playerBasicArray;
}
/**
*
* @return PlayerPositionColumn[]
*/
protected static PlayerPositionColumn[] createPlayerPositionArray(){
final PlayerPositionColumn[] playerPositionArray = new PlayerPositionColumn[19];
playerPositionArray[0] = new PlayerPositionColumn( 190, "TORW", "Torwart", ISpielerPosition.TORWART );
playerPositionArray[1] = new PlayerPositionColumn( 200, "IV", "Innenverteidiger", ISpielerPosition.INNENVERTEIDIGER );
playerPositionArray[2] = new PlayerPositionColumn( 210, "IVA", "Innenverteidiger_Aus", ISpielerPosition.INNENVERTEIDIGER_AUS );
playerPositionArray[3] = new PlayerPositionColumn( 220, "IVO", "Innenverteidiger_Off", ISpielerPosition.INNENVERTEIDIGER_OFF );
playerPositionArray[4] = new PlayerPositionColumn( 230, "AV", "Aussenverteidiger", ISpielerPosition.AUSSENVERTEIDIGER );
playerPositionArray[5] = new PlayerPositionColumn( 240, "AVI", "Aussenverteidiger_In", ISpielerPosition.AUSSENVERTEIDIGER_IN );
playerPositionArray[6] = new PlayerPositionColumn( 250, "AVO", "Aussenverteidiger_Off",ISpielerPosition.AUSSENVERTEIDIGER_OFF );
playerPositionArray[7] = new PlayerPositionColumn( 260, "AVD", "Aussenverteidiger_Def",ISpielerPosition.AUSSENVERTEIDIGER_DEF );
playerPositionArray[8] = new PlayerPositionColumn( 270, "MIT", "Mittelfeld", ISpielerPosition.MITTELFELD );
playerPositionArray[9] = new PlayerPositionColumn( 280, "MITA", "Mittelfeld_Aus", ISpielerPosition.MITTELFELD_AUS );
playerPositionArray[10] = new PlayerPositionColumn( 290, "MITO", "Mittelfeld_Off", ISpielerPosition.MITTELFELD_OFF );
playerPositionArray[11] = new PlayerPositionColumn( 300, "MITD", "Mittelfeld_Def", ISpielerPosition.MITTELFELD_DEF );
playerPositionArray[12] = new PlayerPositionColumn( 310, "FLG", "Fluegelspiel", ISpielerPosition.FLUEGELSPIEL );
playerPositionArray[13] = new PlayerPositionColumn( 320, "FLGI", "Fluegelspiel_In", ISpielerPosition.FLUEGELSPIEL_IN );
playerPositionArray[14] = new PlayerPositionColumn( 330, "FLGO", "Fluegelspiel_Off", ISpielerPosition.FLUEGELSPIEL_OFF );
playerPositionArray[15] = new PlayerPositionColumn( 340, "FLGD", "Fluegelspiel_Def", ISpielerPosition.FLUEGELSPIEL_DEF );
playerPositionArray[16] = new PlayerPositionColumn( 350, "STU", "Sturm", ISpielerPosition.STURM );
playerPositionArray[17] = new PlayerPositionColumn( 360, "STUA", "Sturm_Aus", ISpielerPosition.STURM_AUS );
playerPositionArray[18] = new PlayerPositionColumn( 370, "STUD", "Sturm_Def", ISpielerPosition.STURM_DEF );
return playerPositionArray;
}
/**
*
* @return MatchKurzInfoColumn[]
*/
protected static MatchKurzInfoColumn[] createMatchesArray(){
final MatchKurzInfoColumn[] matchesArray = new MatchKurzInfoColumn[6];
matchesArray[0] = new MatchKurzInfoColumn(450,"Datum",70){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(match.getMatchDateAsTimestamp().getTime(),
java.text.DateFormat.getDateTimeInstance().format(match
.getMatchDateAsTimestamp()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getMatchdate(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
};
matchesArray[1] = new MatchKurzInfoColumn(460," ","Spielart",20){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Spieltyp(match.getMatchTyp()),
match.getMatchTyp(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.CENTER);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Spieltyp(spielerCBItem.getMatchTyp()),
spielerCBItem.getMatchTyp(),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
};
matchesArray[2] = new MatchKurzInfoColumn(470,"Heim",60){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(match.getHeimName(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.LEFT);
entry.setFGColor((match.getHeimID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
if (match.getMatchStatus() != IMatchKurzInfo.FINISHED)
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() > match.getGastTore())
entry.setIcon(Helper.YELLOWSTARIMAGEICON);
else if (match.getHeimTore() < match.getGastTore())
entry.setIcon(Helper.NOIMAGEICON);
else
entry.setIcon(Helper.GREYSTARIMAGEICON);
return entry;
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(spielerCBItem.getHeimteam() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
entry.setFGColor((spielerCBItem.getHeimID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
return entry;
}
public void setSize(TableColumn column){
column.setMinWidth(60);
column.setPreferredWidth((preferredWidth==0)?160:preferredWidth);
}
};
matchesArray[3] = new MatchKurzInfoColumn(480,"Gast",60){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(match.getGastName(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.LEFT);
entry.setFGColor((match.getGastID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
if (match.getMatchStatus() != IMatchKurzInfo.FINISHED)
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() > match.getGastTore())
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() < match.getGastTore())
entry.setIcon(Helper.YELLOWSTARIMAGEICON);
else
entry.setIcon(Helper.GREYSTARIMAGEICON);
return entry;
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(spielerCBItem.getGastteam() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
entry.setFGColor((spielerCBItem.getGastID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
return entry;
}
public void setSize(TableColumn column){
column.setMinWidth(60);
column.setPreferredWidth((preferredWidth==0)?160:preferredWidth);
}
};
matchesArray[4] = new MatchKurzInfoColumn(490,"Ergebnis",45){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(createTorString(match.getHeimTore(),
match.getGastTore()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
return new ColorLabelEntry(createTorString(spielerCBItem.getMatchdetails().getHomeGoals(),
spielerCBItem.getMatchdetails().getGuestGoals()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
};
matchesArray[5] = new MatchKurzInfoColumn(500,"ID",55){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(match.getMatchID(), match.getMatchID() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.RIGHT);
}
};
return matchesArray;
}
/**
* creates an array of various player columns
* @return PlayerColumn[]
*/
protected static PlayerColumn[] createPlayerAdditionalArray(){
final PlayerColumn [] playerAdditionalArray = new PlayerColumn[11];
playerAdditionalArray[0] =new PlayerColumn(10," "," ",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
int sort = player.getTrikotnummer();
if (sort <= 0) {
//Damit die Spieler ohne Trickot nach den andern kommen
sort = 10000;
}
return new ColorLabelEntry(Helper.getImageIcon4Trickotnummer(player
.getTrikotnummer()),
sort, java.awt.Color.black, java.awt.Color.white,
SwingConstants.LEFT);
}
public boolean isEditable(){
return false;
}
};
playerAdditionalArray[1] =new PlayerColumn(20," ","Nationalitaet",25){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(Helper.getImageIcon4Country(player.getNationalitaet()),
player.getNationalitaet(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_FLAGGEN, SwingConstants.CENTER);
}
};
playerAdditionalArray[2] = new PlayerColumn(30, "Alter", 40){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
String ageString = player.getAlterWithAgeDaysAsString();
int birthdays = 0;
boolean playerExists;
if(playerCompare == null){
// Birthdays since last HRF
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - player.getAlter());
playerExists = false;
} else {
// Birthdays since compare
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - Math.floor(playerCompare.getAlterWithAgeDays()));
if (playerCompare.isOld())
// Player was not in our team at compare date
playerExists = false;
else
// Player was in our team at compare date
playerExists = true;
}
return new ColorLabelEntry(
birthdays,
ageString,
player.getAlterWithAgeDays(),
playerExists,
ColorLabelEntry.BG_STANDARD,
true);
}
};
playerAdditionalArray[3] =new PlayerColumn(40,"BestePosition",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
ColorLabelEntry tmp = new ColorLabelEntry(-SpielerPosition.getSortId(player
.getIdealPosition(),
false)
- (player.getIdealPosStaerke(true) / 100.0f),
SpielerPosition.getNameForPosition(player
.getIdealPosition())
+ " ("
+ player.calcPosValue(player
.getIdealPosition(),
true) + ")",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
tmp.setIcon((player.getUserPosFlag() < 0)?Helper.ZAHNRAD:Helper.MANUELL);
return tmp;
}
public boolean isEditable(){
return false;
}
};
// Position
playerAdditionalArray[4] =new PlayerColumn(LINUP," ","Aufgestellt",28){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final HOModel model = HOVerwaltung.instance().getModel();
if (model.getAufstellung().isSpielerAufgestellt(player
.getSpielerID())
&& (model.getAufstellung().getPositionBySpielerId(player
.getSpielerID()) != null)) {
return new ColorLabelEntry(Helper.getImage4Position(model.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
player.getTrikotnummer()),
-model.getAufstellung()
.getPositionBySpielerId(player
.getSpielerID())
.getSortId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImage4Position(null,
player
.getTrikotnummer()),
-player.getTrikotnummer() - 1000,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.CENTER);
}
};
playerAdditionalArray[5] = new PlayerColumn(GROUP,"Gruppe",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SmilieEntry smilieEntry = new SmilieEntry();
smilieEntry.setSpieler(player);
return smilieEntry;
}
};
playerAdditionalArray[6] = new PlayerColumn(70,"Status",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SpielerStatusLabelEntry entry = new SpielerStatusLabelEntry();
entry.setSpieler(player);
return entry;
}
};
- playerAdditionalArray[7] = new PlayerColumn(420,"Gehalt",10){
+ playerAdditionalArray[7] = new PlayerColumn(420,"Gehalt",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String bonus = "";
final int gehalt = (int) (player.getGehalt() / gui.UserParameter.instance().faktorGeld);
final String gehalttext = Helper.getNumberFormat(true, 0).format(gehalt);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
final int gehalt2 = (int) (playerCompare.getGehalt() / gui.UserParameter
.instance().faktorGeld);
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(gehalt - gehalt2,
ColorLabelEntry.BG_STANDARD,
true, false, 0));
}
};
playerAdditionalArray[8] = new PlayerColumn(430,"TSI",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String text = Helper.getNumberFormat(false, 0).format(player.getTSI());
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(player.getTSI()
- playerCompare.getTSI(), ColorLabelEntry.BG_STANDARD,
false, false, 0));
}
public void setSize(TableColumn column){
column.setMinWidth(Helper.calcCellWidth(90));
}
};
playerAdditionalArray[9] = new PlayerColumn(RATING,"Bewertung",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
if (player.getBewertung() > 0) {
//Hat im letzen Spiel gespielt
return new RatingTableEntry(player.getBewertung(), true);
}
return new RatingTableEntry(player.getLetzteBewertung(), false);
}
};
- playerAdditionalArray[10] = new PlayerColumn(436,"Marktwert",10){
+ playerAdditionalArray[10] = new PlayerColumn(436,"Marktwert",140){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
IEPVData data = HOVerwaltung.instance().getModel().getEPV().getEPVData(player);
double price = HOVerwaltung.instance().getModel().getEPV().getPrice(data);
final String text = Helper.getNumberFormat(true, 0).format(price);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
IEPVData comparedata = HOVerwaltung.instance().getModel().getEPV().getEPVData(playerCompare);
int htweek = HelperWrapper.instance().getHTWeek(playerCompare.getHrfDate());
double compareepv = HOVerwaltung.instance().getModel().getEPV().getPrice(comparedata, htweek);
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry((float)(price-compareepv),
ColorLabelEntry.BG_STANDARD,
true, false, 0)
);
}
};
return playerAdditionalArray;
}
}
| false | true | protected static PlayerColumn[] createPlayerAdditionalArray(){
final PlayerColumn [] playerAdditionalArray = new PlayerColumn[11];
playerAdditionalArray[0] =new PlayerColumn(10," "," ",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
int sort = player.getTrikotnummer();
if (sort <= 0) {
//Damit die Spieler ohne Trickot nach den andern kommen
sort = 10000;
}
return new ColorLabelEntry(Helper.getImageIcon4Trickotnummer(player
.getTrikotnummer()),
sort, java.awt.Color.black, java.awt.Color.white,
SwingConstants.LEFT);
}
public boolean isEditable(){
return false;
}
};
playerAdditionalArray[1] =new PlayerColumn(20," ","Nationalitaet",25){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(Helper.getImageIcon4Country(player.getNationalitaet()),
player.getNationalitaet(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_FLAGGEN, SwingConstants.CENTER);
}
};
playerAdditionalArray[2] = new PlayerColumn(30, "Alter", 40){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
String ageString = player.getAlterWithAgeDaysAsString();
int birthdays = 0;
boolean playerExists;
if(playerCompare == null){
// Birthdays since last HRF
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - player.getAlter());
playerExists = false;
} else {
// Birthdays since compare
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - Math.floor(playerCompare.getAlterWithAgeDays()));
if (playerCompare.isOld())
// Player was not in our team at compare date
playerExists = false;
else
// Player was in our team at compare date
playerExists = true;
}
return new ColorLabelEntry(
birthdays,
ageString,
player.getAlterWithAgeDays(),
playerExists,
ColorLabelEntry.BG_STANDARD,
true);
}
};
playerAdditionalArray[3] =new PlayerColumn(40,"BestePosition",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
ColorLabelEntry tmp = new ColorLabelEntry(-SpielerPosition.getSortId(player
.getIdealPosition(),
false)
- (player.getIdealPosStaerke(true) / 100.0f),
SpielerPosition.getNameForPosition(player
.getIdealPosition())
+ " ("
+ player.calcPosValue(player
.getIdealPosition(),
true) + ")",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
tmp.setIcon((player.getUserPosFlag() < 0)?Helper.ZAHNRAD:Helper.MANUELL);
return tmp;
}
public boolean isEditable(){
return false;
}
};
// Position
playerAdditionalArray[4] =new PlayerColumn(LINUP," ","Aufgestellt",28){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final HOModel model = HOVerwaltung.instance().getModel();
if (model.getAufstellung().isSpielerAufgestellt(player
.getSpielerID())
&& (model.getAufstellung().getPositionBySpielerId(player
.getSpielerID()) != null)) {
return new ColorLabelEntry(Helper.getImage4Position(model.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
player.getTrikotnummer()),
-model.getAufstellung()
.getPositionBySpielerId(player
.getSpielerID())
.getSortId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImage4Position(null,
player
.getTrikotnummer()),
-player.getTrikotnummer() - 1000,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.CENTER);
}
};
playerAdditionalArray[5] = new PlayerColumn(GROUP,"Gruppe",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SmilieEntry smilieEntry = new SmilieEntry();
smilieEntry.setSpieler(player);
return smilieEntry;
}
};
playerAdditionalArray[6] = new PlayerColumn(70,"Status",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SpielerStatusLabelEntry entry = new SpielerStatusLabelEntry();
entry.setSpieler(player);
return entry;
}
};
playerAdditionalArray[7] = new PlayerColumn(420,"Gehalt",10){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String bonus = "";
final int gehalt = (int) (player.getGehalt() / gui.UserParameter.instance().faktorGeld);
final String gehalttext = Helper.getNumberFormat(true, 0).format(gehalt);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
final int gehalt2 = (int) (playerCompare.getGehalt() / gui.UserParameter
.instance().faktorGeld);
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(gehalt - gehalt2,
ColorLabelEntry.BG_STANDARD,
true, false, 0));
}
};
playerAdditionalArray[8] = new PlayerColumn(430,"TSI",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String text = Helper.getNumberFormat(false, 0).format(player.getTSI());
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(player.getTSI()
- playerCompare.getTSI(), ColorLabelEntry.BG_STANDARD,
false, false, 0));
}
public void setSize(TableColumn column){
column.setMinWidth(Helper.calcCellWidth(90));
}
};
playerAdditionalArray[9] = new PlayerColumn(RATING,"Bewertung",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
if (player.getBewertung() > 0) {
//Hat im letzen Spiel gespielt
return new RatingTableEntry(player.getBewertung(), true);
}
return new RatingTableEntry(player.getLetzteBewertung(), false);
}
};
playerAdditionalArray[10] = new PlayerColumn(436,"Marktwert",10){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
IEPVData data = HOVerwaltung.instance().getModel().getEPV().getEPVData(player);
double price = HOVerwaltung.instance().getModel().getEPV().getPrice(data);
final String text = Helper.getNumberFormat(true, 0).format(price);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
IEPVData comparedata = HOVerwaltung.instance().getModel().getEPV().getEPVData(playerCompare);
int htweek = HelperWrapper.instance().getHTWeek(playerCompare.getHrfDate());
double compareepv = HOVerwaltung.instance().getModel().getEPV().getPrice(comparedata, htweek);
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry((float)(price-compareepv),
ColorLabelEntry.BG_STANDARD,
true, false, 0)
);
}
};
return playerAdditionalArray;
}
| protected static PlayerColumn[] createPlayerAdditionalArray(){
final PlayerColumn [] playerAdditionalArray = new PlayerColumn[11];
playerAdditionalArray[0] =new PlayerColumn(10," "," ",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
int sort = player.getTrikotnummer();
if (sort <= 0) {
//Damit die Spieler ohne Trickot nach den andern kommen
sort = 10000;
}
return new ColorLabelEntry(Helper.getImageIcon4Trickotnummer(player
.getTrikotnummer()),
sort, java.awt.Color.black, java.awt.Color.white,
SwingConstants.LEFT);
}
public boolean isEditable(){
return false;
}
};
playerAdditionalArray[1] =new PlayerColumn(20," ","Nationalitaet",25){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(Helper.getImageIcon4Country(player.getNationalitaet()),
player.getNationalitaet(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_FLAGGEN, SwingConstants.CENTER);
}
};
playerAdditionalArray[2] = new PlayerColumn(30, "Alter", 40){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
String ageString = player.getAlterWithAgeDaysAsString();
int birthdays = 0;
boolean playerExists;
if(playerCompare == null){
// Birthdays since last HRF
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - player.getAlter());
playerExists = false;
} else {
// Birthdays since compare
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - Math.floor(playerCompare.getAlterWithAgeDays()));
if (playerCompare.isOld())
// Player was not in our team at compare date
playerExists = false;
else
// Player was in our team at compare date
playerExists = true;
}
return new ColorLabelEntry(
birthdays,
ageString,
player.getAlterWithAgeDays(),
playerExists,
ColorLabelEntry.BG_STANDARD,
true);
}
};
playerAdditionalArray[3] =new PlayerColumn(40,"BestePosition",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
ColorLabelEntry tmp = new ColorLabelEntry(-SpielerPosition.getSortId(player
.getIdealPosition(),
false)
- (player.getIdealPosStaerke(true) / 100.0f),
SpielerPosition.getNameForPosition(player
.getIdealPosition())
+ " ("
+ player.calcPosValue(player
.getIdealPosition(),
true) + ")",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
tmp.setIcon((player.getUserPosFlag() < 0)?Helper.ZAHNRAD:Helper.MANUELL);
return tmp;
}
public boolean isEditable(){
return false;
}
};
// Position
playerAdditionalArray[4] =new PlayerColumn(LINUP," ","Aufgestellt",28){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final HOModel model = HOVerwaltung.instance().getModel();
if (model.getAufstellung().isSpielerAufgestellt(player
.getSpielerID())
&& (model.getAufstellung().getPositionBySpielerId(player
.getSpielerID()) != null)) {
return new ColorLabelEntry(Helper.getImage4Position(model.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
player.getTrikotnummer()),
-model.getAufstellung()
.getPositionBySpielerId(player
.getSpielerID())
.getSortId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImage4Position(null,
player
.getTrikotnummer()),
-player.getTrikotnummer() - 1000,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.CENTER);
}
};
playerAdditionalArray[5] = new PlayerColumn(GROUP,"Gruppe",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SmilieEntry smilieEntry = new SmilieEntry();
smilieEntry.setSpieler(player);
return smilieEntry;
}
};
playerAdditionalArray[6] = new PlayerColumn(70,"Status",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SpielerStatusLabelEntry entry = new SpielerStatusLabelEntry();
entry.setSpieler(player);
return entry;
}
};
playerAdditionalArray[7] = new PlayerColumn(420,"Gehalt",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String bonus = "";
final int gehalt = (int) (player.getGehalt() / gui.UserParameter.instance().faktorGeld);
final String gehalttext = Helper.getNumberFormat(true, 0).format(gehalt);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
final int gehalt2 = (int) (playerCompare.getGehalt() / gui.UserParameter
.instance().faktorGeld);
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(gehalt - gehalt2,
ColorLabelEntry.BG_STANDARD,
true, false, 0));
}
};
playerAdditionalArray[8] = new PlayerColumn(430,"TSI",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String text = Helper.getNumberFormat(false, 0).format(player.getTSI());
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(player.getTSI()
- playerCompare.getTSI(), ColorLabelEntry.BG_STANDARD,
false, false, 0));
}
public void setSize(TableColumn column){
column.setMinWidth(Helper.calcCellWidth(90));
}
};
playerAdditionalArray[9] = new PlayerColumn(RATING,"Bewertung",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
if (player.getBewertung() > 0) {
//Hat im letzen Spiel gespielt
return new RatingTableEntry(player.getBewertung(), true);
}
return new RatingTableEntry(player.getLetzteBewertung(), false);
}
};
playerAdditionalArray[10] = new PlayerColumn(436,"Marktwert",140){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
IEPVData data = HOVerwaltung.instance().getModel().getEPV().getEPVData(player);
double price = HOVerwaltung.instance().getModel().getEPV().getPrice(data);
final String text = Helper.getNumberFormat(true, 0).format(price);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
IEPVData comparedata = HOVerwaltung.instance().getModel().getEPV().getEPVData(playerCompare);
int htweek = HelperWrapper.instance().getHTWeek(playerCompare.getHrfDate());
double compareepv = HOVerwaltung.instance().getModel().getEPV().getPrice(comparedata, htweek);
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry((float)(price-compareepv),
ColorLabelEntry.BG_STANDARD,
true, false, 0)
);
}
};
return playerAdditionalArray;
}
|
diff --git a/src/com/android/calendar/event/EditEventView.java b/src/com/android/calendar/event/EditEventView.java
index 8b51ed5c..f1d305a0 100644
--- a/src/com/android/calendar/event/EditEventView.java
+++ b/src/com/android/calendar/event/EditEventView.java
@@ -1,1634 +1,1635 @@
/*
* 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.calendar.event;
import com.android.calendar.CalendarEventModel;
import com.android.calendar.CalendarEventModel.Attendee;
import com.android.calendar.CalendarEventModel.ReminderEntry;
import com.android.calendar.EmailAddressAdapter;
import com.android.calendar.EventInfoFragment;
import com.android.calendar.GeneralPreferences;
import com.android.calendar.R;
import com.android.calendar.RecipientAdapter;
import com.android.calendar.TimezoneAdapter;
import com.android.calendar.TimezoneAdapter.TimezoneRow;
import com.android.calendar.Utils;
import com.android.calendar.event.EditEventHelper.EditDoneRunnable;
import com.android.calendarcommon.EventRecurrence;
import com.android.common.Rfc822InputFilter;
import com.android.common.Rfc822Validator;
import com.android.ex.chips.AccountSpecifier;
import com.android.ex.chips.BaseRecipientAdapter;
import com.android.ex.chips.ChipsUtil;
import com.android.ex.chips.RecipientEditTextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.Service;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Reminders;
import android.provider.Settings;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.util.Rfc822Tokenizer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ResourceCursorAdapter;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
public class EditEventView implements View.OnClickListener, DialogInterface.OnCancelListener,
DialogInterface.OnClickListener, OnItemSelectedListener {
private static final String TAG = "EditEvent";
private static final String GOOGLE_SECONDARY_CALENDAR = "calendar.google.com";
private static final String PERIOD_SPACE = ". ";
private static String DEFAULT_DOMAIN;
ArrayList<View> mEditOnlyList = new ArrayList<View>();
ArrayList<View> mEditViewList = new ArrayList<View>();
ArrayList<View> mViewOnlyList = new ArrayList<View>();
TextView mLoadingMessage;
ScrollView mScrollView;
Button mStartDateButton;
Button mEndDateButton;
Button mStartTimeButton;
Button mEndTimeButton;
Button mTimezoneButton;
TextView mStartTimeHome;
TextView mStartDateHome;
TextView mEndTimeHome;
TextView mEndDateHome;
CheckBox mAllDayCheckBox;
Spinner mCalendarsSpinner;
Spinner mRepeatsSpinner;
Spinner mAvailabilitySpinner;
Spinner mAccessLevelSpinner;
RadioGroup mResponseRadioGroup;
TextView mTitleTextView;
TextView mLocationTextView;
TextView mDescriptionTextView;
TextView mWhenView;
TextView mTimezoneTextView;
TextView mTimezoneLabel;
LinearLayout mRemindersContainer;
MultiAutoCompleteTextView mAttendeesList;
View mCalendarSelectorGroup;
View mCalendarStaticGroup;
View mLocationGroup;
View mDescriptionGroup;
View mRemindersGroup;
View mResponseGroup;
View mOrganizerGroup;
View mAttendeesGroup;
View mStartHomeGroup;
View mEndHomeGroup;
View mAttendeesPane;
View mColorChip;
private int[] mOriginalPadding = new int[4];
private ProgressDialog mLoadingCalendarsDialog;
private AlertDialog mNoCalendarsDialog;
private AlertDialog mTimezoneDialog;
private Activity mActivity;
private EditDoneRunnable mDone;
private View mView;
private CalendarEventModel mModel;
private Cursor mCalendarsCursor;
private AccountSpecifier mAddressAdapter;
private Rfc822Validator mEmailValidator;
private TimezoneAdapter mTimezoneAdapter;
private ArrayList<Integer> mRecurrenceIndexes = new ArrayList<Integer>(0);
/**
* Contents of the "minutes" spinner. This has default values from the XML file, augmented
* with any additional values that were already associated with the event.
*/
private ArrayList<Integer> mReminderMinuteValues;
private ArrayList<String> mReminderMinuteLabels;
/**
* Contents of the "methods" spinner. The "values" list specifies the method constant
* (e.g. {@link Reminders#METHOD_ALERT}) associated with the labels. Any methods that
* aren't allowed by the Calendar will be removed.
*/
private ArrayList<Integer> mReminderMethodValues;
private ArrayList<String> mReminderMethodLabels;
private int mDefaultReminderMinutes;
private boolean mSaveAfterQueryComplete = false;
private Time mStartTime;
private Time mEndTime;
private String mTimezone;
private int mModification = EditEventHelper.MODIFY_UNINITIALIZED;
private EventRecurrence mEventRecurrence = new EventRecurrence();
private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0);
private static StringBuilder mSB = new StringBuilder(50);
private static Formatter mF = new Formatter(mSB, Locale.getDefault());
/* This class is used to update the time buttons. */
private class TimeListener implements OnTimeSetListener {
private View mView;
public TimeListener(View view) {
mView = view;
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mStartTimeButton) {
// The start time was changed.
int hourDuration = endTime.hour - startTime.hour;
int minuteDuration = endTime.minute - startTime.minute;
startTime.hour = hourOfDay;
startTime.minute = minute;
startMillis = startTime.normalize(true);
// Also update the end time to keep the duration constant.
endTime.hour = hourOfDay + hourDuration;
endTime.minute = minute + minuteDuration;
} else {
// The end time was changed.
startMillis = startTime.toMillis(true);
endTime.hour = hourOfDay;
endTime.minute = minute;
// Move to the start time if the end time is before the start
// time.
if (endTime.before(startTime)) {
endTime.monthDay = startTime.monthDay + 1;
}
}
endMillis = endTime.normalize(true);
setDate(mEndDateButton, endMillis);
setTime(mStartTimeButton, startMillis);
setTime(mEndTimeButton, endMillis);
updateHomeTime();
}
}
private class TimeClickListener implements View.OnClickListener {
private Time mTime;
public TimeClickListener(Time time) {
mTime = time;
}
@Override
public void onClick(View v) {
new TimePickerDialog(mActivity, new TimeListener(v), mTime.hour, mTime.minute,
DateFormat.is24HourFormat(mActivity)).show();
}
}
private class DateListener implements OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
@Override
public void onDateSet(DatePicker view, int year, int month, int monthDay) {
Log.d(TAG, "onDateSet: " + year + " " + month + " " + monthDay);
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mStartDateButton) {
// The start date was changed.
int yearDuration = endTime.year - startTime.year;
int monthDuration = endTime.month - startTime.month;
int monthDayDuration = endTime.monthDay - startTime.monthDay;
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
// Also update the end date to keep the duration constant.
endTime.year = year + yearDuration;
endTime.month = month + monthDuration;
endTime.monthDay = monthDay + monthDayDuration;
endMillis = endTime.normalize(true);
// If the start date has changed then update the repeats.
populateRepeats();
} else {
// The end date was changed.
startMillis = startTime.toMillis(true);
endTime.year = year;
endTime.month = month;
endTime.monthDay = monthDay;
endMillis = endTime.normalize(true);
// Do not allow an event to have an end time before the start
// time.
if (endTime.before(startTime)) {
endTime.set(startTime);
endMillis = startMillis;
}
}
setDate(mStartDateButton, startMillis);
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis); // In case end time had to be
// reset
updateHomeTime();
}
}
// Fills in the date and time fields
private void populateWhen() {
long startMillis = mStartTime.toMillis(false /* use isDst */);
long endMillis = mEndTime.toMillis(false /* use isDst */);
setDate(mStartDateButton, startMillis);
setDate(mEndDateButton, endMillis);
setTime(mStartTimeButton, startMillis);
setTime(mEndTimeButton, endMillis);
mStartDateButton.setOnClickListener(new DateClickListener(mStartTime));
mEndDateButton.setOnClickListener(new DateClickListener(mEndTime));
mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime));
mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime));
}
private void populateTimezone() {
mTimezoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTimezoneDialog();
}
});
setTimezone(mTimezoneAdapter.getRowById(mTimezone));
}
private void showTimezoneDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
final Context alertDialogContext = builder.getContext();
mTimezoneAdapter = new TimezoneAdapter(alertDialogContext, mTimezone);
builder.setTitle(R.string.timezone_label);
builder.setSingleChoiceItems(
mTimezoneAdapter, mTimezoneAdapter.getRowById(mTimezone), this);
mTimezoneDialog = builder.create();
LayoutInflater layoutInflater = (LayoutInflater) alertDialogContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final TextView timezoneFooterView = (TextView) layoutInflater.inflate(
R.layout.timezone_footer, null);
timezoneFooterView.setText(mActivity.getString(R.string.edit_event_show_all) + " >");
timezoneFooterView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTimezoneDialog.getListView().removeFooterView(timezoneFooterView);
mTimezoneAdapter.showAllTimezones();
final int row = mTimezoneAdapter.getRowById(mTimezone);
// we need to post the selection changes to have them have
// any effect
mTimezoneDialog.getListView().post(new Runnable() {
@Override
public void run() {
mTimezoneDialog.getListView().setItemChecked(row, true);
mTimezoneDialog.getListView().setSelection(row);
}
});
}
});
mTimezoneDialog.getListView().addFooterView(timezoneFooterView);
mTimezoneDialog.show();
}
private void populateRepeats() {
Time time = mStartTime;
Resources r = mActivity.getResources();
int resource = android.R.layout.simple_spinner_item;
String[] days = new String[] {
DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_MEDIUM),
DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_MEDIUM), };
String[] ordinals = r.getStringArray(R.array.ordinal_labels);
// Only display "Custom" in the spinner if the device does not support
// the recurrence functionality of the event. Only display every weekday
// if the event starts on a weekday.
boolean isCustomRecurrence = isCustomRecurrence();
boolean isWeekdayEvent = isWeekdayEvent();
ArrayList<String> repeatArray = new ArrayList<String>(0);
ArrayList<Integer> recurrenceIndexes = new ArrayList<Integer>(0);
repeatArray.add(r.getString(R.string.does_not_repeat));
recurrenceIndexes.add(EditEventHelper.DOES_NOT_REPEAT);
repeatArray.add(r.getString(R.string.daily));
recurrenceIndexes.add(EditEventHelper.REPEATS_DAILY);
if (isWeekdayEvent) {
repeatArray.add(r.getString(R.string.every_weekday));
recurrenceIndexes.add(EditEventHelper.REPEATS_EVERY_WEEKDAY);
}
String format = r.getString(R.string.weekly);
repeatArray.add(String.format(format, time.format("%A")));
recurrenceIndexes.add(EditEventHelper.REPEATS_WEEKLY_ON_DAY);
// Calculate whether this is the 1st, 2nd, 3rd, 4th, or last appearance
// of the given day.
int dayNumber = (time.monthDay - 1) / 7;
format = r.getString(R.string.monthly_on_day_count);
repeatArray.add(String.format(format, ordinals[dayNumber], days[time.weekDay]));
recurrenceIndexes.add(EditEventHelper.REPEATS_MONTHLY_ON_DAY_COUNT);
format = r.getString(R.string.monthly_on_day);
repeatArray.add(String.format(format, time.monthDay));
recurrenceIndexes.add(EditEventHelper.REPEATS_MONTHLY_ON_DAY);
long when = time.toMillis(false);
format = r.getString(R.string.yearly);
int flags = 0;
if (DateFormat.is24HourFormat(mActivity)) {
flags |= DateUtils.FORMAT_24HOUR;
}
repeatArray.add(String.format(format, DateUtils.formatDateTime(mActivity, when, flags)));
recurrenceIndexes.add(EditEventHelper.REPEATS_YEARLY);
if (isCustomRecurrence) {
repeatArray.add(r.getString(R.string.custom));
recurrenceIndexes.add(EditEventHelper.REPEATS_CUSTOM);
}
mRecurrenceIndexes = recurrenceIndexes;
int position = recurrenceIndexes.indexOf(EditEventHelper.DOES_NOT_REPEAT);
if (!TextUtils.isEmpty(mModel.mRrule)) {
if (isCustomRecurrence) {
position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_CUSTOM);
} else {
switch (mEventRecurrence.freq) {
case EventRecurrence.DAILY:
position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_DAILY);
break;
case EventRecurrence.WEEKLY:
if (mEventRecurrence.repeatsOnEveryWeekDay()) {
position = recurrenceIndexes.indexOf(
EditEventHelper.REPEATS_EVERY_WEEKDAY);
} else {
position = recurrenceIndexes.indexOf(
EditEventHelper.REPEATS_WEEKLY_ON_DAY);
}
break;
case EventRecurrence.MONTHLY:
if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
position = recurrenceIndexes.indexOf(
EditEventHelper.REPEATS_MONTHLY_ON_DAY_COUNT);
} else {
position = recurrenceIndexes.indexOf(
EditEventHelper.REPEATS_MONTHLY_ON_DAY);
}
break;
case EventRecurrence.YEARLY:
position = recurrenceIndexes.indexOf(EditEventHelper.REPEATS_YEARLY);
break;
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mActivity, resource, repeatArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mRepeatsSpinner.setAdapter(adapter);
mRepeatsSpinner.setSelection(position);
// Don't allow the user to make exceptions recurring events.
if (mModel.mOriginalSyncId != null) {
mRepeatsSpinner.setEnabled(false);
}
}
private boolean isCustomRecurrence() {
if (mEventRecurrence.until != null
|| (mEventRecurrence.interval != 0 && mEventRecurrence.interval != 1)
|| mEventRecurrence.count != 0) {
return true;
}
if (mEventRecurrence.freq == 0) {
return false;
}
switch (mEventRecurrence.freq) {
case EventRecurrence.DAILY:
return false;
case EventRecurrence.WEEKLY:
if (mEventRecurrence.repeatsOnEveryWeekDay() && isWeekdayEvent()) {
return false;
} else if (mEventRecurrence.bydayCount == 1) {
return false;
}
break;
case EventRecurrence.MONTHLY:
if (mEventRecurrence.repeatsMonthlyOnDayCount()) {
/* this is a "3rd Tuesday of every month" sort of rule */
return false;
} else if (mEventRecurrence.bydayCount == 0
&& mEventRecurrence.bymonthdayCount == 1
&& mEventRecurrence.bymonthday[0] > 0) {
/* this is a "22nd day of every month" sort of rule */
return false;
}
break;
case EventRecurrence.YEARLY:
return false;
}
return true;
}
private boolean isWeekdayEvent() {
if (mStartTime.weekDay != Time.SUNDAY && mStartTime.weekDay != Time.SATURDAY) {
return true;
}
return false;
}
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
public void onClick(View v) {
DatePickerDialog dpd = new DatePickerDialog(
mActivity, new DateListener(v), mTime.year, mTime.month, mTime.monthDay);
CalendarView cv = dpd.getDatePicker().getCalendarView();
cv.setShowWeekNumber(Utils.getShowWeekNumber(mActivity));
int startOfWeek = Utils.getFirstDayOfWeek(mActivity);
// Utils returns Time days while CalendarView wants Calendar days
if (startOfWeek == Time.SATURDAY) {
startOfWeek = Calendar.SATURDAY;
} else if (startOfWeek == Time.SUNDAY) {
startOfWeek = Calendar.SUNDAY;
} else {
startOfWeek = Calendar.MONDAY;
}
cv.setFirstDayOfWeek(startOfWeek);
dpd.show();
}
}
static private class CalendarsAdapter extends ResourceCursorAdapter {
public CalendarsAdapter(Context context, Cursor c) {
super(context, R.layout.calendars_item, c);
setDropDownViewResource(R.layout.calendars_dropdown_item);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
View colorBar = view.findViewById(R.id.color);
int colorColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
int nameColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME);
int ownerColumn = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
if (colorBar != null) {
colorBar.setBackgroundColor(Utils.getDisplayColorFromColor(cursor
.getInt(colorColumn)));
}
TextView name = (TextView) view.findViewById(R.id.calendar_name);
if (name != null) {
String displayName = cursor.getString(nameColumn);
name.setText(displayName);
TextView accountName = (TextView) view.findViewById(R.id.account_name);
if (accountName != null) {
Resources res = context.getResources();
accountName.setText(cursor.getString(ownerColumn));
accountName.setVisibility(TextView.VISIBLE);
accountName.setTextColor(res.getColor(R.color.calendar_owner_text_color));
}
}
}
}
/**
* Does prep steps for saving a calendar event.
*
* This triggers a parse of the attendees list and checks if the event is
* ready to be saved. An event is ready to be saved so long as a model
* exists and has a calendar it can be associated with, either because it's
* an existing event or we've finished querying.
*
* @return false if there is no model or no calendar had been loaded yet,
* true otherwise.
*/
public boolean prepareForSave() {
if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) {
return false;
}
return fillModelFromUI();
}
public boolean fillModelFromReadOnlyUi() {
if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) {
return false;
}
mModel.mReminders = EventViewUtils.reminderItemsToReminders(
mReminderItems, mReminderMinuteValues, mReminderMethodValues);
int status = EventInfoFragment.getResponseFromButtonId(
mResponseRadioGroup.getCheckedRadioButtonId());
if (status != Attendees.ATTENDEE_STATUS_NONE) {
mModel.mSelfAttendeeStatus = status;
}
return true;
}
// This is called if the user clicks on one of the buttons: "Save",
// "Discard", or "Delete". This is also called if the user clicks
// on the "remove reminder" button.
@Override
public void onClick(View view) {
// This must be a click on one of the "remove reminder" buttons
LinearLayout reminderItem = (LinearLayout) view.getParent();
LinearLayout parent = (LinearLayout) reminderItem.getParent();
parent.removeView(reminderItem);
mReminderItems.remove(reminderItem);
updateRemindersVisibility(mReminderItems.size());
}
// This is called if the user cancels the "No calendars" dialog.
// The "No calendars" dialog is shown if there are no syncable calendars.
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mLoadingCalendarsDialog) {
mLoadingCalendarsDialog = null;
mSaveAfterQueryComplete = false;
} else if (dialog == mNoCalendarsDialog) {
mDone.setDoneCode(Utils.DONE_REVERT);
mDone.run();
return;
}
}
// This is called if the user clicks on a dialog button.
@Override
public void onClick(DialogInterface dialog, int which) {
if (dialog == mNoCalendarsDialog) {
mDone.setDoneCode(Utils.DONE_REVERT);
mDone.run();
if (which == DialogInterface.BUTTON_POSITIVE) {
Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
final String[] array = {"com.android.calendar"};
nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array);
nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.startActivity(nextIntent);
}
} else if (dialog == mTimezoneDialog) {
if (which >= 0 && which < mTimezoneAdapter.getCount()) {
setTimezone(which);
updateHomeTime();
dialog.dismiss();
}
}
}
// Goes through the UI elements and updates the model as necessary
private boolean fillModelFromUI() {
if (mModel == null) {
return false;
}
mModel.mReminders = EventViewUtils.reminderItemsToReminders(mReminderItems,
mReminderMinuteValues, mReminderMethodValues);
mModel.mHasAlarm = mReminderItems.size() > 0;
mModel.mTitle = mTitleTextView.getText().toString();
mModel.mAllDay = mAllDayCheckBox.isChecked();
mModel.mLocation = mLocationTextView.getText().toString();
mModel.mDescription = mDescriptionTextView.getText().toString();
if (TextUtils.isEmpty(mModel.mLocation)) {
mModel.mLocation = null;
}
if (TextUtils.isEmpty(mModel.mDescription)) {
mModel.mDescription = null;
}
int status = EventInfoFragment.getResponseFromButtonId(mResponseRadioGroup
.getCheckedRadioButtonId());
if (status != Attendees.ATTENDEE_STATUS_NONE) {
mModel.mSelfAttendeeStatus = status;
}
if (mAttendeesList != null && !TextUtils.isEmpty(mAttendeesList.getText())) {
mEmailValidator.setRemoveInvalid(true);
mAttendeesList.performValidation();
mModel.addAttendees(mAttendeesList.getText().toString(), mEmailValidator);
}
// If this was a new event we need to fill in the Calendar information
if (mModel.mUri == null) {
mModel.mCalendarId = mCalendarsSpinner.getSelectedItemId();
int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition();
if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) {
String defaultCalendar = mCalendarsCursor.getString(
EditEventHelper.CALENDARS_INDEX_OWNER_ACCOUNT);
Utils.setSharedPreference(
mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, defaultCalendar);
mModel.mOwnerAccount = defaultCalendar;
mModel.mOrganizer = defaultCalendar;
mModel.mCalendarId = mCalendarsCursor.getLong(EditEventHelper.CALENDARS_INDEX_ID);
}
}
if (mModel.mAllDay) {
// Reset start and end time, increment the monthDay by 1, and set
// the timezone to UTC, as required for all-day events.
mTimezone = Time.TIMEZONE_UTC;
mStartTime.hour = 0;
mStartTime.minute = 0;
mStartTime.second = 0;
mStartTime.timezone = mTimezone;
mModel.mStart = mStartTime.normalize(true);
mEndTime.hour = 0;
mEndTime.minute = 0;
mEndTime.second = 0;
mEndTime.timezone = mTimezone;
// When a user see the event duration as "X - Y" (e.g. Oct. 28 - Oct. 29), end time
// should be Y + 1 (Oct.30).
final long normalizedEndTimeMillis =
mEndTime.normalize(true) + DateUtils.DAY_IN_MILLIS;
if (normalizedEndTimeMillis < mModel.mStart) {
// mEnd should be midnight of the next day of mStart.
mModel.mEnd = mModel.mStart + DateUtils.DAY_IN_MILLIS;
} else {
mModel.mEnd = normalizedEndTimeMillis;
}
} else {
mStartTime.timezone = mTimezone;
mEndTime.timezone = mTimezone;
mModel.mStart = mStartTime.toMillis(true);
mModel.mEnd = mEndTime.toMillis(true);
}
mModel.mTimezone = mTimezone;
mModel.mAccessLevel = mAccessLevelSpinner.getSelectedItemPosition();
mModel.mAvailability = mAvailabilitySpinner.getSelectedItemPosition() != 0;
int selection;
// If we're making an exception we don't want it to be a repeating
// event.
if (mModification == EditEventHelper.MODIFY_SELECTED) {
selection = EditEventHelper.DOES_NOT_REPEAT;
} else {
int position = mRepeatsSpinner.getSelectedItemPosition();
selection = mRecurrenceIndexes.get(position);
}
EditEventHelper.updateRecurrenceRule(
selection, mModel, Utils.getFirstDayOfWeek(mActivity) + 1);
// Save the timezone so we can display it as a standard option next time
if (!mModel.mAllDay) {
mTimezoneAdapter.saveRecentTimezone(mTimezone);
}
return true;
}
public EditEventView(Activity activity, View view, EditDoneRunnable done) {
mActivity = activity;
mView = view;
mDone = done;
DEFAULT_DOMAIN = activity.getResources().getString(R.string.google_email_domain);
// cache top level view elements
mLoadingMessage = (TextView) view.findViewById(R.id.loading_message);
mScrollView = (ScrollView) view.findViewById(R.id.scroll_view);
// cache all the widgets
mCalendarsSpinner = (Spinner) view.findViewById(R.id.calendars_spinner);
mTitleTextView = (TextView) view.findViewById(R.id.title);
mLocationTextView = (TextView) view.findViewById(R.id.location);
mDescriptionTextView = (TextView) view.findViewById(R.id.description);
mTimezoneLabel = (TextView) view.findViewById(R.id.timezone_label);
mStartDateButton = (Button) view.findViewById(R.id.start_date);
mEndDateButton = (Button) view.findViewById(R.id.end_date);
mWhenView = (TextView) mView.findViewById(R.id.when);
mTimezoneTextView = (TextView) mView.findViewById(R.id.timezone_textView);
mStartTimeButton = (Button) view.findViewById(R.id.start_time);
mEndTimeButton = (Button) view.findViewById(R.id.end_time);
mTimezoneButton = (Button) view.findViewById(R.id.timezone_button);
mStartTimeHome = (TextView) view.findViewById(R.id.start_time_home_tz);
mStartDateHome = (TextView) view.findViewById(R.id.start_date_home_tz);
mEndTimeHome = (TextView) view.findViewById(R.id.end_time_home_tz);
mEndDateHome = (TextView) view.findViewById(R.id.end_date_home_tz);
mAllDayCheckBox = (CheckBox) view.findViewById(R.id.is_all_day);
mRepeatsSpinner = (Spinner) view.findViewById(R.id.repeats);
mAvailabilitySpinner = (Spinner) view.findViewById(R.id.availability);
mAccessLevelSpinner = (Spinner) view.findViewById(R.id.visibility);
mCalendarSelectorGroup = view.findViewById(R.id.calendar_selector_group);
mCalendarStaticGroup = view.findViewById(R.id.calendar_group);
mRemindersGroup = view.findViewById(R.id.reminders_row);
mResponseGroup = view.findViewById(R.id.response_row);
mOrganizerGroup = view.findViewById(R.id.organizer_row);
mAttendeesPane = view.findViewById(R.id.attendees_group);
mLocationGroup = view.findViewById(R.id.where_row);
mDescriptionGroup = view.findViewById(R.id.description_row);
mStartHomeGroup = view.findViewById(R.id.from_row_home_tz);
mEndHomeGroup = view.findViewById(R.id.to_row_home_tz);
mAttendeesList = (MultiAutoCompleteTextView) view.findViewById(R.id.attendees);
mTitleTextView.setTag(mTitleTextView.getBackground());
mLocationTextView.setTag(mLocationTextView.getBackground());
mDescriptionTextView.setTag(mDescriptionTextView.getBackground());
mRepeatsSpinner.setTag(mRepeatsSpinner.getBackground());
mAttendeesList.setTag(mAttendeesList.getBackground());
mOriginalPadding[0] = mLocationTextView.getPaddingLeft();
mOriginalPadding[1] = mLocationTextView.getPaddingTop();
mOriginalPadding[2] = mLocationTextView.getPaddingRight();
mOriginalPadding[3] = mLocationTextView.getPaddingBottom();
mEditViewList.add(mTitleTextView);
mEditViewList.add(mLocationTextView);
mEditViewList.add(mDescriptionTextView);
mEditViewList.add(mAttendeesList);
mViewOnlyList.add(view.findViewById(R.id.when_row));
mViewOnlyList.add(view.findViewById(R.id.timezone_textview_row));
mEditOnlyList.add(view.findViewById(R.id.all_day_row));
mEditOnlyList.add(view.findViewById(R.id.availability_row));
mEditOnlyList.add(view.findViewById(R.id.visibility_row));
mEditOnlyList.add(view.findViewById(R.id.from_row));
mEditOnlyList.add(view.findViewById(R.id.to_row));
mEditOnlyList.add(view.findViewById(R.id.timezone_button_row));
mEditOnlyList.add(mStartHomeGroup);
mEditOnlyList.add(mEndHomeGroup);
mResponseRadioGroup = (RadioGroup) view.findViewById(R.id.response_value);
mRemindersContainer = (LinearLayout) view.findViewById(R.id.reminder_items_container);
mTimezone = Utils.getTimeZone(activity, null);
mStartTime = new Time(mTimezone);
mEndTime = new Time(mTimezone);
mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
mEmailValidator = new Rfc822Validator(null);
initMultiAutoCompleteTextView((RecipientEditTextView) mAttendeesList);
mColorChip = view.findViewById(R.id.color_chip);
// Display loading screen
setModel(null);
}
/**
* Loads an integer array asset into a list.
*/
private static ArrayList<Integer> loadIntegerArray(Resources r, int resNum) {
int[] vals = r.getIntArray(resNum);
int size = vals.length;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for (int i = 0; i < size; i++) {
list.add(vals[i]);
}
return list;
}
/**
* Loads a String array asset into a list.
*/
private static ArrayList<String> loadStringArray(Resources r, int resNum) {
String[] labels = r.getStringArray(resNum);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(labels));
return list;
}
/**
* Prepares the reminder UI elements.
* <p>
* (Re-)loads the minutes / methods lists from the XML assets, adds/removes items as
* needed for the current set of reminders and calendar properties, and then creates UI
* elements.
*/
private void prepareReminders() {
CalendarEventModel model = mModel;
Resources r = mActivity.getResources();
// Load the labels and corresponding numeric values for the minutes and methods lists
// from the assets. If we're switching calendars, we need to clear and re-populate the
// lists (which may have elements added and removed based on calendar properties). This
// is mostly relevant for "methods", since we shouldn't have any "minutes" values in a
// new event that aren't in the default set.
mReminderMinuteValues = loadIntegerArray(r, R.array.reminder_minutes_values);
mReminderMinuteLabels = loadStringArray(r, R.array.reminder_minutes_labels);
mReminderMethodValues = loadIntegerArray(r, R.array.reminder_methods_values);
mReminderMethodLabels = loadStringArray(r, R.array.reminder_methods_labels);
// Remove any reminder methods that aren't allowed for this calendar. If this is
// a new event, mCalendarAllowedReminders may not be set the first time we're called.
if (mModel.mCalendarAllowedReminders != null) {
EventViewUtils.reduceMethodList(mReminderMethodValues, mReminderMethodLabels,
mModel.mCalendarAllowedReminders);
}
int numReminders = 0;
if (model.mHasAlarm) {
ArrayList<ReminderEntry> reminders = model.mReminders;
numReminders = reminders.size();
// Insert any minute values that aren't represented in the minutes list.
for (ReminderEntry re : reminders) {
EventViewUtils.addMinutesToList(
mActivity, mReminderMinuteValues, mReminderMinuteLabels, re.getMinutes());
}
// Create a UI element for each reminder. We display all of the reminders we get
// from the provider, even if the count exceeds the calendar maximum. (Also, for
// a new event, we won't have a maxReminders value available.)
for (ReminderEntry re : reminders) {
EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
mReminderMinuteValues, mReminderMinuteLabels,
mReminderMethodValues, mReminderMethodLabels,
re, Integer.MAX_VALUE);
}
}
updateRemindersVisibility(numReminders);
}
/**
* Fill in the view with the contents of the given event model. This allows
* an edit view to be initialized before the event has been loaded. Passing
* in null for the model will display a loading screen. A non-null model
* will fill in the view's fields with the data contained in the model.
*
* @param model The event model to pull the data from
*/
public void setModel(CalendarEventModel model) {
mModel = model;
// Need to close the autocomplete adapter to prevent leaking cursors.
if (mAddressAdapter != null && mAddressAdapter instanceof EmailAddressAdapter) {
((EmailAddressAdapter)mAddressAdapter).close();
mAddressAdapter = null;
}
if (model == null) {
// Display loading screen
mLoadingMessage.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
return;
}
boolean canModifyCalendar = EditEventHelper.canModifyCalendar(model);
boolean canModifyEvent = EditEventHelper.canModifyEvent(model);
boolean canRespond = EditEventHelper.canRespond(model);
long begin = model.mStart;
long end = model.mEnd;
mTimezone = model.mTimezone; // this will be UTC for all day events
// Set up the starting times
if (begin > 0) {
mStartTime.timezone = mTimezone;
mStartTime.set(begin);
mStartTime.normalize(true);
}
if (end > 0) {
mEndTime.timezone = mTimezone;
mEndTime.set(end);
mEndTime.normalize(true);
}
String rrule = model.mRrule;
if (!TextUtils.isEmpty(rrule)) {
mEventRecurrence.parse(rrule);
}
// If the user is allowed to change the attendees set up the view and
// validator
if (!model.mHasAttendeeData) {
mAttendeesGroup.setVisibility(View.GONE);
}
mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setAllDayViewsVisibility(isChecked);
}
});
if (model.mAllDay) {
mAllDayCheckBox.setChecked(true);
// put things back in local time for all day events
mTimezone = TimeZone.getDefault().getID();
mStartTime.timezone = mTimezone;
mStartTime.normalize(true);
mEndTime.timezone = mTimezone;
mEndTime.normalize(true);
} else {
mAllDayCheckBox.setChecked(false);
}
mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
if (mTimezoneDialog != null) {
mTimezoneDialog.getListView().setAdapter(mTimezoneAdapter);
}
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
String defaultReminderString = prefs.getString(
GeneralPreferences.KEY_DEFAULT_REMINDER, GeneralPreferences.NO_REMINDER_STRING);
mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
prepareReminders();
ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add);
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
addReminder();
}
};
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mTitleTextView.setText(model.mTitle);
if (model.mIsOrganizer || TextUtils.isEmpty(model.mOrganizer)
|| model.mOrganizer.endsWith(GOOGLE_SECONDARY_CALENDAR)) {
mView.findViewById(R.id.organizer_label).setVisibility(View.GONE);
mView.findViewById(R.id.organizer).setVisibility(View.GONE);
mOrganizerGroup.setVisibility(View.GONE);
} else {
((TextView) mView.findViewById(R.id.organizer)).setText(model.mOrganizerDisplayName);
}
mLocationTextView.setText(model.mLocation);
mDescriptionTextView.setText(model.mDescription);
mAvailabilitySpinner.setSelection(model.mAvailability ? 1 : 0);
mAccessLevelSpinner.setSelection(model.mAccessLevel);
View responseLabel = mView.findViewById(R.id.response_label);
if (canRespond) {
int buttonToCheck = EventInfoFragment
.findButtonIdForResponse(model.mSelfAttendeeStatus);
mResponseRadioGroup.check(buttonToCheck); // -1 clear all radio buttons
mResponseRadioGroup.setVisibility(View.VISIBLE);
responseLabel.setVisibility(View.VISIBLE);
} else {
responseLabel.setVisibility(View.GONE);
mResponseRadioGroup.setVisibility(View.GONE);
+ mResponseGroup.setVisibility(View.GONE);
}
int displayColor = Utils.getDisplayColorFromColor(model.mCalendarColor);
if (model.mUri != null) {
// This is an existing event so hide the calendar spinner
// since we can't change the calendar.
View calendarGroup = mView.findViewById(R.id.calendar_selector_group);
calendarGroup.setVisibility(View.GONE);
TextView tv = (TextView) mView.findViewById(R.id.calendar_textview);
tv.setText(model.mCalendarDisplayName);
tv.setBackgroundColor(displayColor);
mColorChip.setBackgroundColor(displayColor);
} else {
View calendarGroup = mView.findViewById(R.id.calendar_group);
calendarGroup.setVisibility(View.GONE);
mCalendarsSpinner.setBackgroundColor(displayColor);
mCalendarSelectorGroup.setBackgroundColor(displayColor);
}
populateTimezone();
populateWhen();
populateRepeats();
updateAttendees(model.mAttendeesList);
updateView();
mScrollView.setVisibility(View.VISIBLE);
mLoadingMessage.setVisibility(View.GONE);
sendAccessibilityEvent();
}
private void sendAccessibilityEvent() {
AccessibilityManager am =
(AccessibilityManager) mActivity.getSystemService(Service.ACCESSIBILITY_SERVICE);
if (!am.isEnabled() || mModel == null) {
return;
}
StringBuilder b = new StringBuilder();
addFieldsRecursive(b, mView);
CharSequence msg = b.toString();
AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_FOCUSED);
event.setClassName(getClass().getName());
event.setPackageName(mActivity.getPackageName());
event.getText().add(msg);
event.setAddedCount(msg.length());
am.sendAccessibilityEvent(event);
}
private void addFieldsRecursive(StringBuilder b, View v) {
if (v == null || v.getVisibility() != View.VISIBLE) {
return;
}
if (v instanceof TextView) {
CharSequence tv = ((TextView) v).getText();
if (!TextUtils.isEmpty(tv.toString().trim())) {
b.append(tv + PERIOD_SPACE);
}
} else if (v instanceof RadioGroup) {
RadioGroup rg = (RadioGroup) v;
int id = rg.getCheckedRadioButtonId();
if (id != View.NO_ID) {
b.append(((RadioButton) (v.findViewById(id))).getText() + PERIOD_SPACE);
}
} else if (v instanceof Spinner) {
Spinner s = (Spinner) v;
if (s.getSelectedItem() instanceof String) {
String str = ((String) (s.getSelectedItem())).trim();
if (!TextUtils.isEmpty(str)) {
b.append(str + PERIOD_SPACE);
}
}
} else if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
int children = vg.getChildCount();
for (int i = 0; i < children; i++) {
addFieldsRecursive(b, vg.getChildAt(i));
}
}
}
/**
* Creates a single line string for the time/duration
*/
protected void setWhenString() {
String when;
int flags = DateUtils.FORMAT_SHOW_DATE;
String tz = mTimezone;
if (mModel.mAllDay) {
flags |= DateUtils.FORMAT_SHOW_WEEKDAY;
tz = Time.TIMEZONE_UTC;
} else {
flags |= DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(mActivity)) {
flags |= DateUtils.FORMAT_24HOUR;
}
}
long startMillis = mStartTime.normalize(true);
long endMillis = mEndTime.normalize(true);
mSB.setLength(0);
when = DateUtils
.formatDateRange(mActivity, mF, startMillis, endMillis, flags, tz).toString();
mWhenView.setText(when);
}
/**
* Configures the Calendars spinner. This is only done for new events, because only new
* events allow you to select a calendar while editing an event.
* <p>
* We tuck a reference to a Cursor with calendar database data into the spinner, so that
* we can easily extract calendar-specific values when the value changes (the spinner's
* onItemSelected callback is configured).
*/
public void setCalendarsCursor(Cursor cursor, boolean userVisible) {
// If there are no syncable calendars, then we cannot allow
// creating a new event.
mCalendarsCursor = cursor;
if (cursor == null || cursor.getCount() == 0) {
// Cancel the "loading calendars" dialog if it exists
if (mSaveAfterQueryComplete) {
mLoadingCalendarsDialog.cancel();
}
if (!userVisible) {
return;
}
// Create an error message for the user that, when clicked,
// will exit this activity without saving the event.
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(R.string.no_syncable_calendars).setIconAttribute(
android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found)
.setPositiveButton(R.string.add_account, this)
.setNegativeButton(android.R.string.no, this).setOnCancelListener(this);
mNoCalendarsDialog = builder.show();
return;
}
int defaultCalendarPosition = findDefaultCalendarPosition(cursor);
// populate the calendars spinner
CalendarsAdapter adapter = new CalendarsAdapter(mActivity, cursor);
mCalendarsSpinner.setAdapter(adapter);
mCalendarsSpinner.setSelection(defaultCalendarPosition);
mCalendarsSpinner.setOnItemSelectedListener(this);
int colorColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
mColorChip.setBackgroundColor(Utils.getDisplayColorFromColor(cursor.getInt(colorColumn)));
if (mSaveAfterQueryComplete) {
mLoadingCalendarsDialog.cancel();
if (prepareForSave() && fillModelFromUI()) {
int exit = userVisible ? Utils.DONE_EXIT : 0;
mDone.setDoneCode(Utils.DONE_SAVE | exit);
mDone.run();
} else if (userVisible) {
mDone.setDoneCode(Utils.DONE_EXIT);
mDone.run();
} else if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "SetCalendarsCursor:Save failed and unable to exit view");
}
return;
}
}
/**
* Updates the view based on {@link #mModification} and {@link #mModel}
*/
public void updateView() {
if (mModel == null) {
return;
}
if (EditEventHelper.canModifyEvent(mModel)) {
setViewStates(mModification);
} else {
setViewStates(Utils.MODIFY_UNINITIALIZED);
}
}
private void setViewStates(int mode) {
// Extra canModify check just in case
if (mode == Utils.MODIFY_UNINITIALIZED || !EditEventHelper.canModifyEvent(mModel)) {
setWhenString();
for (View v : mViewOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditViewList) {
v.setEnabled(false);
v.setBackgroundDrawable(null);
}
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
mRepeatsSpinner.setEnabled(false);
mRepeatsSpinner.setBackgroundDrawable(null);
if (EditEventHelper.canAddReminders(mModel)) {
mRemindersGroup.setVisibility(View.VISIBLE);
} else {
mRemindersGroup.setVisibility(View.GONE);
}
if (mAllDayCheckBox.isChecked()) {
mView.findViewById(R.id.timezone_textview_row).setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mLocationTextView.getText())) {
mLocationGroup.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(mDescriptionTextView.getText())) {
mDescriptionGroup.setVisibility(View.GONE);
}
} else {
for (View v : mViewOnlyList) {
v.setVisibility(View.GONE);
}
for (View v : mEditOnlyList) {
v.setVisibility(View.VISIBLE);
}
for (View v : mEditViewList) {
v.setEnabled(true);
if (v.getTag() != null) {
v.setBackgroundDrawable((Drawable) v.getTag());
}
}
if (mModel.mUri == null) {
mCalendarSelectorGroup.setVisibility(View.VISIBLE);
mCalendarStaticGroup.setVisibility(View.GONE);
} else {
mCalendarSelectorGroup.setVisibility(View.GONE);
mCalendarStaticGroup.setVisibility(View.VISIBLE);
}
mRepeatsSpinner.setBackgroundDrawable((Drawable) mRepeatsSpinner.getTag());
if (mModel.mOriginalSyncId == null) {
mRepeatsSpinner.setEnabled(true);
} else {
mRepeatsSpinner.setEnabled(false);
}
mRemindersGroup.setVisibility(View.VISIBLE);
mAttendeesPane.setVisibility(View.VISIBLE);
mLocationGroup.setVisibility(View.VISIBLE);
mDescriptionGroup.setVisibility(View.VISIBLE);
}
}
public void setModification(int modifyWhich) {
mModification = modifyWhich;
updateView();
updateHomeTime();
}
// Find the calendar position in the cursor that matches calendar in
// preference
private int findDefaultCalendarPosition(Cursor calendarsCursor) {
if (calendarsCursor.getCount() <= 0) {
return -1;
}
String defaultCalendar = Utils.getSharedPreference(
mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, null);
if (defaultCalendar == null) {
return 0;
}
int calendarsOwnerColumn = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
int position = 0;
calendarsCursor.moveToPosition(-1);
while (calendarsCursor.moveToNext()) {
if (defaultCalendar.equals(calendarsCursor.getString(calendarsOwnerColumn))) {
return position;
}
position++;
}
return 0;
}
private void updateAttendees(HashMap<String, Attendee> attendeesList) {
if (attendeesList == null || attendeesList.isEmpty()) {
return;
}
mAttendeesList.setText(null);
for (Attendee attendee : attendeesList.values()) {
mAttendeesList.append(attendee.mEmail);
}
}
private void updateRemindersVisibility(int numReminders) {
if (numReminders == 0) {
mRemindersContainer.setVisibility(View.GONE);
} else {
mRemindersContainer.setVisibility(View.VISIBLE);
}
}
/**
* Add a new reminder when the user hits the "add reminder" button. We use the default
* reminder time and method.
*/
private void addReminder() {
// TODO: when adding a new reminder, make it different from the
// last one in the list (if any).
if (mDefaultReminderMinutes == GeneralPreferences.NO_REMINDER) {
EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
mReminderMinuteValues, mReminderMinuteLabels,
mReminderMethodValues, mReminderMethodLabels,
ReminderEntry.valueOf(GeneralPreferences.REMINDER_DEFAULT_TIME),
mModel.mCalendarMaxReminders);
} else {
EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems,
mReminderMinuteValues, mReminderMinuteLabels,
mReminderMethodValues, mReminderMethodLabels,
ReminderEntry.valueOf(mDefaultReminderMinutes),
mModel.mCalendarMaxReminders);
}
updateRemindersVisibility(mReminderItems.size());
}
// From com.google.android.gm.ComposeActivity
private MultiAutoCompleteTextView initMultiAutoCompleteTextView(RecipientEditTextView list) {
if (ChipsUtil.supportsChipsUi()) {
mAddressAdapter = new RecipientAdapter(mActivity);
list.setAdapter((BaseRecipientAdapter) mAddressAdapter);
Resources r = mActivity.getResources();
Bitmap def = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
list.setChipDimensions(
r.getDrawable(R.drawable.chip_background),
r.getDrawable(R.drawable.chip_background_selected),
r.getDrawable(R.drawable.chip_background_invalid),
r.getDrawable(R.drawable.chip_delete),
def,
R.layout.more_item,
R.layout.chips_alternate_item,
r.getDimension(R.dimen.chip_height),
r.getDimension(R.dimen.chip_padding),
r.getDimension(R.dimen.chip_text_size));
} else {
mAddressAdapter = new EmailAddressAdapter(mActivity);
list.setAdapter((EmailAddressAdapter)mAddressAdapter);
}
list.setTokenizer(new Rfc822Tokenizer());
list.setValidator(mEmailValidator);
// NOTE: assumes no other filters are set
list.setFilters(sRecipientFilters);
return list;
}
/**
* From com.google.android.gm.ComposeActivity Implements special address
* cleanup rules: The first space key entry following an "@" symbol that is
* followed by any combination of letters and symbols, including one+ dots
* and zero commas, should insert an extra comma (followed by the space).
*/
private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() };
private void setDate(TextView view, long millis) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
| DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH
| DateUtils.FORMAT_ABBREV_WEEKDAY;
// Unfortunately, DateUtils doesn't support a timezone other than the
// default timezone provided by the system, so we have this ugly hack
// here to trick it into formatting our time correctly. In order to
// prevent all sorts of craziness, we synchronize on the TimeZone class
// to prevent other threads from reading an incorrect timezone from
// calls to TimeZone#getDefault()
// TODO fix this if/when DateUtils allows for passing in a timezone
String dateString;
synchronized (TimeZone.class) {
TimeZone.setDefault(TimeZone.getTimeZone(mTimezone));
dateString = DateUtils.formatDateTime(mActivity, millis, flags);
// setting the default back to null restores the correct behavior
TimeZone.setDefault(null);
}
view.setText(dateString);
}
private void setTime(TextView view, long millis) {
int flags = DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(mActivity)) {
flags |= DateUtils.FORMAT_24HOUR;
}
// Unfortunately, DateUtils doesn't support a timezone other than the
// default timezone provided by the system, so we have this ugly hack
// here to trick it into formatting our time correctly. In order to
// prevent all sorts of craziness, we synchronize on the TimeZone class
// to prevent other threads from reading an incorrect timezone from
// calls to TimeZone#getDefault()
// TODO fix this if/when DateUtils allows for passing in a timezone
String timeString;
synchronized (TimeZone.class) {
TimeZone.setDefault(TimeZone.getTimeZone(mTimezone));
timeString = DateUtils.formatDateTime(mActivity, millis, flags);
TimeZone.setDefault(null);
}
view.setText(timeString);
}
private void setTimezone(int i) {
if (i < 0 || i >= mTimezoneAdapter.getCount()) {
return; // do nothing
}
TimezoneRow timezone = mTimezoneAdapter.getItem(i);
mTimezoneTextView.setText(timezone.toString());
mTimezoneButton.setText(timezone.toString());
mTimezone = timezone.mId;
mStartTime.timezone = mTimezone;
mStartTime.normalize(true);
mEndTime.timezone = mTimezone;
mEndTime.normalize(true);
mTimezoneAdapter.setCurrentTimezone(mTimezone);
}
/**
* @param isChecked
*/
protected void setAllDayViewsVisibility(boolean isChecked) {
if (isChecked) {
if (mEndTime.hour == 0 && mEndTime.minute == 0) {
mEndTime.monthDay--;
long endMillis = mEndTime.normalize(true);
// Do not allow an event to have an end time
// before the
// start time.
if (mEndTime.before(mStartTime)) {
mEndTime.set(mStartTime);
endMillis = mEndTime.normalize(true);
}
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis);
}
mStartTimeButton.setVisibility(View.GONE);
mEndTimeButton.setVisibility(View.GONE);
mTimezoneButton.setVisibility(View.GONE);
mTimezoneLabel.setVisibility(View.GONE);
} else {
if (mEndTime.hour == 0 && mEndTime.minute == 0) {
mEndTime.monthDay++;
long endMillis = mEndTime.normalize(true);
setDate(mEndDateButton, endMillis);
setTime(mEndTimeButton, endMillis);
}
mStartTimeButton.setVisibility(View.VISIBLE);
mEndTimeButton.setVisibility(View.VISIBLE);
mTimezoneButton.setVisibility(View.VISIBLE);
mTimezoneLabel.setVisibility(View.VISIBLE);
}
updateHomeTime();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// This is only used for the Calendar spinner in new events, and only fires when the
// calendar selection changes.
Cursor c = (Cursor) parent.getItemAtPosition(position);
if (c == null) {
// TODO: can this happen? should we drop this check?
Log.w(TAG, "Cursor not set on calendar item");
return;
}
int colorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
int color = c.getInt(colorColumn);
int displayColor = Utils.getDisplayColorFromColor(color);
mColorChip.setBackgroundColor(displayColor);
mModel.mCalendarColor = color;
mCalendarsSpinner.setBackgroundColor(displayColor);
mCalendarSelectorGroup.setBackgroundColor(displayColor);
// Update the max/allowed reminders with the new calendar properties.
int maxRemindersColumn = c.getColumnIndexOrThrow(Calendars.MAX_REMINDERS);
mModel.mCalendarMaxReminders = c.getInt(maxRemindersColumn);
int allowedRemindersColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_REMINDERS);
mModel.mCalendarAllowedReminders = c.getString(allowedRemindersColumn);
// Discard the current reminders and replace them with the model's default reminder set.
// We could attempt to save & restore the reminders that have been added, but that's
// probably more trouble than it's worth.
mModel.mReminders.clear();
mModel.mReminders.addAll(mModel.mDefaultReminders);
mModel.mHasAlarm = mModel.mReminders.size() != 0;
// Update the UI elements.
mReminderItems.clear();
LinearLayout reminderLayout =
(LinearLayout) mScrollView.findViewById(R.id.reminder_items_container);
reminderLayout.removeAllViews();
prepareReminders();
}
/**
* Checks if the start and end times for this event should be displayed in
* the Calendar app's time zone as well and formats and displays them.
*/
private void updateHomeTime() {
String tz = Utils.getTimeZone(mActivity, null);
if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone)
&& mModification != EditEventHelper.MODIFY_UNINITIALIZED) {
int flags = DateUtils.FORMAT_SHOW_TIME;
boolean is24Format = DateFormat.is24HourFormat(mActivity);
if (is24Format) {
flags |= DateUtils.FORMAT_24HOUR;
}
long millisStart = mStartTime.toMillis(false);
long millisEnd = mEndTime.toMillis(false);
boolean isDSTStart = mStartTime.isDst != 0;
boolean isDSTEnd = mEndTime.isDst != 0;
// First update the start date and times
String tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(
isDSTStart, TimeZone.SHORT, Locale.getDefault());
StringBuilder time = new StringBuilder();
mSB.setLength(0);
time.append(DateUtils
.formatDateRange(mActivity, mF, millisStart, millisStart, flags, tz))
.append(" ").append(tzDisplay);
mStartTimeHome.setText(time.toString());
flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
mSB.setLength(0);
mStartDateHome
.setText(DateUtils.formatDateRange(
mActivity, mF, millisStart, millisStart, flags, tz).toString());
// Make any adjustments needed for the end times
if (isDSTEnd != isDSTStart) {
tzDisplay = TimeZone.getTimeZone(tz).getDisplayName(
isDSTEnd, TimeZone.SHORT, Locale.getDefault());
}
flags = DateUtils.FORMAT_SHOW_TIME;
if (is24Format) {
flags |= DateUtils.FORMAT_24HOUR;
}
// Then update the end times
time.setLength(0);
mSB.setLength(0);
time.append(DateUtils.formatDateRange(
mActivity, mF, millisEnd, millisEnd, flags, tz)).append(" ").append(tzDisplay);
mEndTimeHome.setText(time.toString());
flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;
mSB.setLength(0);
mEndDateHome.setText(DateUtils.formatDateRange(
mActivity, mF, millisEnd, millisEnd, flags, tz).toString());
mStartHomeGroup.setVisibility(View.VISIBLE);
mEndHomeGroup.setVisibility(View.VISIBLE);
} else {
mStartHomeGroup.setVisibility(View.GONE);
mEndHomeGroup.setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mColorChip.setBackgroundColor(0);
}
}
| true | true | public void setModel(CalendarEventModel model) {
mModel = model;
// Need to close the autocomplete adapter to prevent leaking cursors.
if (mAddressAdapter != null && mAddressAdapter instanceof EmailAddressAdapter) {
((EmailAddressAdapter)mAddressAdapter).close();
mAddressAdapter = null;
}
if (model == null) {
// Display loading screen
mLoadingMessage.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
return;
}
boolean canModifyCalendar = EditEventHelper.canModifyCalendar(model);
boolean canModifyEvent = EditEventHelper.canModifyEvent(model);
boolean canRespond = EditEventHelper.canRespond(model);
long begin = model.mStart;
long end = model.mEnd;
mTimezone = model.mTimezone; // this will be UTC for all day events
// Set up the starting times
if (begin > 0) {
mStartTime.timezone = mTimezone;
mStartTime.set(begin);
mStartTime.normalize(true);
}
if (end > 0) {
mEndTime.timezone = mTimezone;
mEndTime.set(end);
mEndTime.normalize(true);
}
String rrule = model.mRrule;
if (!TextUtils.isEmpty(rrule)) {
mEventRecurrence.parse(rrule);
}
// If the user is allowed to change the attendees set up the view and
// validator
if (!model.mHasAttendeeData) {
mAttendeesGroup.setVisibility(View.GONE);
}
mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setAllDayViewsVisibility(isChecked);
}
});
if (model.mAllDay) {
mAllDayCheckBox.setChecked(true);
// put things back in local time for all day events
mTimezone = TimeZone.getDefault().getID();
mStartTime.timezone = mTimezone;
mStartTime.normalize(true);
mEndTime.timezone = mTimezone;
mEndTime.normalize(true);
} else {
mAllDayCheckBox.setChecked(false);
}
mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
if (mTimezoneDialog != null) {
mTimezoneDialog.getListView().setAdapter(mTimezoneAdapter);
}
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
String defaultReminderString = prefs.getString(
GeneralPreferences.KEY_DEFAULT_REMINDER, GeneralPreferences.NO_REMINDER_STRING);
mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
prepareReminders();
ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add);
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
addReminder();
}
};
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mTitleTextView.setText(model.mTitle);
if (model.mIsOrganizer || TextUtils.isEmpty(model.mOrganizer)
|| model.mOrganizer.endsWith(GOOGLE_SECONDARY_CALENDAR)) {
mView.findViewById(R.id.organizer_label).setVisibility(View.GONE);
mView.findViewById(R.id.organizer).setVisibility(View.GONE);
mOrganizerGroup.setVisibility(View.GONE);
} else {
((TextView) mView.findViewById(R.id.organizer)).setText(model.mOrganizerDisplayName);
}
mLocationTextView.setText(model.mLocation);
mDescriptionTextView.setText(model.mDescription);
mAvailabilitySpinner.setSelection(model.mAvailability ? 1 : 0);
mAccessLevelSpinner.setSelection(model.mAccessLevel);
View responseLabel = mView.findViewById(R.id.response_label);
if (canRespond) {
int buttonToCheck = EventInfoFragment
.findButtonIdForResponse(model.mSelfAttendeeStatus);
mResponseRadioGroup.check(buttonToCheck); // -1 clear all radio buttons
mResponseRadioGroup.setVisibility(View.VISIBLE);
responseLabel.setVisibility(View.VISIBLE);
} else {
responseLabel.setVisibility(View.GONE);
mResponseRadioGroup.setVisibility(View.GONE);
}
int displayColor = Utils.getDisplayColorFromColor(model.mCalendarColor);
if (model.mUri != null) {
// This is an existing event so hide the calendar spinner
// since we can't change the calendar.
View calendarGroup = mView.findViewById(R.id.calendar_selector_group);
calendarGroup.setVisibility(View.GONE);
TextView tv = (TextView) mView.findViewById(R.id.calendar_textview);
tv.setText(model.mCalendarDisplayName);
tv.setBackgroundColor(displayColor);
mColorChip.setBackgroundColor(displayColor);
} else {
View calendarGroup = mView.findViewById(R.id.calendar_group);
calendarGroup.setVisibility(View.GONE);
mCalendarsSpinner.setBackgroundColor(displayColor);
mCalendarSelectorGroup.setBackgroundColor(displayColor);
}
populateTimezone();
populateWhen();
populateRepeats();
updateAttendees(model.mAttendeesList);
updateView();
mScrollView.setVisibility(View.VISIBLE);
mLoadingMessage.setVisibility(View.GONE);
sendAccessibilityEvent();
}
| public void setModel(CalendarEventModel model) {
mModel = model;
// Need to close the autocomplete adapter to prevent leaking cursors.
if (mAddressAdapter != null && mAddressAdapter instanceof EmailAddressAdapter) {
((EmailAddressAdapter)mAddressAdapter).close();
mAddressAdapter = null;
}
if (model == null) {
// Display loading screen
mLoadingMessage.setVisibility(View.VISIBLE);
mScrollView.setVisibility(View.GONE);
return;
}
boolean canModifyCalendar = EditEventHelper.canModifyCalendar(model);
boolean canModifyEvent = EditEventHelper.canModifyEvent(model);
boolean canRespond = EditEventHelper.canRespond(model);
long begin = model.mStart;
long end = model.mEnd;
mTimezone = model.mTimezone; // this will be UTC for all day events
// Set up the starting times
if (begin > 0) {
mStartTime.timezone = mTimezone;
mStartTime.set(begin);
mStartTime.normalize(true);
}
if (end > 0) {
mEndTime.timezone = mTimezone;
mEndTime.set(end);
mEndTime.normalize(true);
}
String rrule = model.mRrule;
if (!TextUtils.isEmpty(rrule)) {
mEventRecurrence.parse(rrule);
}
// If the user is allowed to change the attendees set up the view and
// validator
if (!model.mHasAttendeeData) {
mAttendeesGroup.setVisibility(View.GONE);
}
mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setAllDayViewsVisibility(isChecked);
}
});
if (model.mAllDay) {
mAllDayCheckBox.setChecked(true);
// put things back in local time for all day events
mTimezone = TimeZone.getDefault().getID();
mStartTime.timezone = mTimezone;
mStartTime.normalize(true);
mEndTime.timezone = mTimezone;
mEndTime.normalize(true);
} else {
mAllDayCheckBox.setChecked(false);
}
mTimezoneAdapter = new TimezoneAdapter(mActivity, mTimezone);
if (mTimezoneDialog != null) {
mTimezoneDialog.getListView().setAdapter(mTimezoneAdapter);
}
SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity);
String defaultReminderString = prefs.getString(
GeneralPreferences.KEY_DEFAULT_REMINDER, GeneralPreferences.NO_REMINDER_STRING);
mDefaultReminderMinutes = Integer.parseInt(defaultReminderString);
prepareReminders();
ImageButton reminderAddButton = (ImageButton) mView.findViewById(R.id.reminder_add);
View.OnClickListener addReminderOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
addReminder();
}
};
reminderAddButton.setOnClickListener(addReminderOnClickListener);
mTitleTextView.setText(model.mTitle);
if (model.mIsOrganizer || TextUtils.isEmpty(model.mOrganizer)
|| model.mOrganizer.endsWith(GOOGLE_SECONDARY_CALENDAR)) {
mView.findViewById(R.id.organizer_label).setVisibility(View.GONE);
mView.findViewById(R.id.organizer).setVisibility(View.GONE);
mOrganizerGroup.setVisibility(View.GONE);
} else {
((TextView) mView.findViewById(R.id.organizer)).setText(model.mOrganizerDisplayName);
}
mLocationTextView.setText(model.mLocation);
mDescriptionTextView.setText(model.mDescription);
mAvailabilitySpinner.setSelection(model.mAvailability ? 1 : 0);
mAccessLevelSpinner.setSelection(model.mAccessLevel);
View responseLabel = mView.findViewById(R.id.response_label);
if (canRespond) {
int buttonToCheck = EventInfoFragment
.findButtonIdForResponse(model.mSelfAttendeeStatus);
mResponseRadioGroup.check(buttonToCheck); // -1 clear all radio buttons
mResponseRadioGroup.setVisibility(View.VISIBLE);
responseLabel.setVisibility(View.VISIBLE);
} else {
responseLabel.setVisibility(View.GONE);
mResponseRadioGroup.setVisibility(View.GONE);
mResponseGroup.setVisibility(View.GONE);
}
int displayColor = Utils.getDisplayColorFromColor(model.mCalendarColor);
if (model.mUri != null) {
// This is an existing event so hide the calendar spinner
// since we can't change the calendar.
View calendarGroup = mView.findViewById(R.id.calendar_selector_group);
calendarGroup.setVisibility(View.GONE);
TextView tv = (TextView) mView.findViewById(R.id.calendar_textview);
tv.setText(model.mCalendarDisplayName);
tv.setBackgroundColor(displayColor);
mColorChip.setBackgroundColor(displayColor);
} else {
View calendarGroup = mView.findViewById(R.id.calendar_group);
calendarGroup.setVisibility(View.GONE);
mCalendarsSpinner.setBackgroundColor(displayColor);
mCalendarSelectorGroup.setBackgroundColor(displayColor);
}
populateTimezone();
populateWhen();
populateRepeats();
updateAttendees(model.mAttendeesList);
updateView();
mScrollView.setVisibility(View.VISIBLE);
mLoadingMessage.setVisibility(View.GONE);
sendAccessibilityEvent();
}
|
diff --git a/src/net/azib/ipscan/Main.java b/src/net/azib/ipscan/Main.java
index 55357bd..f54ef4b 100755
--- a/src/net/azib/ipscan/Main.java
+++ b/src/net/azib/ipscan/Main.java
@@ -1,187 +1,187 @@
/**
* This file is a part of Angry IP Scanner source code,
* see http://www.angryip.org/ for more information.
* Licensed under GPLv2.
*/
package net.azib.ipscan;
import net.azib.ipscan.config.*;
import net.azib.ipscan.core.UserErrorException;
import net.azib.ipscan.gui.InfoDialog;
import net.azib.ipscan.gui.MainWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import javax.swing.*;
import java.security.Security;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The main executable class.
* It initializes all the needed stuff and launches the user interface.
* <p/>
* All Exceptions, which are thrown out of the program, are caught and logged
* using the java.util.logging facilities.
*
* @see #main(String...)
* @author Anton Keks
*/
public class Main {
static final Logger LOG = LoggerFactory.getLogger();
/**
* The launching point
* <p/>
* In development, pass the following on the JVM command line:
* <tt>-Djava.util.logging.config.file=config/logging.properties</tt>
* <p/>
* On Mac, add the following (otherwise SWT won't work):
* <tt>-XstartOnFirstThread</tt>
*/
public static void main(String... args) {
try {
long startTime = System.currentTimeMillis();
initSystemProperties();
// this defines the Window class and app name on the Mac
Display.setAppName(Version.NAME);
Display display = Display.getDefault();
LOG.finer("SWT initialized after " + (System.currentTimeMillis() - startTime));
// initialize Labels instance
Labels.initialize(Locale.getDefault());
// initialize Config instance
Config globalConfig = Config.getConfig();
LOG.finer("Labels and Config initialized after " + (System.currentTimeMillis() - startTime));
ComponentRegistry componentRegistry = new ComponentRegistry();
LOG.finer("ComponentRegistry initialized after " + (System.currentTimeMillis() - startTime));
processCommandLine(args, componentRegistry);
// create the main window using dependency injection
MainWindow mainWindow = componentRegistry.getMainWindow();
LOG.fine("Startup time: " + (System.currentTimeMillis() - startTime));
while (!mainWindow.isDisposed()) {
try {
if (!display.readAndDispatch())
display.sleep();
}
catch (Throwable e) {
if (e instanceof SWTException && e.getCause() != null)
e = e.getCause();
// display a nice error message
String localizedMessage = getLocalizedMessage(e);
Shell parent = display.getActiveShell();
showMessage(parent != null ? parent : mainWindow.getShell(),
e instanceof UserErrorException ? SWT.ICON_WARNING : SWT.ICON_ERROR,
Labels.getLabel(e instanceof UserErrorException ? "text.userError" : "text.error"), localizedMessage);
}
}
// save config on exit
globalConfig.store();
// dispose the native objects
display.dispose();
}
catch (UnsatisfiedLinkError e) {
- JOptionPane.showMessageDialog(null, "Failed to load native code. Probably you are using a binary built for wrong OS or CPU - try downloading both 32-bit and 64-bit binaries");
+ JOptionPane.showMessageDialog(null, "Failed to load native code. Probably you are using a binary built for wrong OS or CPU. If 64-bit binary doesn't work for you, try 32-bit version, or vice versa.");
}
catch (Throwable e) {
JOptionPane.showMessageDialog(null, e + "\nPlease submit a bug report mentioning your OS and what were you doing.");
e.printStackTrace();
}
}
private static void showMessage(Shell parent, int flags, String title, String localizedMessage) {
MessageBox messageBox = new MessageBox(parent, SWT.OK | flags);
messageBox.setText(title);
messageBox.setMessage(localizedMessage);
messageBox.open();
}
private static void initSystemProperties() {
// currently we support IPv4 only
System.setProperty("java.net.preferIPv4Stack", "true");
// disable DNS caches
Security.setProperty("networkaddress.cache.ttl", "0");
Security.setProperty("networkaddress.cache.negative.ttl", "0");
}
private static void processCommandLine(String[] args, ComponentRegistry componentRegistry) {
if (args.length != 0) {
CommandLineProcessor cli = componentRegistry.getCommandLineProcessor();
try {
cli.parse(args);
}
catch (Exception e) {
showMessageToConsole(e.getMessage() + "\n\n" + cli);
System.exit(1);
}
}
}
/**
* @param usageText
*/
private static void showMessageToConsole(String usageText) {
// use console for all platforms except Windows by default
boolean haveConsole = !Platform.WINDOWS;
try {
// determine if we have console attached using Java 6 System.console()
haveConsole = System.class.getMethod("console").invoke(null) != null;
}
catch (Exception e) {
// Java 5 will reach here
}
if (haveConsole) {
System.err.println(usageText);
}
else {
InfoDialog dialog = new InfoDialog(Version.NAME, Labels.getLabel("title.commandline"));
dialog.setMessage(usageText);
dialog.open();
}
}
/**
* Returns a nice localized message for the passed exception
* in case it is possible, or toString() otherwise.
*/
static String getLocalizedMessage(Throwable e) {
String localizedMessage;
try {
// try to load localized message
if (e instanceof UserErrorException) {
localizedMessage = e.getMessage();
}
else {
String exceptionClassName = e.getClass().getSimpleName();
String originalMessage = e.getMessage();
localizedMessage = Labels.getLabel("exception." + exceptionClassName + (originalMessage != null ? "." + originalMessage : ""));
}
// add cause summary, if it exists
if (e.getCause() != null) {
localizedMessage += "\n\n" + e.getCause().toString();
}
LOG.log(Level.FINE, "error", e);
}
catch (Exception e2) {
// fallback to default text
localizedMessage = e.toString();
// output stack trace to the console
LOG.log(Level.SEVERE, "unexpected error", e);
}
return localizedMessage;
}
}
| true | true | public static void main(String... args) {
try {
long startTime = System.currentTimeMillis();
initSystemProperties();
// this defines the Window class and app name on the Mac
Display.setAppName(Version.NAME);
Display display = Display.getDefault();
LOG.finer("SWT initialized after " + (System.currentTimeMillis() - startTime));
// initialize Labels instance
Labels.initialize(Locale.getDefault());
// initialize Config instance
Config globalConfig = Config.getConfig();
LOG.finer("Labels and Config initialized after " + (System.currentTimeMillis() - startTime));
ComponentRegistry componentRegistry = new ComponentRegistry();
LOG.finer("ComponentRegistry initialized after " + (System.currentTimeMillis() - startTime));
processCommandLine(args, componentRegistry);
// create the main window using dependency injection
MainWindow mainWindow = componentRegistry.getMainWindow();
LOG.fine("Startup time: " + (System.currentTimeMillis() - startTime));
while (!mainWindow.isDisposed()) {
try {
if (!display.readAndDispatch())
display.sleep();
}
catch (Throwable e) {
if (e instanceof SWTException && e.getCause() != null)
e = e.getCause();
// display a nice error message
String localizedMessage = getLocalizedMessage(e);
Shell parent = display.getActiveShell();
showMessage(parent != null ? parent : mainWindow.getShell(),
e instanceof UserErrorException ? SWT.ICON_WARNING : SWT.ICON_ERROR,
Labels.getLabel(e instanceof UserErrorException ? "text.userError" : "text.error"), localizedMessage);
}
}
// save config on exit
globalConfig.store();
// dispose the native objects
display.dispose();
}
catch (UnsatisfiedLinkError e) {
JOptionPane.showMessageDialog(null, "Failed to load native code. Probably you are using a binary built for wrong OS or CPU - try downloading both 32-bit and 64-bit binaries");
}
catch (Throwable e) {
JOptionPane.showMessageDialog(null, e + "\nPlease submit a bug report mentioning your OS and what were you doing.");
e.printStackTrace();
}
}
| public static void main(String... args) {
try {
long startTime = System.currentTimeMillis();
initSystemProperties();
// this defines the Window class and app name on the Mac
Display.setAppName(Version.NAME);
Display display = Display.getDefault();
LOG.finer("SWT initialized after " + (System.currentTimeMillis() - startTime));
// initialize Labels instance
Labels.initialize(Locale.getDefault());
// initialize Config instance
Config globalConfig = Config.getConfig();
LOG.finer("Labels and Config initialized after " + (System.currentTimeMillis() - startTime));
ComponentRegistry componentRegistry = new ComponentRegistry();
LOG.finer("ComponentRegistry initialized after " + (System.currentTimeMillis() - startTime));
processCommandLine(args, componentRegistry);
// create the main window using dependency injection
MainWindow mainWindow = componentRegistry.getMainWindow();
LOG.fine("Startup time: " + (System.currentTimeMillis() - startTime));
while (!mainWindow.isDisposed()) {
try {
if (!display.readAndDispatch())
display.sleep();
}
catch (Throwable e) {
if (e instanceof SWTException && e.getCause() != null)
e = e.getCause();
// display a nice error message
String localizedMessage = getLocalizedMessage(e);
Shell parent = display.getActiveShell();
showMessage(parent != null ? parent : mainWindow.getShell(),
e instanceof UserErrorException ? SWT.ICON_WARNING : SWT.ICON_ERROR,
Labels.getLabel(e instanceof UserErrorException ? "text.userError" : "text.error"), localizedMessage);
}
}
// save config on exit
globalConfig.store();
// dispose the native objects
display.dispose();
}
catch (UnsatisfiedLinkError e) {
JOptionPane.showMessageDialog(null, "Failed to load native code. Probably you are using a binary built for wrong OS or CPU. If 64-bit binary doesn't work for you, try 32-bit version, or vice versa.");
}
catch (Throwable e) {
JOptionPane.showMessageDialog(null, e + "\nPlease submit a bug report mentioning your OS and what were you doing.");
e.printStackTrace();
}
}
|
diff --git a/RadioPlugin/src/io/github/LilParker/RadioPlugin/RadioPluginCommandExecuter.java b/RadioPlugin/src/io/github/LilParker/RadioPlugin/RadioPluginCommandExecuter.java
index 21a8e4f..a520f2d 100644
--- a/RadioPlugin/src/io/github/LilParker/RadioPlugin/RadioPluginCommandExecuter.java
+++ b/RadioPlugin/src/io/github/LilParker/RadioPlugin/RadioPluginCommandExecuter.java
@@ -1,158 +1,160 @@
package io.github.LilParker.RadioPlugin;
import java.util.HashMap;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
public class RadioPluginCommandExecuter implements CommandExecutor {
RadioPlugin plugin;
public HashMap<String, Float> playerFreqs = new HashMap<String, Float>();
public HashMap<String, String> eKey = new HashMap<String, String>();
private String[] alphanumeric = new String[]{"a","b","c","d","e","f","g","h","i","k","j","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public RadioPluginCommandExecuter (RadioPlugin actPlugin) {
plugin = actPlugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("setfreq")){
if(sender instanceof Player){
if(args.length == 1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(testParse(args[0])){
playerFreqs.put(sender.getName(), Float.parseFloat(args[0]));
sender.sendMessage("Your frequency is now " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Invalid frequency");
return false;
}
}else{
sender.sendMessage("You must have a radio in hand to tune it");
return true;
}
}else{
sender.sendMessage("Need 1 argument");
return false;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if(cmd.getName().equalsIgnoreCase("getfreq")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
sender.sendMessage("Your current frequency is " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to check it's frequency");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if (cmd.getName().equalsIgnoreCase("setEKey")){
if (sender instanceof Player){
if (args.length==1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(args[0].equals("clear") == false){
eKey.put(sender.getName(), (args[0]));
sender.sendMessage("Your encryption key is now " + eKey.get(sender.getName()));
return true;
}else{
eKey.put(sender.getName(), null);
sender.sendMessage("Your encription key has been cleared");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to do this!");
return true;
}
}else{
sender.sendMessage("Need 1 argument!");
return false;
}
}else{
sender.sendMessage("You must be a player to use this command");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("radio")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
- String message = plugin.getConfig().getString("radiocolor") + "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
+ String message = "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(String messagePart : args){
message = message + " " + messagePart;
}
Player[] playerList = Bukkit.getOnlinePlayers();
for(Player player : playerList){
if(playerFreqs.get(player.getName()) != null && player.getInventory().contains(plugin.getConfig().getInt("radioitemid"))){
float playerFreq = playerFreqs.get(player.getName());
String enKey = eKey.get(player.getName());
if(playerFreq == playerFreqs.get(sender.getName())){
if(eKey.get(sender.getName()) != null){
if(enKey != null && enKey.equals(eKey.get(sender.getName()))){
+ message = plugin.getConfig().getString("radioencryptedcolor") + message;
player.sendMessage(message);
}else if(enKey != eKey.get(sender.getName())){
Random randGen = new Random();
String msg = "";
for(String messagePart : args){
msg = msg + " " + messagePart;
}
String scrambledMessage = plugin.getConfig().getString("radioencryptedcolor") + "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(char ch : msg.toCharArray()){
if(ch != ' '){
int randInt = randGen.nextInt(alphanumeric.length);
String str = alphanumeric[randInt];
scrambledMessage = scrambledMessage + str;
}else{
scrambledMessage = scrambledMessage + " ";
}
}
player.sendMessage(scrambledMessage);
}
}else{
+ message = plugin.getConfig().getString("radiocolor") + message;
player.sendMessage(message);
}
}
}
}
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to use it");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
return false;
}
private boolean testParse (String str) {
try{
Float.parseFloat(str);
return true;
}catch(NumberFormatException nfe){
return false;
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("setfreq")){
if(sender instanceof Player){
if(args.length == 1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(testParse(args[0])){
playerFreqs.put(sender.getName(), Float.parseFloat(args[0]));
sender.sendMessage("Your frequency is now " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Invalid frequency");
return false;
}
}else{
sender.sendMessage("You must have a radio in hand to tune it");
return true;
}
}else{
sender.sendMessage("Need 1 argument");
return false;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if(cmd.getName().equalsIgnoreCase("getfreq")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
sender.sendMessage("Your current frequency is " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to check it's frequency");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if (cmd.getName().equalsIgnoreCase("setEKey")){
if (sender instanceof Player){
if (args.length==1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(args[0].equals("clear") == false){
eKey.put(sender.getName(), (args[0]));
sender.sendMessage("Your encryption key is now " + eKey.get(sender.getName()));
return true;
}else{
eKey.put(sender.getName(), null);
sender.sendMessage("Your encription key has been cleared");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to do this!");
return true;
}
}else{
sender.sendMessage("Need 1 argument!");
return false;
}
}else{
sender.sendMessage("You must be a player to use this command");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("radio")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
String message = plugin.getConfig().getString("radiocolor") + "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(String messagePart : args){
message = message + " " + messagePart;
}
Player[] playerList = Bukkit.getOnlinePlayers();
for(Player player : playerList){
if(playerFreqs.get(player.getName()) != null && player.getInventory().contains(plugin.getConfig().getInt("radioitemid"))){
float playerFreq = playerFreqs.get(player.getName());
String enKey = eKey.get(player.getName());
if(playerFreq == playerFreqs.get(sender.getName())){
if(eKey.get(sender.getName()) != null){
if(enKey != null && enKey.equals(eKey.get(sender.getName()))){
player.sendMessage(message);
}else if(enKey != eKey.get(sender.getName())){
Random randGen = new Random();
String msg = "";
for(String messagePart : args){
msg = msg + " " + messagePart;
}
String scrambledMessage = plugin.getConfig().getString("radioencryptedcolor") + "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(char ch : msg.toCharArray()){
if(ch != ' '){
int randInt = randGen.nextInt(alphanumeric.length);
String str = alphanumeric[randInt];
scrambledMessage = scrambledMessage + str;
}else{
scrambledMessage = scrambledMessage + " ";
}
}
player.sendMessage(scrambledMessage);
}
}else{
player.sendMessage(message);
}
}
}
}
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to use it");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("setfreq")){
if(sender instanceof Player){
if(args.length == 1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(testParse(args[0])){
playerFreqs.put(sender.getName(), Float.parseFloat(args[0]));
sender.sendMessage("Your frequency is now " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Invalid frequency");
return false;
}
}else{
sender.sendMessage("You must have a radio in hand to tune it");
return true;
}
}else{
sender.sendMessage("Need 1 argument");
return false;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if(cmd.getName().equalsIgnoreCase("getfreq")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
sender.sendMessage("Your current frequency is " + playerFreqs.get(sender.getName()));
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to check it's frequency");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
if (cmd.getName().equalsIgnoreCase("setEKey")){
if (sender instanceof Player){
if (args.length==1){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(args[0].equals("clear") == false){
eKey.put(sender.getName(), (args[0]));
sender.sendMessage("Your encryption key is now " + eKey.get(sender.getName()));
return true;
}else{
eKey.put(sender.getName(), null);
sender.sendMessage("Your encription key has been cleared");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to do this!");
return true;
}
}else{
sender.sendMessage("Need 1 argument!");
return false;
}
}else{
sender.sendMessage("You must be a player to use this command");
return true;
}
}
if(cmd.getName().equalsIgnoreCase("radio")){
if(sender instanceof Player){
if(((Player) sender).getItemInHand().getTypeId() == plugin.getConfig().getInt("radioitemid")){
if(playerFreqs.get(sender.getName()) != null){
String message = "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(String messagePart : args){
message = message + " " + messagePart;
}
Player[] playerList = Bukkit.getOnlinePlayers();
for(Player player : playerList){
if(playerFreqs.get(player.getName()) != null && player.getInventory().contains(plugin.getConfig().getInt("radioitemid"))){
float playerFreq = playerFreqs.get(player.getName());
String enKey = eKey.get(player.getName());
if(playerFreq == playerFreqs.get(sender.getName())){
if(eKey.get(sender.getName()) != null){
if(enKey != null && enKey.equals(eKey.get(sender.getName()))){
message = plugin.getConfig().getString("radioencryptedcolor") + message;
player.sendMessage(message);
}else if(enKey != eKey.get(sender.getName())){
Random randGen = new Random();
String msg = "";
for(String messagePart : args){
msg = msg + " " + messagePart;
}
String scrambledMessage = plugin.getConfig().getString("radioencryptedcolor") + "[FREQ: " + playerFreqs.get(sender.getName()) + "] " + sender.getName() + ": ";
for(char ch : msg.toCharArray()){
if(ch != ' '){
int randInt = randGen.nextInt(alphanumeric.length);
String str = alphanumeric[randInt];
scrambledMessage = scrambledMessage + str;
}else{
scrambledMessage = scrambledMessage + " ";
}
}
player.sendMessage(scrambledMessage);
}
}else{
message = plugin.getConfig().getString("radiocolor") + message;
player.sendMessage(message);
}
}
}
}
return true;
}else{
sender.sendMessage("Your radio isn't tuned to a frequency");
return true;
}
}else{
sender.sendMessage("You must have a radio in your hand to use it");
return true;
}
}else{
sender.sendMessage("You must be a player");
return false;
}
}
return false;
}
|
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/varianteval/IndelStatistics.java b/java/src/org/broadinstitute/sting/gatk/walkers/varianteval/IndelStatistics.java
index 34f0732da..12142bf96 100755
--- a/java/src/org/broadinstitute/sting/gatk/walkers/varianteval/IndelStatistics.java
+++ b/java/src/org/broadinstitute/sting/gatk/walkers/varianteval/IndelStatistics.java
@@ -1,485 +1,485 @@
package org.broadinstitute.sting.gatk.walkers.varianteval;
import org.broad.tribble.util.variantcontext.Genotype;
import org.broad.tribble.util.variantcontext.VariantContext;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.report.tags.Analysis;
import org.broadinstitute.sting.utils.report.tags.DataPoint;
import org.broadinstitute.sting.utils.report.utils.TableType;
import java.util.Arrays;
import java.util.HashMap;
/*
* Copyright (c) 2010 The Broad Institute
*
* 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.
*/
@Analysis(name = "IndelStatistics", description = "Shows various indel metrics and statistics")
public class IndelStatistics extends VariantEvaluator {
@DataPoint(name="IndelStatistics", description = "Indel Statistics")
IndelStats indelStats = null;
@DataPoint(name="IndelClasses", description = "Indel Classification")
IndelClasses indelClasses = null;
private static final int INDEL_SIZE_LIMIT = 100;
private static final int NUM_SCALAR_COLUMNS = 10;
static int len2Index(int ind) {
return ind+INDEL_SIZE_LIMIT+NUM_SCALAR_COLUMNS;
}
static int index2len(int ind) {
return ind-INDEL_SIZE_LIMIT-NUM_SCALAR_COLUMNS;
}
static class IndelStats implements TableType {
protected final static String ALL_SAMPLES_KEY = "allSamples";
protected final static String[] COLUMN_KEYS;
static {
COLUMN_KEYS= new String[NUM_SCALAR_COLUMNS+2*INDEL_SIZE_LIMIT+1];
COLUMN_KEYS[0] = "heterozygosity";
COLUMN_KEYS[1] = "number_of_insertions";
COLUMN_KEYS[2] = "number_of_deletions";
COLUMN_KEYS[3] = "number_het_insertions";
COLUMN_KEYS[4] = "number_homozygous_insertions";
COLUMN_KEYS[5] = "number_het_deletions";
COLUMN_KEYS[6] = "number_homozygous_deletions";
COLUMN_KEYS[7] = "number of homozygous reference sites";
COLUMN_KEYS[8] = "number of complex events";
COLUMN_KEYS[9] = "number of long indels";
for (int k=NUM_SCALAR_COLUMNS; k < NUM_SCALAR_COLUMNS+ 2*INDEL_SIZE_LIMIT+1; k++)
COLUMN_KEYS[k] = "indel_size_len"+Integer.valueOf(index2len(k));
}
// map of sample to statistics
protected final HashMap<String, double[]> indelSummary = new HashMap<String, double[]>();
public IndelStats(final VariantContext vc) {
indelSummary.put(ALL_SAMPLES_KEY, new double[COLUMN_KEYS.length]);
for( final String sample : vc.getGenotypes().keySet() ) {
indelSummary.put(sample, new double[COLUMN_KEYS.length]);
}
}
/**
*
* @return one row per sample
*/
public Object[] getRowKeys() {
return indelSummary.keySet().toArray(new String[indelSummary.size()]);
}
public Object getCell(int x, int y) {
final Object[] rowKeys = getRowKeys();
return String.format("%4.2f",indelSummary.get(rowKeys[x])[y]);
}
/**
* get the column keys
* @return a list of objects, in this case strings, that are the column names
*/
public Object[] getColumnKeys() {
return COLUMN_KEYS;
}
public String getName() {
return "IndelStats";
}
public int getComparisonOrder() {
return 1; // we only need to see each eval track
}
public String toString() {
return getName();
}
/*
* increment the specified value
*/
public void incrValue(VariantContext vc) {
int eventLength = 0;
boolean isInsertion = false, isDeletion = false;
if ( vc.isInsertion() ) {
eventLength = vc.getAlternateAllele(0).length();
indelSummary.get(ALL_SAMPLES_KEY)[1]++;
isInsertion = true;
} else if ( vc.isDeletion() ) {
indelSummary.get(ALL_SAMPLES_KEY)[2]++;
eventLength = -vc.getReference().length();
isDeletion = true;
}
else {
indelSummary.get(ALL_SAMPLES_KEY)[8]++;
}
// make sure event doesn't overstep array boundaries
if (Math.abs(eventLength) < INDEL_SIZE_LIMIT)
indelSummary.get(ALL_SAMPLES_KEY)[len2Index(eventLength)]++;
else
indelSummary.get(ALL_SAMPLES_KEY)[9]++;
for( final String sample : vc.getGenotypes().keySet() ) {
if ( indelSummary.containsKey(sample) ) {
Genotype g = vc.getGenotype(sample);
boolean isVariant = (g.isCalled() && !g.isHomRef());
if (isVariant) {
// update ins/del count
if (isInsertion) {
indelSummary.get(sample)[1]++;
}
else if (isDeletion)
indelSummary.get(sample)[2]++;
else
indelSummary.get(sample)[8]++;
// update histogram
if (Math.abs(eventLength) < INDEL_SIZE_LIMIT)
indelSummary.get(sample)[len2Index(eventLength)]++;
else
indelSummary.get(sample)[9]++;
if (g.isHet())
if (isInsertion)
indelSummary.get(sample)[3]++;
else
indelSummary.get(sample)[5]++;
else
if (isInsertion)
indelSummary.get(sample)[4]++;
else
indelSummary.get(sample)[6]++;
}
else
indelSummary.get(sample)[7]++;
}
}
}
}
static class IndelClasses implements TableType {
protected final static String ALL_SAMPLES_KEY = "allSamples";
protected final static String[] COLUMN_KEYS;
static {
COLUMN_KEYS= new String[41];
COLUMN_KEYS[0] = "Novel_A";
COLUMN_KEYS[1] = "Novel_C";
COLUMN_KEYS[2] = "Novel_G";
COLUMN_KEYS[3] = "Novel_T";
COLUMN_KEYS[4] = "NOVEL_1";
COLUMN_KEYS[5] = "NOVEL_2";
COLUMN_KEYS[6] = "NOVEL_3";
COLUMN_KEYS[7] = "NOVEL_4";
COLUMN_KEYS[8] = "NOVEL_5";
COLUMN_KEYS[9] = "NOVEL_6";
COLUMN_KEYS[10] = "NOVEL_7";
COLUMN_KEYS[11] = "NOVEL_8";
COLUMN_KEYS[12] = "NOVEL_9";
COLUMN_KEYS[13] = "NOVEL_10orMore";
COLUMN_KEYS[14] = "RepeatExpansion_A";
COLUMN_KEYS[15] = "RepeatExpansion_C";
COLUMN_KEYS[16] = "RepeatExpansion_G";
COLUMN_KEYS[17] = "RepeatExpansion_T";
COLUMN_KEYS[18] = "RepeatExpansion_AC";
COLUMN_KEYS[19] = "RepeatExpansion_AG";
COLUMN_KEYS[20] = "RepeatExpansion_AT";
COLUMN_KEYS[21] = "RepeatExpansion_CA";
COLUMN_KEYS[22] = "RepeatExpansion_CG";
COLUMN_KEYS[23] = "RepeatExpansion_CT";
COLUMN_KEYS[24] = "RepeatExpansion_GA";
COLUMN_KEYS[25] = "RepeatExpansion_GC";
COLUMN_KEYS[26] = "RepeatExpansion_GT";
COLUMN_KEYS[27] = "RepeatExpansion_TA";
COLUMN_KEYS[28] = "RepeatExpansion_TC";
COLUMN_KEYS[29] = "RepeatExpansion_TG";
COLUMN_KEYS[30] = "RepeatExpansion_1";
COLUMN_KEYS[31] = "RepeatExpansion_2";
COLUMN_KEYS[32] = "RepeatExpansion_3";
COLUMN_KEYS[33] = "RepeatExpansion_4";
COLUMN_KEYS[34] = "RepeatExpansion_5";
COLUMN_KEYS[35] = "RepeatExpansion_6";
COLUMN_KEYS[36] = "RepeatExpansion_7";
COLUMN_KEYS[37] = "RepeatExpansion_8";
COLUMN_KEYS[38] = "RepeatExpansion_9";
COLUMN_KEYS[39] = "RepeatExpansion_10orMore";
COLUMN_KEYS[40] = "Other";
}
private static final int START_IND_NOVEL = 4;
private static final int STOP_IND_NOVEL = 13;
private static final int START_IND_FOR_REPEAT_EXPANSION_1 = 14;
private static final int STOP_IND_FOR_REPEAT_EXPANSION_2 = 29;
private static final int START_IND_FOR_REPEAT_EXPANSION_COUNTS = 30;
private static final int STOP_IND_FOR_REPEAT_EXPANSION_COUNTS = 39;
private static final int IND_FOR_OTHER_EVENT = 40;
private static final int START_IND_NOVEL_PER_BASE = 0;
private static final int STOP_IND_NOVEL_PER_BASE = 3;
// map of sample to statistics
protected final HashMap<String, int[]> indelClassSummary = new HashMap<String, int[]>();
public IndelClasses(final VariantContext vc) {
indelClassSummary.put(ALL_SAMPLES_KEY, new int[COLUMN_KEYS.length]);
for( final String sample : vc.getGenotypes().keySet() ) {
indelClassSummary.put(sample, new int[COLUMN_KEYS.length]);
}
}
/**
*
* @return one row per sample
*/
public Object[] getRowKeys() {
return indelClassSummary.keySet().toArray(new String[indelClassSummary.size()]);
}
public Object getCell(int x, int y) {
final Object[] rowKeys = getRowKeys();
return String.format("%d",indelClassSummary.get(rowKeys[x])[y]);
}
/**
* get the column keys
* @return a list of objects, in this case strings, that are the column names
*/
public Object[] getColumnKeys() {
return COLUMN_KEYS;
}
public String getName() {
return "IndelClasses";
}
public int getComparisonOrder() {
return 1; // we only need to see each eval track
}
public String toString() {
return getName();
}
private void incrementSampleStat(VariantContext vc, int index) {
indelClassSummary.get(ALL_SAMPLES_KEY)[index]++;
for( final String sample : vc.getGenotypes().keySet() ) {
if ( indelClassSummary.containsKey(sample) ) {
Genotype g = vc.getGenotype(sample);
boolean isVariant = (g.isCalled() && !g.isHomRef());
if (isVariant)
// update count
indelClassSummary.get(sample)[index]++;
}
}
}
/*
* increment the specified value
*/
public void incrValue(VariantContext vc, ReferenceContext ref) {
int eventLength = 0;
boolean isInsertion = false, isDeletion = false;
String indelAlleleString;
if ( vc.isInsertion() ) {
eventLength = vc.getAlternateAllele(0).length();
isInsertion = true;
indelAlleleString = vc.getAlternateAllele(0).getDisplayString();
} else if ( vc.isDeletion() ) {
eventLength = vc.getReference().length();
isDeletion = true;
indelAlleleString = vc.getReference().getDisplayString();
}
else {
incrementSampleStat(vc, IND_FOR_OTHER_EVENT);
return;
}
byte[] refBases = ref.getBases();
// See first if indel is a repetition of bases before current
- int indStart = refBases.length/2-eventLength;
+ int indStart = refBases.length/2-eventLength+1;
boolean done = false;
int numRepetitions = 0;
while (!done) {
if (indStart < 0)
done = true;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart - eventLength;
}
else
done = true;
}
}
// now do it forward
done = false;
- indStart = refBases.length/2;
+ indStart = refBases.length/2+1;
while (!done) {
if (indStart + eventLength >= refBases.length)
break;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart + eventLength;
}
else
done = true;
}
}
if (numRepetitions == 0) {
//unrepeated sequence from surroundings
int ind = START_IND_NOVEL + (eventLength-1);
if (ind > STOP_IND_NOVEL)
ind = STOP_IND_NOVEL;
incrementSampleStat(vc, ind);
if (eventLength == 1) {
// log single base indels additionally by base
String keyStr = "Novel_" + indelAlleleString;
int k;
for (k=START_IND_NOVEL_PER_BASE; k <= STOP_IND_NOVEL_PER_BASE; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
else {
int ind = START_IND_FOR_REPEAT_EXPANSION_COUNTS + (numRepetitions-1);
if (ind > STOP_IND_FOR_REPEAT_EXPANSION_COUNTS)
ind = STOP_IND_FOR_REPEAT_EXPANSION_COUNTS;
incrementSampleStat(vc, ind);
if (eventLength<=2) {
// for single or dinucleotide indels, we further log the base in which they occurred
String keyStr = "RepeatExpansion_" + indelAlleleString;
int k;
for (k=START_IND_FOR_REPEAT_EXPANSION_1; k <= STOP_IND_FOR_REPEAT_EXPANSION_2; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
//g+
/*
System.out.format("RefBefore: %s\n",new String(refBefore));
System.out.format("RefAfter: %s\n",new String(refAfter));
System.out.format("Indel Allele: %s\n", indelAlleleString);
System.out.format("Num Repetitions: %d\n", numRepetitions);
*/
}
}
public IndelStatistics(VariantEvalWalker parent) {
super(parent);
// don't do anything
}
public String getName() {
return "IndelStatistics";
}
public int getComparisonOrder() {
return 1; // we only need to see each eval track
}
public boolean enabled() {
return true;
}
public String toString() {
return getName();
}
public String update2(VariantContext eval, VariantContext validation, RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context, VariantEvalWalker.EvaluationContext group) {
return null;
}
public String update1(VariantContext eval, RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
if (eval != null ) {
if ( indelStats == null ) {
int nSamples = this.getVEWalker().getNSamplesForEval(eval);
if ( nSamples != -1 )
indelStats = new IndelStats(eval);
}
if ( indelClasses == null ) {
indelClasses = new IndelClasses(eval);
}
if ( eval.isIndel() && eval.isBiallelic() ) {
if (indelStats != null )
indelStats.incrValue(eval);
if (indelClasses != null)
indelClasses.incrValue(eval, ref);
}
}
return null; // This module doesn't capture any interesting sites, so return null
}
public String update0(VariantContext eval, RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
return null;
}
public void finalizeEvaluation() {
//
int k=0;
}
}
| false | true | public void incrValue(VariantContext vc, ReferenceContext ref) {
int eventLength = 0;
boolean isInsertion = false, isDeletion = false;
String indelAlleleString;
if ( vc.isInsertion() ) {
eventLength = vc.getAlternateAllele(0).length();
isInsertion = true;
indelAlleleString = vc.getAlternateAllele(0).getDisplayString();
} else if ( vc.isDeletion() ) {
eventLength = vc.getReference().length();
isDeletion = true;
indelAlleleString = vc.getReference().getDisplayString();
}
else {
incrementSampleStat(vc, IND_FOR_OTHER_EVENT);
return;
}
byte[] refBases = ref.getBases();
// See first if indel is a repetition of bases before current
int indStart = refBases.length/2-eventLength;
boolean done = false;
int numRepetitions = 0;
while (!done) {
if (indStart < 0)
done = true;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart - eventLength;
}
else
done = true;
}
}
// now do it forward
done = false;
indStart = refBases.length/2;
while (!done) {
if (indStart + eventLength >= refBases.length)
break;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart + eventLength;
}
else
done = true;
}
}
if (numRepetitions == 0) {
//unrepeated sequence from surroundings
int ind = START_IND_NOVEL + (eventLength-1);
if (ind > STOP_IND_NOVEL)
ind = STOP_IND_NOVEL;
incrementSampleStat(vc, ind);
if (eventLength == 1) {
// log single base indels additionally by base
String keyStr = "Novel_" + indelAlleleString;
int k;
for (k=START_IND_NOVEL_PER_BASE; k <= STOP_IND_NOVEL_PER_BASE; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
else {
int ind = START_IND_FOR_REPEAT_EXPANSION_COUNTS + (numRepetitions-1);
if (ind > STOP_IND_FOR_REPEAT_EXPANSION_COUNTS)
ind = STOP_IND_FOR_REPEAT_EXPANSION_COUNTS;
incrementSampleStat(vc, ind);
if (eventLength<=2) {
// for single or dinucleotide indels, we further log the base in which they occurred
String keyStr = "RepeatExpansion_" + indelAlleleString;
int k;
for (k=START_IND_FOR_REPEAT_EXPANSION_1; k <= STOP_IND_FOR_REPEAT_EXPANSION_2; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
//g+
/*
System.out.format("RefBefore: %s\n",new String(refBefore));
System.out.format("RefAfter: %s\n",new String(refAfter));
System.out.format("Indel Allele: %s\n", indelAlleleString);
System.out.format("Num Repetitions: %d\n", numRepetitions);
*/
}
| public void incrValue(VariantContext vc, ReferenceContext ref) {
int eventLength = 0;
boolean isInsertion = false, isDeletion = false;
String indelAlleleString;
if ( vc.isInsertion() ) {
eventLength = vc.getAlternateAllele(0).length();
isInsertion = true;
indelAlleleString = vc.getAlternateAllele(0).getDisplayString();
} else if ( vc.isDeletion() ) {
eventLength = vc.getReference().length();
isDeletion = true;
indelAlleleString = vc.getReference().getDisplayString();
}
else {
incrementSampleStat(vc, IND_FOR_OTHER_EVENT);
return;
}
byte[] refBases = ref.getBases();
// See first if indel is a repetition of bases before current
int indStart = refBases.length/2-eventLength+1;
boolean done = false;
int numRepetitions = 0;
while (!done) {
if (indStart < 0)
done = true;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart - eventLength;
}
else
done = true;
}
}
// now do it forward
done = false;
indStart = refBases.length/2+1;
while (!done) {
if (indStart + eventLength >= refBases.length)
break;
else {
String refPiece = new String(Arrays.copyOfRange(refBases,indStart,indStart+eventLength));
if (refPiece.matches(indelAlleleString))
{
numRepetitions++;
indStart = indStart + eventLength;
}
else
done = true;
}
}
if (numRepetitions == 0) {
//unrepeated sequence from surroundings
int ind = START_IND_NOVEL + (eventLength-1);
if (ind > STOP_IND_NOVEL)
ind = STOP_IND_NOVEL;
incrementSampleStat(vc, ind);
if (eventLength == 1) {
// log single base indels additionally by base
String keyStr = "Novel_" + indelAlleleString;
int k;
for (k=START_IND_NOVEL_PER_BASE; k <= STOP_IND_NOVEL_PER_BASE; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
else {
int ind = START_IND_FOR_REPEAT_EXPANSION_COUNTS + (numRepetitions-1);
if (ind > STOP_IND_FOR_REPEAT_EXPANSION_COUNTS)
ind = STOP_IND_FOR_REPEAT_EXPANSION_COUNTS;
incrementSampleStat(vc, ind);
if (eventLength<=2) {
// for single or dinucleotide indels, we further log the base in which they occurred
String keyStr = "RepeatExpansion_" + indelAlleleString;
int k;
for (k=START_IND_FOR_REPEAT_EXPANSION_1; k <= STOP_IND_FOR_REPEAT_EXPANSION_2; k++) {
if (keyStr.matches(COLUMN_KEYS[k]))
break;
}
// log now event
incrementSampleStat(vc, k);
}
}
//g+
/*
System.out.format("RefBefore: %s\n",new String(refBefore));
System.out.format("RefAfter: %s\n",new String(refAfter));
System.out.format("Indel Allele: %s\n", indelAlleleString);
System.out.format("Num Repetitions: %d\n", numRepetitions);
*/
}
|
diff --git a/src/netproj/controller/NetworkWatcher.java b/src/netproj/controller/NetworkWatcher.java
index f0de9a1..3a58e7e 100644
--- a/src/netproj/controller/NetworkWatcher.java
+++ b/src/netproj/controller/NetworkWatcher.java
@@ -1,144 +1,144 @@
package netproj.controller;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import netproj.hosts.tcp.FastTcpHost;
import netproj.hosts.tcp.TcpHost;
import netproj.routers.Router;
import netproj.skeleton.Device;
import netproj.skeleton.Link;
/**
* This class records data files corresponding to the buffer occupancy for
* the input and output buffers of every device on the network, as well
* as the throughput for all links between the devices. It is
* created by the {@code SimulatorSpecification}; since each simulation
* uses exactly one {@code SimulatorSpecification}, each simulation should
* only employ one {@code NetworkWatcher}. The data files are dumped to the
* /data/ directory, organized by device addresses. Note that since the
* NetworkWatcher does not manage open file connections to all data files
* during simulation, it instead appends new log information to the end of
* data files for each iteration of logging. As a result, new data is
* appended to the data files; thus, BETWEEN EACH SIMULATION, DATA FILES
* MUST BE CLEARED.
*
*
* @author nathan
*
*/
public class NetworkWatcher extends Thread {
private List<Device> devices;
private List<Router> routers;
private List<Link> links;
private long timeOffset;
private static final Logger logger = Logger.getLogger(NetworkWatcher.class.getCanonicalName());
public NetworkWatcher(List<Device> d, List<Router> r, List<Link> l) {
devices = d;
routers = r;
links = l;
timeOffset = -1;
}
@Override
public void run() {
if (timeOffset == -1)
timeOffset = System.currentTimeMillis();
while (!this.isInterrupted()) {
try {
synchronized (this) {
wait(900);
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "NetworkWatcher was interrupted.", e);
break;
}
// Collect buffer occupancy stats on all hosts
for (Device d : devices) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + d.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + d.getOutputBuffUsed());
o2.close();
if (d instanceof TcpHost) {
TcpHost tmp = (TcpHost)d;
PrintWriter o3 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "window.dat", true));
o3.println((System.currentTimeMillis() - timeOffset) + " " + tmp.getWindowSize());
o3.close();
double rtt = tmp.getRtt();
if (rtt >= 0) {
PrintWriter o4 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "rtt.dat", true));
o4.println((System.currentTimeMillis() - timeOffset) + " " + rtt);
o4.close();
}
}
if (d instanceof FastTcpHost) {
FastTcpHost tmp = (FastTcpHost)d;
long baseRtt = tmp.getBaseRtt();
if (baseRtt < Long.MAX_VALUE) {
PrintWriter o5 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "basertt.dat", true));
o5.println((System.currentTimeMillis() - timeOffset) + " " + baseRtt);
o5.close();
}
}
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect buffer occupancy stats on all routers
for (Router r : routers) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + r.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + r.getOutputBuffUsed());
o2.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect throughput stats on all links
for (Link l : links) {
long timer = l.getLastReset();
long now = System.currentTimeMillis();
long bits = l.resetBitsSent();
if (timer != 0) {
timer = now - timer;
try {
String linkName = l.toString();
linkName = linkName.substring(1, linkName.length() - 1);
PrintWriter o = new PrintWriter(new FileWriter("data/" +
linkName + "flow.dat", true));
- o.println((now - timeOffset) + " " + (bits * timer / 1000));
+ o.println((now - timeOffset) + " " + (bits * 1000 / timer));
o.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
}
}
}
}
| true | true | public void run() {
if (timeOffset == -1)
timeOffset = System.currentTimeMillis();
while (!this.isInterrupted()) {
try {
synchronized (this) {
wait(900);
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "NetworkWatcher was interrupted.", e);
break;
}
// Collect buffer occupancy stats on all hosts
for (Device d : devices) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + d.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + d.getOutputBuffUsed());
o2.close();
if (d instanceof TcpHost) {
TcpHost tmp = (TcpHost)d;
PrintWriter o3 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "window.dat", true));
o3.println((System.currentTimeMillis() - timeOffset) + " " + tmp.getWindowSize());
o3.close();
double rtt = tmp.getRtt();
if (rtt >= 0) {
PrintWriter o4 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "rtt.dat", true));
o4.println((System.currentTimeMillis() - timeOffset) + " " + rtt);
o4.close();
}
}
if (d instanceof FastTcpHost) {
FastTcpHost tmp = (FastTcpHost)d;
long baseRtt = tmp.getBaseRtt();
if (baseRtt < Long.MAX_VALUE) {
PrintWriter o5 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "basertt.dat", true));
o5.println((System.currentTimeMillis() - timeOffset) + " " + baseRtt);
o5.close();
}
}
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect buffer occupancy stats on all routers
for (Router r : routers) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + r.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + r.getOutputBuffUsed());
o2.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect throughput stats on all links
for (Link l : links) {
long timer = l.getLastReset();
long now = System.currentTimeMillis();
long bits = l.resetBitsSent();
if (timer != 0) {
timer = now - timer;
try {
String linkName = l.toString();
linkName = linkName.substring(1, linkName.length() - 1);
PrintWriter o = new PrintWriter(new FileWriter("data/" +
linkName + "flow.dat", true));
o.println((now - timeOffset) + " " + (bits * timer / 1000));
o.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
}
}
}
| public void run() {
if (timeOffset == -1)
timeOffset = System.currentTimeMillis();
while (!this.isInterrupted()) {
try {
synchronized (this) {
wait(900);
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "NetworkWatcher was interrupted.", e);
break;
}
// Collect buffer occupancy stats on all hosts
for (Device d : devices) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + d.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + d.getOutputBuffUsed());
o2.close();
if (d instanceof TcpHost) {
TcpHost tmp = (TcpHost)d;
PrintWriter o3 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "window.dat", true));
o3.println((System.currentTimeMillis() - timeOffset) + " " + tmp.getWindowSize());
o3.close();
double rtt = tmp.getRtt();
if (rtt >= 0) {
PrintWriter o4 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "rtt.dat", true));
o4.println((System.currentTimeMillis() - timeOffset) + " " + rtt);
o4.close();
}
}
if (d instanceof FastTcpHost) {
FastTcpHost tmp = (FastTcpHost)d;
long baseRtt = tmp.getBaseRtt();
if (baseRtt < Long.MAX_VALUE) {
PrintWriter o5 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(d.getAddress()) + "basertt.dat", true));
o5.println((System.currentTimeMillis() - timeOffset) + " " + baseRtt);
o5.close();
}
}
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect buffer occupancy stats on all routers
for (Router r : routers) {
try {
PrintWriter o1 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "inbuf.dat", true));
o1.println((System.currentTimeMillis() - timeOffset) + " " + r.getInputBuffUsed());
o1.close();
PrintWriter o2 = new PrintWriter(new FileWriter("data/" +
Integer.toHexString(r.getAddress()) + "outbuf.dat", true));
o2.println((System.currentTimeMillis() - timeOffset) + " " + r.getOutputBuffUsed());
o2.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
// Collect throughput stats on all links
for (Link l : links) {
long timer = l.getLastReset();
long now = System.currentTimeMillis();
long bits = l.resetBitsSent();
if (timer != 0) {
timer = now - timer;
try {
String linkName = l.toString();
linkName = linkName.substring(1, linkName.length() - 1);
PrintWriter o = new PrintWriter(new FileWriter("data/" +
linkName + "flow.dat", true));
o.println((now - timeOffset) + " " + (bits * 1000 / timer));
o.close();
} catch (Exception e) {
logger.severe("Failed to write to log file\n" + e);
}
}
}
}
}
|
diff --git a/src/java/fedora/common/PID.java b/src/java/fedora/common/PID.java
index 8d9d275f7..4bafe9e85 100755
--- a/src/java/fedora/common/PID.java
+++ b/src/java/fedora/common/PID.java
@@ -1,242 +1,242 @@
package fedora.common;
import java.io.*; // BufferedReader, InputStreamReader
/**
* A persistent identifier for Fedora digital objects.
*
* <p>The following describes the syntactic constraints for PIDs in normalized
* form. The only differences with non-normalized PIDs are that the
* colon delimiter may be encoded as "%3a" or "%3A", and hex-digits may
* use lowercase [a-f].</p>
*
* <pre>
* PID:
* Length : maximum 64
* Syntax : namespace-id ":" object-id
*
* namespace-id:
* Syntax : ( [A-Z] / [a-z] / [0-9] / "-" / "." ) 1+
*
* object-id:
* Syntax : ( [A-Z] / [a-z] / [0-9] / "-" / "." / "~" / "_" / escaped-octet ) 1+
*
* escaped-octet:
* Syntax : "%" hex-digit hex-digit
*
* hex-digit:
* Syntax : [0-9] / [A-F]
* </pre>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>The contents of this file are subject to the
* Mozilla Public License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.</p>
*
* <p>The entire file consists of original code. Copyright © 2002-2004 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @version $Id$
* @author [email protected]
*/
public class PID {
/** The maximum length of a PID is 64. */
public static final int MAX_LENGTH = 64;
private String m_normalized;
private String m_filename;
/**
* Construct a PID from a string, throwing a MalformedPIDException
* if it's not well-formed.
*/
public PID(String pidString)
throws MalformedPIDException {
m_normalized = normalize(pidString);
}
/**
* Construct a PID given a filename of the form produced by toFilename(),
* throwing a MalformedPIDException if it's not well-formed.
*/
public static PID fromFilename(String filenameString)
throws MalformedPIDException {
String decoded = filenameString.replaceFirst("_", ":");
while (decoded.endsWith("%")) {
decoded = decoded.substring(0, decoded.length() - 1) + ".";
}
return new PID(decoded);
}
/**
* Return the normalized form of the given pid string,
* or throw a MalformedPIDException.
*/
public static String normalize(String pidString)
throws MalformedPIDException {
// First, do null & length checks
if (pidString == null) {
throw new MalformedPIDException("PID is null.");
}
if (pidString.length() > MAX_LENGTH) {
throw new MalformedPIDException("PID length exceeds "
+ MAX_LENGTH + ".");
}
// Then normalize while checking syntax
StringBuffer out = new StringBuffer();
boolean inObjectID = false;
for (int i = 0; i < pidString.length(); i++) {
char c = pidString.charAt(i);
if (!inObjectID) {
if (c == ':') {
out.append(':');
inObjectID = true;
} else if (c == '%') {
// next 2 chars MUST be 3[aA]
if (pidString.length() >= i + 3) {
i++;
if (pidString.charAt(i) == '3') {
i++;
c = pidString.charAt(i);
if ( c == 'a' || c == 'A' ) {
out.append(":");
inObjectID = true;
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '3" + c + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i, i+2) + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i+1) + "'.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.') {
out.append(c);
} else {
// invalid char for namespace-id
throw new MalformedPIDException("PID namespace-id cannot contain '" + c + "' character.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.' || c == '~' || c == '_' ) {
out.append(c);
} else if (c == '%') {
// next 2 chars MUST be [0-9][a-f][A-F]
if (pidString.length() >= i + 3) {
char h1 = getNormalizedHexChar(pidString.charAt(++i));
char h2 = getNormalizedHexChar(pidString.charAt(++i));
out.append("%" + h1 + h2);
} else {
throw new MalformedPIDException("PID object-id ended early: need at least 2 chars after '%'.");
}
} else {
throw new MalformedPIDException("PID object-id cannot contain '" + c + "' character.");
}
}
if (!inObjectID) throw new MalformedPIDException("PID delimiter (:) is missing.");
String outString = out.toString();
if (outString.startsWith(":")) throw new MalformedPIDException("PID namespace-id cannot be empty.");
if (outString.length() < 3) throw new MalformedPIDException("PID object-id cannot be empty.");
// If we got here, it's well-formed, so return it.
- return out.toString();
+ return outString;
}
private static boolean isAlphaNum(char c) {
return ( ( ( c >= '0' ) && ( c <= '9' ) )
|| ( ( c >= 'a' ) && ( c <= 'z' ) )
|| ( ( c >= 'A' ) && ( c <= 'Z' ) ) );
}
private static char getNormalizedHexChar(char c)
throws MalformedPIDException {
if ( c >= '0' && c <= '9' ) return c;
c = ("" + c).toUpperCase().charAt(0);
if ( c >= 'A' && c <= 'F' ) return c;
throw new MalformedPIDException("Bad hex-digit in PID object-id: " + c);
}
/**
* Return the normalized form of this PID.
*/
public String toString() {
return m_normalized;
}
/**
* Return the URI form of this PID.
*
* This is just the PID, prepended with "info:fedora/".
*/
public String toURI() {
return "info:fedora/" + m_normalized;
}
/**
* Return a string representing this PID that can be safely used
* as a filename on any OS.
*
* <ul>
* <li> The colon (:) is replaced with an underscore (_).</li>
* <li> Trailing dots are encoded as percents (%).</li>
* </ul>
*/
public String toFilename() {
if (m_filename == null) { // lazily convert, since not always needed
m_filename = m_normalized.replaceAll(":", "_");
while (m_filename.endsWith(".")) {
m_filename = m_filename.substring(0, m_filename.length() - 1) + "%";
}
}
return m_filename;
}
/**
* Command-line interactive tester.
*
* If one arg given, prints normalized form of that PID and exits.
* If no args, enters interactive mode.
*/
public static void main(String[] args) throws Exception {
if (args.length > 0) {
PID p = new PID(args[0]);
System.out.println("Normalized : " + p.toString());
System.out.println("To filename : " + p.toFilename());
System.out.println("From filename : " + PID.fromFilename(p.toFilename()).toString());
} else {
System.out.println("--------------------------------------");
System.out.println("PID Syntax Checker - Interactive mode");
System.out.println("--------------------------------------");
boolean done = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (!done) {
try {
System.out.print("Enter a PID (ENTER to exit): ");
String line = reader.readLine();
if (line.equals("")) {
done = true;
} else {
PID p = new PID(line);
System.out.println("Normalized : " + p.toString());
System.out.println("To filename : " + p.toFilename());
System.out.println("From filename : " + PID.fromFilename(p.toFilename()).toString());
}
} catch (MalformedPIDException e) {
System.out.println("ERROR: " + e.getMessage());
}
}
}
}
}
| true | true | public static String normalize(String pidString)
throws MalformedPIDException {
// First, do null & length checks
if (pidString == null) {
throw new MalformedPIDException("PID is null.");
}
if (pidString.length() > MAX_LENGTH) {
throw new MalformedPIDException("PID length exceeds "
+ MAX_LENGTH + ".");
}
// Then normalize while checking syntax
StringBuffer out = new StringBuffer();
boolean inObjectID = false;
for (int i = 0; i < pidString.length(); i++) {
char c = pidString.charAt(i);
if (!inObjectID) {
if (c == ':') {
out.append(':');
inObjectID = true;
} else if (c == '%') {
// next 2 chars MUST be 3[aA]
if (pidString.length() >= i + 3) {
i++;
if (pidString.charAt(i) == '3') {
i++;
c = pidString.charAt(i);
if ( c == 'a' || c == 'A' ) {
out.append(":");
inObjectID = true;
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '3" + c + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i, i+2) + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i+1) + "'.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.') {
out.append(c);
} else {
// invalid char for namespace-id
throw new MalformedPIDException("PID namespace-id cannot contain '" + c + "' character.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.' || c == '~' || c == '_' ) {
out.append(c);
} else if (c == '%') {
// next 2 chars MUST be [0-9][a-f][A-F]
if (pidString.length() >= i + 3) {
char h1 = getNormalizedHexChar(pidString.charAt(++i));
char h2 = getNormalizedHexChar(pidString.charAt(++i));
out.append("%" + h1 + h2);
} else {
throw new MalformedPIDException("PID object-id ended early: need at least 2 chars after '%'.");
}
} else {
throw new MalformedPIDException("PID object-id cannot contain '" + c + "' character.");
}
}
if (!inObjectID) throw new MalformedPIDException("PID delimiter (:) is missing.");
String outString = out.toString();
if (outString.startsWith(":")) throw new MalformedPIDException("PID namespace-id cannot be empty.");
if (outString.length() < 3) throw new MalformedPIDException("PID object-id cannot be empty.");
// If we got here, it's well-formed, so return it.
return out.toString();
}
| public static String normalize(String pidString)
throws MalformedPIDException {
// First, do null & length checks
if (pidString == null) {
throw new MalformedPIDException("PID is null.");
}
if (pidString.length() > MAX_LENGTH) {
throw new MalformedPIDException("PID length exceeds "
+ MAX_LENGTH + ".");
}
// Then normalize while checking syntax
StringBuffer out = new StringBuffer();
boolean inObjectID = false;
for (int i = 0; i < pidString.length(); i++) {
char c = pidString.charAt(i);
if (!inObjectID) {
if (c == ':') {
out.append(':');
inObjectID = true;
} else if (c == '%') {
// next 2 chars MUST be 3[aA]
if (pidString.length() >= i + 3) {
i++;
if (pidString.charAt(i) == '3') {
i++;
c = pidString.charAt(i);
if ( c == 'a' || c == 'A' ) {
out.append(":");
inObjectID = true;
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '3" + c + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i, i+2) + "'.");
}
} else {
throw new MalformedPIDException("Error in PID after first '%': expected '3a' or '3A', but saw '" + pidString.substring(i+1) + "'.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.') {
out.append(c);
} else {
// invalid char for namespace-id
throw new MalformedPIDException("PID namespace-id cannot contain '" + c + "' character.");
}
} else if (isAlphaNum(c) || c == '-' || c == '.' || c == '~' || c == '_' ) {
out.append(c);
} else if (c == '%') {
// next 2 chars MUST be [0-9][a-f][A-F]
if (pidString.length() >= i + 3) {
char h1 = getNormalizedHexChar(pidString.charAt(++i));
char h2 = getNormalizedHexChar(pidString.charAt(++i));
out.append("%" + h1 + h2);
} else {
throw new MalformedPIDException("PID object-id ended early: need at least 2 chars after '%'.");
}
} else {
throw new MalformedPIDException("PID object-id cannot contain '" + c + "' character.");
}
}
if (!inObjectID) throw new MalformedPIDException("PID delimiter (:) is missing.");
String outString = out.toString();
if (outString.startsWith(":")) throw new MalformedPIDException("PID namespace-id cannot be empty.");
if (outString.length() < 3) throw new MalformedPIDException("PID object-id cannot be empty.");
// If we got here, it's well-formed, so return it.
return outString;
}
|
diff --git a/rultor-users/src/main/java/com/rultor/users/pgsql/PgAccount.java b/rultor-users/src/main/java/com/rultor/users/pgsql/PgAccount.java
index 18547a9fc..e1dc2bda6 100644
--- a/rultor-users/src/main/java/com/rultor/users/pgsql/PgAccount.java
+++ b/rultor-users/src/main/java/com/rultor/users/pgsql/PgAccount.java
@@ -1,159 +1,158 @@
/**
* 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.pgsql;
import com.jcabi.aspects.Cacheable;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.Tv;
import com.jcabi.jdbc.JdbcSession;
import com.jcabi.jdbc.SingleHandler;
import com.jcabi.urn.URN;
import com.rultor.spi.Account;
import com.rultor.spi.InvalidCouponException;
import com.rultor.spi.Sheet;
import com.rultor.tools.Dollars;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Account in PostgreSQL.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.0
*/
@Immutable
@ToString
@EqualsAndHashCode(of = { "client", "owner" })
@Loggable(Loggable.DEBUG)
final class PgAccount implements Account {
/**
* PostgreSQL client.
*/
private final transient PgClient client;
/**
* Owner of the account.
*/
private final transient URN owner;
/**
* Public ctor.
* @param clnt Client
* @param urn Owner of the account
*/
protected PgAccount(final PgClient clnt, final URN urn) {
this.client = clnt;
this.owner = urn;
}
/**
* {@inheritDoc}
*/
@Override
@Cacheable(lifetime = Tv.FIFTEEN, unit = TimeUnit.MINUTES)
public Dollars balance() {
try {
return new Dollars(
new JdbcSession(this.client.get())
// @checkstyle LineLength (1 line)
.sql("SELECT SUM(CASE WHEN dt=? THEN amount ELSE -amount END) FROM receipt WHERE dt=? OR ct=?")
.set(this.owner)
.set(this.owner)
.set(this.owner)
.select(new SingleHandler<Long>(Long.class))
);
} catch (SQLException ex) {
throw new IllegalStateException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public Sheet sheet() {
return new PgSheet(this.client, this.owner);
}
/**
* {@inheritDoc}
*/
@Override
@Cacheable.FlushAfter
public void fund(final Dollars amount, final String details) {
try {
new JdbcSession(this.client.get())
// @checkstyle LineLength (1 line)
.sql("INSERT INTO receipt (ct, ctrule, dt, dtrule, details, amount) VALUES (?, ?, ?, ?, ?, ?)")
.set(Account.BANK)
.set("")
.set(this.owner)
.set("")
.set(details)
.set(amount.points())
.update();
} catch (SQLException ex) {
throw new IllegalStateException(ex);
}
}
/**
* {@inheritDoc}
* @checkstyle RedundantThrowsCheck (3 lines)
*/
@Override
public void fund(@NotNull final String code) throws InvalidCouponException {
try {
final Dollars amount = new Dollars(
new JdbcSession(this.client.get())
- // @checkstyle LineLength (1 line)
.sql("SELECT amount FROM coupon WHERE code=?")
.set(code)
.select(new SingleHandler<Long>(Long.class))
);
new JdbcSession(this.client.get())
.sql("DELETE FROM coupon WHERE code=?")
.set(code)
.update();
this.fund(
amount, String.format("account funded with coupon %s", code)
);
} catch (SQLException ex) {
throw new InvalidCouponException(ex);
}
}
}
| true | true | public void fund(@NotNull final String code) throws InvalidCouponException {
try {
final Dollars amount = new Dollars(
new JdbcSession(this.client.get())
// @checkstyle LineLength (1 line)
.sql("SELECT amount FROM coupon WHERE code=?")
.set(code)
.select(new SingleHandler<Long>(Long.class))
);
new JdbcSession(this.client.get())
.sql("DELETE FROM coupon WHERE code=?")
.set(code)
.update();
this.fund(
amount, String.format("account funded with coupon %s", code)
);
} catch (SQLException ex) {
throw new InvalidCouponException(ex);
}
}
| public void fund(@NotNull final String code) throws InvalidCouponException {
try {
final Dollars amount = new Dollars(
new JdbcSession(this.client.get())
.sql("SELECT amount FROM coupon WHERE code=?")
.set(code)
.select(new SingleHandler<Long>(Long.class))
);
new JdbcSession(this.client.get())
.sql("DELETE FROM coupon WHERE code=?")
.set(code)
.update();
this.fund(
amount, String.format("account funded with coupon %s", code)
);
} catch (SQLException ex) {
throw new InvalidCouponException(ex);
}
}
|
diff --git a/src/main/java/com/candou/ic/navigation/wxdh/dao/AppDao.java b/src/main/java/com/candou/ic/navigation/wxdh/dao/AppDao.java
index f666d5b..054acf6 100644
--- a/src/main/java/com/candou/ic/navigation/wxdh/dao/AppDao.java
+++ b/src/main/java/com/candou/ic/navigation/wxdh/dao/AppDao.java
@@ -1,57 +1,57 @@
package com.candou.ic.navigation.wxdh.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.candou.db.Database;
import com.candou.ic.navigation.wxdh.vo.App;
import com.candou.util.DateTimeUtil;
public class AppDao {
private static String table_Name = "wxdh_app";
public static void addBatchApps(List<App> apps) {
try {
Connection connection = Database.getConnection();
PreparedStatement ps = connection
.prepareStatement("insert ignore into "+table_Name+" (id, name, intro, url, f, oc, wsu, detail, dts, cid, cname, icon, icon_name, imc,imc_name, sc,direct_number,created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
for (App app : apps) {
String now = DateTimeUtil.nowDateTime();
ps.setInt(1, app.getId());
ps.setString(2, app.getName());
ps.setString(3, app.getIntro());
ps.setString(4, app.getUrl());
ps.setInt(5, app.getF());
ps.setString(6, app.getOc());
ps.setString(7,app.getWsu());
ps.setString(8, app.getDetail());
- ps.setInt(9, app.getCid());
- ps.setInt(10, app.getDts());
+ ps.setInt(9, app.getDts());
+ ps.setInt(10, app.getCid());
ps.setString(11, app.getCname());
ps.setString(12, app.getIcon());
ps.setString(13, app.getIcon_name());
ps.setString(14, app.getImc());
ps.setString(15, app.getImc_name());
ps.setString(16, app.getSc());
ps.setString(17, app.getDirect_number());
ps.setString(18, now);
ps.setString(19, now);
ps.executeUpdate();
}
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true | true | public static void addBatchApps(List<App> apps) {
try {
Connection connection = Database.getConnection();
PreparedStatement ps = connection
.prepareStatement("insert ignore into "+table_Name+" (id, name, intro, url, f, oc, wsu, detail, dts, cid, cname, icon, icon_name, imc,imc_name, sc,direct_number,created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
for (App app : apps) {
String now = DateTimeUtil.nowDateTime();
ps.setInt(1, app.getId());
ps.setString(2, app.getName());
ps.setString(3, app.getIntro());
ps.setString(4, app.getUrl());
ps.setInt(5, app.getF());
ps.setString(6, app.getOc());
ps.setString(7,app.getWsu());
ps.setString(8, app.getDetail());
ps.setInt(9, app.getCid());
ps.setInt(10, app.getDts());
ps.setString(11, app.getCname());
ps.setString(12, app.getIcon());
ps.setString(13, app.getIcon_name());
ps.setString(14, app.getImc());
ps.setString(15, app.getImc_name());
ps.setString(16, app.getSc());
ps.setString(17, app.getDirect_number());
ps.setString(18, now);
ps.setString(19, now);
ps.executeUpdate();
}
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
| public static void addBatchApps(List<App> apps) {
try {
Connection connection = Database.getConnection();
PreparedStatement ps = connection
.prepareStatement("insert ignore into "+table_Name+" (id, name, intro, url, f, oc, wsu, detail, dts, cid, cname, icon, icon_name, imc,imc_name, sc,direct_number,created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
for (App app : apps) {
String now = DateTimeUtil.nowDateTime();
ps.setInt(1, app.getId());
ps.setString(2, app.getName());
ps.setString(3, app.getIntro());
ps.setString(4, app.getUrl());
ps.setInt(5, app.getF());
ps.setString(6, app.getOc());
ps.setString(7,app.getWsu());
ps.setString(8, app.getDetail());
ps.setInt(9, app.getDts());
ps.setInt(10, app.getCid());
ps.setString(11, app.getCname());
ps.setString(12, app.getIcon());
ps.setString(13, app.getIcon_name());
ps.setString(14, app.getImc());
ps.setString(15, app.getImc_name());
ps.setString(16, app.getSc());
ps.setString(17, app.getDirect_number());
ps.setString(18, now);
ps.setString(19, now);
ps.executeUpdate();
}
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
diff --git a/ReactorEE/swing/MainGUI.java b/ReactorEE/swing/MainGUI.java
index 386c064..42df03f 100644
--- a/ReactorEE/swing/MainGUI.java
+++ b/ReactorEE/swing/MainGUI.java
@@ -1,1097 +1,1097 @@
package ReactorEE.swing;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JLayeredPane;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import java.awt.Color;
import javax.swing.JSlider;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.JTextField;
import ReactorEE.model.Repair;
import ReactorEE.pcomponents.*;
import ReactorEE.simulator.PlantController;
import java.awt.ComponentOrientation;
import java.util.ArrayList;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
/**
* This is the main GUI class. Only a reference to the PlantController class is needed when this class is instantiated.
* It creates all the required components, instantiates them and connects them to the plant.
* This class is kept as separated from the plant as possible, the only classes it interacts with are the OperatingSoftware, the PlantController and the UIData.
* At each change in any of the components the gui is updated via dedicated method.
* When the scores need to be shown this class creates ScoresGUI object, which has its own gui.
* When the game is over the EndGame class is instantiated which has its own gui.
* @author
*/
public class MainGUI
{
protected JLayeredPane layeredPane = new JLayeredPane();
// the only reference that is needed to the plant
protected PlantController plantController;
//the main frame
private JFrame frmReactoree;
//the field where the player should write theirs
private JTextField nameTextField;
//the buttons which effect is not dependent on the operating software
protected JButton btnNewGame;
protected JButton btnLoad;
protected JButton btnSave;
protected JButton btnShowManual;
protected JButton btnShowScores;
//make a number of steps
protected JButton btnStep;
protected JButton btnRepairOperatingSoftware;
//the affect of those buttons is dependent on the state of the operating software
private JButton btnValve1;
private JButton btnValve2;
protected JButton btnRepairPump1;
protected JButton btnRepairPump2;
protected JButton btnRepairPump3;
protected JButton btnRepairTurbine;
private JButton btnQuench;
//labels showing the state of the different components that can fail
private JLabel lblPump1State;
private JLabel lblPump2State;
private JLabel lblPump3State;
private JLabel lblTurbineState;
private JLabel lblOperatingSoftwareState;
private JLabel warningLabel;
private JLabel lblScore;
//progress bars showing the temperature, pressure, water level and
//health of the reactor and the condenser
private JProgressBar progressBarReactorTemperature;
private JProgressBar progressBarReactorPressure;
private JProgressBar progressBarReactorHealth;
private JProgressBar progressBarCondenserTemperature;
private JProgressBar progressBarCondenserPressure;
private JProgressBar progressBarCondenserHealth;
private JProgressBar progressBarReactorWaterLevel;
private JProgressBar progressBarCondenserWaterLevel;
//sliders controlling the rpm of the pumps, the level of the
//control rods and the number of timesteps
private JSlider sliderPump1RPM;
private JSlider sliderPump2RPM;
private JSlider sliderPump3RPM;
private JSlider sliderRodsLevel;
//image icons containing the images that are used in the gui
private ImageIcon repairButtonEnabledImageIcon;
private ImageIcon repairButtonDisabledImageIcon;
private ImageIcon stateSafeImageIcon;
private ImageIcon stateBeingRepairedImageIcon;
private ImageIcon stateBrokenImageIcon;
private ImageIcon valveOpenedImageIcon;
private ImageIcon valveClosedImageIcon;
private ImageIcon newGameImageIcon;
private ImageIcon loadGameImageIcon;
private ImageIcon saveGameImageIcon;
private ImageIcon viewManualImageIcon;
private ImageIcon viewScoresImageIcon;
private ImageIcon nextStepImageIcon;
private ImageIcon nextStepPausedImageIcon;
//the repair buttons are not disabled directly but a different image is associated
//with them when they cannot be used - this variable prevents them from being used
//when they are 'disabled'
protected boolean controlButtonsEnabled = true;
//a shorthand for the list of the components that are being repaired
private ArrayList<String> componentsBeingRepaired = new ArrayList<String>();
//the string that is shown initially in the player name field
protected String initialNameValue = "Change me";
//a temporary value which has different usages
private int tempValue;
/**
* The constructor sets the plantController object, initialises the gui
* and makes it visible.
* @param plantController
*/
public MainGUI(PlantController plantController)
{
this.plantController = plantController;
initialize();
frmReactoree.setVisible(true);
}
/**
* Initialises the contents of the frame.
*/
private void initialize()
{
//instantiates the main frame
frmReactoree = new JFrame();
frmReactoree.setTitle("ReactorEE");
frmReactoree.setBounds(100, 100, 1049, 740);
frmReactoree.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//which is layered - two layers: background picture - layer 0
//all interactive components - layer 1
frmReactoree.getContentPane().add(layeredPane, BorderLayout.CENTER);
//loads and sets the background image
java.net.URL imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/plantBackground.png");
ImageIcon backgroundImageIcon = new ImageIcon(imageURL);
warningLabel = new JLabel("Warning");
warningLabel.setToolTipText("Reactor is overheating!");
warningLabel.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/animates.gif")));
warningLabel.setBounds(27, 58, 500, 500);
layeredPane.add(warningLabel);
warningLabel.setVisible(false);
JLabel backgroundImageLabel = new JLabel(backgroundImageIcon);
backgroundImageLabel.setBackground(new Color(0, 153, 0));
backgroundImageLabel.setBounds(0, 0, 1040, 709);
layeredPane.add(backgroundImageLabel);
//loads all the images that are required for the image labels
//the path is relative to the project
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairEnabled.png");
repairButtonEnabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairDisabled.png");
repairButtonDisabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateSafe.png");
stateSafeImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBeingRepaired.png");
stateBeingRepairedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBroken.png");
stateBrokenImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveOpened.png");
valveOpenedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveClosed.png");
valveClosedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/newButtonLabel.png");
newGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/loadButtonLabel.png");
loadGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/saveButtonLabel.png");
saveGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/manualButtonLabel.png");
viewManualImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/scoresButtonLabel.png");
viewScoresImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonLabel.png");
nextStepImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonPausedLabel.png");
nextStepPausedImageIcon = new ImageIcon(imageURL);
//initialises the label that shows the score
lblScore = new JLabel("0");
lblScore.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblScore.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
lblScore.setBounds(860, 81, 160, 23);
layeredPane.setLayer(lblScore, 1);
layeredPane.add(lblScore);
//the player should type in their name in that text field
//when the field loses focus the text is checked and if it is not
//empty or bigger than 15 characters, it is set as the operator's name
//if the text is bigger than 15 characters only the first 15 are used
//if the text field is empty, the initial text is set put it
nameTextField = new JTextField(initialNameValue);
- nameTextField.setFont(new Font("Tahoma", Font.PLAIN, 14));
+ nameTextField.setFont(new Font("OCR A Std", Font.PLAIN, 15));
nameTextField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
nameTextField.setColumns(20);
nameTextField.setOpaque(false);
nameTextField.setBorder(null);
- nameTextField.setBounds(10, 11, 102, 20);
+ nameTextField.setBounds(0, 14, 117, 20);
nameTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
nameTextField.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
if(nameTextField.getText() == "")
{
nameTextField.setText(initialNameValue);
nameTextField.selectAll();
}
else
if(nameTextField.getText().length() > 15)
plantController.getPlant().setOperatorName(nameTextField.getText().substring(0,15));
else plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
nameTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(nameTextField.getText() != "")
plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
layeredPane.setLayer(nameTextField, 1);
layeredPane.add(nameTextField);
//all the labels that show component states are
//initialised with green light showing
lblPump1State = new JLabel(stateSafeImageIcon);
lblPump1State.setBounds(273, 592, 78, 23);
layeredPane.setLayer(lblPump1State, 1);
layeredPane.add(lblPump1State);
lblPump2State = new JLabel(stateSafeImageIcon);
lblPump2State.setBounds(496, 592, 78, 23);
layeredPane.setLayer(lblPump2State, 1);
layeredPane.add(lblPump2State);
lblPump3State = new JLabel(stateSafeImageIcon);
lblPump3State.setBounds(716, 592, 78, 23);
layeredPane.setLayer(lblPump3State, 1);
layeredPane.add(lblPump3State);
lblTurbineState = new JLabel(stateSafeImageIcon);
lblTurbineState.setBounds(826, 592, 78, 23);
layeredPane.setLayer(lblTurbineState, 1);
layeredPane.add(lblTurbineState);
lblOperatingSoftwareState = new JLabel(stateSafeImageIcon);
lblOperatingSoftwareState.setBounds(927, 592, 78, 23);
layeredPane.setLayer(lblOperatingSoftwareState, 1);
layeredPane.add(lblOperatingSoftwareState);
//creation and instantiation of the progress bars
//change state listeners added at the end of this method
progressBarReactorTemperature = new JProgressBar();
progressBarReactorTemperature.setBounds(781, 168, 234, 14);
layeredPane.setLayer(progressBarReactorTemperature, 1);
layeredPane.add(progressBarReactorTemperature);
progressBarReactorPressure = new JProgressBar();
progressBarReactorPressure.setBounds(781, 203, 234, 14);
layeredPane.setLayer(progressBarReactorPressure, 1);
layeredPane.add(progressBarReactorPressure);
progressBarReactorHealth = new JProgressBar();
progressBarReactorHealth.setBounds(781, 273, 234, 14);
layeredPane.setLayer(progressBarReactorHealth, 1);
layeredPane.add(progressBarReactorHealth);
progressBarReactorWaterLevel = new JProgressBar();
progressBarReactorWaterLevel.setBounds(781, 237, 234, 14);
layeredPane.setLayer(progressBarReactorWaterLevel, 1);
layeredPane.add(progressBarReactorWaterLevel);
progressBarCondenserTemperature = new JProgressBar();
progressBarCondenserTemperature.setBounds(781, 359, 234, 14);
layeredPane.setLayer(progressBarCondenserTemperature, 1);
layeredPane.add(progressBarCondenserTemperature);
progressBarCondenserPressure = new JProgressBar();
progressBarCondenserPressure.setBounds(781, 394, 234, 14);
layeredPane.setLayer(progressBarCondenserPressure, 1);
layeredPane.add(progressBarCondenserPressure);
progressBarCondenserHealth = new JProgressBar();
progressBarCondenserHealth.setBounds(781, 468, 234, 14);
layeredPane.setLayer(progressBarCondenserHealth, 1);
layeredPane.add(progressBarCondenserHealth);
progressBarCondenserWaterLevel = new JProgressBar();
progressBarCondenserWaterLevel.setBounds(781, 430, 234, 14);
progressBarCondenserWaterLevel.setForeground(new Color(0, 255, 0));
layeredPane.setLayer(progressBarCondenserWaterLevel, 1);
layeredPane.add(progressBarCondenserWaterLevel);
//creation and instantiation of the sliders
//every slider calls the appropriate method in the OperatingSoftware
//requests its execution from the plantController
//and updates the gui
sliderPump1RPM = new JSlider();
sliderPump1RPM.setOpaque(false);
sliderPump1RPM.setBounds(173, 581, 25, 108);
sliderPump1RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump1RPM.setMaximum(1000);
sliderPump1RPM.setValue(0);
sliderPump1RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{ plantController.getPlant().getOperatingSoftware().setPumpRpm(1, sliderPump1RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump1RPM, 1);
layeredPane.add(sliderPump1RPM);
sliderPump2RPM = new JSlider();
sliderPump2RPM.setBounds(384, 581, 25, 108);
sliderPump2RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump2RPM.setOpaque(false);
sliderPump2RPM.setValue(0);
sliderPump2RPM.setMaximum(1000);
sliderPump2RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(2, sliderPump2RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump2RPM, 1);
layeredPane.add(sliderPump2RPM);
sliderPump3RPM = new JSlider();
sliderPump3RPM.setBounds(597, 581, 42, 108);
sliderPump3RPM.setOpaque(false);
sliderPump3RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump3RPM.setMaximum(1000);
sliderPump3RPM.setValue(0);
sliderPump3RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(3, sliderPump3RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump3RPM, 1);
layeredPane.add(sliderPump3RPM);
sliderRodsLevel = new JSlider();
sliderRodsLevel.setOpaque(false);
sliderRodsLevel.setBounds(27, 592, 25, 106);
sliderRodsLevel.setOrientation(SwingConstants.VERTICAL);
sliderRodsLevel.setValue(0);
sliderRodsLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setControlRods(100-sliderRodsLevel.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderRodsLevel, 1);
layeredPane.add(sliderRodsLevel);
//starts a new game when pressed
//and updates the gui
btnNewGame = new JButton(newGameImageIcon);
btnNewGame.setToolTipText("New Game");
btnNewGame.setMargin(new Insets(0,0,0,0));
btnNewGame.setBorder(null);
btnNewGame.setBounds(749, 17, 40, 40);
btnNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewGame.setEnabled(false);
//plantController.newGame(initialNameValue);
//updateGUI();
btnNewGame.setEnabled(true);
frmReactoree.dispose();
new GameTypeSelectionGUI();
}
});
layeredPane.setLayer(btnNewGame, 1);
layeredPane.add(btnNewGame);
//loads the saved game and updates the gui
btnLoad = new JButton(loadGameImageIcon);
btnLoad.setToolTipText("Load Game");
btnLoad.setMargin(new Insets(0,0,0,0));
btnLoad.setBorder(null);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.loadGame();
updateGUI();
}
});
btnLoad.setBounds(799, 17, 40, 40);
layeredPane.setLayer(btnLoad, 1);
layeredPane.add(btnLoad);
//if the current game is not over it saves it
btnSave = new JButton(saveGameImageIcon);
btnSave.setToolTipText("Save Game");
btnSave.setMargin(new Insets(0,0,0,0));
btnSave.setBorder(null);
btnSave.setBounds(849, 17, 40, 40);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnSave.setEnabled(false);
if(!plantController.getUIData().isGameOver())
plantController.saveGame();
btnSave.setEnabled(true);
}
});
layeredPane.setLayer(btnSave, 1);
layeredPane.add(btnSave);
//shows the scores so far
//by calling a function that instantiates the scoresGUI
btnShowScores = new JButton(viewScoresImageIcon);
btnShowScores.setToolTipText("Leaderboard");
btnShowScores.setMargin(new Insets(0,0,0,0));
btnShowScores.setBorder(null);
btnShowScores.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showScores();
}
});
btnShowScores.setBounds(949, 17, 40, 40);
layeredPane.setLayer(btnShowScores, 1);
layeredPane.add(btnShowScores);
//displays the user manual by opening it with its default program
btnShowManual = new JButton(viewManualImageIcon);
btnShowManual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
java.net.URL manualURL = this.getClass().getClassLoader().getResource("Manual3.pdf");
try{
Desktop.getDesktop().open(new File(manualURL.getPath()));
}catch (IOException e)
{
e.printStackTrace();
}
}
});
btnShowManual.setToolTipText("Manual");
btnShowManual.setMargin(new Insets(0,0,0,0));
btnShowManual.setBorder(null);
btnShowManual.setBounds(899, 17, 40, 40);
layeredPane.setLayer(btnShowManual, 1);
layeredPane.add(btnShowManual);
//when this button is pressed it takes the value of the sliderNumber of time steps,
//and issues a single time step at a time to the plant
//if the plant has not failed and updates the gui
//if the plant has failed - invokes the end game handler
btnStep = new JButton(nextStepImageIcon);
btnStep.setToolTipText("Step");
btnStep.setOpaque(false);
btnStep.setBounds(426, 500, 49, 39);
btnStep.setMargin(new Insets(0,0,0,0));
btnStep.setBorder(null);
btnStep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!plantController.getUIData().isGameOver()) {
plantController.togglePaused();
if(plantController.getPlant().isPaused())
btnStep.setIcon(nextStepImageIcon);
else
btnStep.setIcon(nextStepPausedImageIcon);
updateGUI();
}
if(plantController.getUIData().isGameOver())
{
//Show score and create a new game selection screen
//frame.dispose();
endGameHandler();
}
}
});
layeredPane.setLayer(btnStep, 1);
layeredPane.add(btnStep);
//used to open and close the first valve
btnValve1 = new JButton(valveOpenedImageIcon);
btnValve1.setBounds(860, 508, 59, 23);
btnValve1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(0).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(1, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(1, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve1, 1);
layeredPane.add(btnValve1);
//used to open and close the second valve
btnValve2 = new JButton(valveOpenedImageIcon);
btnValve2.setBounds(968, 508, 59, 23);
btnValve2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(1).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(2, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(2, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve2, 1);
layeredPane.add(btnValve2);
//issues a repair command to pump 1 if it is not operational
btnRepairPump1 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump1.setBounds(283, 626, 59, 57);
btnRepairPump1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(1);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump1.setMargin(new Insets(0,0,0,0));
btnRepairPump1.setBorder(null);
layeredPane.setLayer(btnRepairPump1, 1);
layeredPane.add(btnRepairPump1);
//issues a repair command to pump 2 if it is not operational
btnRepairPump2 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump2.setBounds(506, 626, 59, 57);
btnRepairPump2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(2);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump2.setMargin(new Insets(0,0,0,0));
btnRepairPump2.setBorder(null);
layeredPane.setLayer(btnRepairPump2, 1);
layeredPane.add(btnRepairPump2);
//issues a repair command to pump 3 if it is not operational
btnRepairPump3 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump3.setBounds(726, 626, 59, 57);
btnRepairPump3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(3);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump3.setMargin(new Insets(0,0,0,0));
btnRepairPump3.setBorder(null);
layeredPane.setLayer(btnRepairPump3, 1);
layeredPane.add(btnRepairPump3);
//issues a repair command to the turbine if it is not operational
btnRepairTurbine = new JButton(repairButtonDisabledImageIcon);
btnRepairTurbine.setBounds(836, 626, 59, 57);
btnRepairTurbine.setMargin(new Insets(0,0,0,0));
btnRepairTurbine.setBorder(null);
btnRepairTurbine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isTurbineFunctional() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairTurbine();
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(btnRepairTurbine, 1);
layeredPane.add(btnRepairTurbine);
//directly repairs the operating software - commands from this button are directly
//executed by the plant and cannot fail
btnRepairOperatingSoftware = new JButton(repairButtonDisabledImageIcon);
btnRepairOperatingSoftware.setPreferredSize(new Dimension(93, 71));
btnRepairOperatingSoftware.setBounds(937, 626, 59, 57);
btnRepairOperatingSoftware.setMargin(new Insets(0,0,0,0));
btnRepairOperatingSoftware.setBorder(null);
btnRepairOperatingSoftware.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isOperatingSoftwareFunctional())
{
plantController.repairOperatingSoftware();
updateGUI();
}
}
});
btnQuench = new JButton("QUENCH!");
btnQuench.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/btnRepairDisabled.png")));
btnQuench.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.getPlant().getOperatingSoftware().quench();
plantController.executeStoredCommand();
updateGUI();
}
});
layeredPane.setLayer(btnQuench, 1);
btnQuench.setBounds(70, 626, 59, 62);
layeredPane.add(btnQuench);
layeredPane.setLayer(btnRepairOperatingSoftware, 1);
layeredPane.add(btnRepairOperatingSoftware);
//adds change listeners to the progress bars. Every time a bar's value is changed,
//the colour of the bar changes depending on what is its value
//temperature and pressure bars change colour smoothly from blue to red
//health pressure bars change colour smoothly from red to green
progressBarCondenserHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarCondenserHealth);
}
});
progressBarCondenserPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserPressure);
}
});
progressBarCondenserTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserTemperature);
}
});
progressBarReactorWaterLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorWaterLevel);
}
});
progressBarReactorHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorHealth);
}
});
progressBarReactorPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorPressure);
}
});
progressBarReactorTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorTemperature);
}
});
//after everything but the name is set the gui is updates so it
//synchronises with the plant
updateGUI();
nameTextField.setText(initialNameValue);
}
/**
* This method takes a progress bar, gets its value and based on it
* sets the bars colour, from blue to red, the calculations involved
* give the desired colour
* @param pb
*/
private void colourProgressBarBlueToRed(JProgressBar pb)
{
int pbv = pb.getValue();
//red green and blue colour components
//used to create the new colour
int r=0,g=0,b=255;
if(pbv>0 && pbv<=20)
{
g=(int) (pbv*12.75);
//casting is needed because of the new Colour()
//constructor type - takes int values
}
else if(pbv>20 && pbv<=45)
{
r=0;g=255;b=(int) (255-((pbv-20)*10.2));
}
else if(pbv>45 && pbv<=65)
{
r= (int) ((pbv-45)*12.75);g=255;b=0;
}
else if(pbv>65 && pbv<=90)
{
r=255;g=(int) (255-((pbv-65)*10.2));b=0;
}
else if(pbv>90 && pbv<=100)
{
r=255;g=0;b=0;
}
pb.setForeground(new Color(r, g, b));
}
/**
* This method takes a progress bar, gets its value and based on it
* sets the bars colour, from red to green, the calculations involved
* give the desired colour
* @param pb
*/
private void colourProgressBarRedToGreen(JProgressBar pb)
{
int pbv = pb.getValue();
int r=255,g=0,b=0;
if(pbv>0 && pbv<=20)
{
r=255; g=0; b=0;
}
else if(pbv>20 && pbv<=60)
{
r=255;g = (int) ((pbv-20)*6.375);
}
else if(pbv>60 && pbv<=90)
{
r= (int) (255-((pbv-60)*8.5));g=255;b=0;
}
else if(pbv>90 && pbv<=100)
{
r=0;g=255;b=0;
}
pb.setForeground(new Color(r, g, b));
}
/**
* This method updates the appearance of the gui
* synchronising it with the plant
*/
public void updateGUI()
{
//updates the information that is stored in the UIData object
plantController.getUIData().updateUIData();
//resets the list with components that are being repaired
componentsBeingRepaired.clear();
//restores the state of the control buttons and sliderRodsLevel variables to true
controlButtonsEnabled = true;
//updates the operators name that is shown to that that is stored,
//useful when a game is being loaded
//Only change when text box is not in focus, this allows operator name to be changed while the game is running.
if(!nameTextField.isFocusOwner())
nameTextField.setText(plantController.getUIData().getOperatorName());
//updates the score and enables the buttons the control the valves
//they can be disabled if the operatingSoftware is being repaired
lblScore.setText(""+plantController.getUIData().getScore());
btnValve1.setEnabled(true);
btnValve2.setEnabled(true);
//sets the button valve icons appropriately
if(plantController.getUIData().getValves().get(0).isOpen())
btnValve1.setIcon(valveOpenedImageIcon);
else
btnValve1.setIcon(valveClosedImageIcon);
if(plantController.getUIData().getValves().get(1).isOpen())
btnValve2.setIcon(valveOpenedImageIcon);
else
btnValve2.setIcon(valveClosedImageIcon);
//sets the level of the control rods appropriately
tempValue = plantController.getUIData().getControlRodsPercentage();
if(tempValue >=0 && tempValue <= 100)
//it is 100 - tempValue because in the plant it is shown how much
//the control rods are inside the rods while in the gui it shows how
//much the control rods are out of the rods
sliderRodsLevel.setValue(100 - tempValue);
//sets the values of the progress bars by scaling the value to 100
tempValue = plantController.getUIData().getReactorHealth();
if(tempValue >=0 && tempValue <= 100)
progressBarReactorHealth.setValue(tempValue);
tempValue = plantController.getUIData().getCondenserHealth();
if(tempValue >=0 && tempValue <= 100)
progressBarCondenserHealth.setValue(tempValue);
tempValue = plantController.getUIData().getReactorTemperature();
if(tempValue >=0 && tempValue <= 3000)
progressBarReactorTemperature.setValue((int) tempValue/30);
else if(tempValue > 3000)
progressBarReactorTemperature.setValue(100);
tempValue = plantController.getUIData().getCondenserTemperature();
if(tempValue >=0 && tempValue <= 2000)
progressBarCondenserTemperature.setValue((int) tempValue/20);
else if(tempValue > 2000)
progressBarCondenserTemperature.setValue(100);
tempValue = plantController.getUIData().getReactorPressure();
if(tempValue >=0 && tempValue <= 2000)
progressBarReactorPressure.setValue((int) tempValue/20);
else if(tempValue > 2000)
progressBarReactorPressure.setValue(100);
tempValue = plantController.getUIData().getCondenserPressure();
if(tempValue >=0 && tempValue <= 2000)
progressBarCondenserPressure.setValue((int) tempValue/20);
else if(tempValue > 2000)
progressBarCondenserPressure.setValue(100);
tempValue = plantController.getUIData().getReactorWaterVolume();
if(tempValue >=0 && tempValue <= 10000)
progressBarReactorWaterLevel.setValue((int) tempValue/100);
tempValue = plantController.getUIData().getCondenserWaterVolume();
if(tempValue >=0 && tempValue <= 10000)
progressBarCondenserWaterLevel.setValue((int) tempValue/100);
tempValue = plantController.getUIData().getControlRodsPercentage();
if(tempValue >=0 && tempValue <= 100)
sliderRodsLevel.setValue((int) 100 - tempValue);
tempValue = plantController.getUIData().getPumps().get(0).getRpm();
if(tempValue >=0 && tempValue <= 1000)
sliderPump1RPM.setValue((int) tempValue);
tempValue = plantController.getUIData().getPumps().get(1).getRpm();
if(tempValue >=0 && tempValue <= 1000)
sliderPump2RPM.setValue((int) tempValue);
tempValue = plantController.getUIData().getPumps().get(2).getRpm();
if(tempValue >=0 && tempValue <= 1000)
sliderPump3RPM.setValue((int) tempValue);
//reads all the components that are being repaired and adds them to a short hand
//string quick reference list
for(Repair repair:plantController.getPlant().getBeingRepaired())
{
if(repair.getPlantComponent() instanceof ReactorEE.pcomponents.Pump)
{
int id = ((Pump) repair.getPlantComponent()).getID();
componentsBeingRepaired.add("pump"+id);
}
if(repair.getPlantComponent() instanceof ReactorEE.pcomponents.Turbine)
{
componentsBeingRepaired.add("turbine");
}
if(repair.getPlantComponent() instanceof ReactorEE.pcomponents.OperatingSoftware)
{
componentsBeingRepaired.add("operatingSoftware");
}
}
//checks which components are being repaired and updates the gui in an appropriate way
//if a component is being repaired its controls are disabled and a yellow light is showing
if(componentsBeingRepaired.contains("pump1"))
{
lblPump1State.setIcon(stateBeingRepairedImageIcon);
sliderPump1RPM.setEnabled(false);
btnRepairPump1.setIcon(repairButtonDisabledImageIcon);
}//if a component has failed and is not repaired its controls are disabled and red light is showing
else if(!plantController.getUIData().getPumps().get(0).isOperational())
{
lblPump1State.setIcon(stateBrokenImageIcon);
sliderPump1RPM.setEnabled(false);
btnRepairPump1.setIcon(repairButtonEnabledImageIcon);
}else//the component is in its normal safe operating state
//its controls are enabled and green light is showing
{
lblPump1State.setIcon(stateSafeImageIcon);
sliderPump1RPM.setEnabled(true);
sliderPump1RPM.setValue(plantController.getUIData().getPumps().get(0).getRpm());
btnRepairPump1.setIcon(repairButtonDisabledImageIcon);
}
if(componentsBeingRepaired.contains("pump2"))
{
lblPump2State.setIcon(stateBeingRepairedImageIcon);
sliderPump2RPM.setEnabled(false);
btnRepairPump2.setIcon(repairButtonDisabledImageIcon);
}else if(!plantController.getUIData().getPumps().get(1).isOperational())
{
lblPump2State.setIcon(stateBrokenImageIcon);
sliderPump2RPM.setEnabled(false);
btnRepairPump2.setIcon(repairButtonEnabledImageIcon);
}else
{
lblPump2State.setIcon(stateSafeImageIcon);
sliderPump2RPM.setEnabled(true);
sliderPump2RPM.setValue(plantController.getUIData().getPumps().get(1).getRpm());
btnRepairPump2.setIcon(repairButtonDisabledImageIcon);
}
if(componentsBeingRepaired.contains("pump3"))
{ lblPump3State.setIcon(stateBeingRepairedImageIcon);
sliderPump3RPM.setEnabled(false);
btnRepairPump3.setIcon(repairButtonDisabledImageIcon);
}else if(!plantController.getUIData().getPumps().get(2).isOperational())
{
lblPump3State.setIcon(stateBrokenImageIcon);
sliderPump3RPM.setEnabled(false);
btnRepairPump3.setIcon(repairButtonEnabledImageIcon);
}else
{
lblPump3State.setIcon(stateSafeImageIcon);
sliderPump3RPM.setEnabled(true);
sliderPump3RPM.setValue(plantController.getUIData().getPumps().get(2).getRpm());
btnRepairPump3.setIcon(repairButtonDisabledImageIcon);
}
if(componentsBeingRepaired.contains("turbine"))
{
lblTurbineState.setIcon(stateBeingRepairedImageIcon);
btnRepairTurbine.setIcon(repairButtonDisabledImageIcon);
}else if(!plantController.getUIData().isTurbineFunctional())
{
lblTurbineState.setIcon(stateBrokenImageIcon);
btnRepairTurbine.setIcon(repairButtonEnabledImageIcon);
}else
{
lblTurbineState.setIcon(stateSafeImageIcon);
btnRepairTurbine.setIcon(repairButtonDisabledImageIcon);
}
//if the operating software is being repaired all components that rely on it for their commands to
//be executed are disabled
if(componentsBeingRepaired.contains("operatingSoftware"))
{
lblOperatingSoftwareState.setIcon(stateBeingRepairedImageIcon);
btnRepairOperatingSoftware.setIcon(repairButtonDisabledImageIcon);
controlButtonsEnabled = false;
sliderPump1RPM.setEnabled(false);
sliderPump2RPM.setEnabled(false);
sliderPump3RPM.setEnabled(false);
sliderRodsLevel.setEnabled(false);
btnRepairPump1.setIcon(repairButtonDisabledImageIcon);
btnRepairPump2.setIcon(repairButtonDisabledImageIcon);
btnRepairPump3.setIcon(repairButtonDisabledImageIcon);
btnRepairTurbine.setIcon(repairButtonDisabledImageIcon);
btnValve1.setEnabled(false);
btnValve2.setEnabled(false);
}else if(!plantController.getUIData().isOperatingSoftwareFunctional())
{
//otherwise just set its light to show red and enable its repair button
lblOperatingSoftwareState.setIcon(stateBrokenImageIcon);
btnRepairOperatingSoftware.setIcon(repairButtonEnabledImageIcon);
}else
{ //otherwise just set its light to show green and disable its repair button
lblOperatingSoftwareState.setIcon(stateSafeImageIcon);
btnRepairOperatingSoftware.setIcon(repairButtonDisabledImageIcon);
sliderRodsLevel.setEnabled(true);
}
//Change the play/pause button depending on whether the game is paused or running.
if(plantController.getPlant().isPaused())
btnStep.setIcon(nextStepImageIcon);
else
btnStep.setIcon(nextStepPausedImageIcon);
if(plantController.getPlant().getReactor().isQuenchable()){
btnQuench.setEnabled(true);
warningLabel.setVisible(true);
}else{
btnQuench.setEnabled(false);
warningLabel.setVisible(false);
}
}
/**
* called when the the game is over - creates a new EndGame object passing a reference to this object,
* the operator's name and the end score
* then it updates the gui and set the slider for the timesteps to 1
*/
public void endGameHandler()
{
@SuppressWarnings("unused")
EndGameGUI endGameGui = new EndGameGUI(this, plantController.getUIData().getScore());
plantController.togglePaused();
//plantController.newGame(initialNameValue);
//updateGUI();
//sliderNumberOfSteps.setValue(1);
frmReactoree.dispose();
new GameTypeSelectionGUI();
}
/**
*
* @return the main frame - used for relative positioning
*/
public JFrame getFrame()
{
return frmReactoree;
}
/**
* called when the the scores should be shown - creates a new ScoresGUI object passing a reference to this object,
* and the plantControllers object
*/
private void showScores()
{
@SuppressWarnings("unused")
ScoresGUI scoresGui = new ScoresGUI(this, plantController);
}
}
| false | true | private void initialize()
{
//instantiates the main frame
frmReactoree = new JFrame();
frmReactoree.setTitle("ReactorEE");
frmReactoree.setBounds(100, 100, 1049, 740);
frmReactoree.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//which is layered - two layers: background picture - layer 0
//all interactive components - layer 1
frmReactoree.getContentPane().add(layeredPane, BorderLayout.CENTER);
//loads and sets the background image
java.net.URL imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/plantBackground.png");
ImageIcon backgroundImageIcon = new ImageIcon(imageURL);
warningLabel = new JLabel("Warning");
warningLabel.setToolTipText("Reactor is overheating!");
warningLabel.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/animates.gif")));
warningLabel.setBounds(27, 58, 500, 500);
layeredPane.add(warningLabel);
warningLabel.setVisible(false);
JLabel backgroundImageLabel = new JLabel(backgroundImageIcon);
backgroundImageLabel.setBackground(new Color(0, 153, 0));
backgroundImageLabel.setBounds(0, 0, 1040, 709);
layeredPane.add(backgroundImageLabel);
//loads all the images that are required for the image labels
//the path is relative to the project
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairEnabled.png");
repairButtonEnabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairDisabled.png");
repairButtonDisabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateSafe.png");
stateSafeImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBeingRepaired.png");
stateBeingRepairedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBroken.png");
stateBrokenImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveOpened.png");
valveOpenedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveClosed.png");
valveClosedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/newButtonLabel.png");
newGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/loadButtonLabel.png");
loadGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/saveButtonLabel.png");
saveGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/manualButtonLabel.png");
viewManualImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/scoresButtonLabel.png");
viewScoresImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonLabel.png");
nextStepImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonPausedLabel.png");
nextStepPausedImageIcon = new ImageIcon(imageURL);
//initialises the label that shows the score
lblScore = new JLabel("0");
lblScore.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblScore.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
lblScore.setBounds(860, 81, 160, 23);
layeredPane.setLayer(lblScore, 1);
layeredPane.add(lblScore);
//the player should type in their name in that text field
//when the field loses focus the text is checked and if it is not
//empty or bigger than 15 characters, it is set as the operator's name
//if the text is bigger than 15 characters only the first 15 are used
//if the text field is empty, the initial text is set put it
nameTextField = new JTextField(initialNameValue);
nameTextField.setFont(new Font("Tahoma", Font.PLAIN, 14));
nameTextField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
nameTextField.setColumns(20);
nameTextField.setOpaque(false);
nameTextField.setBorder(null);
nameTextField.setBounds(10, 11, 102, 20);
nameTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
nameTextField.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
if(nameTextField.getText() == "")
{
nameTextField.setText(initialNameValue);
nameTextField.selectAll();
}
else
if(nameTextField.getText().length() > 15)
plantController.getPlant().setOperatorName(nameTextField.getText().substring(0,15));
else plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
nameTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(nameTextField.getText() != "")
plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
layeredPane.setLayer(nameTextField, 1);
layeredPane.add(nameTextField);
//all the labels that show component states are
//initialised with green light showing
lblPump1State = new JLabel(stateSafeImageIcon);
lblPump1State.setBounds(273, 592, 78, 23);
layeredPane.setLayer(lblPump1State, 1);
layeredPane.add(lblPump1State);
lblPump2State = new JLabel(stateSafeImageIcon);
lblPump2State.setBounds(496, 592, 78, 23);
layeredPane.setLayer(lblPump2State, 1);
layeredPane.add(lblPump2State);
lblPump3State = new JLabel(stateSafeImageIcon);
lblPump3State.setBounds(716, 592, 78, 23);
layeredPane.setLayer(lblPump3State, 1);
layeredPane.add(lblPump3State);
lblTurbineState = new JLabel(stateSafeImageIcon);
lblTurbineState.setBounds(826, 592, 78, 23);
layeredPane.setLayer(lblTurbineState, 1);
layeredPane.add(lblTurbineState);
lblOperatingSoftwareState = new JLabel(stateSafeImageIcon);
lblOperatingSoftwareState.setBounds(927, 592, 78, 23);
layeredPane.setLayer(lblOperatingSoftwareState, 1);
layeredPane.add(lblOperatingSoftwareState);
//creation and instantiation of the progress bars
//change state listeners added at the end of this method
progressBarReactorTemperature = new JProgressBar();
progressBarReactorTemperature.setBounds(781, 168, 234, 14);
layeredPane.setLayer(progressBarReactorTemperature, 1);
layeredPane.add(progressBarReactorTemperature);
progressBarReactorPressure = new JProgressBar();
progressBarReactorPressure.setBounds(781, 203, 234, 14);
layeredPane.setLayer(progressBarReactorPressure, 1);
layeredPane.add(progressBarReactorPressure);
progressBarReactorHealth = new JProgressBar();
progressBarReactorHealth.setBounds(781, 273, 234, 14);
layeredPane.setLayer(progressBarReactorHealth, 1);
layeredPane.add(progressBarReactorHealth);
progressBarReactorWaterLevel = new JProgressBar();
progressBarReactorWaterLevel.setBounds(781, 237, 234, 14);
layeredPane.setLayer(progressBarReactorWaterLevel, 1);
layeredPane.add(progressBarReactorWaterLevel);
progressBarCondenserTemperature = new JProgressBar();
progressBarCondenserTemperature.setBounds(781, 359, 234, 14);
layeredPane.setLayer(progressBarCondenserTemperature, 1);
layeredPane.add(progressBarCondenserTemperature);
progressBarCondenserPressure = new JProgressBar();
progressBarCondenserPressure.setBounds(781, 394, 234, 14);
layeredPane.setLayer(progressBarCondenserPressure, 1);
layeredPane.add(progressBarCondenserPressure);
progressBarCondenserHealth = new JProgressBar();
progressBarCondenserHealth.setBounds(781, 468, 234, 14);
layeredPane.setLayer(progressBarCondenserHealth, 1);
layeredPane.add(progressBarCondenserHealth);
progressBarCondenserWaterLevel = new JProgressBar();
progressBarCondenserWaterLevel.setBounds(781, 430, 234, 14);
progressBarCondenserWaterLevel.setForeground(new Color(0, 255, 0));
layeredPane.setLayer(progressBarCondenserWaterLevel, 1);
layeredPane.add(progressBarCondenserWaterLevel);
//creation and instantiation of the sliders
//every slider calls the appropriate method in the OperatingSoftware
//requests its execution from the plantController
//and updates the gui
sliderPump1RPM = new JSlider();
sliderPump1RPM.setOpaque(false);
sliderPump1RPM.setBounds(173, 581, 25, 108);
sliderPump1RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump1RPM.setMaximum(1000);
sliderPump1RPM.setValue(0);
sliderPump1RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{ plantController.getPlant().getOperatingSoftware().setPumpRpm(1, sliderPump1RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump1RPM, 1);
layeredPane.add(sliderPump1RPM);
sliderPump2RPM = new JSlider();
sliderPump2RPM.setBounds(384, 581, 25, 108);
sliderPump2RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump2RPM.setOpaque(false);
sliderPump2RPM.setValue(0);
sliderPump2RPM.setMaximum(1000);
sliderPump2RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(2, sliderPump2RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump2RPM, 1);
layeredPane.add(sliderPump2RPM);
sliderPump3RPM = new JSlider();
sliderPump3RPM.setBounds(597, 581, 42, 108);
sliderPump3RPM.setOpaque(false);
sliderPump3RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump3RPM.setMaximum(1000);
sliderPump3RPM.setValue(0);
sliderPump3RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(3, sliderPump3RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump3RPM, 1);
layeredPane.add(sliderPump3RPM);
sliderRodsLevel = new JSlider();
sliderRodsLevel.setOpaque(false);
sliderRodsLevel.setBounds(27, 592, 25, 106);
sliderRodsLevel.setOrientation(SwingConstants.VERTICAL);
sliderRodsLevel.setValue(0);
sliderRodsLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setControlRods(100-sliderRodsLevel.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderRodsLevel, 1);
layeredPane.add(sliderRodsLevel);
//starts a new game when pressed
//and updates the gui
btnNewGame = new JButton(newGameImageIcon);
btnNewGame.setToolTipText("New Game");
btnNewGame.setMargin(new Insets(0,0,0,0));
btnNewGame.setBorder(null);
btnNewGame.setBounds(749, 17, 40, 40);
btnNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewGame.setEnabled(false);
//plantController.newGame(initialNameValue);
//updateGUI();
btnNewGame.setEnabled(true);
frmReactoree.dispose();
new GameTypeSelectionGUI();
}
});
layeredPane.setLayer(btnNewGame, 1);
layeredPane.add(btnNewGame);
//loads the saved game and updates the gui
btnLoad = new JButton(loadGameImageIcon);
btnLoad.setToolTipText("Load Game");
btnLoad.setMargin(new Insets(0,0,0,0));
btnLoad.setBorder(null);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.loadGame();
updateGUI();
}
});
btnLoad.setBounds(799, 17, 40, 40);
layeredPane.setLayer(btnLoad, 1);
layeredPane.add(btnLoad);
//if the current game is not over it saves it
btnSave = new JButton(saveGameImageIcon);
btnSave.setToolTipText("Save Game");
btnSave.setMargin(new Insets(0,0,0,0));
btnSave.setBorder(null);
btnSave.setBounds(849, 17, 40, 40);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnSave.setEnabled(false);
if(!plantController.getUIData().isGameOver())
plantController.saveGame();
btnSave.setEnabled(true);
}
});
layeredPane.setLayer(btnSave, 1);
layeredPane.add(btnSave);
//shows the scores so far
//by calling a function that instantiates the scoresGUI
btnShowScores = new JButton(viewScoresImageIcon);
btnShowScores.setToolTipText("Leaderboard");
btnShowScores.setMargin(new Insets(0,0,0,0));
btnShowScores.setBorder(null);
btnShowScores.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showScores();
}
});
btnShowScores.setBounds(949, 17, 40, 40);
layeredPane.setLayer(btnShowScores, 1);
layeredPane.add(btnShowScores);
//displays the user manual by opening it with its default program
btnShowManual = new JButton(viewManualImageIcon);
btnShowManual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
java.net.URL manualURL = this.getClass().getClassLoader().getResource("Manual3.pdf");
try{
Desktop.getDesktop().open(new File(manualURL.getPath()));
}catch (IOException e)
{
e.printStackTrace();
}
}
});
btnShowManual.setToolTipText("Manual");
btnShowManual.setMargin(new Insets(0,0,0,0));
btnShowManual.setBorder(null);
btnShowManual.setBounds(899, 17, 40, 40);
layeredPane.setLayer(btnShowManual, 1);
layeredPane.add(btnShowManual);
//when this button is pressed it takes the value of the sliderNumber of time steps,
//and issues a single time step at a time to the plant
//if the plant has not failed and updates the gui
//if the plant has failed - invokes the end game handler
btnStep = new JButton(nextStepImageIcon);
btnStep.setToolTipText("Step");
btnStep.setOpaque(false);
btnStep.setBounds(426, 500, 49, 39);
btnStep.setMargin(new Insets(0,0,0,0));
btnStep.setBorder(null);
btnStep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!plantController.getUIData().isGameOver()) {
plantController.togglePaused();
if(plantController.getPlant().isPaused())
btnStep.setIcon(nextStepImageIcon);
else
btnStep.setIcon(nextStepPausedImageIcon);
updateGUI();
}
if(plantController.getUIData().isGameOver())
{
//Show score and create a new game selection screen
//frame.dispose();
endGameHandler();
}
}
});
layeredPane.setLayer(btnStep, 1);
layeredPane.add(btnStep);
//used to open and close the first valve
btnValve1 = new JButton(valveOpenedImageIcon);
btnValve1.setBounds(860, 508, 59, 23);
btnValve1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(0).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(1, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(1, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve1, 1);
layeredPane.add(btnValve1);
//used to open and close the second valve
btnValve2 = new JButton(valveOpenedImageIcon);
btnValve2.setBounds(968, 508, 59, 23);
btnValve2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(1).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(2, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(2, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve2, 1);
layeredPane.add(btnValve2);
//issues a repair command to pump 1 if it is not operational
btnRepairPump1 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump1.setBounds(283, 626, 59, 57);
btnRepairPump1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(1);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump1.setMargin(new Insets(0,0,0,0));
btnRepairPump1.setBorder(null);
layeredPane.setLayer(btnRepairPump1, 1);
layeredPane.add(btnRepairPump1);
//issues a repair command to pump 2 if it is not operational
btnRepairPump2 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump2.setBounds(506, 626, 59, 57);
btnRepairPump2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(2);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump2.setMargin(new Insets(0,0,0,0));
btnRepairPump2.setBorder(null);
layeredPane.setLayer(btnRepairPump2, 1);
layeredPane.add(btnRepairPump2);
//issues a repair command to pump 3 if it is not operational
btnRepairPump3 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump3.setBounds(726, 626, 59, 57);
btnRepairPump3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(3);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump3.setMargin(new Insets(0,0,0,0));
btnRepairPump3.setBorder(null);
layeredPane.setLayer(btnRepairPump3, 1);
layeredPane.add(btnRepairPump3);
//issues a repair command to the turbine if it is not operational
btnRepairTurbine = new JButton(repairButtonDisabledImageIcon);
btnRepairTurbine.setBounds(836, 626, 59, 57);
btnRepairTurbine.setMargin(new Insets(0,0,0,0));
btnRepairTurbine.setBorder(null);
btnRepairTurbine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isTurbineFunctional() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairTurbine();
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(btnRepairTurbine, 1);
layeredPane.add(btnRepairTurbine);
//directly repairs the operating software - commands from this button are directly
//executed by the plant and cannot fail
btnRepairOperatingSoftware = new JButton(repairButtonDisabledImageIcon);
btnRepairOperatingSoftware.setPreferredSize(new Dimension(93, 71));
btnRepairOperatingSoftware.setBounds(937, 626, 59, 57);
btnRepairOperatingSoftware.setMargin(new Insets(0,0,0,0));
btnRepairOperatingSoftware.setBorder(null);
btnRepairOperatingSoftware.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isOperatingSoftwareFunctional())
{
plantController.repairOperatingSoftware();
updateGUI();
}
}
});
btnQuench = new JButton("QUENCH!");
btnQuench.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/btnRepairDisabled.png")));
btnQuench.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.getPlant().getOperatingSoftware().quench();
plantController.executeStoredCommand();
updateGUI();
}
});
layeredPane.setLayer(btnQuench, 1);
btnQuench.setBounds(70, 626, 59, 62);
layeredPane.add(btnQuench);
layeredPane.setLayer(btnRepairOperatingSoftware, 1);
layeredPane.add(btnRepairOperatingSoftware);
//adds change listeners to the progress bars. Every time a bar's value is changed,
//the colour of the bar changes depending on what is its value
//temperature and pressure bars change colour smoothly from blue to red
//health pressure bars change colour smoothly from red to green
progressBarCondenserHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarCondenserHealth);
}
});
progressBarCondenserPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserPressure);
}
});
progressBarCondenserTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserTemperature);
}
});
progressBarReactorWaterLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorWaterLevel);
}
});
progressBarReactorHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorHealth);
}
});
progressBarReactorPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorPressure);
}
});
progressBarReactorTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorTemperature);
}
});
//after everything but the name is set the gui is updates so it
//synchronises with the plant
updateGUI();
nameTextField.setText(initialNameValue);
}
| private void initialize()
{
//instantiates the main frame
frmReactoree = new JFrame();
frmReactoree.setTitle("ReactorEE");
frmReactoree.setBounds(100, 100, 1049, 740);
frmReactoree.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//which is layered - two layers: background picture - layer 0
//all interactive components - layer 1
frmReactoree.getContentPane().add(layeredPane, BorderLayout.CENTER);
//loads and sets the background image
java.net.URL imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/plantBackground.png");
ImageIcon backgroundImageIcon = new ImageIcon(imageURL);
warningLabel = new JLabel("Warning");
warningLabel.setToolTipText("Reactor is overheating!");
warningLabel.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/animates.gif")));
warningLabel.setBounds(27, 58, 500, 500);
layeredPane.add(warningLabel);
warningLabel.setVisible(false);
JLabel backgroundImageLabel = new JLabel(backgroundImageIcon);
backgroundImageLabel.setBackground(new Color(0, 153, 0));
backgroundImageLabel.setBounds(0, 0, 1040, 709);
layeredPane.add(backgroundImageLabel);
//loads all the images that are required for the image labels
//the path is relative to the project
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairEnabled.png");
repairButtonEnabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/btnRepairDisabled.png");
repairButtonDisabledImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateSafe.png");
stateSafeImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBeingRepaired.png");
stateBeingRepairedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/stateBroken.png");
stateBrokenImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveOpened.png");
valveOpenedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/valveClosed.png");
valveClosedImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/newButtonLabel.png");
newGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/loadButtonLabel.png");
loadGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/saveButtonLabel.png");
saveGameImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/manualButtonLabel.png");
viewManualImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/scoresButtonLabel.png");
viewScoresImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonLabel.png");
nextStepImageIcon = new ImageIcon(imageURL);
imageURL = this.getClass().getClassLoader().getResource("ReactorEE/graphics/nextButtonPausedLabel.png");
nextStepPausedImageIcon = new ImageIcon(imageURL);
//initialises the label that shows the score
lblScore = new JLabel("0");
lblScore.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblScore.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
lblScore.setBounds(860, 81, 160, 23);
layeredPane.setLayer(lblScore, 1);
layeredPane.add(lblScore);
//the player should type in their name in that text field
//when the field loses focus the text is checked and if it is not
//empty or bigger than 15 characters, it is set as the operator's name
//if the text is bigger than 15 characters only the first 15 are used
//if the text field is empty, the initial text is set put it
nameTextField = new JTextField(initialNameValue);
nameTextField.setFont(new Font("OCR A Std", Font.PLAIN, 15));
nameTextField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
nameTextField.setColumns(20);
nameTextField.setOpaque(false);
nameTextField.setBorder(null);
nameTextField.setBounds(0, 14, 117, 20);
nameTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
nameTextField.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
if(nameTextField.getText() == "")
{
nameTextField.setText(initialNameValue);
nameTextField.selectAll();
}
else
if(nameTextField.getText().length() > 15)
plantController.getPlant().setOperatorName(nameTextField.getText().substring(0,15));
else plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
nameTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(nameTextField.getText() != "")
plantController.getPlant().setOperatorName(nameTextField.getText());
}
});
layeredPane.setLayer(nameTextField, 1);
layeredPane.add(nameTextField);
//all the labels that show component states are
//initialised with green light showing
lblPump1State = new JLabel(stateSafeImageIcon);
lblPump1State.setBounds(273, 592, 78, 23);
layeredPane.setLayer(lblPump1State, 1);
layeredPane.add(lblPump1State);
lblPump2State = new JLabel(stateSafeImageIcon);
lblPump2State.setBounds(496, 592, 78, 23);
layeredPane.setLayer(lblPump2State, 1);
layeredPane.add(lblPump2State);
lblPump3State = new JLabel(stateSafeImageIcon);
lblPump3State.setBounds(716, 592, 78, 23);
layeredPane.setLayer(lblPump3State, 1);
layeredPane.add(lblPump3State);
lblTurbineState = new JLabel(stateSafeImageIcon);
lblTurbineState.setBounds(826, 592, 78, 23);
layeredPane.setLayer(lblTurbineState, 1);
layeredPane.add(lblTurbineState);
lblOperatingSoftwareState = new JLabel(stateSafeImageIcon);
lblOperatingSoftwareState.setBounds(927, 592, 78, 23);
layeredPane.setLayer(lblOperatingSoftwareState, 1);
layeredPane.add(lblOperatingSoftwareState);
//creation and instantiation of the progress bars
//change state listeners added at the end of this method
progressBarReactorTemperature = new JProgressBar();
progressBarReactorTemperature.setBounds(781, 168, 234, 14);
layeredPane.setLayer(progressBarReactorTemperature, 1);
layeredPane.add(progressBarReactorTemperature);
progressBarReactorPressure = new JProgressBar();
progressBarReactorPressure.setBounds(781, 203, 234, 14);
layeredPane.setLayer(progressBarReactorPressure, 1);
layeredPane.add(progressBarReactorPressure);
progressBarReactorHealth = new JProgressBar();
progressBarReactorHealth.setBounds(781, 273, 234, 14);
layeredPane.setLayer(progressBarReactorHealth, 1);
layeredPane.add(progressBarReactorHealth);
progressBarReactorWaterLevel = new JProgressBar();
progressBarReactorWaterLevel.setBounds(781, 237, 234, 14);
layeredPane.setLayer(progressBarReactorWaterLevel, 1);
layeredPane.add(progressBarReactorWaterLevel);
progressBarCondenserTemperature = new JProgressBar();
progressBarCondenserTemperature.setBounds(781, 359, 234, 14);
layeredPane.setLayer(progressBarCondenserTemperature, 1);
layeredPane.add(progressBarCondenserTemperature);
progressBarCondenserPressure = new JProgressBar();
progressBarCondenserPressure.setBounds(781, 394, 234, 14);
layeredPane.setLayer(progressBarCondenserPressure, 1);
layeredPane.add(progressBarCondenserPressure);
progressBarCondenserHealth = new JProgressBar();
progressBarCondenserHealth.setBounds(781, 468, 234, 14);
layeredPane.setLayer(progressBarCondenserHealth, 1);
layeredPane.add(progressBarCondenserHealth);
progressBarCondenserWaterLevel = new JProgressBar();
progressBarCondenserWaterLevel.setBounds(781, 430, 234, 14);
progressBarCondenserWaterLevel.setForeground(new Color(0, 255, 0));
layeredPane.setLayer(progressBarCondenserWaterLevel, 1);
layeredPane.add(progressBarCondenserWaterLevel);
//creation and instantiation of the sliders
//every slider calls the appropriate method in the OperatingSoftware
//requests its execution from the plantController
//and updates the gui
sliderPump1RPM = new JSlider();
sliderPump1RPM.setOpaque(false);
sliderPump1RPM.setBounds(173, 581, 25, 108);
sliderPump1RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump1RPM.setMaximum(1000);
sliderPump1RPM.setValue(0);
sliderPump1RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{ plantController.getPlant().getOperatingSoftware().setPumpRpm(1, sliderPump1RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump1RPM, 1);
layeredPane.add(sliderPump1RPM);
sliderPump2RPM = new JSlider();
sliderPump2RPM.setBounds(384, 581, 25, 108);
sliderPump2RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump2RPM.setOpaque(false);
sliderPump2RPM.setValue(0);
sliderPump2RPM.setMaximum(1000);
sliderPump2RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(2, sliderPump2RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump2RPM, 1);
layeredPane.add(sliderPump2RPM);
sliderPump3RPM = new JSlider();
sliderPump3RPM.setBounds(597, 581, 42, 108);
sliderPump3RPM.setOpaque(false);
sliderPump3RPM.setOrientation(SwingConstants.VERTICAL);
sliderPump3RPM.setMaximum(1000);
sliderPump3RPM.setValue(0);
sliderPump3RPM.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if(plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setPumpRpm(3, sliderPump3RPM.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderPump3RPM, 1);
layeredPane.add(sliderPump3RPM);
sliderRodsLevel = new JSlider();
sliderRodsLevel.setOpaque(false);
sliderRodsLevel.setBounds(27, 592, 25, 106);
sliderRodsLevel.setOrientation(SwingConstants.VERTICAL);
sliderRodsLevel.setValue(0);
sliderRodsLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().setControlRods(100-sliderRodsLevel.getValue());
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(sliderRodsLevel, 1);
layeredPane.add(sliderRodsLevel);
//starts a new game when pressed
//and updates the gui
btnNewGame = new JButton(newGameImageIcon);
btnNewGame.setToolTipText("New Game");
btnNewGame.setMargin(new Insets(0,0,0,0));
btnNewGame.setBorder(null);
btnNewGame.setBounds(749, 17, 40, 40);
btnNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnNewGame.setEnabled(false);
//plantController.newGame(initialNameValue);
//updateGUI();
btnNewGame.setEnabled(true);
frmReactoree.dispose();
new GameTypeSelectionGUI();
}
});
layeredPane.setLayer(btnNewGame, 1);
layeredPane.add(btnNewGame);
//loads the saved game and updates the gui
btnLoad = new JButton(loadGameImageIcon);
btnLoad.setToolTipText("Load Game");
btnLoad.setMargin(new Insets(0,0,0,0));
btnLoad.setBorder(null);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.loadGame();
updateGUI();
}
});
btnLoad.setBounds(799, 17, 40, 40);
layeredPane.setLayer(btnLoad, 1);
layeredPane.add(btnLoad);
//if the current game is not over it saves it
btnSave = new JButton(saveGameImageIcon);
btnSave.setToolTipText("Save Game");
btnSave.setMargin(new Insets(0,0,0,0));
btnSave.setBorder(null);
btnSave.setBounds(849, 17, 40, 40);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnSave.setEnabled(false);
if(!plantController.getUIData().isGameOver())
plantController.saveGame();
btnSave.setEnabled(true);
}
});
layeredPane.setLayer(btnSave, 1);
layeredPane.add(btnSave);
//shows the scores so far
//by calling a function that instantiates the scoresGUI
btnShowScores = new JButton(viewScoresImageIcon);
btnShowScores.setToolTipText("Leaderboard");
btnShowScores.setMargin(new Insets(0,0,0,0));
btnShowScores.setBorder(null);
btnShowScores.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showScores();
}
});
btnShowScores.setBounds(949, 17, 40, 40);
layeredPane.setLayer(btnShowScores, 1);
layeredPane.add(btnShowScores);
//displays the user manual by opening it with its default program
btnShowManual = new JButton(viewManualImageIcon);
btnShowManual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
java.net.URL manualURL = this.getClass().getClassLoader().getResource("Manual3.pdf");
try{
Desktop.getDesktop().open(new File(manualURL.getPath()));
}catch (IOException e)
{
e.printStackTrace();
}
}
});
btnShowManual.setToolTipText("Manual");
btnShowManual.setMargin(new Insets(0,0,0,0));
btnShowManual.setBorder(null);
btnShowManual.setBounds(899, 17, 40, 40);
layeredPane.setLayer(btnShowManual, 1);
layeredPane.add(btnShowManual);
//when this button is pressed it takes the value of the sliderNumber of time steps,
//and issues a single time step at a time to the plant
//if the plant has not failed and updates the gui
//if the plant has failed - invokes the end game handler
btnStep = new JButton(nextStepImageIcon);
btnStep.setToolTipText("Step");
btnStep.setOpaque(false);
btnStep.setBounds(426, 500, 49, 39);
btnStep.setMargin(new Insets(0,0,0,0));
btnStep.setBorder(null);
btnStep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!plantController.getUIData().isGameOver()) {
plantController.togglePaused();
if(plantController.getPlant().isPaused())
btnStep.setIcon(nextStepImageIcon);
else
btnStep.setIcon(nextStepPausedImageIcon);
updateGUI();
}
if(plantController.getUIData().isGameOver())
{
//Show score and create a new game selection screen
//frame.dispose();
endGameHandler();
}
}
});
layeredPane.setLayer(btnStep, 1);
layeredPane.add(btnStep);
//used to open and close the first valve
btnValve1 = new JButton(valveOpenedImageIcon);
btnValve1.setBounds(860, 508, 59, 23);
btnValve1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(0).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(1, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(1, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve1, 1);
layeredPane.add(btnValve1);
//used to open and close the second valve
btnValve2 = new JButton(valveOpenedImageIcon);
btnValve2.setBounds(968, 508, 59, 23);
btnValve2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (controlButtonsEnabled)
{
//checks if the valve 1 state and alternates it
if (plantController.getUIData().getValves().get(1).isOpen())
{
plantController.getPlant().getOperatingSoftware().setValve(2, false);
plantController.executeStoredCommand();
updateGUI();
} else
{
plantController.getPlant().getOperatingSoftware().setValve(2, true);
plantController.executeStoredCommand();
updateGUI();
}
}
}
});
layeredPane.setLayer(btnValve2, 1);
layeredPane.add(btnValve2);
//issues a repair command to pump 1 if it is not operational
btnRepairPump1 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump1.setBounds(283, 626, 59, 57);
btnRepairPump1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(0).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(1);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump1.setMargin(new Insets(0,0,0,0));
btnRepairPump1.setBorder(null);
layeredPane.setLayer(btnRepairPump1, 1);
layeredPane.add(btnRepairPump1);
//issues a repair command to pump 2 if it is not operational
btnRepairPump2 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump2.setBounds(506, 626, 59, 57);
btnRepairPump2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(1).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(2);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump2.setMargin(new Insets(0,0,0,0));
btnRepairPump2.setBorder(null);
layeredPane.setLayer(btnRepairPump2, 1);
layeredPane.add(btnRepairPump2);
//issues a repair command to pump 3 if it is not operational
btnRepairPump3 = new JButton(repairButtonDisabledImageIcon);
btnRepairPump3.setBounds(726, 626, 59, 57);
btnRepairPump3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().getPumps().get(2).isOperational() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairPump(3);
plantController.executeStoredCommand();
updateGUI();
}
}
});
btnRepairPump3.setMargin(new Insets(0,0,0,0));
btnRepairPump3.setBorder(null);
layeredPane.setLayer(btnRepairPump3, 1);
layeredPane.add(btnRepairPump3);
//issues a repair command to the turbine if it is not operational
btnRepairTurbine = new JButton(repairButtonDisabledImageIcon);
btnRepairTurbine.setBounds(836, 626, 59, 57);
btnRepairTurbine.setMargin(new Insets(0,0,0,0));
btnRepairTurbine.setBorder(null);
btnRepairTurbine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isTurbineFunctional() && controlButtonsEnabled)
{
plantController.getPlant().getOperatingSoftware().repairTurbine();
plantController.executeStoredCommand();
updateGUI();
}
}
});
layeredPane.setLayer(btnRepairTurbine, 1);
layeredPane.add(btnRepairTurbine);
//directly repairs the operating software - commands from this button are directly
//executed by the plant and cannot fail
btnRepairOperatingSoftware = new JButton(repairButtonDisabledImageIcon);
btnRepairOperatingSoftware.setPreferredSize(new Dimension(93, 71));
btnRepairOperatingSoftware.setBounds(937, 626, 59, 57);
btnRepairOperatingSoftware.setMargin(new Insets(0,0,0,0));
btnRepairOperatingSoftware.setBorder(null);
btnRepairOperatingSoftware.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!plantController.getUIData().isOperatingSoftwareFunctional())
{
plantController.repairOperatingSoftware();
updateGUI();
}
}
});
btnQuench = new JButton("QUENCH!");
btnQuench.setIcon(new ImageIcon(MainGUI.class.getResource("/ReactorEE/graphics/btnRepairDisabled.png")));
btnQuench.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
plantController.getPlant().getOperatingSoftware().quench();
plantController.executeStoredCommand();
updateGUI();
}
});
layeredPane.setLayer(btnQuench, 1);
btnQuench.setBounds(70, 626, 59, 62);
layeredPane.add(btnQuench);
layeredPane.setLayer(btnRepairOperatingSoftware, 1);
layeredPane.add(btnRepairOperatingSoftware);
//adds change listeners to the progress bars. Every time a bar's value is changed,
//the colour of the bar changes depending on what is its value
//temperature and pressure bars change colour smoothly from blue to red
//health pressure bars change colour smoothly from red to green
progressBarCondenserHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarCondenserHealth);
}
});
progressBarCondenserPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserPressure);
}
});
progressBarCondenserTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarCondenserTemperature);
}
});
progressBarReactorWaterLevel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorWaterLevel);
}
});
progressBarReactorHealth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarRedToGreen(progressBarReactorHealth);
}
});
progressBarReactorPressure.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorPressure);
}
});
progressBarReactorTemperature.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
colourProgressBarBlueToRed(progressBarReactorTemperature);
}
});
//after everything but the name is set the gui is updates so it
//synchronises with the plant
updateGUI();
nameTextField.setText(initialNameValue);
}
|
diff --git a/src/main/java/org/hampelratte/net/mms/client/MMSClient.java b/src/main/java/org/hampelratte/net/mms/client/MMSClient.java
index 8666a0b..8d0f97d 100644
--- a/src/main/java/org/hampelratte/net/mms/client/MMSClient.java
+++ b/src/main/java/org/hampelratte/net/mms/client/MMSClient.java
@@ -1,246 +1,246 @@
package org.hampelratte.net.mms.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.hampelratte.net.mms.MMSObject;
import org.hampelratte.net.mms.client.listeners.MMSMessageListener;
import org.hampelratte.net.mms.client.listeners.MMSPacketListener;
import org.hampelratte.net.mms.data.MMSPacket;
import org.hampelratte.net.mms.messages.MMSMessage;
import org.hampelratte.net.mms.messages.client.CancelProtocol;
import org.hampelratte.net.mms.messages.client.MMSRequest;
import org.hampelratte.net.mms.messages.client.StartPlaying;
import org.hampelratte.net.mms.messages.server.ReportOpenFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MMSClient extends IoHandlerAdapter {
private static transient Logger logger = LoggerFactory.getLogger(MMSClient.class);
/** Connect timeout in millisecods */
public static int CONNECT_TIMEOUT = 30000;
private List<MMSMessageListener> messageListeners = new ArrayList<MMSMessageListener>();
private List<MMSPacketListener> packetListeners = new ArrayList<MMSPacketListener>();
private List<IoHandler> additionalIoHandlers = new ArrayList<IoHandler>();
private String host;
private int port;
private SocketConnector connector;
private IoSession session;
private MMSNegotiator negotiator;
private long lastUpdate = 0;
private long packetsReceived = 0;
private long packetsreceivedAtLastLog = 0;
public MMSClient(String host, int port, MMSNegotiator negotiator) {
this.host = host;
this.port = port;
connector = new NioSocketConnector();
//connector.getFilterChain().addFirst("logger", new RawInputStreamDumpFilter());
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ClientProtocolCodecFactory()));
connector.setHandler(this);
this.negotiator = negotiator;
this.addMessageListener(negotiator);
this.addPacketListener(negotiator);
}
// TODO fehler abfangen wie z.b. ein connect timeout
public void connect() throws Exception {
ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
- connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
- session = connectFuture.getSession();
if(connectFuture != null) {
+ connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
+ session = connectFuture.getSession();
connectFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture cf) {
// set throughput calculation interval
session.getConfig().setThroughputCalculationInterval(1);
// set the first sequence number
session.setAttribute("mms.sequence", 0);
// start the streaming negotiation
negotiator.start(session);
}
});
} else {
exceptionCaught(session, new IOException("Connect to host failed"));
}
}
public void disconnect(IoFutureListener<IoFuture> listener) {
sendRequest(new CancelProtocol());
// cancel protocol doesn't work -> kill the connection
if (session != null) {
CloseFuture future = session.close(true);
future.addListener(listener);
}
if(connector != null) {
connector.dispose();
}
}
public void sendRequest(MMSRequest request) {
if (session == null) {
throw new RuntimeException("Not connected");
} else {
session.write(request);
logger.debug("--OUT--> " + request.toString());
}
}
public void messageReceived(IoSession session, Object message) throws Exception {
for (IoHandler handler : additionalIoHandlers) {
handler.messageReceived(session, message);
}
MMSObject mmso = (MMSObject) message;
if(mmso instanceof MMSMessage) {
logger.debug("<--IN-- " + mmso.toString());
fireMessageReceived(mmso);
} else {
if( (++packetsReceived - packetsreceivedAtLastLog) >= 100) {
packetsreceivedAtLastLog = packetsReceived;
logger.debug("{} data packets received", packetsReceived);
}
firePacketReceived(mmso);
}
}
private void firePacketReceived(MMSObject mmso) {
for (MMSPacketListener listener : packetListeners) {
listener.packetReceived((MMSPacket) mmso);
}
}
private void fireMessageReceived(MMSObject mmso) {
for (MMSMessageListener listener : messageListeners) {
listener.messageReceived((MMSMessage) mmso);
}
}
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
logger.warn("Exception occured", cause);
for (IoHandler handler : additionalIoHandlers) {
handler.exceptionCaught(session, cause);
}
}
@Override
public void sessionClosed(IoSession iosession) throws Exception {
super.sessionClosed(iosession);
logger.info("MMS connection closed");
for (IoHandler handler : additionalIoHandlers) {
handler.sessionClosed(iosession);
}
}
public void addMessageListener(MMSMessageListener listener) {
messageListeners.add(listener);
}
public void removeMessageListener(MMSMessageListener listener) {
messageListeners.remove(listener);
}
public void addPacketListener(MMSPacketListener listener) {
packetListeners.add(listener);
}
public void removePacketListener(MMSPacketListener listener) {
packetListeners.remove(listener);
}
public void addAdditionalIoHandler(IoHandler handler) {
additionalIoHandlers.add(handler);
}
public void removeAdditionalIoHandler(IoHandler handler) {
additionalIoHandlers.remove(handler);
}
public double getSpeed() {
if(session != null) {
if( (System.currentTimeMillis() - lastUpdate) > 1000) {
lastUpdate = System.currentTimeMillis();
session.updateThroughput(System.currentTimeMillis(), true);
}
return session.getReadBytesThroughput() / 1024;
}
return 0;
}
@Override
public void messageSent(IoSession iosession, Object obj) throws Exception {
super.messageSent(iosession, obj);
for (IoHandler handler : additionalIoHandlers) {
handler.messageSent(iosession, obj);
}
}
@Override
public void sessionCreated(IoSession iosession) throws Exception {
super.sessionCreated(iosession);
for (IoHandler handler : additionalIoHandlers) {
handler.sessionCreated(iosession);
}
}
@Override
public void sessionIdle(IoSession iosession, IdleStatus idlestatus) throws Exception {
super.sessionIdle(iosession, idlestatus);
for (IoHandler handler : additionalIoHandlers) {
handler.sessionIdle(iosession, idlestatus);
}
}
@Override
public void sessionOpened(IoSession iosession) throws Exception {
super.sessionOpened(iosession);
for (IoHandler handler : additionalIoHandlers) {
handler.sessionOpened(iosession);
}
}
/**
* Starts the streaming
* @param startPacket the packetNumber from which the streaming should start
*/
public void startStreaming(long startPacket) {
StartPlaying sp = new StartPlaying();
ReportOpenFile rof = (ReportOpenFile) session.getAttribute(ReportOpenFile.class);
sp.setOpenFileId(rof.getOpenFileId());
/* this confuses me: we use the packet number to seek the start of streaming.
* in my opinion we should have to use setLocationId for packet numbers, but it
* only works correctly with setAsfOffset ?!?
* maybe the sequence of the values is wrong in the spec */
sp.setPosition(Double.MAX_VALUE);
sp.setLocationId(0xFFFFFFFF);
if(startPacket > 0) {
sp.setAsfOffset(startPacket);
}
sendRequest(sp);
}
}
| false | true | public void connect() throws Exception {
ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
session = connectFuture.getSession();
if(connectFuture != null) {
connectFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture cf) {
// set throughput calculation interval
session.getConfig().setThroughputCalculationInterval(1);
// set the first sequence number
session.setAttribute("mms.sequence", 0);
// start the streaming negotiation
negotiator.start(session);
}
});
} else {
exceptionCaught(session, new IOException("Connect to host failed"));
}
}
| public void connect() throws Exception {
ConnectFuture connectFuture = connector.connect(new InetSocketAddress(host, port));
if(connectFuture != null) {
connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
session = connectFuture.getSession();
connectFuture.addListener(new IoFutureListener<ConnectFuture>() {
public void operationComplete(ConnectFuture cf) {
// set throughput calculation interval
session.getConfig().setThroughputCalculationInterval(1);
// set the first sequence number
session.setAttribute("mms.sequence", 0);
// start the streaming negotiation
negotiator.start(session);
}
});
} else {
exceptionCaught(session, new IOException("Connect to host failed"));
}
}
|
diff --git a/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java b/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java
index 6c1a63df1..49aa58f15 100644
--- a/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java
+++ b/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java
@@ -1,310 +1,310 @@
/*
* Copyright 2005-2008 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package com.noelios.restlet.ext.httpclient;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.logging.Level;
import org.apache.commons.httpclient.ConnectMethod;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.TraceMethod;
import org.restlet.data.Method;
import org.restlet.data.Parameter;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.util.Series;
import com.noelios.restlet.http.HttpClientCall;
/**
* HTTP client connector call based on Apache HTTP Client's HttpMethod class.
*
* @author Jerome Louvel ([email protected])
*/
public class HttpMethodCall extends HttpClientCall {
/** The associated HTTP client. */
private volatile HttpClientHelper clientHelper;
/** The wrapped HTTP method. */
private volatile HttpMethod httpMethod;
/** Indicates if the response headers were added. */
private volatile boolean responseHeadersAdded;
/**
* Constructor.
*
* @param helper
* The parent HTTP client helper.
* @param method
* The method name.
* @param requestUri
* The request URI.
* @param hasEntity
* Indicates if the call will have an entity to send to the
* server.
* @throws IOException
*/
public HttpMethodCall(HttpClientHelper helper, final String method,
String requestUri, boolean hasEntity) throws IOException {
super(helper, method, requestUri);
this.clientHelper = helper;
if (requestUri.startsWith("http")) {
if (method.equalsIgnoreCase(Method.GET.getName())) {
this.httpMethod = new GetMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.POST.getName())) {
this.httpMethod = new PostMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.PUT.getName())) {
this.httpMethod = new PutMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
this.httpMethod = new HeadMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
this.httpMethod = new DeleteMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
HostConfiguration host = new HostConfiguration();
host.setHost(new URI(requestUri, false));
this.httpMethod = new ConnectMethod(host);
} else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
this.httpMethod = new OptionsMethod(requestUri);
} else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
this.httpMethod = new TraceMethod(requestUri);
} else {
this.httpMethod = new EntityEnclosingMethod(requestUri) {
@Override
public String getName() {
return method;
}
};
}
this.httpMethod.setFollowRedirects(this.clientHelper
.isFollowRedirects());
this.httpMethod.setDoAuthentication(false);
this.responseHeadersAdded = false;
setConfidential(this.httpMethod.getURI().getScheme()
.equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
} else {
throw new IllegalArgumentException(
"Only HTTP or HTTPS resource URIs are allowed here");
}
}
/**
* Returns the HTTP method.
*
* @return The HTTP method.
*/
public HttpMethod getHttpMethod() {
return this.httpMethod;
}
/**
* Returns the response reason phrase.
*
* @return The response reason phrase.
*/
@Override
public String getReasonPhrase() {
return getHttpMethod().getStatusText();
}
@Override
public WritableByteChannel getRequestEntityChannel() {
return null;
}
@Override
public OutputStream getRequestEntityStream() {
return null;
}
@Override
public OutputStream getRequestHeadStream() {
return null;
}
@Override
public ReadableByteChannel getResponseEntityChannel(long size) {
return null;
}
@Override
public InputStream getResponseEntityStream(long size) {
InputStream result = null;
try {
// Return a wrapper filter that will release the connection when
// needed
InputStream responseBodyAsStream = getHttpMethod()
.getResponseBodyAsStream();
if (responseBodyAsStream != null) {
result = new FilterInputStream(responseBodyAsStream) {
@Override
public void close() throws IOException {
super.close();
getHttpMethod().releaseConnection();
}
};
}
} catch (IOException ioe) {
}
return result;
}
/**
* Returns the modifiable list of response headers.
*
* @return The modifiable list of response headers.
*/
@Override
public Series<Parameter> getResponseHeaders() {
Series<Parameter> result = super.getResponseHeaders();
if (!this.responseHeadersAdded) {
for (Header header : getHttpMethod().getResponseHeaders()) {
result.add(header.getName(), header.getValue());
}
this.responseHeadersAdded = true;
}
return result;
}
/**
* Returns the response address.<br>
* Corresponds to the IP address of the responding server.
*
* @return The response address.
*/
@Override
public String getServerAddress() {
try {
return getHttpMethod().getURI().getHost();
} catch (URIException e) {
return null;
}
}
/**
* Returns the response status code.
*
* @return The response status code.
*/
@Override
public int getStatusCode() {
return getHttpMethod().getStatusCode();
}
/**
* Sends the request to the client. Commits the request line, headers and
* optional entity and send them over the network.
*
* @param request
* The high-level request.
* @return The result status.
*/
@Override
public Status sendRequest(Request request) {
Status result = null;
try {
final Representation entity = request.getEntity();
// Set the request headers
for (Parameter header : getRequestHeaders()) {
- getHttpMethod().setRequestHeader(header.getName(),
+ getHttpMethod().addRequestHeader(header.getName(),
header.getValue());
}
// For those method that accept enclosing entites, provide it
if ((entity != null)
&& (getHttpMethod() instanceof EntityEnclosingMethod)) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod();
eem.setRequestEntity(new RequestEntity() {
public long getContentLength() {
return entity.getSize();
}
public String getContentType() {
return (entity.getMediaType() != null) ? entity
.getMediaType().toString() : null;
}
public boolean isRepeatable() {
return !entity.isTransient();
}
public void writeRequest(OutputStream os)
throws IOException {
entity.write(os);
}
});
}
// Ensure that the connection is active
this.clientHelper.getHttpClient().executeMethod(getHttpMethod());
// Now we can access the status code, this MUST happen after closing
// any open request stream.
result = new Status(getStatusCode(), null, getReasonPhrase(), null);
// If there is no response body, immediately release the connection
if (getHttpMethod().getResponseBodyAsStream() == null) {
getHttpMethod().releaseConnection();
}
} catch (IOException ioe) {
this.clientHelper
.getLogger()
.log(
Level.WARNING,
"An error occurred during the communication with the remote HTTP server.",
ioe);
result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
// Release the connection
getHttpMethod().releaseConnection();
}
return result;
}
}
| true | true | public Status sendRequest(Request request) {
Status result = null;
try {
final Representation entity = request.getEntity();
// Set the request headers
for (Parameter header : getRequestHeaders()) {
getHttpMethod().setRequestHeader(header.getName(),
header.getValue());
}
// For those method that accept enclosing entites, provide it
if ((entity != null)
&& (getHttpMethod() instanceof EntityEnclosingMethod)) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod();
eem.setRequestEntity(new RequestEntity() {
public long getContentLength() {
return entity.getSize();
}
public String getContentType() {
return (entity.getMediaType() != null) ? entity
.getMediaType().toString() : null;
}
public boolean isRepeatable() {
return !entity.isTransient();
}
public void writeRequest(OutputStream os)
throws IOException {
entity.write(os);
}
});
}
// Ensure that the connection is active
this.clientHelper.getHttpClient().executeMethod(getHttpMethod());
// Now we can access the status code, this MUST happen after closing
// any open request stream.
result = new Status(getStatusCode(), null, getReasonPhrase(), null);
// If there is no response body, immediately release the connection
if (getHttpMethod().getResponseBodyAsStream() == null) {
getHttpMethod().releaseConnection();
}
} catch (IOException ioe) {
this.clientHelper
.getLogger()
.log(
Level.WARNING,
"An error occurred during the communication with the remote HTTP server.",
ioe);
result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
// Release the connection
getHttpMethod().releaseConnection();
}
return result;
}
| public Status sendRequest(Request request) {
Status result = null;
try {
final Representation entity = request.getEntity();
// Set the request headers
for (Parameter header : getRequestHeaders()) {
getHttpMethod().addRequestHeader(header.getName(),
header.getValue());
}
// For those method that accept enclosing entites, provide it
if ((entity != null)
&& (getHttpMethod() instanceof EntityEnclosingMethod)) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod();
eem.setRequestEntity(new RequestEntity() {
public long getContentLength() {
return entity.getSize();
}
public String getContentType() {
return (entity.getMediaType() != null) ? entity
.getMediaType().toString() : null;
}
public boolean isRepeatable() {
return !entity.isTransient();
}
public void writeRequest(OutputStream os)
throws IOException {
entity.write(os);
}
});
}
// Ensure that the connection is active
this.clientHelper.getHttpClient().executeMethod(getHttpMethod());
// Now we can access the status code, this MUST happen after closing
// any open request stream.
result = new Status(getStatusCode(), null, getReasonPhrase(), null);
// If there is no response body, immediately release the connection
if (getHttpMethod().getResponseBodyAsStream() == null) {
getHttpMethod().releaseConnection();
}
} catch (IOException ioe) {
this.clientHelper
.getLogger()
.log(
Level.WARNING,
"An error occurred during the communication with the remote HTTP server.",
ioe);
result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe);
// Release the connection
getHttpMethod().releaseConnection();
}
return result;
}
|
diff --git a/src/test/java/functional/com/thoughtworks/twu/TakeDownOfferFunctionalTest.java b/src/test/java/functional/com/thoughtworks/twu/TakeDownOfferFunctionalTest.java
index 82f0283..4bfcdd2 100644
--- a/src/test/java/functional/com/thoughtworks/twu/TakeDownOfferFunctionalTest.java
+++ b/src/test/java/functional/com/thoughtworks/twu/TakeDownOfferFunctionalTest.java
@@ -1,142 +1,144 @@
package functional.com.thoughtworks.twu;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class TakeDownOfferFunctionalTest {
private WebDriver webDriver;
private String username;
private String password;
@Before
public void setUp() {
webDriver = new FirefoxDriver();
username = "test.twu";
password = "Th0ughtW0rks@12";
}
@Test
public void shouldGoToHomeAfterHideAnOffer() throws Exception {
logIn();
Thread.sleep(1000);
webDriver.findElement(By.id("createOffer")).click();
String offerTitle = "TITLE_"+ GregorianCalendar.getInstance().getTime().getTime();
webDriver.findElement(By.name("title")).sendKeys(offerTitle);
Select select = new Select(webDriver.findElement(By.tagName("select")));
select.selectByValue("Cars");
webDriver.findElement(By.name("description")).sendKeys("To pass the test or not, this is a question");
webDriver.findElement(By.name("submit")).click();
Thread.sleep(1000);
webDriver.findElement(By.id("takeDownButton")).click();
String pageTitle = webDriver.getTitle();
String expectedPageTitle = "Home";
assertThat(pageTitle, is(expectedPageTitle));
}
@Test
public void shouldNotDisplayHiddenOfferInBrowsePageAfterTakeDown() throws Exception {
logIn();
- Thread.sleep(1000);
+// Thread.sleep(1000);
+ WebDriverWait waitToBrowse = new WebDriverWait(webDriver, 1000);
+ waitToBrowse.until(ExpectedConditions.visibilityOfElementLocated(By.id("browse")));
webDriver.findElement(By.id("browse")).click();
List<WebElement> initialList = webDriver.findElements(By.className("offer"));
webDriver.get("http://127.0.0.1:8080/twu/");
webDriver.findElement(By.id("createOffer")).click();
WebDriverWait wait = new WebDriverWait(webDriver, 5000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("title")));
String offerTitle = "TITLE_"+ GregorianCalendar.getInstance().getTime().getTime();
webDriver.findElement(By.name("title")).sendKeys(offerTitle);
Select select = new Select(webDriver.findElement(By.tagName("select")));
select.selectByValue("Cars");
webDriver.findElement(By.name("description")).sendKeys("To pass the test or not, this is a question");
webDriver.findElement(By.name("submit")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("takeDownButton")));
webDriver.findElement(By.id("takeDownButton")).click();
webDriver.findElement(By.id("browse")).click();
List<WebElement> offerList = webDriver.findElements(By.className("offer"));
assertThat(offerList.size(), is(initialList.size()));
}
private WebElement findElementById(String id) {
try {
return webDriver.findElement(By.id(id));
} catch (org.openqa.selenium.NoSuchElementException e) {
String pageSource = webDriver.getPageSource();
try {
FileUtils.writeStringToFile(new File("build/test-results/lastPage.html"), pageSource);
} catch (IOException e1) {
e1.printStackTrace();
}
throw e;
}
}
private void loginUser2() {
webDriver.get("http://127.0.0.1:8080/twu/");
webDriver.findElement(By.id("username")).sendKeys();
webDriver.findElement(By.id("password")).sendKeys();
webDriver.findElement(By.name("submit")).click();
}
@After
public void tearDown() throws Exception {
webDriver.close();
}
private void logIn() {
webDriver.get("http://127.0.0.1:8080/twu/");
webDriver.findElement(By.id("username")).sendKeys(username);
webDriver.findElement(By.id("password")).sendKeys(password);
webDriver.findElement(By.name("submit")).click();
}
}
| false | true | public void shouldNotDisplayHiddenOfferInBrowsePageAfterTakeDown() throws Exception {
logIn();
Thread.sleep(1000);
webDriver.findElement(By.id("browse")).click();
List<WebElement> initialList = webDriver.findElements(By.className("offer"));
webDriver.get("http://127.0.0.1:8080/twu/");
webDriver.findElement(By.id("createOffer")).click();
WebDriverWait wait = new WebDriverWait(webDriver, 5000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("title")));
String offerTitle = "TITLE_"+ GregorianCalendar.getInstance().getTime().getTime();
webDriver.findElement(By.name("title")).sendKeys(offerTitle);
Select select = new Select(webDriver.findElement(By.tagName("select")));
select.selectByValue("Cars");
webDriver.findElement(By.name("description")).sendKeys("To pass the test or not, this is a question");
webDriver.findElement(By.name("submit")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("takeDownButton")));
webDriver.findElement(By.id("takeDownButton")).click();
webDriver.findElement(By.id("browse")).click();
List<WebElement> offerList = webDriver.findElements(By.className("offer"));
assertThat(offerList.size(), is(initialList.size()));
}
| public void shouldNotDisplayHiddenOfferInBrowsePageAfterTakeDown() throws Exception {
logIn();
// Thread.sleep(1000);
WebDriverWait waitToBrowse = new WebDriverWait(webDriver, 1000);
waitToBrowse.until(ExpectedConditions.visibilityOfElementLocated(By.id("browse")));
webDriver.findElement(By.id("browse")).click();
List<WebElement> initialList = webDriver.findElements(By.className("offer"));
webDriver.get("http://127.0.0.1:8080/twu/");
webDriver.findElement(By.id("createOffer")).click();
WebDriverWait wait = new WebDriverWait(webDriver, 5000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("title")));
String offerTitle = "TITLE_"+ GregorianCalendar.getInstance().getTime().getTime();
webDriver.findElement(By.name("title")).sendKeys(offerTitle);
Select select = new Select(webDriver.findElement(By.tagName("select")));
select.selectByValue("Cars");
webDriver.findElement(By.name("description")).sendKeys("To pass the test or not, this is a question");
webDriver.findElement(By.name("submit")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("takeDownButton")));
webDriver.findElement(By.id("takeDownButton")).click();
webDriver.findElement(By.id("browse")).click();
List<WebElement> offerList = webDriver.findElements(By.className("offer"));
assertThat(offerList.size(), is(initialList.size()));
}
|
diff --git a/src/com/asylumsw/bukkit/waypoints/Waypoints.java b/src/com/asylumsw/bukkit/waypoints/Waypoints.java
index 9baba79..ca6dae6 100644
--- a/src/com/asylumsw/bukkit/waypoints/Waypoints.java
+++ b/src/com/asylumsw/bukkit/waypoints/Waypoints.java
@@ -1,101 +1,101 @@
package com.asylumsw.bukkit.waypoints;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author jonathan
*/
public class Waypoints extends JavaPlugin {
public static Server serverInstance;
public final static String DATABASE = "jdbc:sqlite:waypoints.db";
@Override
public void onEnable() {
serverInstance = this.getServer();
Homes.loadHomes();
Gates.loadGates();
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!");
}
@Override
public void onDisable() {
System.out.println("Waypoints Disabled.");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if( !(sender instanceof Player) ) return false;
if( !cmd.getName().equalsIgnoreCase("wp") ) return false;
if( 1 > args.length ) return false;
String action = args[0];
if( action.equalsIgnoreCase("home") ) {
- if( 2 > args.length ) {
+ if( 2 <= args.length ) {
if( args[1].equalsIgnoreCase("activate") ) {
Homes.setHomePoint((Player)sender);
return true;
}
else if( args[1].equalsIgnoreCase("remove") ) {
Homes.unsetHomePoint((Player)sender);
return true;
}
return false;
}
else {
Homes.sendPlayerHome((Player)sender, false, false);
return true;
}
}
- else if(action.equalsIgnoreCase("gate") && 2 > args.length ) {
+ else if(action.equalsIgnoreCase("gate") && 2 <= args.length ) {
String gateAction = args[1];
if( gateAction.equalsIgnoreCase("list") ) {
Gates.listPlayerGates((Player)sender);
return true;
}
else if( gateAction.equalsIgnoreCase("remove") ) {
sender.sendMessage(ChatColor.RED+"Error: Removeing gates is not yet implemented.");
return true;
}
else if( gateAction.equalsIgnoreCase("activate") ) {
- if( 3 > args.length ) {
+ if( 3 <= args.length ) {
sender.sendMessage(ChatColor.RED + "Error: Must supply gate name.");
return false;
}
Gates.activateGate((Player)sender, args[2]);
return true;
}
else {
Gates.sendPlayerToGate((Player)sender, gateAction);
}
}
return false;
}
public static void warpPlayerTo(Player player, Location loc, int delay) {
int sleepTime = 0;
while (sleepTime < delay) {
try {
Thread.sleep(1000);
player.sendMessage(ChatColor.GRAY+"* Teleport in " + (delay - sleepTime));
sleepTime += 1;
}
catch (InterruptedException ex) {
}
}
player.teleportTo(loc);
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if( !(sender instanceof Player) ) return false;
if( !cmd.getName().equalsIgnoreCase("wp") ) return false;
if( 1 > args.length ) return false;
String action = args[0];
if( action.equalsIgnoreCase("home") ) {
if( 2 > args.length ) {
if( args[1].equalsIgnoreCase("activate") ) {
Homes.setHomePoint((Player)sender);
return true;
}
else if( args[1].equalsIgnoreCase("remove") ) {
Homes.unsetHomePoint((Player)sender);
return true;
}
return false;
}
else {
Homes.sendPlayerHome((Player)sender, false, false);
return true;
}
}
else if(action.equalsIgnoreCase("gate") && 2 > args.length ) {
String gateAction = args[1];
if( gateAction.equalsIgnoreCase("list") ) {
Gates.listPlayerGates((Player)sender);
return true;
}
else if( gateAction.equalsIgnoreCase("remove") ) {
sender.sendMessage(ChatColor.RED+"Error: Removeing gates is not yet implemented.");
return true;
}
else if( gateAction.equalsIgnoreCase("activate") ) {
if( 3 > args.length ) {
sender.sendMessage(ChatColor.RED + "Error: Must supply gate name.");
return false;
}
Gates.activateGate((Player)sender, args[2]);
return true;
}
else {
Gates.sendPlayerToGate((Player)sender, gateAction);
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if( !(sender instanceof Player) ) return false;
if( !cmd.getName().equalsIgnoreCase("wp") ) return false;
if( 1 > args.length ) return false;
String action = args[0];
if( action.equalsIgnoreCase("home") ) {
if( 2 <= args.length ) {
if( args[1].equalsIgnoreCase("activate") ) {
Homes.setHomePoint((Player)sender);
return true;
}
else if( args[1].equalsIgnoreCase("remove") ) {
Homes.unsetHomePoint((Player)sender);
return true;
}
return false;
}
else {
Homes.sendPlayerHome((Player)sender, false, false);
return true;
}
}
else if(action.equalsIgnoreCase("gate") && 2 <= args.length ) {
String gateAction = args[1];
if( gateAction.equalsIgnoreCase("list") ) {
Gates.listPlayerGates((Player)sender);
return true;
}
else if( gateAction.equalsIgnoreCase("remove") ) {
sender.sendMessage(ChatColor.RED+"Error: Removeing gates is not yet implemented.");
return true;
}
else if( gateAction.equalsIgnoreCase("activate") ) {
if( 3 <= args.length ) {
sender.sendMessage(ChatColor.RED + "Error: Must supply gate name.");
return false;
}
Gates.activateGate((Player)sender, args[2]);
return true;
}
else {
Gates.sendPlayerToGate((Player)sender, gateAction);
}
}
return false;
}
|
diff --git a/src/main/org/jboss/reflect/InheritableAnnotationHolder.java b/src/main/org/jboss/reflect/InheritableAnnotationHolder.java
index fdb0f36..21abb66 100644
--- a/src/main/org/jboss/reflect/InheritableAnnotationHolder.java
+++ b/src/main/org/jboss/reflect/InheritableAnnotationHolder.java
@@ -1,99 +1,99 @@
/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.reflect;
import java.util.HashMap;
/**
* comment
*
* @author <a href="mailto:[email protected]">Bill Burke</a>
*/
public class InheritableAnnotationHolder implements AnnotatedInfo
{
protected HashMap declaredAnnotations;
protected HashMap allAnnotations;
protected AnnotationValue[] allAnnotationsArray;
protected AnnotationValue[] declaredAnnotationsArray;
protected InheritableAnnotationHolder superHolder;
public InheritableAnnotationHolder()
{
}
public InheritableAnnotationHolder(AnnotationValue[] annotations)
{
setupAnnotations(annotations);
}
public AnnotationValue[] getAnnotations()
{
return allAnnotationsArray;
}
public AnnotationValue[] getDeclaredAnnotations()
{
return declaredAnnotationsArray;
}
public AnnotationValue getAnnotation(String name)
{
return (AnnotationValue) allAnnotations.get(name);
}
public boolean isAnnotationPresent(String name)
{
return allAnnotations.containsKey(name);
}
protected void setupAnnotations(AnnotationValue[] annotations)
{
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
{
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotations = new HashMap();
if (superHolder != null && superHolder.allAnnotationsArray != null)
{
for (int i = 0; i < superHolder.allAnnotationsArray.length; i++)
{
AnnotationValue av = superHolder.allAnnotationsArray[i];
- if (av.getAnnotationType().isAnnotationPresent(java.lang.annotation.Inherited.class.getName()))
+ if (av.getAnnotationType().isAnnotationPresent("java.lang.annotation.Inherited"));
{
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
}
else
{
allAnnotationsArray = declaredAnnotationsArray;
}
for (int i = 0; i < annotations.length; i++)
{
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.allAnnotations;
allAnnotationsArray = superHolder.allAnnotationsArray;
}
}
}
}
| true | true | protected void setupAnnotations(AnnotationValue[] annotations)
{
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
{
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotations = new HashMap();
if (superHolder != null && superHolder.allAnnotationsArray != null)
{
for (int i = 0; i < superHolder.allAnnotationsArray.length; i++)
{
AnnotationValue av = superHolder.allAnnotationsArray[i];
if (av.getAnnotationType().isAnnotationPresent(java.lang.annotation.Inherited.class.getName()))
{
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
}
else
{
allAnnotationsArray = declaredAnnotationsArray;
}
for (int i = 0; i < annotations.length; i++)
{
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.allAnnotations;
allAnnotationsArray = superHolder.allAnnotationsArray;
}
}
}
| protected void setupAnnotations(AnnotationValue[] annotations)
{
if (annotations != null && annotations.length > 0)
{
declaredAnnotations = new HashMap();
declaredAnnotationsArray = annotations;
for (int i = 0; i < annotations.length; i++)
{
declaredAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotations = new HashMap();
if (superHolder != null && superHolder.allAnnotationsArray != null)
{
for (int i = 0; i < superHolder.allAnnotationsArray.length; i++)
{
AnnotationValue av = superHolder.allAnnotationsArray[i];
if (av.getAnnotationType().isAnnotationPresent("java.lang.annotation.Inherited"));
{
allAnnotations.put(av.getAnnotationType().getName(), av);
}
}
}
else
{
allAnnotationsArray = declaredAnnotationsArray;
}
for (int i = 0; i < annotations.length; i++)
{
allAnnotations.put(annotations[i].getAnnotationType().getName(), annotations[i]);
}
allAnnotationsArray = (AnnotationValue[])allAnnotations.values().toArray(new AnnotationValue[allAnnotations.size()]);
}
else
{
if (superHolder != null)
{
allAnnotations = superHolder.allAnnotations;
allAnnotationsArray = superHolder.allAnnotationsArray;
}
}
}
|
diff --git a/src/org/protege/editor/owl/ui/library/EditOntologyLibraryAction.java b/src/org/protege/editor/owl/ui/library/EditOntologyLibraryAction.java
index e0a64eb9..d1b3b95f 100644
--- a/src/org/protege/editor/owl/ui/library/EditOntologyLibraryAction.java
+++ b/src/org/protege/editor/owl/ui/library/EditOntologyLibraryAction.java
@@ -1,42 +1,44 @@
package org.protege.editor.owl.ui.library;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Collections;
import org.protege.editor.core.ProtegeApplication;
import org.protege.editor.core.ui.util.UIUtil;
import org.protege.editor.owl.ui.action.ProtegeOWLAction;
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Medical Informatics Group<br>
* Date: 24-Aug-2006<br><br>
* <p/>
* [email protected]<br>
* www.cs.man.ac.uk/~horridgm<br><br>
*/
public class EditOntologyLibraryAction extends ProtegeOWLAction {
private static final long serialVersionUID = -4297673435512878237L;
public void actionPerformed(ActionEvent e) {
try {
File catalogFile = UIUtil.openFile(getOWLWorkspace(), "Choose catalog file containing ontology repository information", "Choose XML Catalog", Collections.singleton("xml"));
- OntologyLibraryPanel.showDialog(getOWLEditorKit(), catalogFile);
+ if (catalogFile != null) {
+ OntologyLibraryPanel.showDialog(getOWLEditorKit(), catalogFile);
+ }
}
catch (Exception ex) {
ProtegeApplication.getErrorLog().logError(ex);
}
}
public void initialise() throws Exception {
}
public void dispose() {
}
}
| true | true | public void actionPerformed(ActionEvent e) {
try {
File catalogFile = UIUtil.openFile(getOWLWorkspace(), "Choose catalog file containing ontology repository information", "Choose XML Catalog", Collections.singleton("xml"));
OntologyLibraryPanel.showDialog(getOWLEditorKit(), catalogFile);
}
catch (Exception ex) {
ProtegeApplication.getErrorLog().logError(ex);
}
}
| public void actionPerformed(ActionEvent e) {
try {
File catalogFile = UIUtil.openFile(getOWLWorkspace(), "Choose catalog file containing ontology repository information", "Choose XML Catalog", Collections.singleton("xml"));
if (catalogFile != null) {
OntologyLibraryPanel.showDialog(getOWLEditorKit(), catalogFile);
}
}
catch (Exception ex) {
ProtegeApplication.getErrorLog().logError(ex);
}
}
|
diff --git a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/cimi/tools/NetworkShowCommand.java b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/cimi/tools/NetworkShowCommand.java
index 6db5048..84ab7b5 100644
--- a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/cimi/tools/NetworkShowCommand.java
+++ b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/cimi/tools/NetworkShowCommand.java
@@ -1,71 +1,71 @@
/**
*
* SIROCCO
* Copyright (C) 2011 France Telecom
* Contact: [email protected]
*
* 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 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
*
* $Id$
*
*/
package org.ow2.sirocco.cimi.tools;
import java.util.List;
import org.nocrala.tools.texttablefmt.Table;
import org.ow2.sirocco.cimi.sdk.CimiClient;
import org.ow2.sirocco.cimi.sdk.CimiClientException;
import org.ow2.sirocco.cimi.sdk.Network;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
@Parameters(commandDescription = "show network")
public class NetworkShowCommand implements Command {
@Parameter(description = "<network id>", required = true)
private List<String> networkIds;
@ParametersDelegate
private ResourceSelectExpandParams showParams = new ResourceSelectExpandParams();
@Override
public String getName() {
return "network-show";
}
@Override
public void execute(final CimiClient cimiClient) throws CimiClientException {
Network net = Network.getNetworkByReference(cimiClient, this.networkIds.get(0), this.showParams.getQueryParams());
NetworkShowCommand.printNetwork(net, this.showParams);
}
public static void printNetwork(final Network net, final ResourceSelectExpandParams showParams) throws CimiClientException {
Table table = CommandHelper.createResourceShowTable(net, showParams);
- if (showParams.isSelected("state")) {
+ if (showParams.isSelected("state") && net.getState() != null) {
table.addCell("state");
table.addCell(net.getState().toString());
}
- if (showParams.isSelected("networkType")) {
+ if (showParams.isSelected("networkType") && net.getNetworkType() != null) {
table.addCell("network type");
table.addCell(net.getNetworkType());
}
System.out.println(table.render());
}
}
| false | true | public static void printNetwork(final Network net, final ResourceSelectExpandParams showParams) throws CimiClientException {
Table table = CommandHelper.createResourceShowTable(net, showParams);
if (showParams.isSelected("state")) {
table.addCell("state");
table.addCell(net.getState().toString());
}
if (showParams.isSelected("networkType")) {
table.addCell("network type");
table.addCell(net.getNetworkType());
}
System.out.println(table.render());
}
| public static void printNetwork(final Network net, final ResourceSelectExpandParams showParams) throws CimiClientException {
Table table = CommandHelper.createResourceShowTable(net, showParams);
if (showParams.isSelected("state") && net.getState() != null) {
table.addCell("state");
table.addCell(net.getState().toString());
}
if (showParams.isSelected("networkType") && net.getNetworkType() != null) {
table.addCell("network type");
table.addCell(net.getNetworkType());
}
System.out.println(table.render());
}
|
diff --git a/src/test/java/test/strangeforest/currencywatch/unit/ParallelCurrencyRateProviderProxyTest.java b/src/test/java/test/strangeforest/currencywatch/unit/ParallelCurrencyRateProviderProxyTest.java
index 8b0fff0..b93375f 100644
--- a/src/test/java/test/strangeforest/currencywatch/unit/ParallelCurrencyRateProviderProxyTest.java
+++ b/src/test/java/test/strangeforest/currencywatch/unit/ParallelCurrencyRateProviderProxyTest.java
@@ -1,92 +1,94 @@
package test.strangeforest.currencywatch.unit;
import java.util.*;
import org.junit.*;
import org.mockito.*;
import org.mockito.invocation.*;
import org.mockito.stubbing.*;
import org.strangeforest.currencywatch.core.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static test.strangeforest.currencywatch.TestData.*;
public class ParallelCurrencyRateProviderProxyTest {
@Test
public void getRate() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE)).thenReturn(RATE);
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 1)) {
RateValue rate = parallelProvider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE);
assertEquals(RATE, rate);
verify(listener).newRate(any(CurrencyRateEvent.class));
}
}
@Test
public void getRates() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(eq(SYMBOL_FROM), eq(SYMBOL_TO), any(Date.class))).thenAnswer(new Answer<Object>() {
@Override public Object answer(InvocationOnMock invocation) throws Throwable {
return RATES.get(invocation.getArguments()[2]);
}
});
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 2)) {
Map<Date, RateValue> rates = parallelProvider.getRates(SYMBOL_FROM, SYMBOL_TO, RATES.keySet());
assertEquals(RATES, rates);
verify(listener, times(RATES.size())).newRate(any(CurrencyRateEvent.class));
}
}
@Test
public void getRatesRetried() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE)).thenThrow(new CurrencyRateException("Booom!")).thenReturn(RATE);
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 1)) {
Map<Date, RateValue> rates = parallelProvider.getRates(SYMBOL_FROM, SYMBOL_TO, Collections.singleton(DATE));
assertEquals(Collections.singletonMap(DATE, RATE), rates);
verify(provider, times(2)).getRate(SYMBOL_FROM, SYMBOL_TO, DATE);
verify(listener).newRate(any(CurrencyRateEvent.class));
}
}
@Test
public void getRatesRetryFail() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE)).thenThrow(new CurrencyRateException("Booom!"));
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 1)) {
+ parallelProvider.setRetryCount(2);
+ parallelProvider.setMaxExceptions(0);
try {
parallelProvider.getRates(SYMBOL_FROM, SYMBOL_TO, Collections.singleton(DATE));
fail("Exception is not thrown.");
}
catch (CurrencyRateException ex) {
InOrder inOrder = inOrder(provider);
inOrder.verify(provider).init();
inOrder.verify(provider, times(3)).getRate(SYMBOL_FROM, SYMBOL_TO, DATE);
inOrder.verify(provider).close();
inOrder.verify(provider).init();
verify(listener, never()).newRate(any(CurrencyRateEvent.class));
}
}
}
private ParallelCurrencyRateProviderProxy createParallelProvider(CurrencyRateProvider provider, CurrencyRateListener listener, int threadCount) {
ParallelCurrencyRateProviderProxy parallelProvider = new ParallelCurrencyRateProviderProxy(provider, threadCount);
parallelProvider.addListener(listener);
parallelProvider.init();
return parallelProvider;
}
}
| true | true | public void getRatesRetryFail() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE)).thenThrow(new CurrencyRateException("Booom!"));
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 1)) {
try {
parallelProvider.getRates(SYMBOL_FROM, SYMBOL_TO, Collections.singleton(DATE));
fail("Exception is not thrown.");
}
catch (CurrencyRateException ex) {
InOrder inOrder = inOrder(provider);
inOrder.verify(provider).init();
inOrder.verify(provider, times(3)).getRate(SYMBOL_FROM, SYMBOL_TO, DATE);
inOrder.verify(provider).close();
inOrder.verify(provider).init();
verify(listener, never()).newRate(any(CurrencyRateEvent.class));
}
}
}
| public void getRatesRetryFail() {
CurrencyRateProvider provider = mock(CurrencyRateProvider.class);
when(provider.getRate(SYMBOL_FROM, SYMBOL_TO, DATE)).thenThrow(new CurrencyRateException("Booom!"));
CurrencyRateListener listener = mock(CurrencyRateListener.class);
try (ParallelCurrencyRateProviderProxy parallelProvider = createParallelProvider(provider, listener, 1)) {
parallelProvider.setRetryCount(2);
parallelProvider.setMaxExceptions(0);
try {
parallelProvider.getRates(SYMBOL_FROM, SYMBOL_TO, Collections.singleton(DATE));
fail("Exception is not thrown.");
}
catch (CurrencyRateException ex) {
InOrder inOrder = inOrder(provider);
inOrder.verify(provider).init();
inOrder.verify(provider, times(3)).getRate(SYMBOL_FROM, SYMBOL_TO, DATE);
inOrder.verify(provider).close();
inOrder.verify(provider).init();
verify(listener, never()).newRate(any(CurrencyRateEvent.class));
}
}
}
|
diff --git a/src/lang/psi/impl/symbols/LuaWrapperReferenceElementImpl.java b/src/lang/psi/impl/symbols/LuaWrapperReferenceElementImpl.java
index 3247d276..0a2adc0d 100644
--- a/src/lang/psi/impl/symbols/LuaWrapperReferenceElementImpl.java
+++ b/src/lang/psi/impl/symbols/LuaWrapperReferenceElementImpl.java
@@ -1,62 +1,64 @@
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.psi.impl.symbols;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.PsiReference;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaExpression;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaIdentifier;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 2/4/11
* Time: 10:36 PM
*/
public class LuaWrapperReferenceElementImpl extends LuaReferenceElementImpl implements LuaExpression {
@Override
public boolean isSameKind(LuaSymbol symbol) {
- assert false;
- return false; //To change body of implemented methods use File | Settings | File Templates.
+// assert false;
+ if (getElement() instanceof LuaSymbol)
+ return ((LuaSymbol) getElement()).isSameKind(symbol);
+ return false;
}
public LuaWrapperReferenceElementImpl(ASTNode node) {
super(node);
}
public PsiElement getElement() {
return findChildByClass(LuaIdentifier.class);
}
public PsiReference getReference() {
return this;
}
@Override
public String getName() {
return ((PsiNamedElement)getElement()).getName();
}
@Override
public String toString() {
return "Reference: " + getName();
}
}
| true | true | public boolean isSameKind(LuaSymbol symbol) {
assert false;
return false; //To change body of implemented methods use File | Settings | File Templates.
}
| public boolean isSameKind(LuaSymbol symbol) {
// assert false;
if (getElement() instanceof LuaSymbol)
return ((LuaSymbol) getElement()).isSameKind(symbol);
return false;
}
|
diff --git a/src/base/PatchBuilder.java b/src/base/PatchBuilder.java
index 492a17d..9498a35 100644
--- a/src/base/PatchBuilder.java
+++ b/src/base/PatchBuilder.java
@@ -1,143 +1,144 @@
package base;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Vector;
import crypt.DecryptTable;
public class PatchBuilder extends DecryptTable {
public void create(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList(args));
list.remove(0);
String outfile = list.get(list.size()-1);
list.remove(list.size()-1);
try {
RandomAccessFile out = new RandomAccessFile(outfile, "rw");
int table_size = (list.size() + 1) * 4 * 2;
System.out.println("Table size: " + table_size + " bytes");
if(table_size % 16 > 0) {
table_size += 16 - (table_size % 16);
System.out.println("Table size (padded): " + table_size + " bytes");
}
out.setLength(table_size);
out.seek(0);
long current = 0;
writeInt(out, list.size());
for (String file : list) {
int offset = getOffset(extractNumber(file)) << 11;
writeInt(out, offset);
InputStream in = new FileInputStream(file);
int len = (int)new File(file).length();
writeInt(out, (int)len);
System.out.println(file + ", offset: " + offset + ", size: " + len);
current = out.getFilePointer();
byte buffer[] = new byte[1024];
out.seek(out.length());
while((len = in.read(buffer)) > 0)
out.write(buffer, 0, len);
in.close();
out.seek(current);
}
writeInt(out, 0);
install_tables(out, list);
out.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void install_tables(RandomAccessFile out, List<String> list) {
System.out.print("Trying to add data_install tables...");
try {
BufferedReader in = new BufferedReader(new FileReader("data_install.txt"));
out.seek(out.length());
String line;
Vector<Integer> patch_files = new Vector<Integer>();
Vector<String> install_files = new Vector<String>();
Vector<String> offsets = new Vector<String>();
while((line = in.readLine()) != null) {
if(!line.startsWith("#")) {
String []tokens = line.split(",");
patch_files.add(Integer.parseInt(tokens[0]));
install_files.add(tokens[1]);
offsets.add(tokens[2]);
}
}
Vector<String> install_uniq = new Vector<String>(new LinkedHashSet<String>(install_files));
+ while(install_uniq.remove("NONE"));
writeInt(out, install_uniq.size());
int install_count = 0;
String match = install_files.firstElement();
out.write(match.getBytes());
writeInt(out, install_count);
for(String file : install_files) {
- if(!match.equals(file)) {
+ if(!file.equals("NONE") && !match.equals(file)) {
out.write(file.getBytes());
match = file;
writeInt(out, install_count);
}
install_count++;
}
for(String trans_file : list) {
int index = patch_files.indexOf(extractNumber(trans_file));
int offset = -1;
if(index != -1) {
// UGH!!, 11 years and the Integer.parseInt bug isn't fixed
// This is the last time that i use Java in a project of mine
// http://bugs.sun.com/view_bug.do?bug_id=4215269
offset = (int)Long.parseLong(offsets.get(index),16);
} else {
System.out.println("Install info not found for " + trans_file);
}
writeInt(out, offset);
}
long filelength = out.length();
if(filelength % 16 > 0) {
filelength += 16 - (filelength % 16);
out.setLength(filelength);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
System.out.println("\ndata_install.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* The "writeInt" function of java writes in BigEndian mode but we need
* LittleEndian so i made a custom function for that
*
* @param file
* @throws IOException
* if any error occur while writing
*/
private void writeInt(RandomAccessFile file, int value)
throws IOException {
int ch1 = (byte) (value >>> 24);
int ch2 = (byte) (value >>> 16);
int ch3 = (byte) (value >>> 8);
int ch4 = (byte) value;
file.write(ch4);
file.write(ch3);
file.write(ch2);
file.write(ch1);
}
}
| false | true | private void install_tables(RandomAccessFile out, List<String> list) {
System.out.print("Trying to add data_install tables...");
try {
BufferedReader in = new BufferedReader(new FileReader("data_install.txt"));
out.seek(out.length());
String line;
Vector<Integer> patch_files = new Vector<Integer>();
Vector<String> install_files = new Vector<String>();
Vector<String> offsets = new Vector<String>();
while((line = in.readLine()) != null) {
if(!line.startsWith("#")) {
String []tokens = line.split(",");
patch_files.add(Integer.parseInt(tokens[0]));
install_files.add(tokens[1]);
offsets.add(tokens[2]);
}
}
Vector<String> install_uniq = new Vector<String>(new LinkedHashSet<String>(install_files));
writeInt(out, install_uniq.size());
int install_count = 0;
String match = install_files.firstElement();
out.write(match.getBytes());
writeInt(out, install_count);
for(String file : install_files) {
if(!match.equals(file)) {
out.write(file.getBytes());
match = file;
writeInt(out, install_count);
}
install_count++;
}
for(String trans_file : list) {
int index = patch_files.indexOf(extractNumber(trans_file));
int offset = -1;
if(index != -1) {
// UGH!!, 11 years and the Integer.parseInt bug isn't fixed
// This is the last time that i use Java in a project of mine
// http://bugs.sun.com/view_bug.do?bug_id=4215269
offset = (int)Long.parseLong(offsets.get(index),16);
} else {
System.out.println("Install info not found for " + trans_file);
}
writeInt(out, offset);
}
long filelength = out.length();
if(filelength % 16 > 0) {
filelength += 16 - (filelength % 16);
out.setLength(filelength);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
System.out.println("\ndata_install.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
}
| private void install_tables(RandomAccessFile out, List<String> list) {
System.out.print("Trying to add data_install tables...");
try {
BufferedReader in = new BufferedReader(new FileReader("data_install.txt"));
out.seek(out.length());
String line;
Vector<Integer> patch_files = new Vector<Integer>();
Vector<String> install_files = new Vector<String>();
Vector<String> offsets = new Vector<String>();
while((line = in.readLine()) != null) {
if(!line.startsWith("#")) {
String []tokens = line.split(",");
patch_files.add(Integer.parseInt(tokens[0]));
install_files.add(tokens[1]);
offsets.add(tokens[2]);
}
}
Vector<String> install_uniq = new Vector<String>(new LinkedHashSet<String>(install_files));
while(install_uniq.remove("NONE"));
writeInt(out, install_uniq.size());
int install_count = 0;
String match = install_files.firstElement();
out.write(match.getBytes());
writeInt(out, install_count);
for(String file : install_files) {
if(!file.equals("NONE") && !match.equals(file)) {
out.write(file.getBytes());
match = file;
writeInt(out, install_count);
}
install_count++;
}
for(String trans_file : list) {
int index = patch_files.indexOf(extractNumber(trans_file));
int offset = -1;
if(index != -1) {
// UGH!!, 11 years and the Integer.parseInt bug isn't fixed
// This is the last time that i use Java in a project of mine
// http://bugs.sun.com/view_bug.do?bug_id=4215269
offset = (int)Long.parseLong(offsets.get(index),16);
} else {
System.out.println("Install info not found for " + trans_file);
}
writeInt(out, offset);
}
long filelength = out.length();
if(filelength % 16 > 0) {
filelength += 16 - (filelength % 16);
out.setLength(filelength);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
System.out.println("\ndata_install.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/src/entities/players/abilities/RangedAttackAbility.java b/src/entities/players/abilities/RangedAttackAbility.java
index 5b77513..a04ebf8 100644
--- a/src/entities/players/abilities/RangedAttackAbility.java
+++ b/src/entities/players/abilities/RangedAttackAbility.java
@@ -1,26 +1,26 @@
package entities.players.abilities;
import utils.GameplayMouseInput;
import utils.MapLoader;
import utils.Position;
import entities.players.Player;
import items.projectiles.Projectile;
public class RangedAttackAbility extends PlayerAbility {
@Override
public void use(Player p) {
Projectile pro = null;
Position vec = GameplayMouseInput.getMousePosition().clone();
vec.translate(-p.getCentreX(), -p.getCentreY());
- pro = new Projectile(p.getX(), p.getY(), 10, vec.getAngle(), vec.getMagnitudeSquared());
+ pro = new Projectile(p.getCentreX(), p.getCentreY(), 10, vec.getAngle(), vec.getMagnitudeSquared());
MapLoader.getCurrentCell().addProjectile(pro);
}
@Override
public void stop_sounds() {
// TODO Auto-generated method stub
}
}
| true | true | public void use(Player p) {
Projectile pro = null;
Position vec = GameplayMouseInput.getMousePosition().clone();
vec.translate(-p.getCentreX(), -p.getCentreY());
pro = new Projectile(p.getX(), p.getY(), 10, vec.getAngle(), vec.getMagnitudeSquared());
MapLoader.getCurrentCell().addProjectile(pro);
}
| public void use(Player p) {
Projectile pro = null;
Position vec = GameplayMouseInput.getMousePosition().clone();
vec.translate(-p.getCentreX(), -p.getCentreY());
pro = new Projectile(p.getCentreX(), p.getCentreY(), 10, vec.getAngle(), vec.getMagnitudeSquared());
MapLoader.getCurrentCell().addProjectile(pro);
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
index 595343b..bf6e14d 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatXFileInput.java
@@ -1,1358 +1,1362 @@
package org.agmip.translators.dssat;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import static org.agmip.util.MapUtil.*;
/**
* DSSAT Experiment Data I/O API Class1
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileInput extends DssatCommonInput {
public String eventKey = "data";
public String icEventKey = "soilLayer";
/**
* Constructor with no parameters Set jsonKey as "experiment"
*
*/
public DssatXFileInput() {
super();
jsonKey = "management";
}
/**
* DSSAT XFile Data input method for only inputing experiment file
*
* @param brMap The holder for BufferReader objects for all files
* @return result data holder object
*/
@Override
protected HashMap readFile(HashMap brMap) throws IOException {
HashMap ret = new HashMap();
HashMap metaData = new HashMap();
ArrayList<HashMap> expArr = new ArrayList<HashMap>();
HashMap expData;
ArrayList<HashMap> mgnArr = readTreatments(brMap, metaData);
for (int i = 0; i < mgnArr.size(); i++) {
// Set meta data block for this treatment
expData = setupMetaData(metaData, i);
// Set soil_analysis block to soil block
copyItem(expData, expData, "soil", "soil_analysis", true);
HashMap soilTmp = getObjectOr(expData, "soil", new HashMap());
expData.put("soil_id", expData.get("soil_id") + "_" + (i + 1));
copyItem(soilTmp, expData, "soil_id");
copyItem(soilTmp, expData, "sltx");
copyItem(soilTmp, expData, "sldp");
ArrayList<HashMap> soilSubArr = getObjectOr(soilTmp, icEventKey, new ArrayList());
for (int j = 0; j < soilSubArr.size(); j++) {
soilSubArr.get(j).remove("slsc");
}
expData.put("soil", soilTmp);
// Set management data for this treatment
setupTrnData(expData, mgnArr.get(i));
// Add to output array
expArr.add(expData);
}
// compressData(expArr);
ret.put("experiments", expArr);
return ret;
}
/**
* DSSAT XFile Data input method for Controller using (no compressing data)
*
* @param brMap The holder for BufferReader objects for all files
* @param metaData
* @return trArr The array of treatment data
*/
protected ArrayList<HashMap> readTreatments(HashMap brMap, HashMap metaData) throws IOException {
String line;
BufferedReader br;
Object buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapX;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList<HashMap> trArr = new ArrayList<HashMap>();
HashMap trData = new HashMap();
ArrayList<HashMap> evtArr = new ArrayList<HashMap>();
String ireff = ""; // P.S. special handling for EFIR in irrigation section
// Set meta data info for each treatment
ArrayList<HashMap> trMetaArr = new ArrayList<HashMap>();
HashMap trMetaData;
metaData.put("tr_meta", trMetaArr);
mapX = (HashMap) brMap.get("X");
mapW = (HashMap) brMap.get("W");
// If XFile is no been found
if (mapX.isEmpty()) {
return trArr;
}
for (Object keyX : mapX.keySet()) {
buf = mapX.get(keyX);
if (buf instanceof char[]) {
br = new BufferedReader(new CharArrayReader((char[]) buf));
} else {
br = (BufferedReader) buf;
}
// fileName = (String) brMap.get("Z");
fileName = (String) keyX;
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// String exname = fileName.replaceAll("\\.", "").replaceAll("X$", "");
String exname = fileName.replaceAll("\\.\\w\\wX$", "");
HashMap meta = new HashMap();
metaData.put(exname, meta);
ArrayList<HashMap> sqArr = new ArrayList<HashMap>();
HashMap sqData;
ArrayList<HashMap> cuArr = new ArrayList<HashMap>();
ArrayList<HashMap> flArr = new ArrayList<HashMap>();
ArrayList<HashMap> saArr = new ArrayList<HashMap>();
ArrayList<HashMap> sadArr = new ArrayList<HashMap>();
ArrayList<HashMap> icArr = new ArrayList<HashMap>();
ArrayList<HashMap> icdArr = new ArrayList<HashMap>();
ArrayList<HashMap> plArr = new ArrayList<HashMap>();
ArrayList<HashMap> irArr = new ArrayList<HashMap>();
ArrayList<HashMap> irdArr = new ArrayList<HashMap>();
ArrayList<HashMap> feArr = new ArrayList<HashMap>();
ArrayList<HashMap> omArr = new ArrayList<HashMap>();
ArrayList<HashMap> chArr = new ArrayList<HashMap>();
ArrayList<HashMap> tiArr = new ArrayList<HashMap>();
ArrayList<HashMap> emArr = new ArrayList<HashMap>();
ArrayList<HashMap> haArr = new ArrayList<HashMap>();
ArrayList<HashMap> smArr = new ArrayList<HashMap>();
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("null_1", 14);
formats.put("null_2", 11); // P.S. Since exname in top line is not reliable, read from file name
formats.put("local_name", 61);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
meta.put("exname", exname);
meta.put("in", getObjectOr(meta, "exname", " ").substring(0, 2).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
if (checkValidValue(line.trim())) {
meta.put("person_notes", line.trim());
}
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
// String[] addr;
if (checkValidValue(line.trim())) {
// addr = line.split(",[ ]*");
meta.put("institution", line.trim());
} else {
// addr = new String[0];
}
// switch (addr.length) {
// case 0:
// break;
// case 1:
// meta.put("fl_loc_1", addr[0]);
// break;
// case 2:
// meta.put("fl_loc_1", addr[1]);
// meta.put("fl_loc_2", addr[0]);
// break;
// case 3:
// meta.put("fl_loc_1", addr[2]);
// meta.put("fl_loc_2", addr[1]);
// meta.put("fl_loc_3", addr[0]);
// break;
// default:
// meta.put("fl_loc_1", addr[addr.length - 1]);
// meta.put("fl_loc_2", addr[addr.length - 2]);
// String loc3 = "";
// for (int i = 0; i < addr.length - 2; i++) {
// loc3 += addr[i] + ", ";
// }
// meta.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
// }
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
// P.S. site is missing in the master variables list
if (checkValidValue(line.trim())) {
meta.put("site_name", line.trim());
}
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("plta", 7);
formats.put("pltr#", 6);
formats.put("pltln", 6);
formats.put("pldr", 6);
formats.put("pltsp", 6);
formats.put("pllay", 6);
formats.put("pltha", 6);
formats.put("plth#", 6);
formats.put("plthl", 6);
formats.put("plthm", 16);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
if (!meta.containsKey("tr_notes")) {
meta.put("tr_notes", line + "\r\n");
} else {
String notes = (String) meta.get("tr_notes");
notes += line + "\r\n";
meta.put("tr_notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data / Rotation data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 3); // For 3-bit treatment number (2->3)
formats.put("sq", 1); // For 3-bit treatment number (2->1)
formats.put("op", 2);
formats.put("co", 2);
formats.put("trt_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
if (tmp.get("trt_name") == null) {
tmp.put("trt_name", meta.get("exname"));
}
sqArr.add(tmp);
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("crid", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
Object cul_id = tmp.get("cul_id");
if (cul_id != null) {
tmp.put("dssat_cul_id", cul_id);
}
Object crid = tmp.get("crid");
if (crid == null) {
crid = fileName.replaceAll("\\w+\\.", "").replaceAll("X$", "");
}
tmp.put("crid", DssatCRIDHelper.get3BitCrid((String) crid));
cuArr.add(tmp);
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wst_id", 9); // P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(flArr, tmp, "fl");
// Read weather station id
wid = (String) tmp.get("wst_id");
if (wid != null && wid.matches("\\w{4}\\d{4}$")) {
wid = wid.substring(0, 4);
// tmp.put("wst_id", wid);
}
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_long", 16);
formats.put("fl_lat", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = null;
strLong = null;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = null;
strLong = null;
}
}
if (tmp.containsKey("fl_lat")) {
tmp.put("fl_lat", strLat);
}
if (tmp.containsKey("fl_long")) {
tmp.put("fl_long", strLong);
}
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("smhb", 6); // P.S. changed from samhb to smhb to match the soil variable name
formats.put("smpx", 6); // P.S. changed from sampx to smpx to match the soil variable name
formats.put("smke", 6); // P.S. changed from samke to smke to match the soil variable name
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "sadat");
saArr.add(tmp);
sadArr = new ArrayList<HashMap>();
tmp.put(icEventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sabl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sllb", 6); // P.S. changed from sabl to sllb to match the soil variable name
formats.put("slbdm", 6); // P.S. changed from sabdm to slbdm to match the soil variable name
formats.put("sloc", 6); // P.S. changed from saoc to sloc to match the soil variable name
formats.put("slni", 6); // P.S. changed from sani to slni to match the soil variable name
formats.put("slphw", 6); // P.S. changed from saphw to slphw to match the soil variable name
formats.put("slphb", 6); // P.S. changed from saphb to slphb to match the soil variable name
formats.put("slpx", 6); // P.S. changed from sapx to slpx to match the soil variable name
formats.put("slke", 6); // P.S. changed from sake to slke to match the soil variable name
formats.put("slsc", 6); // P.S. changed from sasc to slsc to match the soil variable name
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6);
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "icdat");
+ Object icpcr = tmp.get("icpcr");
+ if (icpcr != null) {
+ tmp.put("icpcr", DssatCRIDHelper.get3BitCrid((String) icpcr));
+ }
icArr.add(tmp);
icdArr = new ArrayList<HashMap>();
tmp.put(icEventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plma", 6); // P.S. 2012.07.13 changed from plme to plma
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("plenv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "pdate");
translateDateStr(tmp, "pldae");
// cm -> mm
String pldp = getObjectOr(tmp, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.multiply(new BigDecimal("10"));
tmp.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
plArr.add(tmp);
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if ((flg[1].startsWith("i efir") || flg4 % 2 == 1) && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
ireff = (String) tmp.get("ireff");
if (ireff != null) {
tmp.remove("ireff");
}
irArr.add(tmp);
irdArr = new ArrayList<HashMap>();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.getOr("idate"))); // P.S. DOY handling
tmp.put("ireff", ireff);
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "fdate"); // P.S. DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6);
formats.put("omp%", 6);
formats.put("omk%", 6);
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "omdat"); // P.S. DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "cdate");
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "tdate");
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
// formats.put("emday", 6);
// formats.put("ecdyl", 2);
// formats.put("emdyl", 4);
// formats.put("ecrad", 2);
// formats.put("emrad", 4);
// formats.put("ecmax", 2);
// formats.put("emmax", 4);
// formats.put("ecmin", 2);
// formats.put("emmin", 4);
// formats.put("ecrai", 2);
// formats.put("emrai", 4);
// formats.put("ecco2", 2);
// formats.put("emco2", 4);
// formats.put("ecdew", 2);
// formats.put("emdew", 4);
// formats.put("ecwnd", 2);
// formats.put("emwnd", 4);
// formats.put("em_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "emday");
tmp.put("em_data", line.substring(2));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hadat", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hap%", 6);
formats.put("hab%", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "hadat");
haArr.add(tmp);
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_general", line.length());
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "sdate");
// smSubArr = new ArrayList();
// smArr.add(tmp);
// tmp.put(eventKey, smSubArr);
// smSubArr.add(line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_options", line.length());
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_methods", line.length());
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_management", line.length());
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_outputs", line.length());
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_planting", line.length());
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "pfrst");
// translateDateStr(tmp, "plast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_irrigation", line.length());
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_nitrogen", line.length());
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_residues", line.length());
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_harvests", line.length());
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "hlast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
// Combine all the sections data into the related treatment block
String trno = null;
HashMap dssatSq;
// HashMap dssatInfo = new HashMap();
ArrayList<HashMap> sqArrNew = new ArrayList<HashMap>();
for (int i = 0, seqid = 1; i < sqArr.size(); i++, seqid++) {
sqData = (HashMap) sqArr.get(i);
trMetaData = new HashMap();
trMetaArr.add(trMetaData);
if (!sqData.get("trno").equals(trno)) {
trno = sqData.get("trno").toString();
trData = new HashMap();
evtArr = new ArrayList<HashMap>();
trArr.add(trData);
trData.put("events", evtArr);
dssatSq = new HashMap();
sqArrNew = new ArrayList<HashMap>();
// dssatInfo = new HashMap();
dssatSq.put(eventKey, sqArrNew);
trData.put("dssat_sequence", dssatSq);
// trData.put("dssat_info", dssatInfo);
trMetaData.put("trt_name", sqData.get("trt_name"));
trMetaData.put("trno", trno);
trMetaData.put("exname", exname);
seqid = 1;
} else {
// The case of multiple sequence
trMetaData.remove("trt_name");
}
sqData.put("seqid", seqid + "");
sqArrNew.add(sqData);
// cultivar
HashMap crData = new HashMap();
if (!getObjectOr(sqData, "ge", "0").equals("0")) {
// Get related cultivar data
crData = (HashMap) getSectionDataObj(cuArr, "ge", sqData.get("ge").toString());
}
// field
if (!getObjectOr(sqData, "fl", "0").equals("0")) {
// Move field info into meta data block
trMetaData.putAll((HashMap) getSectionDataObj(flArr, "fl", sqData.get("fl").toString()));
trMetaData.remove("fl");
}
// initial_condition
if (!getObjectOr(sqData, "ic", "0").equals("0")) {
HashMap icTmpArr = (HashMap) getSectionDataObj(icArr, "ic", sqData.get("ic").toString());
if (!icTmpArr.isEmpty()) {
trData.put("initial_conditions", icTmpArr);
}
}
// planting
String pdate = "";
if (!getObjectOr(sqData, "pl", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(plArr, "pl", sqData.get("pl").toString()), "pdate", "planting", seqid);
// add cultivar data into planting event
if (crData != null) {
evtArr.get(evtArr.size() - 1).putAll(crData);
}
// Get planting date for DOY value handling
pdate = getValueOr(evtArr.get(evtArr.size() - 1), "pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// irrigation
if (!getObjectOr(sqData, "ir", "0").equals("0")) {
// Date adjust based on realted treatment info (handling for DOY type value)
HashMap irTmp = (HashMap) getSectionDataObj(irArr, "ir", sqData.get("ir").toString());
ArrayList<HashMap> irTmpSubs = getObjectOr(irTmp, "data", new ArrayList());
for (int j = 0; j < irTmpSubs.size(); j++) {
HashMap irTmpSub = irTmpSubs.get(j);
translateDateStrForDOY(irTmpSub, "idate", pdate);
}
// add event data into array
addEvent(evtArr, irTmp, "idate", "irrigation", seqid);
}
// fertilizer
if (!getObjectOr(sqData, "fe", "0").equals("0")) {
ArrayList<HashMap> feTmps = (ArrayList) getSectionDataObj(feArr, "fe", sqData.get("fe").toString());
HashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = feTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(feTmp, "fdate", pdate);
// add event data into array
addEvent(evtArr, feTmp, "fdate", "fertilizer", seqid);
}
}
// organic_matter
if (!getObjectOr(sqData, "om", "0").equals("0")) {
ArrayList<HashMap> omTmps = (ArrayList) getSectionDataObj(omArr, "om", sqData.get("om").toString());
HashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = omTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(omTmp, "omdat", pdate);
// add event data into array
addEvent(evtArr, omTmp, "omdat", "organic_matter", seqid); // P.S. change event name to organic-materials; Back to organic_matter again
}
}
// chemical
if (!getObjectOr(sqData, "ch", "0").equals("0")) {
ArrayList<HashMap> chTmps = (ArrayList) getSectionDataObj(chArr, "ch", sqData.get("ch").toString());
for (int j = 0; j < chTmps.size(); j++) {
// add event data into array
addEvent(evtArr, chTmps.get(j), "cdate", "chemical", seqid);
}
}
// tillage
if (!getObjectOr(sqData, "ti", "0").equals("0")) {
ArrayList<HashMap> tiTmps = (ArrayList) getSectionDataObj(tiArr, "ti", sqData.get("ti").toString());
for (int j = 0; j < tiTmps.size(); j++) {
// add event data into array
addEvent(evtArr, tiTmps.get(j), "tdate", "tillage", seqid);
}
}
// emvironment // P.S. keep for furture using
if (!getObjectOr(sqData, "em", "0").equals("0")) {
String em = (String) sqData.get("em");
ArrayList<HashMap> emDataArr = (ArrayList) getSectionDataObj(emArr, "em", em);
// ArrayList arr = new ArrayList();
// for (int j = 0; j < emDataArr.size(); j++) {
// arr.add(emDataArr.get(j).get("em_data"));
// }
// sqData.put("em_data", arr);
HashMap tmp = getObjectOr(trData, "dssat_environment_modification", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (em.equals(arr.get(j).get("em"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.addAll(emDataArr);
}
tmp.put(eventKey, arr);
trData.put("dssat_environment_modification", tmp);
}
// harvest
if (!getObjectOr(sqData, "ha", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(haArr, "ha", sqData.get("ha").toString()), "hadat", "harvest", seqid);
}
// simulation
if (!getObjectOr(sqData, "sm", "0").equals("0")) {
String sm = (String) sqData.get("sm");
HashMap smData = (HashMap) getSectionDataObj(smArr, "sm", sm);
// sqData.putAll((HashMap) getSectionDataObj(smArr, "sm", sm));
HashMap tmp = getObjectOr(trData, "dssat_simulation_control", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (sm.equals(arr.get(j).get("sm"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.add(smData);
}
tmp.put(eventKey, arr);
trData.put("dssat_simulation_control", tmp);
}
// soil_analysis
if (!getObjectOr(sqData, "sa", "0").equals("0")) {
HashMap saTmp = (HashMap) getSectionDataObj(saArr, "sa", sqData.get("sa").toString());
// ArrayList<HashMap> saSubArr = getObjectOr(saTmp, icEventKey, new ArrayList());
// temporally put soil_analysis block into treatment meta data
trMetaData.put("soil_analysis", saTmp);
// // Add SASC into initial condition block
// ArrayList<HashMap> icSubArrNew;
// HashMap icTmp;
// String[] copyKeys = {"slsc"};
// if (!trData.containsKey("initial_condition")) {
// // Add a dummy ic block to hold SASC
// icTmp = new HashMap();
// trData.put("initial_condition", icTmp);
// icSubArrNew = combinLayers(new ArrayList<HashMap>(), saSubArr, "icbl", "sllb", copyKeys);
// } else {
// // Add SASC into initial condition block
// icTmp = (HashMap) trData.get("initial_condition");
// ArrayList<HashMap> icSubArr = getObjectOr(icTmp, icEventKey, new ArrayList());
// icSubArrNew = combinLayers(icSubArr, saSubArr, "icbl", "sllb", copyKeys);
// }
// icTmp.put(icEventKey, icSubArrNew);
}
}
}
// Remove relational index
ArrayList idNames = new ArrayList();
idNames.add("ge");
idNames.add("fl");
idNames.add("sa");
idNames.add("ic");
idNames.add("pl");
idNames.add("ir");
idNames.add("fe");
idNames.add("om");
idNames.add("ch");
idNames.add("ti");
// idNames.add("em");
idNames.add("ha");
// idNames.add("sm");
removeIndex(trArr, idNames);
removeIndex(metaData, idNames);
return trArr;
}
/**
* Set reading flags for title lines (marked with *)
*
* @param line the string of reading line
*/
@Override
protected void setTitleFlgs(String line) {
flg[0] = line.substring(1).trim().toLowerCase();
flg[1] = "";
flg[2] = "";
}
/**
* Get the section data by given index value and key
*
* @param secArr Section data array
* @param key index variable name
* @param value index variable value
*/
private Object getSectionDataObj(ArrayList secArr, Object key, String value) {
ArrayList ret = new ArrayList();
// Define the section with single sub data
ArrayList singleSubRecSecList = new ArrayList();
singleSubRecSecList.add("ge");
singleSubRecSecList.add("fl");
singleSubRecSecList.add("pl");
singleSubRecSecList.add("ha");
singleSubRecSecList.add("sm");
// Get First data node
if (secArr.isEmpty() || value == null) {
if (key.equals("icbl") || key.equals("ir") || key.equals("ic") || key.equals("sa") || singleSubRecSecList.contains(key)) {
return new HashMap();
} else {
return ret;
}
}
if (key.equals("icbl")) {
return getSectionDataWithNocopy(secArr, key, value);
} else {
HashMap fstNode = (HashMap) secArr.get(0);
// If it contains multiple sub array of data, or it does not have multiple sub records
if (fstNode.containsKey(eventKey) || fstNode.containsKey(icEventKey) || singleSubRecSecList.contains(key)) {
for (int i = 0; i < secArr.size(); i++) {
if (value.equals(((HashMap) secArr.get(i)).get(key))) {
return CopyList((HashMap) secArr.get(i));
}
}
} // If it is simple array
else {
HashMap node;
for (int i = 0; i < secArr.size(); i++) {
node = (HashMap) secArr.get(i);
if (value.equals(node.get(key))) {
ret.add(CopyList(node));
}
}
}
}
return ret;
}
/**
* Add event data into event array from input data holder (map)
*
* @param events event array
* @param mCopy input map
* @param dateId the key name of event date variable
* @param eventName the event name
* @param seqId the sequence id for DSSAT
*/
private void addEvent(ArrayList events, HashMap m, String dateId, String eventName, int seqId) {
HashMap<String, String> ret = new HashMap<String, String>();
HashMap mCopy = CopyList(m);
if (mCopy.containsKey(dateId)) {
ret.put("date", mCopy.remove(dateId).toString());
}
ret.put("event", eventName);
if (mCopy.containsKey(eventKey)) {
ArrayList<HashMap> subArr = (ArrayList) mCopy.remove(eventKey);
if (subArr == null || subArr.isEmpty()) {
ret.putAll(mCopy);
events.add(ret);
}
for (int i = 0; i < subArr.size(); i++) {
HashMap tmp = subArr.get(i);
ret.put("date", tmp.remove(dateId).toString());
ret.putAll(mCopy);
ret.putAll(tmp);
ret.put("seqid", seqId + "");
events.add(CopyList(ret));
}
} else {
ret.putAll(mCopy);
ret.put("seqid", seqId + "");
events.add(ret);
}
}
/**
* Setup the meta data block for the treatment
*
* @param metaData meta data holder
* @param trId treatment array index for the current treatment
*
* @return expData experiment data holder (contain all blocks)
*/
public HashMap setupMetaData(HashMap metaData, int trId) {
// Set meta data for all treatment
HashMap expData = new HashMap();
// Set meta data per treatment
ArrayList<HashMap> trMetaArr = (ArrayList<HashMap>) metaData.get("tr_meta");
String exname = getValueOr(trMetaArr.get(trId), "exname", "");
expData.putAll(getObjectOr(metaData, exname, new HashMap()));
expData.putAll(trMetaArr.get(trId));
if (!exname.equals("")) {
expData.put("exname", exname + "_" + expData.get("trno"));
}
expData.put("exname_o", exname);
return expData;
}
/**
* Setup the treatment data, includes management, initial condition and
* Dssat specific data block (for the case which only read XFile)
*
* @param expData experiment data holder (contain all blocks)
* @param mgnData management data holder (contain events array)
*/
private void setupTrnData(HashMap expData, HashMap mgnData) {
setupTrnData(expData, mgnData, new HashMap(), new HashMap());
}
/**
* Setup the treatment data, includes management, initial condition and
* Dssat specific data block
*
* @param expData experiment data holder (contain all blocks)
* @param mgnData management data holder (contain events array)
* @param obvAFile summary observed data holder
* @param obvTFile time series observed data holder
*/
public void setupTrnData(HashMap expData, HashMap mgnData, HashMap obvAFile, HashMap obvTFile) {
// remove unused variable
expData.remove("sltx");
expData.remove("sldp");
// Set management data block for this treatment
expData.put(jsonKey, mgnData);
// Set Initial Condition data block for this treatment
copyItem(expData, mgnData, "initial_conditions", true);
// Set DSSAT specific data blocks
// dssat_sequence
copyItem(expData, mgnData, "dssat_sequence", true);
// dssat_environment_modification
copyItem(expData, mgnData, "dssat_environment_modification", true);
// dssat_simulation_control
copyItem(expData, mgnData, "dssat_simulation_control", true);
// dssat_info
// cutDataBlock(mgnData, expData, "dssat_info");
// Create dssat info holder
HashMap dssatInfo = new HashMap();
// Move field history code into dssat_info block
copyItem(dssatInfo, expData, "flhst", true);
copyItem(dssatInfo, expData, "fhdur", true);
// Set dssat_info if it is available
if (!dssatInfo.isEmpty()) {
expData.put("dssat_info", dssatInfo);
}
// remove index variables
ArrayList idNames = new ArrayList();
idNames.add("trno");
idNames.add("trno_a");
idNames.add("trno_t");
removeIndex(expData, idNames);
}
}
| true | true | protected ArrayList<HashMap> readTreatments(HashMap brMap, HashMap metaData) throws IOException {
String line;
BufferedReader br;
Object buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapX;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList<HashMap> trArr = new ArrayList<HashMap>();
HashMap trData = new HashMap();
ArrayList<HashMap> evtArr = new ArrayList<HashMap>();
String ireff = ""; // P.S. special handling for EFIR in irrigation section
// Set meta data info for each treatment
ArrayList<HashMap> trMetaArr = new ArrayList<HashMap>();
HashMap trMetaData;
metaData.put("tr_meta", trMetaArr);
mapX = (HashMap) brMap.get("X");
mapW = (HashMap) brMap.get("W");
// If XFile is no been found
if (mapX.isEmpty()) {
return trArr;
}
for (Object keyX : mapX.keySet()) {
buf = mapX.get(keyX);
if (buf instanceof char[]) {
br = new BufferedReader(new CharArrayReader((char[]) buf));
} else {
br = (BufferedReader) buf;
}
// fileName = (String) brMap.get("Z");
fileName = (String) keyX;
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// String exname = fileName.replaceAll("\\.", "").replaceAll("X$", "");
String exname = fileName.replaceAll("\\.\\w\\wX$", "");
HashMap meta = new HashMap();
metaData.put(exname, meta);
ArrayList<HashMap> sqArr = new ArrayList<HashMap>();
HashMap sqData;
ArrayList<HashMap> cuArr = new ArrayList<HashMap>();
ArrayList<HashMap> flArr = new ArrayList<HashMap>();
ArrayList<HashMap> saArr = new ArrayList<HashMap>();
ArrayList<HashMap> sadArr = new ArrayList<HashMap>();
ArrayList<HashMap> icArr = new ArrayList<HashMap>();
ArrayList<HashMap> icdArr = new ArrayList<HashMap>();
ArrayList<HashMap> plArr = new ArrayList<HashMap>();
ArrayList<HashMap> irArr = new ArrayList<HashMap>();
ArrayList<HashMap> irdArr = new ArrayList<HashMap>();
ArrayList<HashMap> feArr = new ArrayList<HashMap>();
ArrayList<HashMap> omArr = new ArrayList<HashMap>();
ArrayList<HashMap> chArr = new ArrayList<HashMap>();
ArrayList<HashMap> tiArr = new ArrayList<HashMap>();
ArrayList<HashMap> emArr = new ArrayList<HashMap>();
ArrayList<HashMap> haArr = new ArrayList<HashMap>();
ArrayList<HashMap> smArr = new ArrayList<HashMap>();
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("null_1", 14);
formats.put("null_2", 11); // P.S. Since exname in top line is not reliable, read from file name
formats.put("local_name", 61);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
meta.put("exname", exname);
meta.put("in", getObjectOr(meta, "exname", " ").substring(0, 2).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
if (checkValidValue(line.trim())) {
meta.put("person_notes", line.trim());
}
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
// String[] addr;
if (checkValidValue(line.trim())) {
// addr = line.split(",[ ]*");
meta.put("institution", line.trim());
} else {
// addr = new String[0];
}
// switch (addr.length) {
// case 0:
// break;
// case 1:
// meta.put("fl_loc_1", addr[0]);
// break;
// case 2:
// meta.put("fl_loc_1", addr[1]);
// meta.put("fl_loc_2", addr[0]);
// break;
// case 3:
// meta.put("fl_loc_1", addr[2]);
// meta.put("fl_loc_2", addr[1]);
// meta.put("fl_loc_3", addr[0]);
// break;
// default:
// meta.put("fl_loc_1", addr[addr.length - 1]);
// meta.put("fl_loc_2", addr[addr.length - 2]);
// String loc3 = "";
// for (int i = 0; i < addr.length - 2; i++) {
// loc3 += addr[i] + ", ";
// }
// meta.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
// }
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
// P.S. site is missing in the master variables list
if (checkValidValue(line.trim())) {
meta.put("site_name", line.trim());
}
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("plta", 7);
formats.put("pltr#", 6);
formats.put("pltln", 6);
formats.put("pldr", 6);
formats.put("pltsp", 6);
formats.put("pllay", 6);
formats.put("pltha", 6);
formats.put("plth#", 6);
formats.put("plthl", 6);
formats.put("plthm", 16);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
if (!meta.containsKey("tr_notes")) {
meta.put("tr_notes", line + "\r\n");
} else {
String notes = (String) meta.get("tr_notes");
notes += line + "\r\n";
meta.put("tr_notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data / Rotation data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 3); // For 3-bit treatment number (2->3)
formats.put("sq", 1); // For 3-bit treatment number (2->1)
formats.put("op", 2);
formats.put("co", 2);
formats.put("trt_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
if (tmp.get("trt_name") == null) {
tmp.put("trt_name", meta.get("exname"));
}
sqArr.add(tmp);
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("crid", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
Object cul_id = tmp.get("cul_id");
if (cul_id != null) {
tmp.put("dssat_cul_id", cul_id);
}
Object crid = tmp.get("crid");
if (crid == null) {
crid = fileName.replaceAll("\\w+\\.", "").replaceAll("X$", "");
}
tmp.put("crid", DssatCRIDHelper.get3BitCrid((String) crid));
cuArr.add(tmp);
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wst_id", 9); // P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(flArr, tmp, "fl");
// Read weather station id
wid = (String) tmp.get("wst_id");
if (wid != null && wid.matches("\\w{4}\\d{4}$")) {
wid = wid.substring(0, 4);
// tmp.put("wst_id", wid);
}
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_long", 16);
formats.put("fl_lat", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = null;
strLong = null;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = null;
strLong = null;
}
}
if (tmp.containsKey("fl_lat")) {
tmp.put("fl_lat", strLat);
}
if (tmp.containsKey("fl_long")) {
tmp.put("fl_long", strLong);
}
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("smhb", 6); // P.S. changed from samhb to smhb to match the soil variable name
formats.put("smpx", 6); // P.S. changed from sampx to smpx to match the soil variable name
formats.put("smke", 6); // P.S. changed from samke to smke to match the soil variable name
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "sadat");
saArr.add(tmp);
sadArr = new ArrayList<HashMap>();
tmp.put(icEventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sabl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sllb", 6); // P.S. changed from sabl to sllb to match the soil variable name
formats.put("slbdm", 6); // P.S. changed from sabdm to slbdm to match the soil variable name
formats.put("sloc", 6); // P.S. changed from saoc to sloc to match the soil variable name
formats.put("slni", 6); // P.S. changed from sani to slni to match the soil variable name
formats.put("slphw", 6); // P.S. changed from saphw to slphw to match the soil variable name
formats.put("slphb", 6); // P.S. changed from saphb to slphb to match the soil variable name
formats.put("slpx", 6); // P.S. changed from sapx to slpx to match the soil variable name
formats.put("slke", 6); // P.S. changed from sake to slke to match the soil variable name
formats.put("slsc", 6); // P.S. changed from sasc to slsc to match the soil variable name
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6);
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "icdat");
icArr.add(tmp);
icdArr = new ArrayList<HashMap>();
tmp.put(icEventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plma", 6); // P.S. 2012.07.13 changed from plme to plma
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("plenv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "pdate");
translateDateStr(tmp, "pldae");
// cm -> mm
String pldp = getObjectOr(tmp, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.multiply(new BigDecimal("10"));
tmp.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
plArr.add(tmp);
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if ((flg[1].startsWith("i efir") || flg4 % 2 == 1) && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
ireff = (String) tmp.get("ireff");
if (ireff != null) {
tmp.remove("ireff");
}
irArr.add(tmp);
irdArr = new ArrayList<HashMap>();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.getOr("idate"))); // P.S. DOY handling
tmp.put("ireff", ireff);
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "fdate"); // P.S. DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6);
formats.put("omp%", 6);
formats.put("omk%", 6);
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "omdat"); // P.S. DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "cdate");
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "tdate");
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
// formats.put("emday", 6);
// formats.put("ecdyl", 2);
// formats.put("emdyl", 4);
// formats.put("ecrad", 2);
// formats.put("emrad", 4);
// formats.put("ecmax", 2);
// formats.put("emmax", 4);
// formats.put("ecmin", 2);
// formats.put("emmin", 4);
// formats.put("ecrai", 2);
// formats.put("emrai", 4);
// formats.put("ecco2", 2);
// formats.put("emco2", 4);
// formats.put("ecdew", 2);
// formats.put("emdew", 4);
// formats.put("ecwnd", 2);
// formats.put("emwnd", 4);
// formats.put("em_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "emday");
tmp.put("em_data", line.substring(2));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hadat", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hap%", 6);
formats.put("hab%", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "hadat");
haArr.add(tmp);
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_general", line.length());
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "sdate");
// smSubArr = new ArrayList();
// smArr.add(tmp);
// tmp.put(eventKey, smSubArr);
// smSubArr.add(line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_options", line.length());
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_methods", line.length());
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_management", line.length());
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_outputs", line.length());
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_planting", line.length());
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "pfrst");
// translateDateStr(tmp, "plast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_irrigation", line.length());
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_nitrogen", line.length());
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_residues", line.length());
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_harvests", line.length());
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "hlast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
// Combine all the sections data into the related treatment block
String trno = null;
HashMap dssatSq;
// HashMap dssatInfo = new HashMap();
ArrayList<HashMap> sqArrNew = new ArrayList<HashMap>();
for (int i = 0, seqid = 1; i < sqArr.size(); i++, seqid++) {
sqData = (HashMap) sqArr.get(i);
trMetaData = new HashMap();
trMetaArr.add(trMetaData);
if (!sqData.get("trno").equals(trno)) {
trno = sqData.get("trno").toString();
trData = new HashMap();
evtArr = new ArrayList<HashMap>();
trArr.add(trData);
trData.put("events", evtArr);
dssatSq = new HashMap();
sqArrNew = new ArrayList<HashMap>();
// dssatInfo = new HashMap();
dssatSq.put(eventKey, sqArrNew);
trData.put("dssat_sequence", dssatSq);
// trData.put("dssat_info", dssatInfo);
trMetaData.put("trt_name", sqData.get("trt_name"));
trMetaData.put("trno", trno);
trMetaData.put("exname", exname);
seqid = 1;
} else {
// The case of multiple sequence
trMetaData.remove("trt_name");
}
sqData.put("seqid", seqid + "");
sqArrNew.add(sqData);
// cultivar
HashMap crData = new HashMap();
if (!getObjectOr(sqData, "ge", "0").equals("0")) {
// Get related cultivar data
crData = (HashMap) getSectionDataObj(cuArr, "ge", sqData.get("ge").toString());
}
// field
if (!getObjectOr(sqData, "fl", "0").equals("0")) {
// Move field info into meta data block
trMetaData.putAll((HashMap) getSectionDataObj(flArr, "fl", sqData.get("fl").toString()));
trMetaData.remove("fl");
}
// initial_condition
if (!getObjectOr(sqData, "ic", "0").equals("0")) {
HashMap icTmpArr = (HashMap) getSectionDataObj(icArr, "ic", sqData.get("ic").toString());
if (!icTmpArr.isEmpty()) {
trData.put("initial_conditions", icTmpArr);
}
}
// planting
String pdate = "";
if (!getObjectOr(sqData, "pl", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(plArr, "pl", sqData.get("pl").toString()), "pdate", "planting", seqid);
// add cultivar data into planting event
if (crData != null) {
evtArr.get(evtArr.size() - 1).putAll(crData);
}
// Get planting date for DOY value handling
pdate = getValueOr(evtArr.get(evtArr.size() - 1), "pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// irrigation
if (!getObjectOr(sqData, "ir", "0").equals("0")) {
// Date adjust based on realted treatment info (handling for DOY type value)
HashMap irTmp = (HashMap) getSectionDataObj(irArr, "ir", sqData.get("ir").toString());
ArrayList<HashMap> irTmpSubs = getObjectOr(irTmp, "data", new ArrayList());
for (int j = 0; j < irTmpSubs.size(); j++) {
HashMap irTmpSub = irTmpSubs.get(j);
translateDateStrForDOY(irTmpSub, "idate", pdate);
}
// add event data into array
addEvent(evtArr, irTmp, "idate", "irrigation", seqid);
}
// fertilizer
if (!getObjectOr(sqData, "fe", "0").equals("0")) {
ArrayList<HashMap> feTmps = (ArrayList) getSectionDataObj(feArr, "fe", sqData.get("fe").toString());
HashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = feTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(feTmp, "fdate", pdate);
// add event data into array
addEvent(evtArr, feTmp, "fdate", "fertilizer", seqid);
}
}
// organic_matter
if (!getObjectOr(sqData, "om", "0").equals("0")) {
ArrayList<HashMap> omTmps = (ArrayList) getSectionDataObj(omArr, "om", sqData.get("om").toString());
HashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = omTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(omTmp, "omdat", pdate);
// add event data into array
addEvent(evtArr, omTmp, "omdat", "organic_matter", seqid); // P.S. change event name to organic-materials; Back to organic_matter again
}
}
// chemical
if (!getObjectOr(sqData, "ch", "0").equals("0")) {
ArrayList<HashMap> chTmps = (ArrayList) getSectionDataObj(chArr, "ch", sqData.get("ch").toString());
for (int j = 0; j < chTmps.size(); j++) {
// add event data into array
addEvent(evtArr, chTmps.get(j), "cdate", "chemical", seqid);
}
}
// tillage
if (!getObjectOr(sqData, "ti", "0").equals("0")) {
ArrayList<HashMap> tiTmps = (ArrayList) getSectionDataObj(tiArr, "ti", sqData.get("ti").toString());
for (int j = 0; j < tiTmps.size(); j++) {
// add event data into array
addEvent(evtArr, tiTmps.get(j), "tdate", "tillage", seqid);
}
}
// emvironment // P.S. keep for furture using
if (!getObjectOr(sqData, "em", "0").equals("0")) {
String em = (String) sqData.get("em");
ArrayList<HashMap> emDataArr = (ArrayList) getSectionDataObj(emArr, "em", em);
// ArrayList arr = new ArrayList();
// for (int j = 0; j < emDataArr.size(); j++) {
// arr.add(emDataArr.get(j).get("em_data"));
// }
// sqData.put("em_data", arr);
HashMap tmp = getObjectOr(trData, "dssat_environment_modification", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (em.equals(arr.get(j).get("em"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.addAll(emDataArr);
}
tmp.put(eventKey, arr);
trData.put("dssat_environment_modification", tmp);
}
// harvest
if (!getObjectOr(sqData, "ha", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(haArr, "ha", sqData.get("ha").toString()), "hadat", "harvest", seqid);
}
// simulation
if (!getObjectOr(sqData, "sm", "0").equals("0")) {
String sm = (String) sqData.get("sm");
HashMap smData = (HashMap) getSectionDataObj(smArr, "sm", sm);
// sqData.putAll((HashMap) getSectionDataObj(smArr, "sm", sm));
HashMap tmp = getObjectOr(trData, "dssat_simulation_control", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (sm.equals(arr.get(j).get("sm"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.add(smData);
}
tmp.put(eventKey, arr);
trData.put("dssat_simulation_control", tmp);
}
// soil_analysis
if (!getObjectOr(sqData, "sa", "0").equals("0")) {
HashMap saTmp = (HashMap) getSectionDataObj(saArr, "sa", sqData.get("sa").toString());
// ArrayList<HashMap> saSubArr = getObjectOr(saTmp, icEventKey, new ArrayList());
// temporally put soil_analysis block into treatment meta data
trMetaData.put("soil_analysis", saTmp);
// // Add SASC into initial condition block
// ArrayList<HashMap> icSubArrNew;
// HashMap icTmp;
// String[] copyKeys = {"slsc"};
// if (!trData.containsKey("initial_condition")) {
// // Add a dummy ic block to hold SASC
// icTmp = new HashMap();
// trData.put("initial_condition", icTmp);
// icSubArrNew = combinLayers(new ArrayList<HashMap>(), saSubArr, "icbl", "sllb", copyKeys);
// } else {
// // Add SASC into initial condition block
// icTmp = (HashMap) trData.get("initial_condition");
// ArrayList<HashMap> icSubArr = getObjectOr(icTmp, icEventKey, new ArrayList());
// icSubArrNew = combinLayers(icSubArr, saSubArr, "icbl", "sllb", copyKeys);
// }
// icTmp.put(icEventKey, icSubArrNew);
}
}
}
// Remove relational index
ArrayList idNames = new ArrayList();
idNames.add("ge");
idNames.add("fl");
idNames.add("sa");
idNames.add("ic");
idNames.add("pl");
idNames.add("ir");
idNames.add("fe");
idNames.add("om");
idNames.add("ch");
idNames.add("ti");
// idNames.add("em");
idNames.add("ha");
// idNames.add("sm");
removeIndex(trArr, idNames);
removeIndex(metaData, idNames);
return trArr;
}
| protected ArrayList<HashMap> readTreatments(HashMap brMap, HashMap metaData) throws IOException {
String line;
BufferedReader br;
Object buf;
BufferedReader brw = null;
char[] bufW = null;
HashMap mapX;
HashMap mapW;
String wid;
String fileName;
LinkedHashMap formats = new LinkedHashMap();
ArrayList<HashMap> trArr = new ArrayList<HashMap>();
HashMap trData = new HashMap();
ArrayList<HashMap> evtArr = new ArrayList<HashMap>();
String ireff = ""; // P.S. special handling for EFIR in irrigation section
// Set meta data info for each treatment
ArrayList<HashMap> trMetaArr = new ArrayList<HashMap>();
HashMap trMetaData;
metaData.put("tr_meta", trMetaArr);
mapX = (HashMap) brMap.get("X");
mapW = (HashMap) brMap.get("W");
// If XFile is no been found
if (mapX.isEmpty()) {
return trArr;
}
for (Object keyX : mapX.keySet()) {
buf = mapX.get(keyX);
if (buf instanceof char[]) {
br = new BufferedReader(new CharArrayReader((char[]) buf));
} else {
br = (BufferedReader) buf;
}
// fileName = (String) brMap.get("Z");
fileName = (String) keyX;
wid = fileName.length() > 4 ? fileName.substring(0, 4) : fileName;
// String exname = fileName.replaceAll("\\.", "").replaceAll("X$", "");
String exname = fileName.replaceAll("\\.\\w\\wX$", "");
HashMap meta = new HashMap();
metaData.put(exname, meta);
ArrayList<HashMap> sqArr = new ArrayList<HashMap>();
HashMap sqData;
ArrayList<HashMap> cuArr = new ArrayList<HashMap>();
ArrayList<HashMap> flArr = new ArrayList<HashMap>();
ArrayList<HashMap> saArr = new ArrayList<HashMap>();
ArrayList<HashMap> sadArr = new ArrayList<HashMap>();
ArrayList<HashMap> icArr = new ArrayList<HashMap>();
ArrayList<HashMap> icdArr = new ArrayList<HashMap>();
ArrayList<HashMap> plArr = new ArrayList<HashMap>();
ArrayList<HashMap> irArr = new ArrayList<HashMap>();
ArrayList<HashMap> irdArr = new ArrayList<HashMap>();
ArrayList<HashMap> feArr = new ArrayList<HashMap>();
ArrayList<HashMap> omArr = new ArrayList<HashMap>();
ArrayList<HashMap> chArr = new ArrayList<HashMap>();
ArrayList<HashMap> tiArr = new ArrayList<HashMap>();
ArrayList<HashMap> emArr = new ArrayList<HashMap>();
ArrayList<HashMap> haArr = new ArrayList<HashMap>();
ArrayList<HashMap> smArr = new ArrayList<HashMap>();
while ((line = br.readLine()) != null) {
// Get content type of line
judgeContentType(line);
// Read Exp title info
if (flg[0].startsWith("exp.details:") && flg[2].equals("")) {
// Set variables' formats
formats.clear();
formats.put("null_1", 14);
formats.put("null_2", 11); // P.S. Since exname in top line is not reliable, read from file name
formats.put("local_name", 61);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
meta.put("exname", exname);
meta.put("in", getObjectOr(meta, "exname", " ").substring(0, 2).trim());
} // Read General Section
else if (flg[0].startsWith("general")) {
// People info
if (flg[1].equals("people") && flg[2].equals("data")) {
if (checkValidValue(line.trim())) {
meta.put("person_notes", line.trim());
}
} // Address info
else if (flg[1].equals("address") && flg[2].equals("data")) {
// String[] addr;
if (checkValidValue(line.trim())) {
// addr = line.split(",[ ]*");
meta.put("institution", line.trim());
} else {
// addr = new String[0];
}
// switch (addr.length) {
// case 0:
// break;
// case 1:
// meta.put("fl_loc_1", addr[0]);
// break;
// case 2:
// meta.put("fl_loc_1", addr[1]);
// meta.put("fl_loc_2", addr[0]);
// break;
// case 3:
// meta.put("fl_loc_1", addr[2]);
// meta.put("fl_loc_2", addr[1]);
// meta.put("fl_loc_3", addr[0]);
// break;
// default:
// meta.put("fl_loc_1", addr[addr.length - 1]);
// meta.put("fl_loc_2", addr[addr.length - 2]);
// String loc3 = "";
// for (int i = 0; i < addr.length - 2; i++) {
// loc3 += addr[i] + ", ";
// }
// meta.put("fl_loc_3", loc3.substring(0, loc3.length() - 2));
// }
} // Site info
else if ((flg[1].equals("site") || flg[1].equals("sites")) && flg[2].equals("data")) {
// P.S. site is missing in the master variables list
if (checkValidValue(line.trim())) {
meta.put("site_name", line.trim());
}
} // Plot Info
else if (flg[1].startsWith("parea") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("plta", 7);
formats.put("pltr#", 6);
formats.put("pltln", 6);
formats.put("pldr", 6);
formats.put("pltsp", 6);
formats.put("pllay", 6);
formats.put("pltha", 6);
formats.put("plth#", 6);
formats.put("plthl", 6);
formats.put("plthm", 16);
// Read line and save into return holder
meta.putAll(readLine(line, formats));
} // Notes field
else if (flg[1].equals("notes") && flg[2].equals("data")) {
if (!meta.containsKey("tr_notes")) {
meta.put("tr_notes", line + "\r\n");
} else {
String notes = (String) meta.get("tr_notes");
notes += line + "\r\n";
meta.put("tr_notes", notes);
}
} else {
}
} // Read TREATMENTS Section
else if (flg[0].startsWith("treatments")) {
// Read TREATMENTS data / Rotation data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("trno", 3); // For 3-bit treatment number (2->3)
formats.put("sq", 1); // For 3-bit treatment number (2->1)
formats.put("op", 2);
formats.put("co", 2);
formats.put("trt_name", 26);
formats.put("ge", 3);
formats.put("fl", 3);
formats.put("sa", 3);
formats.put("ic", 3);
formats.put("pl", 3);
formats.put("ir", 3);
formats.put("fe", 3);
formats.put("om", 3);
formats.put("ch", 3);
formats.put("ti", 3);
formats.put("em", 3);
formats.put("ha", 3);
formats.put("sm", 3);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
if (tmp.get("trt_name") == null) {
tmp.put("trt_name", meta.get("exname"));
}
sqArr.add(tmp);
} else {
}
} // Read CULTIVARS Section
else if (flg[0].startsWith("cultivars")) {
// Read CULTIVARS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ge", 2);
formats.put("crid", 3);
formats.put("cul_id", 7);
formats.put("cul_name", 17);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
Object cul_id = tmp.get("cul_id");
if (cul_id != null) {
tmp.put("dssat_cul_id", cul_id);
}
Object crid = tmp.get("crid");
if (crid == null) {
crid = fileName.replaceAll("\\w+\\.", "").replaceAll("X$", "");
}
tmp.put("crid", DssatCRIDHelper.get3BitCrid((String) crid));
cuArr.add(tmp);
} else {
}
} // Read FIELDS Section
else if (flg[0].startsWith("fields")) {
// Read field info 1st line
if (flg[1].startsWith("l id_") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("id_field", 9);
formats.put("wst_id", 9); // P.S. id do not match with the master list "wth_id"; might have another id name
formats.put("flsl", 6);
formats.put("flob", 6);
formats.put("fl_drntype", 6);
formats.put("fldrd", 6);
formats.put("fldrs", 6);
formats.put("flst", 6);
formats.put("sltx", 6);
formats.put("sldp", 6);
formats.put("soil_id", 11);
formats.put("fl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(flArr, tmp, "fl");
// Read weather station id
wid = (String) tmp.get("wst_id");
if (wid != null && wid.matches("\\w{4}\\d{4}$")) {
wid = wid.substring(0, 4);
// tmp.put("wst_id", wid);
}
}// // Read field info 2nd line
else if (flg[1].startsWith("l ...") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fl", 2);
formats.put("fl_long", 16);
formats.put("fl_lat", 16);
formats.put("flele", 10);
formats.put("farea", 18);
formats.put("", 6); // P.S. id do not find in the master list (? it seems to be calculated by other fields)
formats.put("fllwr", 6);
formats.put("flsla", 6);
formats.put("flhst", 6); // P.S. id do not find in the master list (field histoy code)
formats.put("fhdur", 6); // P.S. id do not find in the master list (duration associated with field history code in years)
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// Read lat and long
String strLat = (String) tmp.get("fl_lat");
String strLong = (String) tmp.get("fl_long");
// If lat or long is not valid data, read data from weather file
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
// check if weather is validable
for (Object key : mapW.keySet()) {
if (((String) key).contains(wid)) {
bufW = (char[]) mapW.get(key);
break;
}
}
if (bufW != null) {
brw = new BufferedReader(new CharArrayReader(bufW));
String lineW;
while ((lineW = brw.readLine()) != null) {
if (lineW.startsWith("@ INSI")) {
lineW = brw.readLine();
strLat = lineW.substring(6, 15).trim();
strLong = lineW.substring(15, 24).trim();
break;
}
}
// check if lat and long are valid in the weather file; if not, set invalid value for them
if (!checkValidValue(strLat) || !checkValidValue(strLong) || (Double.parseDouble(strLat) == 0 && Double.parseDouble(strLong) == 0)) {
strLat = null;
strLong = null;
}
} // if weather file is not avaliable to read, set invalid value for lat and long
else {
strLat = null;
strLong = null;
}
}
if (tmp.containsKey("fl_lat")) {
tmp.put("fl_lat", strLat);
}
if (tmp.containsKey("fl_long")) {
tmp.put("fl_long", strLong);
}
addToArray(flArr, tmp, "fl");
}
} // Read SOIL ANALYSIS Section
else if (flg[0].startsWith("soil")) {
// Read SOIL ANALYSIS global data
if (flg[1].startsWith("a sadat") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sa", 2);
formats.put("sadat", 6);
formats.put("smhb", 6); // P.S. changed from samhb to smhb to match the soil variable name
formats.put("smpx", 6); // P.S. changed from sampx to smpx to match the soil variable name
formats.put("smke", 6); // P.S. changed from samke to smke to match the soil variable name
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "sadat");
saArr.add(tmp);
sadArr = new ArrayList<HashMap>();
tmp.put(icEventKey, sadArr);
} // Read SOIL ANALYSIS layer data
else if (flg[1].startsWith("a sabl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "sa"
formats.put("sllb", 6); // P.S. changed from sabl to sllb to match the soil variable name
formats.put("slbdm", 6); // P.S. changed from sabdm to slbdm to match the soil variable name
formats.put("sloc", 6); // P.S. changed from saoc to sloc to match the soil variable name
formats.put("slni", 6); // P.S. changed from sani to slni to match the soil variable name
formats.put("slphw", 6); // P.S. changed from saphw to slphw to match the soil variable name
formats.put("slphb", 6); // P.S. changed from saphb to slphb to match the soil variable name
formats.put("slpx", 6); // P.S. changed from sapx to slpx to match the soil variable name
formats.put("slke", 6); // P.S. changed from sake to slke to match the soil variable name
formats.put("slsc", 6); // P.S. changed from sasc to slsc to match the soil variable name
// Read line and save into return holder
sadArr.add(readLine(line, formats));
} else {
}
} // Read INITIAL CONDITIONS Section
else if (flg[0].startsWith("initial")) {
// Read INITIAL CONDITIONS global data
if (flg[1].startsWith("c pcr") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ic", 2);
formats.put("icpcr", 6);
formats.put("icdat", 6);
formats.put("icrt", 6);
formats.put("icnd", 6);
formats.put("icrz#", 6);
formats.put("icrze", 6);
formats.put("icwt", 6);
formats.put("icrag", 6);
formats.put("icrn", 6);
formats.put("icrp", 6);
formats.put("icrip", 6);
formats.put("icrdp", 6);
formats.put("ic_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "icdat");
Object icpcr = tmp.get("icpcr");
if (icpcr != null) {
tmp.put("icpcr", DssatCRIDHelper.get3BitCrid((String) icpcr));
}
icArr.add(tmp);
icdArr = new ArrayList<HashMap>();
tmp.put(icEventKey, icdArr);
} else // INITIAL CONDITIONS layer data
if (flg[1].startsWith("c icbl") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the detail (event) data index "ic"
formats.put("icbl", 6);
formats.put("ich2o", 6);
formats.put("icnh4", 6);
formats.put("icno3", 6);
// Read line and save into return holder
icdArr.add(readLine(line, formats));
} else {
}
} // Read PLANTING DETAILS Section
else if (flg[0].startsWith("planting")) {
// Read PLANTING data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("pl", 2);
formats.put("pdate", 6);
formats.put("pldae", 6);
formats.put("plpop", 6);
formats.put("plpoe", 6);
formats.put("plma", 6); // P.S. 2012.07.13 changed from plme to plma
formats.put("plds", 6);
formats.put("plrs", 6);
formats.put("plrd", 6);
formats.put("pldp", 6);
formats.put("plmwt", 6);
formats.put("page", 6);
formats.put("plenv", 6);
formats.put("plph", 6);
formats.put("plspl", 6);
formats.put("pl_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "pdate");
translateDateStr(tmp, "pldae");
// cm -> mm
String pldp = getObjectOr(tmp, "pldp", "");
if (!pldp.equals("")) {
try {
BigDecimal pldpBD = new BigDecimal(pldp);
pldpBD = pldpBD.multiply(new BigDecimal("10"));
tmp.put("pldp", pldpBD.toString());
} catch (NumberFormatException e) {
}
}
plArr.add(tmp);
} else {
}
} // Read IRRIGATION AND WATER MANAGEMENT Section
else if (flg[0].startsWith("irrigation")) {
// Read IRRIGATION global data
if ((flg[1].startsWith("i efir") || flg4 % 2 == 1) && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ir", 2);
formats.put("ireff", 6);
formats.put("irmdp", 6);
formats.put("irthr", 6);
formats.put("irept", 6);
formats.put("irstg", 6);
formats.put("iame", 6);
formats.put("iamt", 6);
formats.put("ir_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
ireff = (String) tmp.get("ireff");
if (ireff != null) {
tmp.remove("ireff");
}
irArr.add(tmp);
irdArr = new ArrayList<HashMap>();
tmp.put(eventKey, irdArr);
} // Read IRRIGATION appliction data
else if (flg[1].startsWith("i idate") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("", 2); // P.S. ignore the data index "ir"
formats.put("idate", 6);
formats.put("irop", 6);
formats.put("irval", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// tmp.put("idate", translateDateStr((String) tmp.getOr("idate"))); // P.S. DOY handling
tmp.put("ireff", ireff);
irdArr.add(tmp);
} else {
}
} // Read FERTILIZERS (INORGANIC) Section
else if (flg[0].startsWith("fertilizers")) {
// Read FERTILIZERS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("fe", 2);
formats.put("fdate", 6);
formats.put("fecd", 6);
formats.put("feacd", 6);
formats.put("fedep", 6);
formats.put("feamn", 6);
formats.put("feamp", 6);
formats.put("feamk", 6);
formats.put("feamc", 6);
formats.put("feamo", 6);
formats.put("feocd", 6);
formats.put("fe_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "fdate"); // P.S. DOY handling
feArr.add(tmp);
} else {
}
} // Read RESIDUES AND OTHER ORGANIC MATERIALS Section
else if (flg[0].startsWith("residues")) {
// Read ORGANIC MATERIALS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("om", 2);
formats.put("omdat", 6); // P.S. id do not match with the master list "omday"
formats.put("omcd", 6);
formats.put("omamt", 6);
formats.put("omn%", 6);
formats.put("omp%", 6);
formats.put("omk%", 6);
formats.put("ominp", 6);
formats.put("omdep", 6);
formats.put("omacd", 6);
formats.put("om_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "omdat"); // P.S. DOY handling
omArr.add(tmp);
} else {
}
} // Read CHEMICAL APPLICATIONS Section
else if (flg[0].startsWith("chemical")) {
// Read CHEMICAL APPLICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ch", 2);
formats.put("cdate", 6);
formats.put("chcd", 6);
formats.put("chamt", 6);
formats.put("chacd", 6);
formats.put("chdep", 6);
formats.put("ch_targets", 6);
formats.put("ch_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "cdate");
chArr.add(tmp);
} else {
}
} // Read TILLAGE Section
else if (flg[0].startsWith("tillage")) {
// Read TILLAGE data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ti", 2);
formats.put("tdate", 6);
formats.put("tiimp", 6);
formats.put("tidep", 6);
formats.put("ti_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "tdate");
tiArr.add(tmp);
} else {
}
} // Read ENVIRONMENT MODIFICATIONS Section
else if (flg[0].startsWith("environment")) {
// Read ENVIRONMENT MODIFICATIONS data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("em", 2);
// formats.put("emday", 6);
// formats.put("ecdyl", 2);
// formats.put("emdyl", 4);
// formats.put("ecrad", 2);
// formats.put("emrad", 4);
// formats.put("ecmax", 2);
// formats.put("emmax", 4);
// formats.put("ecmin", 2);
// formats.put("emmin", 4);
// formats.put("ecrai", 2);
// formats.put("emrai", 4);
// formats.put("ecco2", 2);
// formats.put("emco2", 4);
// formats.put("ecdew", 2);
// formats.put("emdew", 4);
// formats.put("ecwnd", 2);
// formats.put("emwnd", 4);
// formats.put("em_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "emday");
tmp.put("em_data", line.substring(2));
emArr.add(tmp);
} else {
}
} // Read HARVEST DETAILS Section
else if (flg[0].startsWith("harvest")) {
// Read HARVEST data
if (flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("ha", 2);
formats.put("hadat", 6);
formats.put("hastg", 6);
formats.put("hacom", 6);
formats.put("hasiz", 6);
formats.put("hap%", 6);
formats.put("hab%", 6);
formats.put("ha_name", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
translateDateStr(tmp, "hadat");
haArr.add(tmp);
} else {
}
} // Read SIMULATION CONTROLS Section // P.S. no need to be divided
else if (flg[0].startsWith("simulation")) {
// Read general info
if (flg[1].startsWith("n general") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_general", line.length());
// formats.put("general", 12);
// formats.put("nyers", 6);
// formats.put("nreps", 6);
// formats.put("start", 6);
// formats.put("sdate", 6);
// formats.put("rseed", 6);
// formats.put("sname", 26);
// formats.put("model", line.length());
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "sdate");
// smSubArr = new ArrayList();
// smArr.add(tmp);
// tmp.put(eventKey, smSubArr);
// smSubArr.add(line);
addToArray(smArr, tmp, "sm");
} // Read options info
else if (flg[1].startsWith("n options") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_options", line.length());
// formats.put("options", 12);
// formats.put("water", 6);
// formats.put("nitro", 6);
// formats.put("symbi", 6);
// formats.put("phosp", 6);
// formats.put("potas", 6);
// formats.put("dises", 6);
// formats.put("chem", 6);
// formats.put("till", 6);
// formats.put("co2", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read methods info
else if (flg[1].startsWith("n methods") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_methods", line.length());
// formats.put("methods", 12);
// formats.put("wther", 6);
// formats.put("incon", 6);
// formats.put("light", 6);
// formats.put("evapo", 6);
// formats.put("infil", 6);
// formats.put("photo", 6);
// formats.put("hydro", 6);
// formats.put("nswit", 6);
// formats.put("mesom", 6);
// formats.put("mesev", 6);
// formats.put("mesol", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read management info
else if (flg[1].startsWith("n management") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_management", line.length());
// formats.put("management", 12);
// formats.put("plant", 6);
// formats.put("irrig", 6);
// formats.put("ferti", 6);
// formats.put("resid", 6);
// formats.put("harvs", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read outputs info
else if (flg[1].startsWith("n outputs") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_outputs", line.length());
// formats.put("outputs", 12);
// formats.put("fname", 6);
// formats.put("ovvew", 6);
// formats.put("sumry", 6);
// formats.put("fropt", 6);
// formats.put("grout", 6);
// formats.put("caout", 6);
// formats.put("waout", 6);
// formats.put("niout", 6);
// formats.put("miout", 6);
// formats.put("diout", 6);
// formats.put("long", 6);
// formats.put("chout", 6);
// formats.put("opout", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read planting info
else if (flg[1].startsWith("n planting") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_planting", line.length());
// formats.put("planting", 12);
// formats.put("pfrst", 6);
// formats.put("plast", 6);
// formats.put("ph20l", 6);
// formats.put("ph2ou", 6);
// formats.put("ph20d", 6);
// formats.put("pstmx", 6);
// formats.put("pstmn", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "pfrst");
// translateDateStr(tmp, "plast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read irrigation info
else if (flg[1].startsWith("n irrigation") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_irrigation", line.length());
// formats.put("irrigation", 12);
// formats.put("imdep", 6);
// formats.put("ithrl", 6);
// formats.put("ithru", 6);
// formats.put("iroff", 6);
// formats.put("imeth", 6);
// formats.put("iramt", 6);
// formats.put("ireff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read nitrogen info
else if (flg[1].startsWith("n nitrogen") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_nitrogen", line.length());
// formats.put("nitrogen", 12);
// formats.put("nmdep", 6);
// formats.put("nmthr", 6);
// formats.put("namnt", 6);
// formats.put("ncode", 6);
// formats.put("naoff", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read residues info
else if (flg[1].startsWith("n residues") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_residues", line.length());
// formats.put("residues", 12);
// formats.put("ripcn", 6);
// formats.put("rtime", 6);
// formats.put("ridep", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} // Read harvest info
else if (flg[1].startsWith("n harvest") && flg[2].equals("data")) {
// Set variables' formats
formats.clear();
formats.put("sm", 2);
formats.put("sm_harvests", line.length());
// formats.put("harvests", 12);
// formats.put("hfrst", 6); // P.S. Keep the original value
// formats.put("hlast", 6);
// formats.put("hpcnp", 6);
// formats.put("hrcnr", 6);
// Read line and save into return holder
HashMap tmp = readLine(line, formats);
// translateDateStr(tmp, "hlast");
addToArray(smArr, tmp, "sm");
// smSubArr.add(line);
} else {
}
} else {
}
}
br.close();
if (brw != null) {
brw.close();
}
// Combine all the sections data into the related treatment block
String trno = null;
HashMap dssatSq;
// HashMap dssatInfo = new HashMap();
ArrayList<HashMap> sqArrNew = new ArrayList<HashMap>();
for (int i = 0, seqid = 1; i < sqArr.size(); i++, seqid++) {
sqData = (HashMap) sqArr.get(i);
trMetaData = new HashMap();
trMetaArr.add(trMetaData);
if (!sqData.get("trno").equals(trno)) {
trno = sqData.get("trno").toString();
trData = new HashMap();
evtArr = new ArrayList<HashMap>();
trArr.add(trData);
trData.put("events", evtArr);
dssatSq = new HashMap();
sqArrNew = new ArrayList<HashMap>();
// dssatInfo = new HashMap();
dssatSq.put(eventKey, sqArrNew);
trData.put("dssat_sequence", dssatSq);
// trData.put("dssat_info", dssatInfo);
trMetaData.put("trt_name", sqData.get("trt_name"));
trMetaData.put("trno", trno);
trMetaData.put("exname", exname);
seqid = 1;
} else {
// The case of multiple sequence
trMetaData.remove("trt_name");
}
sqData.put("seqid", seqid + "");
sqArrNew.add(sqData);
// cultivar
HashMap crData = new HashMap();
if (!getObjectOr(sqData, "ge", "0").equals("0")) {
// Get related cultivar data
crData = (HashMap) getSectionDataObj(cuArr, "ge", sqData.get("ge").toString());
}
// field
if (!getObjectOr(sqData, "fl", "0").equals("0")) {
// Move field info into meta data block
trMetaData.putAll((HashMap) getSectionDataObj(flArr, "fl", sqData.get("fl").toString()));
trMetaData.remove("fl");
}
// initial_condition
if (!getObjectOr(sqData, "ic", "0").equals("0")) {
HashMap icTmpArr = (HashMap) getSectionDataObj(icArr, "ic", sqData.get("ic").toString());
if (!icTmpArr.isEmpty()) {
trData.put("initial_conditions", icTmpArr);
}
}
// planting
String pdate = "";
if (!getObjectOr(sqData, "pl", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(plArr, "pl", sqData.get("pl").toString()), "pdate", "planting", seqid);
// add cultivar data into planting event
if (crData != null) {
evtArr.get(evtArr.size() - 1).putAll(crData);
}
// Get planting date for DOY value handling
pdate = getValueOr(evtArr.get(evtArr.size() - 1), "pdate", "");
if (pdate.length() > 5) {
pdate = pdate.substring(2);
}
}
// irrigation
if (!getObjectOr(sqData, "ir", "0").equals("0")) {
// Date adjust based on realted treatment info (handling for DOY type value)
HashMap irTmp = (HashMap) getSectionDataObj(irArr, "ir", sqData.get("ir").toString());
ArrayList<HashMap> irTmpSubs = getObjectOr(irTmp, "data", new ArrayList());
for (int j = 0; j < irTmpSubs.size(); j++) {
HashMap irTmpSub = irTmpSubs.get(j);
translateDateStrForDOY(irTmpSub, "idate", pdate);
}
// add event data into array
addEvent(evtArr, irTmp, "idate", "irrigation", seqid);
}
// fertilizer
if (!getObjectOr(sqData, "fe", "0").equals("0")) {
ArrayList<HashMap> feTmps = (ArrayList) getSectionDataObj(feArr, "fe", sqData.get("fe").toString());
HashMap feTmp;
for (int j = 0; j < feTmps.size(); j++) {
feTmp = feTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(feTmp, "fdate", pdate);
// add event data into array
addEvent(evtArr, feTmp, "fdate", "fertilizer", seqid);
}
}
// organic_matter
if (!getObjectOr(sqData, "om", "0").equals("0")) {
ArrayList<HashMap> omTmps = (ArrayList) getSectionDataObj(omArr, "om", sqData.get("om").toString());
HashMap omTmp;
for (int j = 0; j < omTmps.size(); j++) {
omTmp = omTmps.get(j);
// Date adjust based on realted treatment info (handling for DOY type value)
translateDateStrForDOY(omTmp, "omdat", pdate);
// add event data into array
addEvent(evtArr, omTmp, "omdat", "organic_matter", seqid); // P.S. change event name to organic-materials; Back to organic_matter again
}
}
// chemical
if (!getObjectOr(sqData, "ch", "0").equals("0")) {
ArrayList<HashMap> chTmps = (ArrayList) getSectionDataObj(chArr, "ch", sqData.get("ch").toString());
for (int j = 0; j < chTmps.size(); j++) {
// add event data into array
addEvent(evtArr, chTmps.get(j), "cdate", "chemical", seqid);
}
}
// tillage
if (!getObjectOr(sqData, "ti", "0").equals("0")) {
ArrayList<HashMap> tiTmps = (ArrayList) getSectionDataObj(tiArr, "ti", sqData.get("ti").toString());
for (int j = 0; j < tiTmps.size(); j++) {
// add event data into array
addEvent(evtArr, tiTmps.get(j), "tdate", "tillage", seqid);
}
}
// emvironment // P.S. keep for furture using
if (!getObjectOr(sqData, "em", "0").equals("0")) {
String em = (String) sqData.get("em");
ArrayList<HashMap> emDataArr = (ArrayList) getSectionDataObj(emArr, "em", em);
// ArrayList arr = new ArrayList();
// for (int j = 0; j < emDataArr.size(); j++) {
// arr.add(emDataArr.get(j).get("em_data"));
// }
// sqData.put("em_data", arr);
HashMap tmp = getObjectOr(trData, "dssat_environment_modification", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (em.equals(arr.get(j).get("em"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.addAll(emDataArr);
}
tmp.put(eventKey, arr);
trData.put("dssat_environment_modification", tmp);
}
// harvest
if (!getObjectOr(sqData, "ha", "0").equals("0")) {
// add event data into array
addEvent(evtArr, (HashMap) getSectionDataObj(haArr, "ha", sqData.get("ha").toString()), "hadat", "harvest", seqid);
}
// simulation
if (!getObjectOr(sqData, "sm", "0").equals("0")) {
String sm = (String) sqData.get("sm");
HashMap smData = (HashMap) getSectionDataObj(smArr, "sm", sm);
// sqData.putAll((HashMap) getSectionDataObj(smArr, "sm", sm));
HashMap tmp = getObjectOr(trData, "dssat_simulation_control", new HashMap());
ArrayList<HashMap> arr = getObjectOr(tmp, eventKey, new ArrayList());
boolean isExistFlg = false;
for (int j = 0; j < arr.size(); j++) {
if (sm.equals(arr.get(j).get("sm"))) {
isExistFlg = true;
break;
}
}
if (!isExistFlg) {
arr.add(smData);
}
tmp.put(eventKey, arr);
trData.put("dssat_simulation_control", tmp);
}
// soil_analysis
if (!getObjectOr(sqData, "sa", "0").equals("0")) {
HashMap saTmp = (HashMap) getSectionDataObj(saArr, "sa", sqData.get("sa").toString());
// ArrayList<HashMap> saSubArr = getObjectOr(saTmp, icEventKey, new ArrayList());
// temporally put soil_analysis block into treatment meta data
trMetaData.put("soil_analysis", saTmp);
// // Add SASC into initial condition block
// ArrayList<HashMap> icSubArrNew;
// HashMap icTmp;
// String[] copyKeys = {"slsc"};
// if (!trData.containsKey("initial_condition")) {
// // Add a dummy ic block to hold SASC
// icTmp = new HashMap();
// trData.put("initial_condition", icTmp);
// icSubArrNew = combinLayers(new ArrayList<HashMap>(), saSubArr, "icbl", "sllb", copyKeys);
// } else {
// // Add SASC into initial condition block
// icTmp = (HashMap) trData.get("initial_condition");
// ArrayList<HashMap> icSubArr = getObjectOr(icTmp, icEventKey, new ArrayList());
// icSubArrNew = combinLayers(icSubArr, saSubArr, "icbl", "sllb", copyKeys);
// }
// icTmp.put(icEventKey, icSubArrNew);
}
}
}
// Remove relational index
ArrayList idNames = new ArrayList();
idNames.add("ge");
idNames.add("fl");
idNames.add("sa");
idNames.add("ic");
idNames.add("pl");
idNames.add("ir");
idNames.add("fe");
idNames.add("om");
idNames.add("ch");
idNames.add("ti");
// idNames.add("em");
idNames.add("ha");
// idNames.add("sm");
removeIndex(trArr, idNames);
removeIndex(metaData, idNames);
return trArr;
}
|
diff --git a/src/de/mpicbg/tds/knime/heatmap/PlateViewer.java b/src/de/mpicbg/tds/knime/heatmap/PlateViewer.java
index 9bdbfdb..c3e3968 100644
--- a/src/de/mpicbg/tds/knime/heatmap/PlateViewer.java
+++ b/src/de/mpicbg/tds/knime/heatmap/PlateViewer.java
@@ -1,211 +1,213 @@
package de.mpicbg.tds.knime.heatmap;
import de.mpicbg.tds.knime.heatmap.menu.HeatMapColorToolBar;
import de.mpicbg.tds.knime.heatmap.menu.HeatMapInputToolbar;
import de.mpicbg.tds.knime.heatmap.menu.HiLiteMenu;
import de.mpicbg.tds.knime.heatmap.menu.ViewMenu;
import de.mpicbg.tds.core.model.Plate;
import de.mpicbg.tds.core.util.PanelImageExporter;
import de.mpicbg.tds.knime.heatmap.renderer.HeatPlate;
import de.mpicbg.tds.knime.heatmap.renderer.HeatTrellis;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
/**
* Creates a window for a detailed plate view.
* Replaces PlatePanel
*
* @author Felix Meyenhofer
* created: 20/12/12
*
* TODO: I would be a nice thing to have the option to keep the plate dimensions during resizing.
*/
public class PlateViewer extends JFrame implements HeatMapModelChangeListener, HeatMapViewer {
/** The plate grid {@link de.mpicbg.tds.knime.heatmap.renderer.HeatTrellis} holds the {@link HeatMapModel} instance
* containing the {@link HeatMapModelChangeListener} needed to update the GUIs */
private HeatTrellis updater;
/** The {@link HeatMapModel} object which is partially separated for this instance of the PlateViewer. */
private HeatMapModel heatMapModel;
/** GUI components made accessible */
private JPanel heatMapContainer;
private HeatMapColorToolBar colorbar;
private HeatMapInputToolbar toolbar;
/**
* Constructor for the GUI component initialization.
*/
public PlateViewer() {
this.initialize();
}
/**
* Constructor of the PlateViewer allowing to propagate the data from
* {@link ScreenViewer}.
*
* @param parent {@link HeatTrellis} is the plate grid from the {@link ScreenViewer}.
* @param plate {@link Plate} object containing the data for visualization.
*/
public PlateViewer(HeatTrellis parent, Plate plate) {
this();
this.updater = parent;
// Create a new instance of the HeatMapModel and copy some attributes.
HeatMapModel model = new HeatMapModel();
model.setCurrentReadout(parent.heatMapModel.getSelectedReadOut());
model.setCurrentOverlay(parent.heatMapModel.getCurrentOverlay());
model.setColorScheme(parent.heatMapModel.getColorScheme());
model.setHideMostFreqOverlay(parent.heatMapModel.doHideMostFreqOverlay());
model.setWellSelection(parent.heatMapModel.getWellSelection());
model.setHiLite(parent.heatMapModel.getHiLite());
model.setHiLiteHandler(parent.heatMapModel.getHiLiteHandler());
model.setColorGradient(parent.heatMapModel.getColorGradient());
model.setKnimeColorAttribute(parent.heatMapModel.getKnimeColorAttribute());
model.setReferencePopulations(parent.heatMapModel.getReferencePopulations());
+ model.setAnnotations(parent.heatMapModel.getAnnotations());
+ model.setReadouts(parent.heatMapModel.getReadouts());
if ( parent.heatMapModel.isGlobalScaling() ) {
model.setScreen(parent.heatMapModel.getScreen());
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategy());
} else {
model.setScreen(Arrays.asList(plate));
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategyInstance());
}
this.heatMapModel = model;
// Creating the menu
JMenuBar menu = new JMenuBar();
menu.add(new HiLiteMenu(this));
ViewMenu viewMenu = new ViewMenu(this);
menu.add(viewMenu);
if ( parent.heatMapModel.isGlobalScaling() )
viewMenu.getColorMenuItem().setEnabled(!parent.heatMapModel.isGlobalScaling());
setJMenuBar(menu);
// Register the Viewer in the ChangeListeners
parent.heatMapModel.addChangeListener(this);
this.heatMapModel.addChangeListener(this);
// Give a meaningful title.
this.setTitle("Plate Viewer (" + plate.getBarcode() + ")");
// Remove the HeatMapModelChangeListener when closing the window.
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
PlateViewer viewer = (PlateViewer) windowEvent.getSource();
HeatMapModel model = viewer.updater.getHeatMapModel();
model.removeChangeListener(viewer);
viewer.setVisible(false);
}
});
// Configure the toolbars.
toolbar.configure(this.heatMapModel);
colorbar.configure(this.heatMapModel);
// Add the plate heatmap
HeatPlate heatMap = new HeatPlate(this, plate);
heatMapContainer.add(heatMap);
// Add "save image" functionality
new PanelImageExporter(heatMapContainer, true);
// Set the window dimensions given by the plate heatmap size.
Dimension ms = heatMap.getPreferredSize();
heatMapContainer.setPreferredSize(new Dimension(ms.width+10, ms.height+10));
pack();
// Set the location of the new PlateViewer
Random posJitter = new Random();
double left = Toolkit.getDefaultToolkit().getScreenSize().getWidth() - this.getWidth() - 100;
setLocation((int) left + posJitter.nextInt(100), 200 + posJitter.nextInt(100));
}
/**
* GUI component initialization.
*/
private void initialize() {
setMinimumSize(new Dimension(400, 250));
setLayout(new BorderLayout());
toolbar = new HeatMapInputToolbar(this);
add(toolbar, BorderLayout.NORTH);
heatMapContainer = new JPanel(new BorderLayout());
heatMapContainer.setBorder(BorderFactory.createEmptyBorder(0,0,10,10));
add(heatMapContainer, BorderLayout.CENTER);
colorbar = new HeatMapColorToolBar();
add(colorbar, BorderLayout.SOUTH);
}
/**
* Getter for the {@link HeatTrellis} object.
*
* @return {@link HeatTrellis}
*/
public HeatTrellis getUpdater() {
return updater;
}
/**
* The HeatMapModelChangeListener interface.
*/
@Override
public void modelChanged() {
if (isVisible() && getWidth() > 0)
repaint();
}
/** {@inheritDoc} */
@Override
public HeatMapColorToolBar getColorBar() {
return colorbar;
}
/** {@inheritDoc} */
@Override
public HeatMapInputToolbar getToolBar() {
return toolbar;
}
/** {@inheritDoc} */
@Override
public HeatMapModel getHeatMapModel() {
return heatMapModel;
}
/** {@inheritDoc} */
@Override
public Map<UUID, PlateViewer> getChildViews() {
return null;
}
/**
* Quick testing.
*/
public static void main(String[] args) {
PlateViewer plateViewer = new PlateViewer();
plateViewer.heatMapModel = new HeatMapModel();
plateViewer.setSize(new Dimension(400, 250));
plateViewer.setVisible(true);
}
}
| true | true | public PlateViewer(HeatTrellis parent, Plate plate) {
this();
this.updater = parent;
// Create a new instance of the HeatMapModel and copy some attributes.
HeatMapModel model = new HeatMapModel();
model.setCurrentReadout(parent.heatMapModel.getSelectedReadOut());
model.setCurrentOverlay(parent.heatMapModel.getCurrentOverlay());
model.setColorScheme(parent.heatMapModel.getColorScheme());
model.setHideMostFreqOverlay(parent.heatMapModel.doHideMostFreqOverlay());
model.setWellSelection(parent.heatMapModel.getWellSelection());
model.setHiLite(parent.heatMapModel.getHiLite());
model.setHiLiteHandler(parent.heatMapModel.getHiLiteHandler());
model.setColorGradient(parent.heatMapModel.getColorGradient());
model.setKnimeColorAttribute(parent.heatMapModel.getKnimeColorAttribute());
model.setReferencePopulations(parent.heatMapModel.getReferencePopulations());
if ( parent.heatMapModel.isGlobalScaling() ) {
model.setScreen(parent.heatMapModel.getScreen());
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategy());
} else {
model.setScreen(Arrays.asList(plate));
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategyInstance());
}
this.heatMapModel = model;
// Creating the menu
JMenuBar menu = new JMenuBar();
menu.add(new HiLiteMenu(this));
ViewMenu viewMenu = new ViewMenu(this);
menu.add(viewMenu);
if ( parent.heatMapModel.isGlobalScaling() )
viewMenu.getColorMenuItem().setEnabled(!parent.heatMapModel.isGlobalScaling());
setJMenuBar(menu);
// Register the Viewer in the ChangeListeners
parent.heatMapModel.addChangeListener(this);
this.heatMapModel.addChangeListener(this);
// Give a meaningful title.
this.setTitle("Plate Viewer (" + plate.getBarcode() + ")");
// Remove the HeatMapModelChangeListener when closing the window.
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
PlateViewer viewer = (PlateViewer) windowEvent.getSource();
HeatMapModel model = viewer.updater.getHeatMapModel();
model.removeChangeListener(viewer);
viewer.setVisible(false);
}
});
// Configure the toolbars.
toolbar.configure(this.heatMapModel);
colorbar.configure(this.heatMapModel);
// Add the plate heatmap
HeatPlate heatMap = new HeatPlate(this, plate);
heatMapContainer.add(heatMap);
// Add "save image" functionality
new PanelImageExporter(heatMapContainer, true);
// Set the window dimensions given by the plate heatmap size.
Dimension ms = heatMap.getPreferredSize();
heatMapContainer.setPreferredSize(new Dimension(ms.width+10, ms.height+10));
pack();
// Set the location of the new PlateViewer
Random posJitter = new Random();
double left = Toolkit.getDefaultToolkit().getScreenSize().getWidth() - this.getWidth() - 100;
setLocation((int) left + posJitter.nextInt(100), 200 + posJitter.nextInt(100));
}
| public PlateViewer(HeatTrellis parent, Plate plate) {
this();
this.updater = parent;
// Create a new instance of the HeatMapModel and copy some attributes.
HeatMapModel model = new HeatMapModel();
model.setCurrentReadout(parent.heatMapModel.getSelectedReadOut());
model.setCurrentOverlay(parent.heatMapModel.getCurrentOverlay());
model.setColorScheme(parent.heatMapModel.getColorScheme());
model.setHideMostFreqOverlay(parent.heatMapModel.doHideMostFreqOverlay());
model.setWellSelection(parent.heatMapModel.getWellSelection());
model.setHiLite(parent.heatMapModel.getHiLite());
model.setHiLiteHandler(parent.heatMapModel.getHiLiteHandler());
model.setColorGradient(parent.heatMapModel.getColorGradient());
model.setKnimeColorAttribute(parent.heatMapModel.getKnimeColorAttribute());
model.setReferencePopulations(parent.heatMapModel.getReferencePopulations());
model.setAnnotations(parent.heatMapModel.getAnnotations());
model.setReadouts(parent.heatMapModel.getReadouts());
if ( parent.heatMapModel.isGlobalScaling() ) {
model.setScreen(parent.heatMapModel.getScreen());
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategy());
} else {
model.setScreen(Arrays.asList(plate));
model.setReadoutRescaleStrategy(parent.heatMapModel.getReadoutRescaleStrategyInstance());
}
this.heatMapModel = model;
// Creating the menu
JMenuBar menu = new JMenuBar();
menu.add(new HiLiteMenu(this));
ViewMenu viewMenu = new ViewMenu(this);
menu.add(viewMenu);
if ( parent.heatMapModel.isGlobalScaling() )
viewMenu.getColorMenuItem().setEnabled(!parent.heatMapModel.isGlobalScaling());
setJMenuBar(menu);
// Register the Viewer in the ChangeListeners
parent.heatMapModel.addChangeListener(this);
this.heatMapModel.addChangeListener(this);
// Give a meaningful title.
this.setTitle("Plate Viewer (" + plate.getBarcode() + ")");
// Remove the HeatMapModelChangeListener when closing the window.
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
PlateViewer viewer = (PlateViewer) windowEvent.getSource();
HeatMapModel model = viewer.updater.getHeatMapModel();
model.removeChangeListener(viewer);
viewer.setVisible(false);
}
});
// Configure the toolbars.
toolbar.configure(this.heatMapModel);
colorbar.configure(this.heatMapModel);
// Add the plate heatmap
HeatPlate heatMap = new HeatPlate(this, plate);
heatMapContainer.add(heatMap);
// Add "save image" functionality
new PanelImageExporter(heatMapContainer, true);
// Set the window dimensions given by the plate heatmap size.
Dimension ms = heatMap.getPreferredSize();
heatMapContainer.setPreferredSize(new Dimension(ms.width+10, ms.height+10));
pack();
// Set the location of the new PlateViewer
Random posJitter = new Random();
double left = Toolkit.getDefaultToolkit().getScreenSize().getWidth() - this.getWidth() - 100;
setLocation((int) left + posJitter.nextInt(100), 200 + posJitter.nextInt(100));
}
|
diff --git a/src/Client/Roster.java b/src/Client/Roster.java
index b5922307..4179b034 100644
--- a/src/Client/Roster.java
+++ b/src/Client/Roster.java
@@ -1,2838 +1,2840 @@
/*
* Roster.java
*
* Created on 6.01.2005, 19:16
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org
*
* 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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package Client;
//#ifdef AUTOTASK
//# import AutoTasks.AutoTask;
//#endif
import Account.Account;
import Account.AccountSelect;
import Alerts.AlertCustomize;
import Alerts.AlertProfile;
//#ifndef WMUC
import Conference.BookmarkQuery;
import Conference.Bookmarks;
import Conference.ConferenceGroup;
import Conference.MucContact;
import Conference.affiliation.ConferenceQuickPrivelegeModify;
import Conference.ConferenceForm;
//#endif
import Fonts.FontCache;
import Statistic.Stats;
import images.MenuIcons;
//#ifdef ARCHIVE
import Archive.ArchiveList;
//#endif
import Menu.RosterItemActions;
import Menu.RosterToolsMenu;
//#ifdef CLIENTS_ICONS
import images.ClientsIconsData;
//#endif
import images.RosterIcons;
//#ifndef MENU_LISTENER
//# import javax.microedition.lcdui.CommandListener;
//# import javax.microedition.lcdui.Command;
//#else
import Menu.MenuListener;
import Menu.Command;
import Menu.MyMenu;
//#endif
//#if FILE_TRANSFER
import io.file.transfer.TransferDispatcher;
//#endif
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import locale.SR;
import login.LoginListener;
//#ifdef NON_SASL_AUTH
//# import login.NonSASLAuth;
//#endif
//#if SASL_XGOOGLETOKEN
//# import login.GoogleTokenAuth;
//#endif
import login.SASLAuth;
import midlet.BombusMod;
import ui.controls.AlertBox;
import util.StringUtils;
import VCard.VCard;
import VCard.VCardEdit;
import VCard.VCardView;
import com.alsutton.jabber.*;
import com.alsutton.jabber.datablocks.*;
import java.util.*;
import ui.*;
import xmpp.EntityCaps;
import xmpp.XmppError;
//#ifdef CAPTCHA
//# import xmpp.extensions.Captcha;
//#endif
import xmpp.extensions.IqQueryRoster;
//#if SASL_XGOOGLETOKEN
//# import xmpp.extensions.IqGmail;
//#endif
import xmpp.extensions.IqLast;
import xmpp.extensions.IqPing;
import xmpp.extensions.IqVersionReply;
import xmpp.extensions.IqTimeReply;
//#ifdef ADHOC
//# import xmpp.extensions.IQCommands;
//#endif
//#ifdef PEP
//# import xmpp.extensions.PepListener;
//#endif
public class Roster
extends VirtualList
implements
JabberListener,
//#ifndef MENU_LISTENER
//# CommandListener,
//#else
MenuListener,
//#endif
Runnable,
LoginListener
{
private Command cmdActions=new Command(SR.MS_ITEM_ACTIONS, Command.SCREEN, 1);
private Command cmdStatus=new Command(SR.MS_STATUS_MENU, Command.SCREEN, 2);
private Command cmdActiveContacts;//=new Command(SR.MS_ACTIVE_CONTACTS, Command.SCREEN, 3);
private Command cmdAlert=new Command(SR.MS_ALERT_PROFILE_CMD, Command.SCREEN, 8);
//#ifndef WMUC
private Command cmdConference=new Command(SR.MS_CONFERENCE, Command.SCREEN, 10);
//#endif
//#ifdef ARCHIVE
private Command cmdArchive=new Command(SR.MS_ARCHIVE, Command.SCREEN, 10);
//#endif
private Command cmdAdd=new Command(SR.MS_ADD_CONTACT, Command.SCREEN, 12);
private Command cmdTools=new Command(SR.MS_TOOLS, Command.SCREEN, 14);
private Command cmdAccount=new Command(SR.MS_ACCOUNT_, Command.SCREEN, 15);
private Command cmdCleanAllMessages=new Command(SR.MS_CLEAN_ALL_MESSAGES, Command.SCREEN, 50);
private Command cmdInfo=new Command(SR.MS_ABOUT, Command.SCREEN, 80);
private Command cmdMinimize=new Command(SR.MS_APP_MINIMIZE, Command.SCREEN, 90);
private Command cmdQuit=new Command(SR.MS_APP_QUIT, Command.SCREEN, 99);
private Config cf=Config.getInstance();
private StaticData sd=StaticData.getInstance();
public Contact activeContact = null;
private Jid myJid;
public JabberStream theStream;
public int messageCount;
int highliteMessageCount;
public Object transferIcon;
public Vector hContacts;
private Vector vContacts;
private Vector paintVContacts;
public Groups groups;
public Vector bookmarks;
//#ifdef RUNNING_MESSAGE
//# public MessageEdit me=null;
//#endif
private StatusList sl;
public int myStatus=cf.loginstatus;
private static String myMessage;
public static int oldStatus=0;
private static int lastOnlineStatus;
public int currentReconnect=0;
public boolean doReconnect=false;
public boolean querysign=false;
//#ifdef AUTOSTATUS
//# private AutoStatusTask autostatus;
//# public static boolean autoAway=false;
//# public static boolean autoXa=false;
//#endif
//#if SASL_XGOOGLETOKEN
//# private String token;
//#endif
public long lastMessageTime=Time.utcTimeMillis();
public static String startTime=Time.dispLocalTime();
private static long notifyReadyTime=System.currentTimeMillis();
private static int blockNotifyEvent=-111;
private int blState=Integer.MAX_VALUE;
//#ifdef AUTOTASK
//# private AutoTask at=sd.autoTask;
//#endif
private final static int SOUND_FOR_ME=500;
private final static int SOUND_FOR_CONFERENCE=800;
private final static int SOUND_MESSAGE=1000;
private final static int SOUND_CONNECTED=777;
private final static int SOUND_FOR_VIP=100;
private final static int SOUND_COMPOSING=888;
private final static int SOUND_OUTGOING=999;
SplashScreen splash;
public Roster(Display display) {
super();
this.display=display;
splash = SplashScreen.getInstance(display);
sl=StatusList.getInstance();
setLight(cf.lightState);
MainBar mainbar=new MainBar(4, null, null, false);
setMainBarItem(mainbar);
mainbar.addRAlign();
mainbar.addElement(null);
mainbar.addElement(null);
mainbar.addElement(null); //ft
hContacts=null;
hContacts=new Vector();
groups=null;
groups=new Groups();
vContacts=null;
vContacts=new Vector(); // just for displaying
updateMainBar();
commandState();
setCommandListener(this);
splash.setExit(display, this);
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE || cf.autoAwayType==Config.AWAY_MESSAGE)
//# autostatus=new AutoStatusTask();
//#
//# if (myStatus<2)
//# messageActivity();
//#endif
}
public void setLight(boolean state) {
if (phoneManufacturer==Config.SIEMENS || phoneManufacturer==Config.SIEMENS2) {
try {
if (state) com.siemens.mp.game.Light.setLightOn();
else com.siemens.mp.game.Light.setLightOff();
} catch( Exception e ) { }
return;
}
if (!state) return;
//#ifdef SE_LIGHT
//# if (phoneManufacturer==Config.SONYE || phoneManufacturer==Config.NOKIA) {
//# new KeepLightTask().start();
//# }
//#endif
}
public void commandState(){
//#ifdef MENU_LISTENER
menuCommands.removeAllElements();
//#endif
int activeType=Command.SCREEN;
if (phoneManufacturer==Config.NOKIA) activeType=Command.BACK;
if (phoneManufacturer==Config.INTENT) activeType=Command.BACK;
if (phoneManufacturer==Config.J2ME) activeType=Command.BACK;
cmdActiveContacts=new Command(SR.MS_ACTIVE_CONTACTS, activeType, 3);
//#ifndef MENU_LISTENER
//# addCommand(cmdActions);
//#endif
addCommand(cmdStatus);
addCommand(cmdActiveContacts);
//#ifndef WMUC
//#ifdef MENU_LISTENER
if (isLoggedIn())
//#endif
addCommand(cmdConference);
//#endif
addCommand(cmdAlert);
//#ifdef ARCHIVE
//#ifdef PLUGINS
//# if (sd.Archive)
//#endif
addCommand(cmdArchive);
//#endif
//#ifdef MENU_LISTENER
if (isLoggedIn())
//#endif
addCommand(cmdAdd);
addCommand(cmdAccount);
addCommand(cmdTools);
addCommand(cmdInfo);
if (cf.allowMinimize)
addCommand(cmdMinimize);
addCommand(cmdCleanAllMessages);
if (phoneManufacturer!=Config.NOKIA_9XXX)
addCommand(cmdQuit);
//#ifdef MENU_LISTENER
cmdActions.setImg(MenuIcons.ICON_ITEM_ACTIONS);
cmdStatus.setImg(MenuIcons.ICON_STATUS);
cmdActiveContacts.setImg(MenuIcons.ICON_CONFERENCE);
cmdAlert.setImg(MenuIcons.ICON_NOTIFY);
//#ifndef WMUC
cmdConference.setImg(MenuIcons.ICON_CONFERENCE);
//#endif
//#ifdef ARCHIVE
cmdArchive.setImg(MenuIcons.ICON_ARCHIVE);
//#endif
cmdAdd.setImg(MenuIcons.ICON_ADD_CONTACT);
cmdTools.setImg(MenuIcons.ICON_SETTINGS);
cmdAccount.setImg(MenuIcons.ICON_VCARD);
cmdInfo.setImg(MenuIcons.ICON_CHECK_UPD);
if (cf.allowMinimize)
cmdMinimize.setImg(MenuIcons.ICON_FILEMAN);
cmdCleanAllMessages.setImg(MenuIcons.ICON_CLEAN_MESSAGES);
cmdQuit.setImg(MenuIcons.ICON_BUILD_NEW);
//#endif
}
public void setProgress(String pgs,int percent){
if (splash!=null)
splash.setProgress(pgs, percent);
setRosterMainBar(pgs);
redraw();
}
public void setProgress(int percent){
if (splash!=null)
splash.setProgress(percent);
}
private void setRosterMainBar(String s){
getMainBarItem().setElementAt(s, 3);
}
private int rscaler;
private int rpercent;
public void rosterItemNotify(){
rscaler++;
if (rscaler<4) return;
rscaler=0;
if (rpercent<100) rpercent++;
if (splash!=null)
splash.setProgress(rpercent);
}
// establishing connection process
public void run(){
//#ifdef POPUPS
//if (cf.firstRun) setWobbler(1, (Contact) null, SR.MS_ENTER_SETTINGS);
//#endif
setQuerySign(true);
if (!doReconnect) {
setProgress(25);
resetRoster();
}
try {
Account a=sd.account;
//#if SASL_XGOOGLETOKEN
//# if (a.useGoogleToken()) {
//# setProgress(SR.MS_TOKEN, 30);
//# token=new GoogleTokenAuth(a).responseXGoogleToken();
//# if (token==null) throw new SecurityException("Can't get Google token");
//# }
//#endif
setProgress(SR.MS_CONNECT_TO_+a.getServer(), 30);
theStream= a.openJabberStream();
setProgress(SR.MS_OPENING_STREAM, 40);
theStream.setJabberListener( this );
theStream.initiateStream();
} catch( Exception e ) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
//SplashScreen.getInstance().close();
setProgress(SR.MS_FAILED, 100);
doReconnect=false;
myStatus=Presence.PRESENCE_OFFLINE;
setQuerySign(false);
redraw();
askReconnect(e);
}
}
public void resetRoster() {
synchronized (hContacts) {
hContacts=null;
hContacts=new Vector();
groups=null;
groups=new Groups();
vContacts=null;
vContacts=new Vector(); // just for displaying
bookmarks=null;
}
setMyJid(new Jid(sd.account.getJid()));
updateContact(sd.account.getNick(), myJid.getBareJid(), SR.MS_SELF_CONTACT, "self", false);
}
public void systemGC() {
//#ifndef WSYSTEMGC
System.gc();
try { Thread.sleep(50); } catch (InterruptedException e){}
//#endif
}
public void errorLog(String s){
if (s==null) return;
Msg m=new Msg(Msg.MESSAGE_TYPE_OUT, "local", "Error", s);
messageStore(selfContact(), m);
}
public void beginPaint() {
paintVContacts=vContacts;
}
public VirtualElement getItemRef(int Index){
return (VirtualElement) paintVContacts.elementAt(Index);
}
public int getItemCount(){
return paintVContacts.size();
}
public void setEventIcon(Object icon){
transferIcon=icon;
getMainBarItem().setElementAt(icon, 7);
redraw();
}
public Object getEventIcon() {
if (transferIcon!=null) return transferIcon;
return null;
}
private void updateMainBar(){
int s=querysign?RosterIcons.ICON_PROGRESS_INDEX:myStatus;
int profile=cf.profile;
Object en=(profile>0)? new Integer(profile+RosterIcons.ICON_PROFILE_INDEX+1):null;
MainBar mainbar=(MainBar) getMainBarItem();
mainbar.setElementAt((messageCount==0)?null:new Integer(RosterIcons.ICON_MESSAGE_INDEX), 0);
mainbar.setElementAt((messageCount==0)?null:getHeaderString(),1);
mainbar.setElementAt(new Integer(s), 2);
mainbar.setElementAt(en, 5);
if (phoneManufacturer==Config.WINDOWS) {
if (messageCount==0) {
setTitle("BombusMod");
} else {
setTitle("BombusMod "+getHeaderString());
}
}
}
public String getHeaderString() {
return ((highliteMessageCount==0)?" ":" "+highliteMessageCount+"/")+messageCount+" ";
}
boolean countNewMsgs() {
int m=0;
int h=0;
synchronized (hContacts) {
for (Enumeration e=hContacts.elements();e.hasMoreElements();){
Contact c=(Contact)e.nextElement();
m+=c.getNewMsgsCount();
h+=c.getNewHighliteMsgsCount();
}
}
highliteMessageCount=h;
messageCount=m;
updateMainBar();
return (m>0);
}
public void cleanupSearch(){
int index=0;
synchronized (hContacts) {
while (index<hContacts.size()) {
if ( ((Contact) hContacts.elementAt(index)).getGroupType()==Groups.TYPE_SEARCH_RESULT )
hContacts.removeElementAt(index);
else index++;
}
}
reEnumRoster();
}
public void cmdCleanAllMessages(){
if (messageCount>0) {
new AlertBox(SR.MS_UNREAD_MESSAGES+": "+messageCount, SR.MS_SURE_DELETE, display, this) {
public void yes() { cleanAllMessages(); }
public void no() { }
};
} else {
cleanAllMessages();
}
}
public void cleanAllMessages(){
synchronized (hContacts) {
for (Enumeration e=hContacts.elements();e.hasMoreElements();) {
Contact c=(Contact)e.nextElement();
try {
c.purge();
} catch (Exception ex) { }
}
}
highliteMessageCount=0;
messageCount=0;
//reEnumRoster();
redraw();
}
public void cleanupGroup(){
Group g=(Group)getFocusedObject();
if (g==null) return;
if (!g.collapsed) return;
//#ifndef WMUC
if (g instanceof ConferenceGroup) {
ConferenceGroup cg= (ConferenceGroup) g;
if (!cg.inRoom) {
int index=0;
boolean removeGroup=true;
synchronized (hContacts) {
while (index<hContacts.size()) {
Contact contact=(Contact)hContacts.elementAt(index);
if (contact.group==g) {
if (contact.getNewMsgsCount()==0) {
contact.msgs=null;
contact=null;
hContacts.removeElementAt(index);
} else {
removeGroup=false;
index++;
}
} else index++;
}
if (removeGroup) {
groups.removeGroup(g);
} else {
return;
}
}
}// else return;
}
//#endif
int index=0;
synchronized (hContacts) {
while (index<hContacts.size()) {
Contact contact=(Contact)hContacts.elementAt(index);
if (contact.group==g) {
if ( contact.origin>Contact.ORIGIN_ROSTERRES
&& contact.status>=Presence.PRESENCE_OFFLINE
&& contact.getNewMsgsCount()==0
&& contact.origin!=Contact.ORIGIN_GROUPCHAT) {
contact.msgs=null;
contact=null;
hContacts.removeElementAt(index);
} else {
index++;
}
}
else index++;
}
if (g.getOnlines()==0 && !(g instanceof ConferenceGroup)) {
if (g.type==Groups.TYPE_MUC) groups.removeGroup(g);
}
}
}
ReEnumerator reEnumerator=null;
public void reEnumRoster(){
if (reEnumerator==null) reEnumerator=new ReEnumerator();
reEnumerator.queueEnum();
systemGC();
}
public Vector getHContacts() {return hContacts;}
public void updateContact(String nick, String jid, String grpName, String subscr, boolean ask) {
// called only on roster read
int status=Presence.PRESENCE_OFFLINE;
if (subscr.equals("none")) status=Presence.PRESENCE_UNKNOWN;
if (ask) status=Presence.PRESENCE_ASK;
if (subscr.equals("remove")) status=-1;
Jid J=new Jid(jid);
Contact c=findContact(J,false); // search by bare jid
if (c==null) {
c=new Contact(nick, jid, Presence.PRESENCE_OFFLINE, null);
addContact(c);
}
boolean firstInstance=true; //FS#712 workaround
int index=0;
synchronized (hContacts) {
for (Enumeration e=hContacts.elements();e.hasMoreElements();) {
c=(Contact)e.nextElement();
if (c.jid.equals(J,false)) {
Group group= (c.jid.isTransport())?
groups.getGroup(Groups.TYPE_TRANSP) :
groups.getGroup(grpName);
if (group==null) {
group=groups.addGroup(grpName, Groups.TYPE_COMMON);
}
if (status<0) {
hContacts.removeElementAt(index);
continue;
}
c.nick=nick;
c.group=group;
c.subscr=subscr;
c.offline_type=status;
c.ask_subscribe=ask;
if (c.origin==Contact.ORIGIN_PRESENCE) {
if (firstInstance) c.origin=Contact.ORIGIN_ROSTERRES;
else c.origin=Contact.ORIGIN_CLONE;
}
firstInstance=false;
if (querysign==true) {
if (cf.collapsedGroups) {
Group g=c.group;
g.collapsed=true;
}
}
c.setSortKey((nick==null)? jid:nick);
}
index++;
}
}
//if (status<0) removeTrash();
}
private final void removeTrash(){
int index=0;
synchronized (hContacts) {
while (index<hContacts.size()) {
Contact c=(Contact)hContacts.elementAt(index);
if (c.offline_type<0) {
hContacts.removeElementAt(index);
} else index++;
}
countNewMsgs();
}
}
//#ifndef WMUC
public MucContact findMucContact(Jid jid) {
Contact contact=findContact(jid, true);
try {
return (MucContact) contact;
} catch (Exception e) {
// drop buggy bookmark in roster
synchronized (hContacts) {
hContacts.removeElement(contact);
}
return null;
}
}
public final ConferenceGroup initMuc(String from, String joinPassword){
//#ifdef AUTOSTATUS
//# if (autoAway) {
//# ExtendedStatus es=sl.getStatus(oldStatus);
//# String ms=es.getMessage();
//# sendPresence(oldStatus, ms);
//# autoAway=false;
//# autoXa=false;
//# myStatus=oldStatus;
//#
//# messageActivity();
//# }
//#endif
// muc message
int ri=from.indexOf('@');
int rp=from.indexOf('/');
String room=from.substring(0,ri);
String roomJid=from.substring(0,rp).toLowerCase();
ConferenceGroup grp=(ConferenceGroup)groups.getGroup(roomJid);
// creating room
if (grp==null) // we hasn't joined this room yet
groups.addGroup(grp=new ConferenceGroup(roomJid, room) );
grp.password=joinPassword;
MucContact c=findMucContact( new Jid(roomJid) );
if (c==null) {
c=new MucContact(room, roomJid);
addContact(c);
}
// change nick if already in room
if (c.status==Presence.PRESENCE_ONLINE) return grp;
c.setStatus(Presence.PRESENCE_ONLINE);
c.transport=RosterIcons.ICON_GROUPCHAT_INDEX; //FIXME: убрать хардкод
c.bareJid=from;
c.origin=Contact.ORIGIN_GROUPCHAT;
c.commonPresence=true;
grp.conferenceJoinTime=Time.utcTimeMillis();
grp.confContact=c;
c.group=grp;
String nick=from.substring(rp+1);
// old self-contact
c=grp.selfContact;
// check for existing entry - it may be our old self-contact
// or another contact whose nick we pretend
MucContact foundInRoom = findMucContact( new Jid(from) );
if (foundInRoom!=null) {
c=foundInRoom; //choose found contact instead of old self-contact
}
// if exists (and online - rudimentary check due to line 500)
// rename contact
if (c!=null) if (c.status>=Presence.PRESENCE_OFFLINE) {
c.nick=nick;
c.jid.setJid(from);
c.bareJid=from;
}
// create self-contact if no any candidates found
if (c==null) {
c=new MucContact(nick, from);
addContact(c);
}
grp.selfContact=c;
c.group=grp;
c.origin=Contact.ORIGIN_GC_MYSELF;
grp.collapsed=true; //test
sort(hContacts);
return grp;
}
public final MucContact mucContact(String from){
// muc message
int ri=from.indexOf('@');
int rp=from.indexOf('/');
String room=from.substring(0,ri);
String roomJid=from.substring(0,rp).toLowerCase();
ConferenceGroup grp=(ConferenceGroup)groups.getGroup(roomJid);
if (grp==null) return null; // we are not joined this room
MucContact c=findMucContact( new Jid(from) );
if (c==null) {
c=new MucContact(from.substring(rp+1), from);
addContact(c);
c.origin=Contact.ORIGIN_GC_MEMBER;
}
c.group=grp;
sort(hContacts);
return c;
}
//#endif
public final Contact getContact(final String jid, boolean createInNIL) {
Jid J=new Jid(jid);
Contact c=findContact(J, true);
if (c!=null)
return c;
c=findContact(J, false);
if (c==null) {
if (!createInNIL) return null;
c=new Contact(null, jid, Presence.PRESENCE_OFFLINE, "none" ); /*"not-in-list"*/
c.bareJid=J.getBareJid();
c.origin=Contact.ORIGIN_PRESENCE;
c.group=groups.getGroup(Groups.TYPE_NOT_IN_LIST);
addContact(c);
} else {
if (c.origin==Contact.ORIGIN_ROSTER) {
c.origin=Contact.ORIGIN_ROSTERRES;
c.setStatus(Presence.PRESENCE_OFFLINE);
c.jid=J;
//System.out.println("add resource");
} else {
c=c.clone(J, Presence.PRESENCE_OFFLINE);
addContact(c);
//System.out.println("cloned");
}
}
sort(hContacts);
return c;
}
public void addContact(Contact c) {
synchronized (hContacts) { hContacts.addElement(c); }
}
public final Contact findContact(final Jid j, final boolean compareResources) {
synchronized (hContacts) {
for (Enumeration e=hContacts.elements();e.hasMoreElements();){
Contact c=(Contact)e.nextElement();
if (c.jid.equals(j,compareResources)) return c;
}
}
return null;
}
public void sendPresence(int newStatus, String message) {
if (newStatus!=Presence.PRESENCE_SAME)
myStatus=newStatus;
//#ifdef AUTOSTATUS
//# messageActivity();
//#endif
if (message!=null)
myMessage=message;
setQuerySign(false);
if (myStatus!=Presence.PRESENCE_OFFLINE) {
lastOnlineStatus=myStatus;
}
// reconnect if disconnected
if (myStatus!=Presence.PRESENCE_OFFLINE && theStream==null ) {
synchronized (hContacts) {
doReconnect=(hContacts.size()>1);
}
redraw();
new Thread(this).start();
return;
}
blockNotify(-111,13000);
if (isLoggedIn()) {
if (myStatus==Presence.PRESENCE_OFFLINE && !cf.collapsedGroups)
groups.queryGroupState(false);
// send presence
ExtendedStatus es= sl.getStatus(myStatus);
if (message==null)
myMessage=StringUtils.toExtendedString(es.getMessage());;
myMessage=StringUtils.toExtendedString(myMessage);
int myPriority=es.getPriority();
Presence presence = new Presence(myStatus, myPriority, myMessage, sd.account.getNick());
if (!sd.account.isMucOnly() )
theStream.send( presence );
//#ifndef WMUC
multicastConferencePresence(myStatus, myMessage, myPriority);
//#endif
}
// disconnect
if (myStatus==Presence.PRESENCE_OFFLINE) {
try {
theStream.close(); // sends </stream:stream> and closes socket
} catch (Exception e) { /*e.printStackTrace();*/ }
synchronized(hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();){
((Contact)e.nextElement()).setStatus(Presence.PRESENCE_OFFLINE); // keep error & unknown
}
}
theStream=null;
//#ifdef AUTOSTATUS
//# autoAway=false;
//# autoXa=false;
//#endif
systemGC();
}
Contact c=selfContact();
c.setStatus(myStatus);
sort(hContacts);
reEnumRoster();
}
public void sendDirectPresence(int status, String to, JabberDataBlock x) {
if (to==null) {
sendPresence(status, null);
return;
}
ExtendedStatus es= sl.getStatus(status);
myMessage=es.getMessage();
myMessage=StringUtils.toExtendedString(myMessage);
Presence presence = new Presence(status, es.getPriority(), myMessage, sd.account.getNick());
presence.setTo(to);
if (x!=null) presence.addChild(x);
if (theStream!=null) {
theStream.send( presence );
}
}
public void sendDirectPresence(int status, Contact to, JabberDataBlock x) {
sendDirectPresence(status, (to==null)? null: to.getJid(), x);
if (to.jid.isTransport()) blockNotify(-111,10000);
//#ifndef WMUC
if (to instanceof MucContact) ((MucContact)to).commonPresence=false;
//#endif
}
public boolean isLoggedIn() {
if (theStream==null) return false;
return theStream.loggedIn;
}
public Contact selfContact() {
return getContact(myJid.getJid(), false);
}
//#ifndef WMUC
public void multicastConferencePresence(int myStatus, String myMessage, int myPriority) {
//if (!cf.autoJoinConferences) return; //requested to disable
if (myStatus==Presence.PRESENCE_INVISIBLE) return; //block multicasting presence invisible
synchronized (hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();) {
Contact c=(Contact) e.nextElement();
if (c.origin!=Contact.ORIGIN_GROUPCHAT) continue;
if (!((MucContact)c).commonPresence) continue; // stop if room left manually
ConferenceGroup confGroup=(ConferenceGroup)c.group;
if (!confGroup.inRoom) continue; // don`t reenter to leaved rooms
Contact myself=confGroup.selfContact;
if (c.status==Presence.PRESENCE_OFFLINE){
ConferenceForm.join(confGroup.desc, myself.getJid(), confGroup.password, 20);
continue;
}
Presence presence = new Presence(myStatus, myPriority, myMessage, null);
presence.setTo(myself.bareJid);
theStream.send(presence);
}
}
}
//#endif
public void sendPresence(String to, String type, JabberDataBlock child, boolean conference) {
JabberDataBlock presence=new Presence(to, type);
if (child!=null) {
presence.addChild(child);
ExtendedStatus es= sl.getStatus(myStatus);
switch (myStatus){
case Presence.PRESENCE_CHAT: presence.addChild("show", Presence.PRS_CHAT);break;
case Presence.PRESENCE_AWAY: presence.addChild("show", Presence.PRS_AWAY);break;
case Presence.PRESENCE_XA: presence.addChild("show", Presence.PRS_XA);break;
case Presence.PRESENCE_DND: presence.addChild("show", Presence.PRS_DND);break;
}
if (es.getPriority()!=0)
presence.addChild("priority",Integer.toString(es.getPriority()));
if (es.getMessage()!=null)
presence.addChild("status", StringUtils.toExtendedString(es.getMessage()));
} else if (conference) {
ExtendedStatus es= sl.getStatus(Presence.PRESENCE_OFFLINE);
if (es.getMessage()!=null)
presence.addChild("status", StringUtils.toExtendedString(es.getMessage()));
}
theStream.send(presence);
}
public void doSubscribe(Contact c) {
if (c.subscr==null) return;
boolean subscribe =
c.subscr.startsWith("none") ||
c.subscr.startsWith("from");
if (c.ask_subscribe) subscribe=false;
boolean subscribed =
c.subscr.startsWith("none") ||
c.subscr.startsWith("to");
//getMessage(cursor).messageType==Msg.MESSAGE_TYPE_AUTH;
String to=(c.jid.isTransport())?c.getJid():c.bareJid;
if (subscribed) sendPresence(to,"subscribed", null, false);
if (subscribe) sendPresence(to,"subscribe", null, false);
}
public void sendMessage(Contact to, String id, final String body, final String subject , String composingState) {
try {
//#ifndef WMUC
boolean groupchat=to.origin==Contact.ORIGIN_GROUPCHAT;
//#else
//# boolean groupchat=false;
//#endif
//#ifdef AUTOSTATUS
//# if (autoAway) {
//# ExtendedStatus es=sl.getStatus(oldStatus);
//# String ms=es.getMessage();
//# sendPresence(oldStatus, ms);
//# autoAway=false;
//# autoXa=false;
//# myStatus=oldStatus;
//# }
//#endif
Message message = new Message(
to.getJid(),
body,
subject,
groupchat
);
message.setAttribute("id", id);
if (groupchat && body==null && subject==null) return;
if (composingState!=null)
message.addChildNs(composingState, "http://jabber.org/protocol/chatstates");
if (!groupchat)
if (body!=null) if (cf.eventDelivery)
message.addChildNs("request", "urn:xmpp:receipts");
theStream.send( message );
lastMessageTime=Time.utcTimeMillis();
playNotify(SOUND_OUTGOING);
} catch (Exception e) { e.printStackTrace(); }
//#ifdef AUTOSTATUS
//# messageActivity();
//#endif
}
private void sendDeliveryMessage(Contact c, String id) {
if (!cf.eventDelivery) return;
if (myStatus==Presence.PRESENCE_INVISIBLE) return;
Message message=new Message(c.jid.getJid());
//xep-0184
message.setAttribute("id", id);
message.addChildNs("received", "urn:xmpp:receipts");
theStream.send( message );
}
private Vector vCardQueue;
public void resolveNicknames(String transport){
vCardQueue=null;
vCardQueue=new Vector();
synchronized (hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();){
Contact k=(Contact) e.nextElement();
if (k.jid.isTransport())
continue;
int grpType=k.getGroupType();
if (k.jid.getServer().equals(transport) && k.nick==null && (grpType==Groups.TYPE_COMMON || grpType==Groups.TYPE_NO_GROUP))
vCardQueue.addElement(VCard.getQueryVCard(k.getJid(), "nickvc"+k.bareJid));
}
}
setQuerySign(true);
sendVCardReq();
}
private void sendVCardReq(){
querysign=false;
if (vCardQueue!=null) {
if (!vCardQueue.isEmpty()) {
JabberDataBlock req=(JabberDataBlock) vCardQueue.lastElement();
vCardQueue.removeElement(req);
//System.out.println(k.nick);
theStream.send(req);
querysign=true;
}
}
updateMainBar();
}
//#if CHANGE_TRANSPORT
//# public void contactChangeTransport(String srcTransport, String dstTransport){ //<voffk>
//# setQuerySign(true);
//# for (Enumeration e=hContacts.elements(); e.hasMoreElements(); ) {
//# Contact k=(Contact) e.nextElement();
//# if (k.jid.isTransport()) continue;
//# int grpType=k.getGroupType();
//# if (k.jid.getServer().equals(srcTransport) &&
//# (grpType==Groups.TYPE_COMMON || grpType==Groups.TYPE_NO_GROUP ||
//# grpType==Groups.TYPE_VISIBLE || grpType==Groups.TYPE_VIP ||
//# grpType==Groups.TYPE_IGNORE)) {
//# String jid=k.getJid();
//# jid=StringUtils.stringReplace(jid, srcTransport, dstTransport);
//# storeContact(jid, k.nick, (!k.group.getName().equals(SR.MS_GENERAL))?(k.group.getName()):"", true); //new contact addition
//# try {
//# Thread.sleep(300);
//# } catch (Exception ex) { }
//# deleteContact(k); //old contact deletion
//# }
//# }
//# setQuerySign(false);
//# }
//#endif
public void loginFailed(String error){
myStatus=Presence.PRESENCE_OFFLINE;
setProgress(SR.MS_LOGIN_FAILED, 100);
errorLog(error);
try {
theStream.close();
} catch (Exception e) {
//e.printStackTrace();
}
theStream=null;
systemGC();
doReconnect=false;
setQuerySign(false);
redraw();
}
public void loginSuccess() {
theStream.addBlockListener(new EntityCaps());
theStream.addBlockListener(new IqPing());
theStream.addBlockListener(new IqVersionReply());
theStream.startKeepAliveTask(); //enable keep-alive packets
theStream.loggedIn=true;
currentReconnect=0;
theStream.addBlockListener(new IqLast());
theStream.addBlockListener(new IqTimeReply());
//#ifdef ADHOC
//# if (cf.adhoc)
//#ifdef PLUGINS
//# if (sd.Adhoc)
//#endif
//# IQCommands.getInstance().addBlockListener();
//#endif
//#ifdef PEP
//# if (cf.sndrcvmood)
//#ifdef PLUGINS
//# if (sd.PEP)
//#endif
//# PepListener.getInstance().addBlockListener();
//#endif
//#if SASL_XGOOGLETOKEN
//# if (StaticData.getInstance().account.isGmail())
//# theStream.addBlockListener(new IqGmail());
//#endif
//#if FILE_TRANSFER
if (cf.fileTransfer) // enable File transfers
//#ifdef PLUGINS
//# if (sd.FileTransfer)
//#endif
TransferDispatcher.getInstance().addBlockListener();
//#endif
//#ifdef CAPTCHA
//# theStream.addBlockListener(new Captcha(display));
//#endif
playNotify(SOUND_CONNECTED);
if (doReconnect) {
querysign=doReconnect=false;
sendPresence(myStatus, null);
return;
}
//
theStream.enableRosterNotify(true);
rpercent=50;
if (sd.account.isMucOnly()) {
setProgress(SR.MS_CONNECTED,100);
try {
reEnumRoster();
} catch (Exception e) { }
setQuerySign(false);
doReconnect=false;
if (splash!=null)
splash.close(); // display.setCurrent(this);
splash=null;
//query bookmarks
theStream.addBlockListener(new BookmarkQuery(BookmarkQuery.LOAD));
} else {
JabberDataBlock qr=new IqQueryRoster();
setProgress(SR.MS_ROSTER_REQUEST, 49);
theStream.send( qr );
}
//#ifndef WMUC
//query bookmarks
if (bookmarks==null)
theStream.addBlockListener(new BookmarkQuery(BookmarkQuery.LOAD));
//#endif
}
public void bindResource(String myJid) {
Contact self=selfContact();
self.jid=this.myJid=new Jid(myJid);
}
public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from=data.getAttribute("from");
String type = (String) data.getTypeAttribute();
String id=(String) data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("get") || type.equals("set") || type.equals("error") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (display.getCurrent() instanceof VirtualList) {
if (c.getGroupType()==Groups.TYPE_SELF)
new VCardEdit(display, this, vcard);
else
new VCardView(display, this, c);
}
} else {
new VCardView(display, this, c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")){
theStream.enableRosterNotify(false);
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
if (splash!=null)
splash.close();
splash=null;
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) { /*e.printStackTrace();*/ }
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null)
getClientIcon(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence || chatPres.indexOf(SR.MS_WAS_BANNED)>-1 || chatPres.indexOf(SR.MS_WAS_KICKED)>-1) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) { }
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#if DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL= cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.getInstance().processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.getInstance().processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# System.out.println(lang);
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
sort(hContacts);
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
+ } catch(OutOfMemoryError eom){
+ System.out.println("error bombusmod\\src\\Client\\Roster.java:12");
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
//#ifdef CLIENTS_ICONS
private void getClientIcon(Contact c, String data) {
ClientsIconsData.getInstance().processData(c, data);
}
//#endif
boolean processRoster(JabberDataBlock data){
JabberDataBlock q=data.findNamespace("query", "jabber:iq:roster");
if (q==null) return false;
int type=0;
//verifying from attribute as in RFC3921/7.2
String from=data.getAttribute("from");
if (from!=null) {
Jid fromJid=new Jid(from);
if (fromJid.hasResource())
if (!myJid.equals(fromJid, true)) return false;
}
Vector cont=(q!=null)?q.getChildBlocks():null;
if (cont!=null)
for (Enumeration e=cont.elements(); e.hasMoreElements();){
JabberDataBlock i=(JabberDataBlock)e.nextElement();
if (i.getTagName().equals("item")) {
String name=i.getAttribute("name");
String jid=i.getAttribute("jid");
String subscr=i.getAttribute("subscription");
boolean ask= (i.getAttribute("ask")!=null);
String group=i.getChildBlockText("group");
if (group.length()==0) group=Groups.COMMON_GROUP;
updateContact(name,jid,group, subscr, ask);
//sort(hContacts);
}
}
sort(hContacts);
return true;
}
//#ifdef POPUPS
boolean showWobbler(Contact c) {
if (!cf.popUps)
return false;
if (activeContact==null)
return true;
return(!c.equals(activeContact));
}
//#endif
//#ifdef FILE_TRANSFER
public void addFileQuery(String from, String message) {
Contact c=getContact(from, true);
c.fileQuery=true;
messageStore(c, new Msg(Msg.MESSAGE_TYPE_SYSTEM, from, SR.MS_FILE, message));
}
//#endif
public void messageStore(Contact c, Msg message) {
if (c==null) return;
c.addMessage(message);
boolean autorespond = false;
//#ifdef RUNNING_MESSAGE
//# if (message.messageType==Msg.MESSAGE_TYPE_IN)
//# setTicker(c, message.body);
//#endif
//#ifndef WSYSTEMGC
if (cf.ghostMotor) {
systemGC();
}
//#endif
if (countNewMsgs()) reEnumRoster();
if (!message.unread) return;
//TODO: clear unread flag if not-in-list IS HIDDEN
if (c.getGroupType()==Groups.TYPE_IGNORE)
return; // no signalling/focus on ignore
//#ifdef POPUPS
if (cf.popUps)
if (message.messageType==Msg.MESSAGE_TYPE_AUTH && showWobbler(c))
setWobbler(2, c, message.from+"\n"+message.body);
//#endif
if (cf.popupFromMinimized)
BombusMod.getInstance().hideApp(false);
if (cf.autoFocus)
focusToContact(c, false);
if (message.highlite) {
playNotify(SOUND_FOR_ME);
//#ifdef POPUPS
if (showWobbler(c))
setWobbler(2, c, message.body);
//#endif
autorespond = true;
} else if (message.messageType==Msg.MESSAGE_TYPE_IN || message.messageType==Msg.MESSAGE_TYPE_HEADLINE) {
if (c.origin<Contact.ORIGIN_GROUPCHAT) {
//#ifndef WMUC
if (!(c instanceof MucContact))
//#endif
//#ifdef POPUPS
if (showWobbler(c)) {
setWobbler(2, c, c.toString()+": "+message.body);
autorespond = true;
}
//#endif
if (c.group.type==Groups.TYPE_VIP) {
playNotify(SOUND_FOR_VIP);
autorespond = true;
} else {
playNotify(SOUND_MESSAGE);
autorespond = true;
}
}
//#ifndef WMUC
else {
if (c.origin!=Contact.ORIGIN_GROUPCHAT && c instanceof MucContact) {
playNotify(SOUND_MESSAGE); //private message
autorespond = true;
} else {
playNotify(SOUND_FOR_CONFERENCE);
}
}
//#endif
}
if (c.origin==Contact.ORIGIN_GROUPCHAT || c.jid.isTransport() || c.getGroupType()==Groups.TYPE_TRANSP || c.getGroupType()==Groups.TYPE_SEARCH_RESULT || c.getGroupType()==Groups.TYPE_SELF)
autorespond=false;
if (message.messageType!=Msg.MESSAGE_TYPE_IN)
autorespond=false;
if (!c.autoresponded && autorespond) {
ExtendedStatus es=sl.getStatus(myStatus);
if (es.getAutoRespond()) {
//#if DEBUG
//# System.out.println(SR.MS_AUTORESPOND+" "+c.getJid());
//#endif
Message autoMessage = new Message(
c.getJid(),
es.getAutoRespondMessage(),
SR.MS_AUTORESPOND,
false
);
theStream.send( autoMessage );
c.autoresponded=true;
c.addMessage(new Msg(Msg.MESSAGE_TYPE_SYSTEM, "local", SR.MS_AUTORESPOND, ""));
}
}
}
public void blockNotify(int event, long ms) {
if (!notifyReady(-111)) return;
blockNotifyEvent=event;
notifyReadyTime=System.currentTimeMillis()+ms;
}
public boolean notifyReady(int event) {
if ((blockNotifyEvent==event ||
(blockNotifyEvent==-111 && event<=7)) &&
System.currentTimeMillis()<notifyReadyTime) return false;
else return true;
}
public void playNotify(int event) {
if (!notifyReady(event)) return;
//#if DEBUG
//# System.out.println("event: "+event);
//#endif
AlertCustomize ac=AlertCustomize.getInstance();
int volume=ac.soundVol;
int vibraLen=cf.vibraLen;
String type, message;
//boolean flashBackLight=ac.flashBackLight;
switch (event) {
case 0: //online
case 1: //chat
if (cf.notifySound) {
message=ac.soundOnline;
type=ac.soundOnlineType;
} else {
message=null; type=null;
}
vibraLen=0;
//flashBackLight=false;
break;
case 5: //offline
message=ac.soundOffline;
type=ac.soundOfflineType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_FOR_VIP: //VIP
message=ac.soundVIP;
type=ac.soundVIPType;
break;
case SOUND_MESSAGE: //message
message=ac.messagesnd;
type=ac.messageSndType;
break;
case SOUND_FOR_CONFERENCE: //conference
message=ac.soundConference;
type=ac.soundConferenceType;
if (ac.vibrateOnlyHighlited)
vibraLen=0;
break;
case SOUND_FOR_ME: //message for you
message=ac.soundForYou;
type=ac.soundForYouType;
break;
case SOUND_CONNECTED: //startup
message=ac.soundStartUp;
type=ac.soundStartUpType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_COMPOSING: //composing
message=ac.soundComposing;
type=ac.soundComposingType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_OUTGOING: //Outgoing
message=ac.soundOutgoing;
type=ac.soundOutgoingType;
vibraLen=0;
//flashBackLight=false;
break;
default:
message="";
type="none";
vibraLen=0;
//flashBackLight=false;
break;
}
int profile=cf.profile;
EventNotify notify=null;
switch (profile) {
//display fileType soundName volume vibrate
case AlertProfile.ALL: notify=new EventNotify(display, type, message, volume, vibraLen); break;
case AlertProfile.NONE: notify=new EventNotify(display, null, null, volume, 0); break;
case AlertProfile.VIBRA: notify=new EventNotify(display, null, null, volume, vibraLen); break;
case AlertProfile.SOUND: notify=new EventNotify(display, type, message, volume, 0); break;
}
if (notify!=null) notify.startNotify();
blockNotify(event, 2000);
}
private void focusToContact(final Contact c, boolean force) {
Group g=c.group;
if (g.collapsed) {
g.collapsed=false;
reEnumerator.queueEnum(c, force);
}
int index=vContacts.indexOf(c);
if (index>=0) moveCursorTo(index);
}
public void beginConversation() { //todo: verify xmpp version
if (theStream.isXmppV1())
new SASLAuth(sd.account, this, theStream)
//#if SASL_XGOOGLETOKEN
//# .setToken(token)
//#endif
;
//#if NON_SASL_AUTH
//# else new NonSASLAuth(sd.account, this, theStream);
//#endif
}
public void connectionTerminated( Exception e ) {
if( e!=null ) {
askReconnect(e);
} else {
setProgress(SR.MS_DISCONNECTED, 0);
try {
sendPresence(Presence.PRESENCE_OFFLINE, null);
} catch (Exception e2) {
//#if DEBUG
//# e2.printStackTrace();
//#endif
}
}
redraw();
}
private void askReconnect(final Exception e) {
StringBuffer error=new StringBuffer();
if (e.getClass().getName().indexOf("java.lang.Exception")<0) {
error.append(e.getClass().getName());
error.append('\n');
}
if (e.getMessage()!=null)
error.append(e.getMessage());
if (e instanceof SecurityException) { errorLog(error.toString()); return; }
if (currentReconnect>=cf.reconnectCount) { errorLog(error.toString()); return; }
currentReconnect++;
String topBar="("+currentReconnect+"/"+cf.reconnectCount+") Reconnecting";
errorLog(topBar+"\n"+error.toString());
reconnectWindow.getInstance().startReconnect();
}
public void doReconnect() {
setProgress(SR.MS_DISCONNECTED, 0);
logoff(null);
try {
sendPresence(lastOnlineStatus, null);
} catch (Exception e2) { }
}
public void eventOk(){
super.eventOk();
if (createMsgList()==null) {
cleanupGroup();
reEnumRoster();
}
}
public void eventLongOk(){
super.eventLongOk();
//#ifndef WMUC
//#ifdef POPUPS
showInfo();
//#endif
//#endif
}
private Displayable createMsgList(){
Object e=getFocusedObject();
if (e instanceof Contact) {
return new ContactMessageList((Contact)e,display);
}
return null;
}
protected void keyGreen(){
if (!isLoggedIn()) return;
Displayable pview=createMsgList();
if (pview!=null) {
Contact c=(Contact)getFocusedObject();
//#ifdef RUNNING_MESSAGE
//# me = new MessageEdit(display, pview, c, c.msgSuspended);
//#else
new MessageEdit(display, pview, c, c.msgSuspended);
//#endif
c.msgSuspended=null;
}
}
protected void keyClear(){
if (isLoggedIn()) {
Contact c=(Contact) getFocusedObject();
try {
boolean isContact=( getFocusedObject() instanceof Contact );
//#ifndef WMUC
boolean isMucContact=( getFocusedObject() instanceof MucContact );
//#else
//# boolean isMucContact=false;
//#endif
if (isContact && !isMucContact) {
new AlertBox(SR.MS_DELETE_ASK, c.getNickJid(), display, this) {
public void yes() {
deleteContact((Contact)getFocusedObject());
}
public void no() {}
};
}
//#ifndef WMUC
else if (isContact && isMucContact && c.origin!=Contact.ORIGIN_GROUPCHAT) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.roleCode==MucContact.ROLE_MODERATOR) {
String myNick=mucGrp.selfContact.getName();
MucContact mc=(MucContact) c;
new ConferenceQuickPrivelegeModify(display, this, mc, ConferenceQuickPrivelegeModify.KICK,myNick);
}
}
//#endif
} catch (Exception e) { /* NullPointerException */ }
}
}
public void keyPressed(int keyCode){
super.keyPressed(keyCode);
switch (keyCode) {
//#ifdef POPUPS
case KEY_POUND:
if (getItemCount()==0)
return;
showInfo();
return;
//#endif
case KEY_NUM1:
if (cf.collapsedGroups) { //collapse all groups
for (Enumeration e=groups.elements(); e.hasMoreElements();) {
Group grp=(Group)e.nextElement();
grp.collapsed=true;
}
reEnumRoster();
}
break;
case KEY_NUM4:
super.pageLeft();
return;
case KEY_NUM6:
super.pageRight();
return;
//#ifdef AUTOSTATUS
//# case SE_FLIPCLOSE_JP6:
//# case SIEMENS_FLIPCLOSE:
//# case MOTOROLA_FLIP:
//# if (phoneManufacturer!=Config.SONYE) { //workaround for SE JP6 - enabling vibra in closed state
//# display.setCurrent(null);
//# try {
//# Thread.sleep(300);
//# } catch (Exception ex) {}
//# display.setCurrent(this);
//# }
//#if DEBUG
//# System.out.println("Flip closed");
//#endif
//# if (cf.autoAwayType==Config.AWAY_LOCK)
//# if (!autoAway)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# break;
//#endif
case KEY_NUM0:
if (getItemCount()==0)
return;
synchronized(hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();){
Contact c=(Contact)e.nextElement();
c.setIncoming(Contact.INC_NONE);
c=null;
}
}
redraw();
systemGC();
if (messageCount==0) return;
Object atcursor=getFocusedObject();
Contact c=(atcursor instanceof Contact)?(Contact)atcursor:(Contact)hContacts.firstElement();
Enumeration i=hContacts.elements();
int pass=0; //
while (pass<2) {
if (!i.hasMoreElements()) i=hContacts.elements();
Contact p=(Contact)i.nextElement();
if (pass==1) if (p.getNewMsgsCount()>0) {
focusToContact(p, true);
setRotator();
break;
}
if (p==c) pass++;
}
break;
case KEY_NUM3:
if (getItemCount()==0)
return;
int newpos=searchGroup(-1);
if (newpos>-1) {
moveCursorTo(newpos);
setRotator();
}
break;
case KEY_NUM9:
if (getItemCount()==0)
return;
int newpos2=searchGroup(1);
if (newpos2>-1) {
moveCursorTo(newpos2);
setRotator();
}
break;
case KEY_STAR:
if (cf.ghostMotor) {
// backlight management
blState=(blState==1)? Integer.MAX_VALUE : 1;
display.flashBacklight(blState);
}
break;
}
//#ifdef AUTOSTATUS
//# userActivity();
//#endif
}
protected void keyRepeated(int keyCode) {
super.keyRepeated(keyCode);
if (kHold==keyCode) return;
kHold=keyCode;
if (keyCode==cf.keyLock) {
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_LOCK) {
//# if (!autoAway) {
//# autoAway=true;
//# if (cf.setAutoStatusMessage) {
//# sendPresence(Presence.PRESENCE_AWAY, "Auto Status on KeyLock since %t");
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# }
//# }
//# }
//#endif
new SplashScreen(display, getMainBarItem(), cf.keyLock);
return;
} else if (keyCode==cf.keyVibra || keyCode==MOTOE680_FMRADIO /* TODO: redefine keyVibra*/) {
// swap profiles
int profile=cf.profile;
cf.profile=(profile==AlertProfile.VIBRA)?cf.lastProfile : AlertProfile.VIBRA;
cf.lastProfile=profile;
updateMainBar();
redraw();
return;
} else if (keyCode==KEY_NUM0) {
cf.showOfflineContacts=!cf.showOfflineContacts;
reEnumRoster();
return;
}
//#ifndef WMUC
else if (keyCode==KEY_NUM1 && isLoggedIn()) new Bookmarks(display, this, null);
//#endif
else if (keyCode==KEY_NUM3) new ActiveContacts(display, this, null);
else if (keyCode==KEY_NUM4) new ConfigForm(display, this);
else if (keyCode==KEY_NUM6) {
cf.fullscreen=!cf.fullscreen;
cf.saveToStorage();
VirtualList.fullscreen=cf.fullscreen;
StaticData.getInstance().roster.setFullScreenMode(cf.fullscreen);
}
else if (keyCode==KEY_NUM7)
new RosterToolsMenu(display, this);
else if (keyCode==KEY_NUM9) {
if (cf.allowMinimize)
BombusMod.getInstance().hideApp(true);
else if (phoneManufacturer==Config.SIEMENS2)//SIEMENS: MYMENU call. Possible Main Menu for capable phones
try {
BombusMod.getInstance().platformRequest("native:ELSE_STR_MYMENU");
} catch (Exception e) { }
else if (phoneManufacturer==Config.SIEMENS)//SIEMENS-NSG: MYMENU call. Possible Native Menu for capable phones
try {
BombusMod.getInstance().platformRequest("native:NAT_MAIN_MENU");
} catch (Exception e) { }
}
}
//#ifdef AUTOSTATUS
//# private void userActivity() {
//# if (autostatus==null) return;
//#
//# if (cf.autoAwayType==Config.AWAY_IDLE) {
//# if (!autoAway) {
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# return;
//# }
//# } else {
//# return;
//# }
//# autostatus.setTimeEvent(0);
//# setAutoStatus(Presence.PRESENCE_ONLINE);
//# }
//#
//# public void messageActivity() {
//# if (autostatus==null) return;
//#
//# if (cf.autoAwayType==Config.AWAY_MESSAGE) {
//# //System.out.println("messageActivity "+myStatus.getImageIndex());
//# if (myStatus<2)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# else if (!autoAway)
//# autostatus.setTimeEvent(0);
//# }
//# }
//#endif
//#ifdef POPUPS
public void showInfo() {
if (getFocusedObject()==null)
return;
try {
VirtualList.popup.next();
if (getFocusedObject() instanceof Group
//#ifndef WMUC
|| getFocusedObject() instanceof ConferenceGroup
//#endif
)
return;
setWobbler(1, (Contact) null, null);
} catch (Exception e) { }
}
public void setWobbler(int type, Contact contact, String info) {
if (info==null) {
StringBuffer mess=new StringBuffer();
boolean isContact=(getFocusedObject() instanceof Contact);
Contact cntact=(Contact)getFocusedObject();
//#ifndef WMUC
boolean isMucContact=(getFocusedObject() instanceof MucContact);
if (isMucContact) {
MucContact mucContact=(MucContact)getFocusedObject();
if (mucContact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append((mucContact.realJid==null)?"":"jid: "+mucContact.realJid+"\n");
if (mucContact.affiliationCode>MucContact.AFFILIATION_NONE)
mess.append(MucContact.getAffiliationLocale(mucContact.affiliationCode));
if (!(mucContact.roleCode==MucContact.ROLE_PARTICIPANT && mucContact.affiliationCode==MucContact.AFFILIATION_MEMBER)) {
if (mucContact.affiliationCode>MucContact.AFFILIATION_NONE)
mess.append(SR.MS_AND);
mess.append(MucContact.getRoleLocale(mucContact.roleCode));
}
}
} else {
//#endif
mess.append("jid: ")
.append(cntact.bareJid)
.append(cntact.jid.getResource())
.append("\n")
.append(SR.MS_SUBSCRIPTION)
.append(": ")
.append(cntact.subscr);
//#ifdef PEP
//# if (cntact.hasMood()) {
//# mess.append("\n")
//# .append(SR.MS_USERMOOD)
//# .append(": ")
//# .append(cntact.getMoodString());
//# }
//#ifdef PEP_ACTIVITY
//# if (cntact.hasActivity()) {
//# mess.append("\n").append(SR.MS_USERACTIVITY).append(": ").append(cntact.activity);
//# }
//#endif
//#ifdef PEP_TUNE
//# if (cntact.pepTune) {
//# mess.append("\n").append(SR.MS_USERTUNE);
//# if (cntact.pepTuneText!="") {
//# mess.append(": ").append(cntact.pepTuneText);
//# }
//# }
//#endif
//#endif
//#ifndef WMUC
}
//#endif
if (cntact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append((cntact.j2j!=null)?"\nJ2J: "+cntact.j2j:"");
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (cf.showClientIcon)
//#endif
if (cntact.client>-1)
mess.append("\nUse: "+cntact.clientName);
//#endif
if (cntact.version!=null) mess.append("\nVersion: "+cntact.version);
if (cntact.lang!=null) mess.append("\nLang: "+cntact.lang);
}
if (cntact.statusString!=null) {
if (cntact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append("\n")
.append(SR.MS_STATUS)
.append(": ");
}
mess.append(cntact.statusString);
}
VirtualList.setWobble(1, null, mess.toString());
mess=null;
} else {
VirtualList.setWobble(type, contact.getJid(), info);
}
redraw();
}
//#endif
public void logoff(String mess){
if (isLoggedIn()) {
try {
if (mess==null) mess=sl.getStatus(Presence.PRESENCE_OFFLINE).getMessage();
sendPresence(Presence.PRESENCE_OFFLINE, mess);
} catch (Exception e) { }
}
//#ifdef STATS
//#ifdef PLUGINS
//# if (sd.Stats)
//#endif
//# Stats.getInstance().saveToStorage(false);
//#endif
}
public void quit() {
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType!=Config.AWAY_OFF) {
//# try {
//# autostatus.destroyTask();
//# } catch (Exception ex) {}
//# }
//#endif
destroyView();
logoff(null);
BombusMod.getInstance().notifyDestroyed();
}
//#ifndef MENU
public void commandAction(Command c, Displayable d){
//#ifdef AUTOSTATUS
//# userActivity();
//#endif
if (c==cmdActions) { cmdActions(); }
else if (c==cmdMinimize) { cmdMinimize(); }
else if (c==cmdActiveContacts) { cmdActiveContacts(); }
else if (c==cmdAccount){ cmdAccount(); }
else if (c==cmdStatus) { cmdStatus(); }
else if (c==cmdAlert) { cmdAlert(); }
//#ifdef ARCHIVE
else if (c==cmdArchive) { cmdArchive(); }
//#endif
else if (c==cmdInfo) { cmdInfo(); }
else if (c==cmdTools) { cmdTools(); }
else if (c==cmdCleanAllMessages) { cmdCleanAllMessages(); }
//#ifndef WMUC
else if (c==cmdConference) { cmdConference(); }
//#endif
else if (c==cmdQuit) { cmdQuit(); }
else if (c==cmdAdd) { cmdAdd(); }
}
//#endif
//menu actions
public void cmdQuit() {
if (cf.queryExit) {
new AlertBox(SR.MS_QUIT_ASK, SR.MS_SURE_QUIT, display, null) {
public void yes() { quit(); }
public void no() { }
};
} else {
quit();
}
}
public void cmdMinimize() { BombusMod.getInstance().hideApp(true); }
public void cmdActiveContacts() { new ActiveContacts(display, this, null); }
public void cmdAccount(){ new AccountSelect(display, this, false); }
public void cmdStatus() { currentReconnect=0; new StatusSelect(display, this, null); }
public void cmdAlert() { new AlertProfile(display, this); }
//#ifdef ARCHIVE
public void cmdArchive() { new ArchiveList(display, this, -1, 1, null); }
//#endif
public void cmdInfo() { new Info.InfoWindow(display, this); }
public void cmdTools() { new RosterToolsMenu(display, this); }
//#ifdef POPUPS
public void cmdClearPopups() { VirtualList.popup.clear(); }
//#endif
//#ifndef WMUC
public void cmdConference() { if (isLoggedIn()) new Bookmarks(display, this, null); }
//#endif
public void cmdActions() {
if (isLoggedIn()) {
try {
new RosterItemActions(display, this, getFocusedObject(), -1);
} catch (Exception ex) {}
}
}
public void cmdAdd() {
if (isLoggedIn()) {
Object o=getFocusedObject();
Contact cn=null;
if (o instanceof Contact) {
cn=(Contact)o;
if (cn.getGroupType()!=Groups.TYPE_NOT_IN_LIST && cn.getGroupType()!=Groups.TYPE_SEARCH_RESULT)
cn=null;
}
//#ifndef WMUC
if (o instanceof MucContact)
cn=(Contact)o;
//#endif
new ContactEdit(display, this, cn);
}
}
//#ifndef WMUC
public void reEnterRoom(Group group) {
ConferenceGroup confGroup=(ConferenceGroup)group;
String confJid=confGroup.selfContact.getJid();
String name=confGroup.desc;
new ConferenceForm(display, this, name, confJid, confGroup.password, false);
}
public void leaveRoom(Group group){
ConferenceGroup confGroup=(ConferenceGroup)group;
Contact myself=confGroup.selfContact;
confGroup.confContact.commonPresence=false; //disable reenter after reconnect
sendPresence(myself.getJid(), "unavailable", null, true);
confGroup.inRoom=false;
roomOffline(group);
}
public void roomOffline(final Group group) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();) {
Contact contact=(Contact)e.nextElement();
if (contact.group==group) {
contact.setStatus(Presence.PRESENCE_OFFLINE);
}
}
}
//#endif
protected void showNotify() {
super.showNotify();
countNewMsgs();
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE)
//# if (!autostatus.isAwayTimerSet())
//# if (!autoAway)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//#endif
}
protected void hideNotify() {
super.hideNotify();
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE)
//# if (kHold==0)
//# autostatus.setTimeEvent(0);
//#endif
}
private int searchGroup(int direction){
int newpos=-1;
synchronized (vContacts) {
int size=vContacts.size();
int pos=cursor;
int count=size;
try {
while (count>0) {
pos+=direction;
if (pos<0) pos=size-1;
if (pos>=size) pos=0;
if (vContacts.elementAt(pos) instanceof Group) break;
}
} catch (Exception e) { }
newpos=pos;
}
return newpos;
}
public void searchActiveContact(int direction){
Vector activeContacts=new Vector();
int nowContact = -1, contacts=-1, currentContact=-1;
synchronized (hContacts) {
for (Enumeration r=hContacts.elements(); r.hasMoreElements(); ){
Contact c=(Contact)r.nextElement();
if (c.active()) {
activeContacts.addElement(c);
contacts=contacts+1;
if (c==activeContact) {
nowContact=contacts;
currentContact=contacts;
}
}
}
}
int size=activeContacts.size();
if (size==0) return;
try {
nowContact+=direction;
if (nowContact<0) nowContact=size-1;
if (nowContact>=size) nowContact=0;
if (currentContact==nowContact) return;
Contact c=(Contact)activeContacts.elementAt(nowContact);
new ContactMessageList((Contact)c,display);
} catch (Exception e) { }
}
public void deleteContact(Contact c) {
synchronized (hContacts) {
for (Enumeration e=hContacts.elements();e.hasMoreElements();) {
Contact c2=(Contact)e. nextElement();
if (c.jid.equals(c2. jid,false)) {
c2.setStatus(Presence.PRESENCE_TRASH);
c2.offline_type=Presence.PRESENCE_TRASH;
}
}
if (c.getGroupType()==Groups.TYPE_NOT_IN_LIST) {
hContacts.removeElement(c);
countNewMsgs();
reEnumRoster();
} else {
theStream.send(new IqQueryRoster(c.bareJid,null,null,"remove"));
sendPresence(c.bareJid, "unsubscribe", null, false);
sendPresence(c.bareJid, "unsubscribed", null, false);
}
}
}
public void setQuerySign(boolean requestState) {
querysign=requestState;
updateMainBar();
}
public void storeContact(String jid, String name, String group, boolean askSubscribe){
theStream.send(new IqQueryRoster(jid, name, group, null));
if (askSubscribe) theStream.send(new Presence(jid,"subscribe"));
}
public void loginMessage(String msg, int pos) {
setProgress(msg, pos);
}
public void setMyJid(Jid myJid) {
this.myJid = myJid;
}
//#ifdef AUTOSTATUS
//# public void setAutoAway() {
//# if (!autoAway) {
//# oldStatus=myStatus;
//# if (myStatus==0 || myStatus==1) {
//# autoAway=true;
//# if (cf.setAutoStatusMessage) {
//# sendPresence(Presence.PRESENCE_AWAY, SR.MS_AUTO_AWAY);
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# }
//# }
//# }
//# }
//#
//# public void setAutoXa() {
//# if (autoAway && !autoXa) {
//# autoXa=true;
//# if (cf.setAutoStatusMessage) {
//# sendPresence(Presence.PRESENCE_XA, SR.MS_AUTO_XA);
//# } else {
//# sendPresence(Presence.PRESENCE_XA, null);
//# }
//# }
//# }
//#
//# public void setAutoStatus(int status) {
//# if (!isLoggedIn())
//# return;
//# if (status==Presence.PRESENCE_ONLINE && autoAway) {
//# autoAway=false;
//# autoXa=false;
//# sendPresence(Presence.PRESENCE_ONLINE, null);
//# return;
//# }
//# if (status!=Presence.PRESENCE_ONLINE && myStatus==Presence.PRESENCE_ONLINE && !autoAway) {
//# autoAway=true;
//# if (cf.setAutoStatusMessage) {
//# sendPresence(Presence.PRESENCE_AWAY, "Auto Status on KeyLock since %t");
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# }
//# }
//# }
//#endif
public void deleteGroup(Group deleteGroup) {
synchronized (hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();){
Contact cr=(Contact)e.nextElement();
if (cr.group==deleteGroup)
deleteContact(cr);
}
}
}
//#ifdef MENU_LISTENER
public void showMenu() {
commandState();
new MyMenu(display, parentView, this, SR.MS_MAIN_MENU, MenuIcons.getInstance(), menuCommands);
}
public String touchRightCommand(){ return (cf.oldSE)?SR.MS_MENU:SR.MS_ACTION; }
public String touchLeftCommand(){ return (cf.oldSE)?SR.MS_ACTION:SR.MS_MENU; }
public void touchRightPressed(){ if (cf.oldSE) showMenu(); else cmdActions(); }
public void touchLeftPressed(){ if (cf.oldSE) cmdActions(); else showMenu(); }
//#endif
//#ifdef RUNNING_MESSAGE
//# void setTicker(Contact c, String message) {
//# if (cf.notifyWhenMessageType) {
//# if (me!=null)
//# if (me.to==c)
//# me.setMyTicker(message);
//# }
//# }
//#endif
private class ReEnumerator implements Runnable{
//Thread thread;
int pendingRepaints=0;
boolean force;
Object desiredFocus;
public void queueEnum(Object focusTo, boolean force) {
desiredFocus=focusTo;
this.force=force;
queueEnum();
}
synchronized public void queueEnum() {
pendingRepaints++;
//if (thread==null) (thread=new Thread(this)).start();
new Thread(this).start();
}
public void run(){
//try {
while (pendingRepaints>0) {
pendingRepaints=0;
int locCursor=cursor;
Object focused=(desiredFocus==null)?getFocusedObject():desiredFocus;
desiredFocus=null;
Vector tContacts=new Vector(vContacts.size());
groups.resetCounters();
synchronized (hContacts) {
for (Enumeration e=hContacts.elements(); e.hasMoreElements();){
Contact c=(Contact)e.nextElement();
Group grp=c.group;
grp.addContact(c);
}
}
// self-contact group
Group selfContactGroup=groups.getGroup(Groups.TYPE_SELF);
selfContactGroup.visible=(cf.selfContact || selfContactGroup.tonlines>1 || selfContactGroup.unreadMessages>0 );
// hiddens
groups.getGroup(Groups.TYPE_IGNORE).visible= cf.ignore ;
// transports
Group transpGroup=groups.getGroup(Groups.TYPE_TRANSP);
transpGroup.visible= (cf.showTransports || transpGroup.unreadMessages>0);
// adding groups
for (int i=0; i<groups.getCount(); i++)
groups.addToVector(tContacts,i);
vContacts=tContacts;
tContacts=null;
StringBuffer onl=new StringBuffer()
.append("(")
.append(groups.getRosterOnline())
.append("/")
.append(groups.getRosterContacts())
.append(")");
setRosterMainBar(onl.toString());
onl=null;
if (cursor<0) cursor=0;
if ( locCursor==cursor && focused!=null ) {
int c=vContacts.indexOf(focused);
if (c>=0) moveCursorTo(c);
force=false;
}
focusedItem(cursor);
redraw();
}
//} catch (Exception e) {
//#ifdef DEBUG
//# //e.printStackTrace();
//#endif
//}
//thread=null;
}
}
}
| true | true | public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from=data.getAttribute("from");
String type = (String) data.getTypeAttribute();
String id=(String) data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("get") || type.equals("set") || type.equals("error") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (display.getCurrent() instanceof VirtualList) {
if (c.getGroupType()==Groups.TYPE_SELF)
new VCardEdit(display, this, vcard);
else
new VCardView(display, this, c);
}
} else {
new VCardView(display, this, c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")){
theStream.enableRosterNotify(false);
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
if (splash!=null)
splash.close();
splash=null;
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) { /*e.printStackTrace();*/ }
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null)
getClientIcon(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence || chatPres.indexOf(SR.MS_WAS_BANNED)>-1 || chatPres.indexOf(SR.MS_WAS_KICKED)>-1) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) { }
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#if DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL= cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.getInstance().processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.getInstance().processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# System.out.println(lang);
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
sort(hContacts);
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
| public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from=data.getAttribute("from");
String type = (String) data.getTypeAttribute();
String id=(String) data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("get") || type.equals("set") || type.equals("error") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (display.getCurrent() instanceof VirtualList) {
if (c.getGroupType()==Groups.TYPE_SELF)
new VCardEdit(display, this, vcard);
else
new VCardView(display, this, c);
}
} else {
new VCardView(display, this, c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")){
theStream.enableRosterNotify(false);
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
if (splash!=null)
splash.close();
splash=null;
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) { /*e.printStackTrace();*/ }
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null)
getClientIcon(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence || chatPres.indexOf(SR.MS_WAS_BANNED)>-1 || chatPres.indexOf(SR.MS_WAS_KICKED)>-1) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) { }
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#if DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL= cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.getInstance().processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.getInstance().processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# System.out.println(lang);
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
sort(hContacts);
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
} catch(OutOfMemoryError eom){
System.out.println("error bombusmod\\src\\Client\\Roster.java:12");
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
|
diff --git a/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java b/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java
index 3e9870c..377a780 100755
--- a/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java
+++ b/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java
@@ -1,125 +1,125 @@
/**
* Copyright (c) 2008 Andrew Rapp. All rights reserved.
*
* This file is part of XBee-API.
*
* XBee-API 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.
*
* XBee-API 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 XBee-API. If not, see <http://www.gnu.org/licenses/>.
*/
package com.rapplogic.xbee.examples;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.nfc.ryanjfahsel.DBConnection;
import com.rapplogic.xbee.api.RemoteAtRequest;
import com.rapplogic.xbee.api.RemoteAtResponse;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeAddress64;
import com.rapplogic.xbee.api.XBeeException;
import com.rapplogic.xbee.api.XBeeTimeoutException;
/**
* This example uses Remote AT to turn on/off I/O pins.
* This example is more interesting if you connect a LED to pin 20 on your end device.
* Remember to use a resistor to limit the current flow. I used a 215 Ohm resistor.
* <p/>
* Note: if your coordinator is powered on and receiving I/O samples, make sure you power off/on to drain
* the traffic before running this example.
*
* @author andrew
*
*/
public class RemoteAtExample {
private final static Logger log = Logger.getLogger(RemoteAtExample.class);
private RemoteAtExample(int mode) throws XBeeException, InterruptedException {
XBee xbee = new XBee();
try {
// replace with your coordinator com/baud
String SerialPortID="/dev/ttyAMA0";
System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID);
xbee.open(SerialPortID, 9600);
// xbee.open("COM5", 9600);
// replace with SH + SL of your end device
XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF);
// turn on end device (pin 20) D0 (Digital output high = 5)
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3});
- RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5});
+ RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {mode});
RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
if (response.isOk()) {
log.info("successfully turned on pin 20 (D0)");
} else {
throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus());
}
//System.exit(0);
// wait a bit
Thread.sleep(5000);
//
// // now turn off end device D0
// request.setValue(new int[] {4});
// response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
// if (response.isOk()) {
/// log.info("successfully turned off pin 20 (D0)");
// } else {
// throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus());
// }
} catch (XBeeTimeoutException e) {
log.error("request timed out. make sure you remote XBee is configured and powered on");
} catch (Exception e) {
log.error("unexpected error", e);
} finally {
xbee.close();
}
}
public static void main(String[] args) throws XBeeException, InterruptedException {
PropertyConfigurator.configure("log4j.properties");
DBConnection conn=new DBConnection("admin","admin");
int result;
int prevResult;
result=Integer.parseInt(conn.Connect());
prevResult=Integer.parseInt(conn.Connect());
new RemoteAtExample(result+4);
Thread.sleep(7000);
System.out.println("Enterring loop");
while(true) {
result=Integer.parseInt(conn.Connect());
if(result==prevResult) {
//Do nothing
}
else {
new RemoteAtExample(result+4);
prevResult=result;
}
result=Integer.parseInt(conn.Connect());
Thread.sleep(1000);
}
}
}
| true | true | private RemoteAtExample(int mode) throws XBeeException, InterruptedException {
XBee xbee = new XBee();
try {
// replace with your coordinator com/baud
String SerialPortID="/dev/ttyAMA0";
System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID);
xbee.open(SerialPortID, 9600);
// xbee.open("COM5", 9600);
// replace with SH + SL of your end device
XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF);
// turn on end device (pin 20) D0 (Digital output high = 5)
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3});
RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5});
RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
if (response.isOk()) {
log.info("successfully turned on pin 20 (D0)");
} else {
throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus());
}
//System.exit(0);
// wait a bit
Thread.sleep(5000);
//
// // now turn off end device D0
// request.setValue(new int[] {4});
// response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
// if (response.isOk()) {
/// log.info("successfully turned off pin 20 (D0)");
// } else {
// throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus());
// }
} catch (XBeeTimeoutException e) {
log.error("request timed out. make sure you remote XBee is configured and powered on");
} catch (Exception e) {
log.error("unexpected error", e);
} finally {
xbee.close();
}
}
| private RemoteAtExample(int mode) throws XBeeException, InterruptedException {
XBee xbee = new XBee();
try {
// replace with your coordinator com/baud
String SerialPortID="/dev/ttyAMA0";
System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID);
xbee.open(SerialPortID, 9600);
// xbee.open("COM5", 9600);
// replace with SH + SL of your end device
XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF);
// turn on end device (pin 20) D0 (Digital output high = 5)
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2});
//RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3});
RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {mode});
RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
if (response.isOk()) {
log.info("successfully turned on pin 20 (D0)");
} else {
throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus());
}
//System.exit(0);
// wait a bit
Thread.sleep(5000);
//
// // now turn off end device D0
// request.setValue(new int[] {4});
// response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000);
// if (response.isOk()) {
/// log.info("successfully turned off pin 20 (D0)");
// } else {
// throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus());
// }
} catch (XBeeTimeoutException e) {
log.error("request timed out. make sure you remote XBee is configured and powered on");
} catch (Exception e) {
log.error("unexpected error", e);
} finally {
xbee.close();
}
}
|
diff --git a/src/main/java/org/nuxeo/ecm/platform/audit/web/access/WebAccessLogActionListener.java b/src/main/java/org/nuxeo/ecm/platform/audit/web/access/WebAccessLogActionListener.java
index b742c6e..f07c612 100644
--- a/src/main/java/org/nuxeo/ecm/platform/audit/web/access/WebAccessLogActionListener.java
+++ b/src/main/java/org/nuxeo/ecm/platform/audit/web/access/WebAccessLogActionListener.java
@@ -1,104 +1,107 @@
/*
* (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* 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.
*
* Contributors:
* anguenot
*
* $Id: WebAccessLogActionListener.java 28475 2008-01-04 09:49:02Z sfermigier $
*/
package org.nuxeo.ecm.platform.audit.web.access;
import static org.jboss.seam.ScopeType.CONVERSATION;
import java.security.Principal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.event.CoreEventConstants;
import org.nuxeo.ecm.core.api.event.DocumentEventCategories;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventService;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.platform.audit.web.access.api.AccessLogObserver;
import org.nuxeo.ecm.platform.audit.web.access.api.WebAccessConstants;
import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
import org.nuxeo.ecm.webapp.helpers.EventNames;
import org.nuxeo.runtime.api.Framework;
/**
* Access log action listener.
*
* <p>
* Responsible of logging web access. Attention, this will decrease the
* performances of the webapp.
* </p>
*
* @author <a href="mailto:[email protected]">Julien Anguenot</a>
* @author <a href="mailto:[email protected]">Vincent Dutat</a>
*
*
*/
@Name("webAccessLogObserver")
@Scope(CONVERSATION)
public class WebAccessLogActionListener implements AccessLogObserver {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(WebAccessLogActionListener.class);
@In(create = true)
protected NavigationContext navigationContext;
@In(create = true)
protected Principal currentUser;
@Observer( { EventNames.USER_ALL_DOCUMENT_TYPES_SELECTION_CHANGED })
public void log() {
DocumentModel dm = navigationContext.getCurrentDocument();
+ if (dm==null) {
+ return;
+ }
DocumentEventContext ctx = new DocumentEventContext(navigationContext.getCurrentDocument().getCoreSession(),
currentUser, dm);
ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
ctx.setProperty(CoreEventConstants.DOC_LIFE_CYCLE, dm.getCurrentLifeCycleState());
ctx.setProperty(CoreEventConstants.SESSION_ID, dm.getSessionId());
} catch (ClientException e1) {
log.error("Error while getting document's lifecycle or session ID", e1);
}
Event event = ctx.newEvent(WebAccessConstants.EVENT_ID);
EventService evtService = null;
try {
evtService = Framework.getService(EventService.class);
}
catch (Exception e) {
log.error("Cannot find EventService", e);
}
if (evtService != null) {
log.debug("Sending scheduled event id=" + WebAccessConstants.EVENT_ID + ", category="
+ DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
evtService.fireEvent(event);
} catch (ClientException e) {
log.error("Error while sending event to EventService", e);
}
}
}
}
| true | true | public void log() {
DocumentModel dm = navigationContext.getCurrentDocument();
DocumentEventContext ctx = new DocumentEventContext(navigationContext.getCurrentDocument().getCoreSession(),
currentUser, dm);
ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
ctx.setProperty(CoreEventConstants.DOC_LIFE_CYCLE, dm.getCurrentLifeCycleState());
ctx.setProperty(CoreEventConstants.SESSION_ID, dm.getSessionId());
} catch (ClientException e1) {
log.error("Error while getting document's lifecycle or session ID", e1);
}
Event event = ctx.newEvent(WebAccessConstants.EVENT_ID);
EventService evtService = null;
try {
evtService = Framework.getService(EventService.class);
}
catch (Exception e) {
log.error("Cannot find EventService", e);
}
if (evtService != null) {
log.debug("Sending scheduled event id=" + WebAccessConstants.EVENT_ID + ", category="
+ DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
evtService.fireEvent(event);
} catch (ClientException e) {
log.error("Error while sending event to EventService", e);
}
}
}
| public void log() {
DocumentModel dm = navigationContext.getCurrentDocument();
if (dm==null) {
return;
}
DocumentEventContext ctx = new DocumentEventContext(navigationContext.getCurrentDocument().getCoreSession(),
currentUser, dm);
ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
ctx.setProperty(CoreEventConstants.DOC_LIFE_CYCLE, dm.getCurrentLifeCycleState());
ctx.setProperty(CoreEventConstants.SESSION_ID, dm.getSessionId());
} catch (ClientException e1) {
log.error("Error while getting document's lifecycle or session ID", e1);
}
Event event = ctx.newEvent(WebAccessConstants.EVENT_ID);
EventService evtService = null;
try {
evtService = Framework.getService(EventService.class);
}
catch (Exception e) {
log.error("Cannot find EventService", e);
}
if (evtService != null) {
log.debug("Sending scheduled event id=" + WebAccessConstants.EVENT_ID + ", category="
+ DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
try {
evtService.fireEvent(event);
} catch (ClientException e) {
log.error("Error while sending event to EventService", e);
}
}
}
|
diff --git a/src/br/com/suelengc/calctributospj/model/TributacaoNormal.java b/src/br/com/suelengc/calctributospj/model/TributacaoNormal.java
index 3b3c969..162b367 100644
--- a/src/br/com/suelengc/calctributospj/model/TributacaoNormal.java
+++ b/src/br/com/suelengc/calctributospj/model/TributacaoNormal.java
@@ -1,74 +1,74 @@
package br.com.suelengc.calctributospj.model;
public class TributacaoNormal {
private double irpjMensal;
private double irpjTrimestral;
private double cofinsMensal;
private double pisMensal;
private double csllMensal;
private double csllTrimetral;
private double inssMensal;
private double valorBrutoNotaFiscal;
private double valorLiquidoNotaFiscal;
public TributacaoNormal(double valorTotalNotaFiscal) {
this.valorBrutoNotaFiscal = valorTotalNotaFiscal;
this.irpjMensal = valorTotalNotaFiscal * 0.015;
this.irpjTrimestral = valorTotalNotaFiscal * 0.009;
this.cofinsMensal = valorTotalNotaFiscal * 0.03;
- this.pisMensal = valorTotalNotaFiscal * 0.065;
+ this.pisMensal = valorTotalNotaFiscal * 0.0065;
this.csllMensal = valorTotalNotaFiscal * 0.01;
this.csllTrimetral = valorTotalNotaFiscal * 0.0188;
this.inssMensal = valorTotalNotaFiscal * 0.02;
this.valorLiquidoNotaFiscal = this.valorBrutoNotaFiscal - (this.irpjMensal + this.cofinsMensal +
this.pisMensal + this.csllMensal + this.inssMensal);
}
public double getIrpjMensal() {
return irpjMensal;
}
public double getIrpjTrimestral() {
return irpjTrimestral;
}
public double getCofinsMensal() {
return cofinsMensal;
}
public double getPisMensal() {
return pisMensal;
}
public double getCsllMensal() {
return csllMensal;
}
public double getCsllTrimetral() {
return csllTrimetral;
}
public double getInssMensal() {
return inssMensal;
}
public double getValorTotalNotaFiscal() {
return valorBrutoNotaFiscal;
}
public double getValorBrutoNotaFiscal() {
return valorBrutoNotaFiscal;
}
public double getValorLiquidoNotaFiscal() {
return valorLiquidoNotaFiscal;
}
}
| true | true | public TributacaoNormal(double valorTotalNotaFiscal) {
this.valorBrutoNotaFiscal = valorTotalNotaFiscal;
this.irpjMensal = valorTotalNotaFiscal * 0.015;
this.irpjTrimestral = valorTotalNotaFiscal * 0.009;
this.cofinsMensal = valorTotalNotaFiscal * 0.03;
this.pisMensal = valorTotalNotaFiscal * 0.065;
this.csllMensal = valorTotalNotaFiscal * 0.01;
this.csllTrimetral = valorTotalNotaFiscal * 0.0188;
this.inssMensal = valorTotalNotaFiscal * 0.02;
this.valorLiquidoNotaFiscal = this.valorBrutoNotaFiscal - (this.irpjMensal + this.cofinsMensal +
this.pisMensal + this.csllMensal + this.inssMensal);
}
| public TributacaoNormal(double valorTotalNotaFiscal) {
this.valorBrutoNotaFiscal = valorTotalNotaFiscal;
this.irpjMensal = valorTotalNotaFiscal * 0.015;
this.irpjTrimestral = valorTotalNotaFiscal * 0.009;
this.cofinsMensal = valorTotalNotaFiscal * 0.03;
this.pisMensal = valorTotalNotaFiscal * 0.0065;
this.csllMensal = valorTotalNotaFiscal * 0.01;
this.csllTrimetral = valorTotalNotaFiscal * 0.0188;
this.inssMensal = valorTotalNotaFiscal * 0.02;
this.valorLiquidoNotaFiscal = this.valorBrutoNotaFiscal - (this.irpjMensal + this.cofinsMensal +
this.pisMensal + this.csllMensal + this.inssMensal);
}
|
diff --git a/core/src/main/java/com/ning/metrics/meteo/subscribers/FileSubscriber.java b/core/src/main/java/com/ning/metrics/meteo/subscribers/FileSubscriber.java
index ce0de30..3b28950 100644
--- a/core/src/main/java/com/ning/metrics/meteo/subscribers/FileSubscriber.java
+++ b/core/src/main/java/com/ning/metrics/meteo/subscribers/FileSubscriber.java
@@ -1,96 +1,96 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning 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 com.ning.metrics.meteo.subscribers;
import com.espertech.esper.client.EPServiceProvider;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
class FileSubscriber implements Subscriber
{
private final Logger log = Logger.getLogger(FileSubscriber.class);
private final EPServiceProvider esperSink;
private final FileSubscriberConfig subscriberConfig;
private final static LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
@Inject
public FileSubscriber(FileSubscriberConfig subscriberConfig, EPServiceProvider esperSink)
{
this.subscriberConfig = subscriberConfig;
this.esperSink = esperSink;
}
@Override
public void subscribe()
{
List<LinkedHashMap<String, Object>> dataPoints = getDataPoints();
log.info(String.format("Found %d data points", dataPoints.size()));
for (LinkedHashMap<String, Object> s : dataPoints) {
try {
log.debug("Received a message, yay!\n" + s);
esperSink.getEPRuntime().sendEvent(s, subscriberConfig.getEventOutputName());
}
catch (ClassCastException ex) {
log.info("Received message that I couldn't parse: " + s, ex);
}
}
}
@Override
public void unsubscribe()
{
// Do nothing
}
private ImmutableList<LinkedHashMap<String, Object>> getDataPoints()
{
ImmutableList.Builder<LinkedHashMap<String, Object>> builder = new ImmutableList.Builder<LinkedHashMap<String, Object>>();
try {
for (String line : (List<String>) IOUtils.readLines(new FileReader(subscriberConfig.getFilePath()))) {
if (line.trim().length() > 0) {
map.clear();
String[] items = line.split(subscriberConfig.getSeparator());
long dateTime = new DateTime(items[0], DateTimeZone.forID("UTC")).getMillis();
map.put("timestamp", dateTime);
for (int j = 1; j < items.length; j++) {
double value = Double.valueOf(items[j]);
- map.put(subscriberConfig.getAttributes()[j], value);
+ map.put(subscriberConfig.getAttributes()[j-1], value);
}
builder.add(new LinkedHashMap(map));
}
}
return builder.build();
}
catch (IOException e) {
log.error("Unable to read file: " + subscriberConfig.getFilePath());
return null;
}
}
}
| true | true | private ImmutableList<LinkedHashMap<String, Object>> getDataPoints()
{
ImmutableList.Builder<LinkedHashMap<String, Object>> builder = new ImmutableList.Builder<LinkedHashMap<String, Object>>();
try {
for (String line : (List<String>) IOUtils.readLines(new FileReader(subscriberConfig.getFilePath()))) {
if (line.trim().length() > 0) {
map.clear();
String[] items = line.split(subscriberConfig.getSeparator());
long dateTime = new DateTime(items[0], DateTimeZone.forID("UTC")).getMillis();
map.put("timestamp", dateTime);
for (int j = 1; j < items.length; j++) {
double value = Double.valueOf(items[j]);
map.put(subscriberConfig.getAttributes()[j], value);
}
builder.add(new LinkedHashMap(map));
}
}
return builder.build();
}
catch (IOException e) {
log.error("Unable to read file: " + subscriberConfig.getFilePath());
return null;
}
}
| private ImmutableList<LinkedHashMap<String, Object>> getDataPoints()
{
ImmutableList.Builder<LinkedHashMap<String, Object>> builder = new ImmutableList.Builder<LinkedHashMap<String, Object>>();
try {
for (String line : (List<String>) IOUtils.readLines(new FileReader(subscriberConfig.getFilePath()))) {
if (line.trim().length() > 0) {
map.clear();
String[] items = line.split(subscriberConfig.getSeparator());
long dateTime = new DateTime(items[0], DateTimeZone.forID("UTC")).getMillis();
map.put("timestamp", dateTime);
for (int j = 1; j < items.length; j++) {
double value = Double.valueOf(items[j]);
map.put(subscriberConfig.getAttributes()[j-1], value);
}
builder.add(new LinkedHashMap(map));
}
}
return builder.build();
}
catch (IOException e) {
log.error("Unable to read file: " + subscriberConfig.getFilePath());
return null;
}
}
|
diff --git a/org.eclipse.b3.beelang.ui/src/org/eclipse/b3/commands/ExecuteHandler.java b/org.eclipse.b3.beelang.ui/src/org/eclipse/b3/commands/ExecuteHandler.java
index ec25a023..21913cab 100644
--- a/org.eclipse.b3.beelang.ui/src/org/eclipse/b3/commands/ExecuteHandler.java
+++ b/org.eclipse.b3.beelang.ui/src/org/eclipse/b3/commands/ExecuteHandler.java
@@ -1,57 +1,57 @@
package org.eclipse.b3.commands;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.b3.backend.core.B3Engine;
import org.eclipse.b3.backend.evaluator.b3backend.BFunction;
import org.eclipse.b3.beeLang.BeeModel;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.expressions.EvaluationContext;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.ui.common.editor.outline.ContentOutlineNode;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
public class ExecuteHandler extends AbstractHandler {
@SuppressWarnings("unchecked")
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.print("Running the main function...\n");
EvaluationContext ctx = (EvaluationContext)event.getApplicationContext();
List<ContentOutlineNode> nodes = (List<ContentOutlineNode>)ctx.getDefaultVariable();
ContentOutlineNode node = nodes.get(0);
Object result = node.getEObjectHandle().readOnly(new IUnitOfWork<Object, EObject>() {
public Object exec(EObject state) throws Exception {
B3Engine engine = new B3Engine();
// Define all functions, and
// find a function called main (use the first found) and call it with a List<Object> argv
BFunction main = null;
for(BFunction f : ((BeeModel)state).getFunctions()) {
engine.getContext().defineFunction(f);
if("main".equals(f.getName())) {
main = f;
}
}
if(main == null)
return null;
final List<Object> argv = new ArrayList<Object>();
try {
return engine.getContext().callFunction("main", new Object[] { argv }, new Type[] { List.class });
} catch (Throwable e) {
// Just print some errors
e.printStackTrace();
}
return null;
}
}
);
- System.out.print("Result = " + result == null ? "null" : result.toString()+"\n");
+ System.out.print("Result = " + (result == null ? "null" : result.toString())+"\n");
return null;
}
}
| true | true | public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.print("Running the main function...\n");
EvaluationContext ctx = (EvaluationContext)event.getApplicationContext();
List<ContentOutlineNode> nodes = (List<ContentOutlineNode>)ctx.getDefaultVariable();
ContentOutlineNode node = nodes.get(0);
Object result = node.getEObjectHandle().readOnly(new IUnitOfWork<Object, EObject>() {
public Object exec(EObject state) throws Exception {
B3Engine engine = new B3Engine();
// Define all functions, and
// find a function called main (use the first found) and call it with a List<Object> argv
BFunction main = null;
for(BFunction f : ((BeeModel)state).getFunctions()) {
engine.getContext().defineFunction(f);
if("main".equals(f.getName())) {
main = f;
}
}
if(main == null)
return null;
final List<Object> argv = new ArrayList<Object>();
try {
return engine.getContext().callFunction("main", new Object[] { argv }, new Type[] { List.class });
} catch (Throwable e) {
// Just print some errors
e.printStackTrace();
}
return null;
}
}
);
System.out.print("Result = " + result == null ? "null" : result.toString()+"\n");
return null;
}
| public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.print("Running the main function...\n");
EvaluationContext ctx = (EvaluationContext)event.getApplicationContext();
List<ContentOutlineNode> nodes = (List<ContentOutlineNode>)ctx.getDefaultVariable();
ContentOutlineNode node = nodes.get(0);
Object result = node.getEObjectHandle().readOnly(new IUnitOfWork<Object, EObject>() {
public Object exec(EObject state) throws Exception {
B3Engine engine = new B3Engine();
// Define all functions, and
// find a function called main (use the first found) and call it with a List<Object> argv
BFunction main = null;
for(BFunction f : ((BeeModel)state).getFunctions()) {
engine.getContext().defineFunction(f);
if("main".equals(f.getName())) {
main = f;
}
}
if(main == null)
return null;
final List<Object> argv = new ArrayList<Object>();
try {
return engine.getContext().callFunction("main", new Object[] { argv }, new Type[] { List.class });
} catch (Throwable e) {
// Just print some errors
e.printStackTrace();
}
return null;
}
}
);
System.out.print("Result = " + (result == null ? "null" : result.toString())+"\n");
return null;
}
|
diff --git a/src/main/java/eu/serscis/SAMMethod.java b/src/main/java/eu/serscis/SAMMethod.java
index 6667715..13ca97f 100644
--- a/src/main/java/eu/serscis/SAMMethod.java
+++ b/src/main/java/eu/serscis/SAMMethod.java
@@ -1,439 +1,444 @@
/////////////////////////////////////////////////////////////////////////
//
// © University of Southampton IT Innovation Centre, 2011
//
// Copyright in this library belongs to the University of Southampton
// University Road, Highfield, Southampton, UK, SO17 1BJ
//
// This software may not be used, sold, licensed, transferred, copied
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// without the prior written consent of the copyright owners.
//
// This software is distributed WITHOUT ANY WARRANTY, without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
//
// Created By : Thomas Leonard
// Created Date : 2011-04-04
// Created for Project : SERSCIS
//
/////////////////////////////////////////////////////////////////////////
//
// License : GNU Lesser General Public License, version 2.1
//
/////////////////////////////////////////////////////////////////////////
package eu.serscis;
import java.util.HashSet;
import java.util.Set;
import eu.serscis.sam.node.*;
import java.io.StringReader;
import java.io.PushbackReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.io.FileWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.IOException;
import org.deri.iris.Configuration;
import org.deri.iris.KnowledgeBaseFactory;
import org.deri.iris.api.IKnowledgeBase;
import org.deri.iris.api.basics.IPredicate;
import org.deri.iris.api.basics.IQuery;
import org.deri.iris.api.basics.IRule;
import org.deri.iris.api.basics.ITuple;
import org.deri.iris.api.basics.ILiteral;
import org.deri.iris.api.terms.IVariable;
import org.deri.iris.api.terms.ITerm;
import org.deri.iris.storage.IRelation;
import org.deri.iris.rules.IRuleSafetyProcessor;
import org.deri.iris.RuleUnsafeException;
import org.deri.iris.compiler.BuiltinRegister;
import static org.deri.iris.factory.Factory.*;
import eu.serscis.sam.lexer.Lexer;
import eu.serscis.sam.parser.Parser;
import eu.serscis.sam.parser.ParserException;
import static eu.serscis.Constants.*;
class SAMMethod {
private Set<String> locals = new HashSet<String>();
private SAMClass parent;
private String localPrefix;
private AMethod method;
private ITerm methodNameFull;
private int nextCallSite = 1;
public SAMMethod(SAMClass parent, AMethod m, ITerm methodNameFull) throws Exception {
this.parent = parent;
this.method = m;
this.methodNameFull = methodNameFull;
this.localPrefix = methodNameFull.getValue() + ".";
}
private String parsePattern(PPattern parsed) {
if (parsed instanceof ANamedPattern) {
return ((ANamedPattern) parsed).getName().getText();
} else {
return "*";
}
}
public void addDatalog() throws Exception {
ACode code = (ACode) method.getCode();
// mayAccept(type, param)
IRelation acceptRel = parent.model.getRelation(mayAcceptP);
AParams params = (AParams) method.getParams();
if (params != null) {
addParam(methodNameFull, acceptRel, params.getParam());
for (PParamsTail tail : params.getParamsTail()) {
AParam param2 = (AParam) ((AParamsTail) tail).getParam();
addParam(methodNameFull, acceptRel, param2);
}
}
processCode(code.getStatement());
}
private void processCode(List<PStatement> statements) throws Exception {
for (PStatement ps : statements) {
if (ps instanceof AAssignStatement) {
AAssignStatement s = (AAssignStatement) ps;
AAssign assign = (AAssign) s.getAssign();
PExpr expr = (PExpr) s.getExpr();
String callSite = methodNameFull.getValue() + "-" + nextCallSite;
nextCallSite++;
// hasCallSite(methodFull, callSite).
IRelation rel = parent.model.getRelation(hasCallSiteP);
rel.add(BASIC.createTuple(methodNameFull, TERM.createString(callSite)));
IPredicate valueP = null;
if (expr instanceof ACallExpr) {
ACallExpr callExpr = (ACallExpr) expr;
// mayCallObject(?Caller, ?CallerInvocation, ?CallSite, ?Value) :-
// isA(?Caller, ?Type),
// liveMethod(?Caller, ?CallerInvocation, method),
// value(?Caller, ?CallerInvocation, ?TargetVar, ?Value).
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(mayCallObjectP, tuple));
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(this.parent.name))));
ILiteral liveMethod = BASIC.createLiteral(true, BASIC.createAtom(liveMethodP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
methodNameFull)));
IRule rule = BASIC.createRule(makeList(head), makeList(isA, liveMethod, getValue(callExpr.getName())));
//System.out.println(rule);
parent.model.rules.add(rule);
addArgs(callSite, (AArgs) callExpr.getArgs());
// callsMethod(callSite, method)
String targetMethod = parsePattern(callExpr.getMethod());
if ("*".equals(targetMethod)) {
rel = parent.model.getRelation(callsAnyMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite)));
} else {
rel = parent.model.getRelation(callsMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite), TERM.createString(targetMethod)));
}
valueP = didGetP;
} else if (expr instanceof ANewExpr) {
ANewExpr newExpr = (ANewExpr) expr;
// mayCreate(classname, newType, var)
rel = parent.model.getRelation(mayCreateP);
String newType = ((AType) newExpr.getType()).getName().getText();
rel.add(BASIC.createTuple(TERM.createString(callSite),
TERM.createString(newType)));
addArgs(callSite, (AArgs) newExpr.getArgs());
valueP = didCreateP;
} else if (expr instanceof ACopyExpr) {
// a = b
ACopyExpr copyExpr = (ACopyExpr) expr;
if (assign == null) {
throw new RuntimeException("Pointless var expression");
}
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP,
BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(parent.name))));
TName sourceVar = copyExpr.getName();
assignVar(assign, makeList(isA, getValue(sourceVar)));
} else {
throw new RuntimeException("Unknown expr type: " + expr);
}
if (assign != null && valueP != null) {
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral value = BASIC.createLiteral(true, BASIC.createAtom(valueP, tuple));
assignVar(assign, makeList(value));
}
} else if (ps instanceof ADeclStatement) {
ADeclStatement decl = (ADeclStatement) ps;
declareLocal(decl.getType(), decl.getName());
} else if (ps instanceof AReturnStatement) {
- returnOrThrow(mayReturnP, methodNameFull, ((AReturnStatement) ps).getName());
+ boolean returnsVoid = "void".equals(((AType) method.getType()).getName().getText());
+ TName expr = ((AReturnStatement) ps).getName();
+ if (returnsVoid && expr.getText() != null) {
+ throw new ParserException(expr, "Return with a value in method declared to return void!");
+ }
+ returnOrThrow(mayReturnP, methodNameFull, expr);
} else if (ps instanceof AThrowStatement) {
returnOrThrow(mayThrowP, methodNameFull, ((AThrowStatement) ps).getName());
} else if (ps instanceof ATryStatement) {
ATryStatement ts = (ATryStatement) ps;
processCode(ts.getStatement());
for (PCatchBlock c : ts.getCatchBlock()) {
ACatchBlock cb = (ACatchBlock) c;
declareLocal(cb.getType(), cb.getName());
// local(?Object, ?Innovation, name, ?Exception) :-
// didGetException(?Object, ?Invocation, ?CallSite, ?Exception),
// hasCallSite(?Method, ?CallSite).
// (note: we currently catch all exceptions from this method, not just those in the try block)
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(localP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createString(expandLocal(cb.getName().getText())),
TERM.createVariable("Exception"))));
ILiteral didGetException = BASIC.createLiteral(true, BASIC.createAtom(didGetExceptionP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createVariable("CallSite"),
TERM.createVariable("Exception"))));
ILiteral hasCallSite = BASIC.createLiteral(true, BASIC.createAtom(hasCallSiteP,
BASIC.createTuple(
methodNameFull,
TERM.createVariable("CallSite"))));
IRule rule = BASIC.createRule(makeList(head), makeList(didGetException, hasCallSite));
//System.out.println(rule);
parent.model.rules.add(rule);
processCode(cb.getStatement());
}
} else {
throw new RuntimeException("Unknown statement type: " + ps);
}
}
}
private void returnOrThrow(IPredicate pred, ITerm methodNameFull, TName name) throws ParserException {
// mayReturn(?Target, ?TargetInvocation, ?Method, ?Value) :-
// isA(?Target, name),
// liveMethod(?Target, ?TargetInvocation, ?Method),
// (value)
ITuple tuple = BASIC.createTuple(
// XXX: badly named: should be Target, but getValue uses "Caller"
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
methodNameFull,
TERM.createVariable("Value"));
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(pred, tuple));
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(this.parent.name))));
ILiteral live = BASIC.createLiteral(true, BASIC.createAtom(liveMethodP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
methodNameFull)));
IRule rule = BASIC.createRule(makeList(head), makeList(isA, live, getValue(name)));
//System.out.println(rule);
parent.model.rules.add(rule);
}
private void declareLocal(AAssign assign) {
AType type = (AType) assign.getType();
if (type != null) {
declareLocal(type, assign.getName());
}
}
private void declareLocal(PType type, TName aName) {
String name = aName.getText();
if (locals.contains(name)) {
throw new RuntimeException("Duplicate definition of local " + name);
} else if (parent.fields.contains(name)) {
throw new RuntimeException("Local variable shadows field of same name: " + name);
} else {
locals.add(name);
}
}
/* Assign a local or field, as appropriate:
* local(?Caller, ?CallerInvocation, 'var', ?Value) :- body
* or
* field(?Caller, 'var', ?Value) :- body
*/
private void assignVar(AAssign assign, List<ILiteral> body) {
ILiteral head;
declareLocal(assign);
String varName = assign.getName().getText();
if (locals.contains(varName)) {
ITuple tuple = BASIC.createTuple(TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(expandLocal(varName)),
TERM.createVariable("Value"));
head = BASIC.createLiteral(true, BASIC.createAtom(localP, tuple));
} else if (parent.fields.contains(varName)) {
ITuple tuple = BASIC.createTuple(TERM.createVariable("Caller"),
TERM.createString(varName),
TERM.createVariable("Value"));
head = BASIC.createLiteral(true, BASIC.createAtom(fieldP, tuple));
} else {
throw new RuntimeException("Undeclared variable: " + varName);
}
IRule rule = BASIC.createRule(makeList(head), body);
//System.out.println(rule);
parent.model.rules.add(rule);
}
private void addParam(ITerm method, IRelation acceptRel, PParam param) {
String name = ((AParam) param).getName().getText();
acceptRel.add(BASIC.createTuple(method, TERM.createString(expandLocal(name))));
if (locals.contains(name)) {
throw new RuntimeException("Duplicate definition of local " + name);
} else if (parent.fields.contains(name)) {
throw new RuntimeException("Local variable shadows field of same name: " + name);
} else {
locals.add(name);
}
}
/* mayGet(?Target, ?TargetInvocation, ?Method, ?Pos, ?Value) :-
* didCall(?Caller, ?CallerInvocation, ?CallSite, ?Target, ?TargetInvocation, ?Method),
* local|field,
*/
private void addArg(String callSite, int pos, PExpr expr) throws ParserException {
ILiteral didCall = BASIC.createLiteral(true, didCallP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Target"),
TERM.createVariable("TargetInvocation"),
TERM.createVariable("Method")
));
IRule rule;
if (expr instanceof AStringExpr) {
ILiteral head = BASIC.createLiteral(true, maySendP, BASIC.createTuple(
TERM.createVariable("Target"),
TERM.createVariable("TargetInvocation"),
TERM.createVariable("Method"),
CONCRETE.createInt(pos),
TERM.createString(getString(((AStringExpr) expr).getStringLiteral()))
));
rule = BASIC.createRule(makeList(head), makeList(didCall));
} else {
TName varName = ((ACopyExpr) expr).getName();
ILiteral head = BASIC.createLiteral(true, maySendP, BASIC.createTuple(
TERM.createVariable("Target"),
TERM.createVariable("TargetInvocation"),
TERM.createVariable("Method"),
CONCRETE.createInt(pos),
TERM.createVariable("Value")
));
rule = BASIC.createRule(makeList(head), makeList(didCall, getValue(varName)));
}
parent.model.rules.add(rule);
//System.out.println(rule);
}
private void addArgs(String callSite, AArgs args) throws ParserException {
if (args == null) {
return;
}
int pos = 0;
PExpr arg0 = args.getExpr();
addArg(callSite, pos, arg0);
for (PArgsTail tail : args.getArgsTail()) {
pos += 1;
PExpr arg = ((AArgsTail) tail).getExpr();
addArg(callSite, pos, arg);
}
}
/* Returns
* local(?Caller, ?CallerInvocation, 'var', ?Value)
* or
* field(?Caller, 'var', ?Value)
* or
* equals(?Caller, ?Value) (for "this")
* depending on whether varName refers to a local or a field.
*/
private ILiteral getValue(TName var) throws ParserException {
String sourceVar = var.getText();
if (locals.contains(sourceVar)) {
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(expandLocal(sourceVar)),
TERM.createVariable("Value"));
return BASIC.createLiteral(true, BASIC.createAtom(localP, tuple));
} else if (parent.fields.contains(sourceVar)) {
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(sourceVar),
TERM.createVariable("Value"));
return BASIC.createLiteral(true, BASIC.createAtom(fieldP, tuple));
} else if (sourceVar.equals("this")) {
return BASIC.createLiteral(true, BUILTIN.createEqual(
TERM.createVariable("Caller"),
TERM.createVariable("Value")));
} else {
throw new ParserException(var, "Unknown variable " + sourceVar);
}
}
private String expandLocal(String local) {
return localPrefix + local;
}
}
| true | true | private void processCode(List<PStatement> statements) throws Exception {
for (PStatement ps : statements) {
if (ps instanceof AAssignStatement) {
AAssignStatement s = (AAssignStatement) ps;
AAssign assign = (AAssign) s.getAssign();
PExpr expr = (PExpr) s.getExpr();
String callSite = methodNameFull.getValue() + "-" + nextCallSite;
nextCallSite++;
// hasCallSite(methodFull, callSite).
IRelation rel = parent.model.getRelation(hasCallSiteP);
rel.add(BASIC.createTuple(methodNameFull, TERM.createString(callSite)));
IPredicate valueP = null;
if (expr instanceof ACallExpr) {
ACallExpr callExpr = (ACallExpr) expr;
// mayCallObject(?Caller, ?CallerInvocation, ?CallSite, ?Value) :-
// isA(?Caller, ?Type),
// liveMethod(?Caller, ?CallerInvocation, method),
// value(?Caller, ?CallerInvocation, ?TargetVar, ?Value).
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(mayCallObjectP, tuple));
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(this.parent.name))));
ILiteral liveMethod = BASIC.createLiteral(true, BASIC.createAtom(liveMethodP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
methodNameFull)));
IRule rule = BASIC.createRule(makeList(head), makeList(isA, liveMethod, getValue(callExpr.getName())));
//System.out.println(rule);
parent.model.rules.add(rule);
addArgs(callSite, (AArgs) callExpr.getArgs());
// callsMethod(callSite, method)
String targetMethod = parsePattern(callExpr.getMethod());
if ("*".equals(targetMethod)) {
rel = parent.model.getRelation(callsAnyMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite)));
} else {
rel = parent.model.getRelation(callsMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite), TERM.createString(targetMethod)));
}
valueP = didGetP;
} else if (expr instanceof ANewExpr) {
ANewExpr newExpr = (ANewExpr) expr;
// mayCreate(classname, newType, var)
rel = parent.model.getRelation(mayCreateP);
String newType = ((AType) newExpr.getType()).getName().getText();
rel.add(BASIC.createTuple(TERM.createString(callSite),
TERM.createString(newType)));
addArgs(callSite, (AArgs) newExpr.getArgs());
valueP = didCreateP;
} else if (expr instanceof ACopyExpr) {
// a = b
ACopyExpr copyExpr = (ACopyExpr) expr;
if (assign == null) {
throw new RuntimeException("Pointless var expression");
}
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP,
BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(parent.name))));
TName sourceVar = copyExpr.getName();
assignVar(assign, makeList(isA, getValue(sourceVar)));
} else {
throw new RuntimeException("Unknown expr type: " + expr);
}
if (assign != null && valueP != null) {
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral value = BASIC.createLiteral(true, BASIC.createAtom(valueP, tuple));
assignVar(assign, makeList(value));
}
} else if (ps instanceof ADeclStatement) {
ADeclStatement decl = (ADeclStatement) ps;
declareLocal(decl.getType(), decl.getName());
} else if (ps instanceof AReturnStatement) {
returnOrThrow(mayReturnP, methodNameFull, ((AReturnStatement) ps).getName());
} else if (ps instanceof AThrowStatement) {
returnOrThrow(mayThrowP, methodNameFull, ((AThrowStatement) ps).getName());
} else if (ps instanceof ATryStatement) {
ATryStatement ts = (ATryStatement) ps;
processCode(ts.getStatement());
for (PCatchBlock c : ts.getCatchBlock()) {
ACatchBlock cb = (ACatchBlock) c;
declareLocal(cb.getType(), cb.getName());
// local(?Object, ?Innovation, name, ?Exception) :-
// didGetException(?Object, ?Invocation, ?CallSite, ?Exception),
// hasCallSite(?Method, ?CallSite).
// (note: we currently catch all exceptions from this method, not just those in the try block)
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(localP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createString(expandLocal(cb.getName().getText())),
TERM.createVariable("Exception"))));
ILiteral didGetException = BASIC.createLiteral(true, BASIC.createAtom(didGetExceptionP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createVariable("CallSite"),
TERM.createVariable("Exception"))));
ILiteral hasCallSite = BASIC.createLiteral(true, BASIC.createAtom(hasCallSiteP,
BASIC.createTuple(
methodNameFull,
TERM.createVariable("CallSite"))));
IRule rule = BASIC.createRule(makeList(head), makeList(didGetException, hasCallSite));
//System.out.println(rule);
parent.model.rules.add(rule);
processCode(cb.getStatement());
}
} else {
throw new RuntimeException("Unknown statement type: " + ps);
}
}
}
| private void processCode(List<PStatement> statements) throws Exception {
for (PStatement ps : statements) {
if (ps instanceof AAssignStatement) {
AAssignStatement s = (AAssignStatement) ps;
AAssign assign = (AAssign) s.getAssign();
PExpr expr = (PExpr) s.getExpr();
String callSite = methodNameFull.getValue() + "-" + nextCallSite;
nextCallSite++;
// hasCallSite(methodFull, callSite).
IRelation rel = parent.model.getRelation(hasCallSiteP);
rel.add(BASIC.createTuple(methodNameFull, TERM.createString(callSite)));
IPredicate valueP = null;
if (expr instanceof ACallExpr) {
ACallExpr callExpr = (ACallExpr) expr;
// mayCallObject(?Caller, ?CallerInvocation, ?CallSite, ?Value) :-
// isA(?Caller, ?Type),
// liveMethod(?Caller, ?CallerInvocation, method),
// value(?Caller, ?CallerInvocation, ?TargetVar, ?Value).
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(mayCallObjectP, tuple));
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(this.parent.name))));
ILiteral liveMethod = BASIC.createLiteral(true, BASIC.createAtom(liveMethodP, BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
methodNameFull)));
IRule rule = BASIC.createRule(makeList(head), makeList(isA, liveMethod, getValue(callExpr.getName())));
//System.out.println(rule);
parent.model.rules.add(rule);
addArgs(callSite, (AArgs) callExpr.getArgs());
// callsMethod(callSite, method)
String targetMethod = parsePattern(callExpr.getMethod());
if ("*".equals(targetMethod)) {
rel = parent.model.getRelation(callsAnyMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite)));
} else {
rel = parent.model.getRelation(callsMethodP);
rel.add(BASIC.createTuple(TERM.createString(callSite), TERM.createString(targetMethod)));
}
valueP = didGetP;
} else if (expr instanceof ANewExpr) {
ANewExpr newExpr = (ANewExpr) expr;
// mayCreate(classname, newType, var)
rel = parent.model.getRelation(mayCreateP);
String newType = ((AType) newExpr.getType()).getName().getText();
rel.add(BASIC.createTuple(TERM.createString(callSite),
TERM.createString(newType)));
addArgs(callSite, (AArgs) newExpr.getArgs());
valueP = didCreateP;
} else if (expr instanceof ACopyExpr) {
// a = b
ACopyExpr copyExpr = (ACopyExpr) expr;
if (assign == null) {
throw new RuntimeException("Pointless var expression");
}
ILiteral isA = BASIC.createLiteral(true, BASIC.createAtom(isAP,
BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createString(parent.name))));
TName sourceVar = copyExpr.getName();
assignVar(assign, makeList(isA, getValue(sourceVar)));
} else {
throw new RuntimeException("Unknown expr type: " + expr);
}
if (assign != null && valueP != null) {
ITuple tuple = BASIC.createTuple(
TERM.createVariable("Caller"),
TERM.createVariable("CallerInvocation"),
TERM.createString(callSite),
TERM.createVariable("Value"));
ILiteral value = BASIC.createLiteral(true, BASIC.createAtom(valueP, tuple));
assignVar(assign, makeList(value));
}
} else if (ps instanceof ADeclStatement) {
ADeclStatement decl = (ADeclStatement) ps;
declareLocal(decl.getType(), decl.getName());
} else if (ps instanceof AReturnStatement) {
boolean returnsVoid = "void".equals(((AType) method.getType()).getName().getText());
TName expr = ((AReturnStatement) ps).getName();
if (returnsVoid && expr.getText() != null) {
throw new ParserException(expr, "Return with a value in method declared to return void!");
}
returnOrThrow(mayReturnP, methodNameFull, expr);
} else if (ps instanceof AThrowStatement) {
returnOrThrow(mayThrowP, methodNameFull, ((AThrowStatement) ps).getName());
} else if (ps instanceof ATryStatement) {
ATryStatement ts = (ATryStatement) ps;
processCode(ts.getStatement());
for (PCatchBlock c : ts.getCatchBlock()) {
ACatchBlock cb = (ACatchBlock) c;
declareLocal(cb.getType(), cb.getName());
// local(?Object, ?Innovation, name, ?Exception) :-
// didGetException(?Object, ?Invocation, ?CallSite, ?Exception),
// hasCallSite(?Method, ?CallSite).
// (note: we currently catch all exceptions from this method, not just those in the try block)
ILiteral head = BASIC.createLiteral(true, BASIC.createAtom(localP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createString(expandLocal(cb.getName().getText())),
TERM.createVariable("Exception"))));
ILiteral didGetException = BASIC.createLiteral(true, BASIC.createAtom(didGetExceptionP,
BASIC.createTuple(
TERM.createVariable("Object"),
TERM.createVariable("Invocation"),
TERM.createVariable("CallSite"),
TERM.createVariable("Exception"))));
ILiteral hasCallSite = BASIC.createLiteral(true, BASIC.createAtom(hasCallSiteP,
BASIC.createTuple(
methodNameFull,
TERM.createVariable("CallSite"))));
IRule rule = BASIC.createRule(makeList(head), makeList(didGetException, hasCallSite));
//System.out.println(rule);
parent.model.rules.add(rule);
processCode(cb.getStatement());
}
} else {
throw new RuntimeException("Unknown statement type: " + ps);
}
}
}
|
diff --git a/src/net/majorkernelpanic/spydroid/SpydroidApplication.java b/src/net/majorkernelpanic/spydroid/SpydroidApplication.java
index 5bd948b..bbe3b2d 100644
--- a/src/net/majorkernelpanic/spydroid/SpydroidApplication.java
+++ b/src/net/majorkernelpanic/spydroid/SpydroidApplication.java
@@ -1,16 +1,16 @@
package net.majorkernelpanic.spydroid;
import org.acra.ACRA;
import org.acra.annotation.ReportsCrashes;
import static org.acra.ReportField.*;
@ReportsCrashes(formKey = "dGhWbUlacEV6X0hlS2xqcmhyYzNrWlE6MQ", customReportContent = { APP_VERSION_NAME, PHONE_MODEL, BRAND, PRODUCT, ANDROID_VERSION, STACK_TRACE, USER_APP_START_DATE, USER_CRASH_DATE, LOGCAT, DEVICE_FEATURES, SHARED_PREFERENCES })
public class SpydroidApplication extends android.app.Application {
@Override
public void onCreate() {
// The following line triggers the initialization of ACRA
// Please do not uncomment this line unless you change the form id or I will receive your crash reports !
- //ACRA.init(this);
+ ACRA.init(this);
super.onCreate();
}
}
| true | true | public void onCreate() {
// The following line triggers the initialization of ACRA
// Please do not uncomment this line unless you change the form id or I will receive your crash reports !
//ACRA.init(this);
super.onCreate();
}
| public void onCreate() {
// The following line triggers the initialization of ACRA
// Please do not uncomment this line unless you change the form id or I will receive your crash reports !
ACRA.init(this);
super.onCreate();
}
|
diff --git a/src/edu/umn/genomics/table/DefaultTableContext.java b/src/edu/umn/genomics/table/DefaultTableContext.java
index 1569b1e..347a725 100644
--- a/src/edu/umn/genomics/table/DefaultTableContext.java
+++ b/src/edu/umn/genomics/table/DefaultTableContext.java
@@ -1,1117 +1,1117 @@
/*
* @(#) $RCSfile: DefaultTableContext.java,v $ $Revision: 1.15 $ $Date: 2004/09/16 13:44:48 $ $Name: $
*
* Center for Computational Genomics and Bioinformatics
* Academic Health Center, University of Minnesota
* Copyright (c) 2000-2002. The Regents of the University of Minnesota
*
* 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.
* see: http://www.gnu.org/copyleft/gpl.html
*
* 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.
*
* 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.
*
*/
package edu.umn.genomics.table;
import edu.umn.genomics.component.SaveImage;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
/*
All returned values are interfaces so that they can be implemented as needed.
*/
/**
* DefaultTableContext manages TableModels and any subtables, views, or selections
* related to those tables.
* The managed objects are maintained in a TreeModel that may be viewed by JTree.
* @author J Johnson
* @version $Revision: 1.15 $ $Date: 2004/09/16 13:44:48 $ $Name: $
* @since 1.0
*/
public class DefaultTableContext implements TableContext {
DefaultSetOperator setOperator = new DefaultSetOperator();
DefaultTreeModel dtm = new DefaultTreeModel(new DefaultMutableTreeNode("Tables"));
Hashtable tm_vtm = new Hashtable(); // tm -> vtm
Hashtable rowSelHash = new Hashtable(); // tm -> rsm
Hashtable colSelHash = new Hashtable(); // tm -> csm
Hashtable tblMapHash = new Hashtable(); // tm -> ColumnMaps
Hashtable obj_nodeHt = new Hashtable(); // obj -> node
Hashtable node_objHt = new Hashtable(); // node -> obj
static Hashtable defaultViews = new Hashtable(); // viewName -> viewClass
static Vector defaultViewList = new Vector(); // an ordered list of built in viewNames
static Hashtable defaultViewIcons24 = new Hashtable(); // viewClass -> 16x16icon
static Hashtable defaultViewIcons16 = new Hashtable(); // viewClass -> 24x24icon
static { // add the built in views
try {
String path = "edu/umn/genomics/table/view.properties";
ClassLoader cl = DefaultTableContext.class.getClassLoader();
Properties properties = new Properties();
properties.load(cl.getResourceAsStream(path));
setDefaultViews(properties);
} catch(Exception ex) {
ExceptionHandler.popupException(""+ex);
}
}
private Hashtable views = (Hashtable)defaultViews.clone(); // viewName -> viewClass
private Vector viewList = (Vector)defaultViewList.clone(); // an ordered list of viewNames
private Hashtable viewIcons24 = (Hashtable)defaultViewIcons24.clone();
private Hashtable viewIcons16 = (Hashtable)defaultViewIcons16.clone();
// Locations and Sizes of frames
// so that recreated frames are placed in the previous location:
Hashtable frameLoc = new Hashtable(); // Frame location
Hashtable frameDim = new Hashtable(); // Frame size
/** tracks the location and size of frames and stores values in Hashtables.
* The title of the frame is used as the key for the Hashtables.
*/
ComponentAdapter ca = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
if (e.getComponent() instanceof Frame) {
Frame f = (Frame)e.getComponent();
frameDim.put(f.getTitle(),f.getSize());
}
}
public void componentMoved(ComponentEvent e) {
if (e.getComponent() instanceof Frame) {
Frame f = (Frame)e.getComponent();
frameLoc.put(f.getTitle(),f.getLocation());
}
}
public void componentShown(ComponentEvent e) {
if (e.getComponent() instanceof Frame) {
Frame f = (Frame)e.getComponent();
frameDim.put(f.getTitle(),f.getSize());
frameLoc.put(f.getTitle(),f.getLocation());
}
}
};
class ColumnMaps implements TableModelListener {
TableModel tm = null;
Vector maps = null;
ColumnMaps(TableModel tm) {
this.tm = tm;
maps = new Vector();
maps.setSize(tm.getColumnCount());
tm.addTableModelListener(this);
}
public synchronized ColumnMap getColumnMap(int columnIndex) {
ColumnMap cmap = null;
if (columnIndex < tm.getColumnCount()) {
if (columnIndex < maps.size()) {
cmap = (ColumnMap)maps.get(columnIndex);
} else {
maps.setSize(tm.getColumnCount());
}
if (cmap == null) {
if (tm instanceof TableColumnMap) {
cmap = ((TableColumnMap)tm).getColumnMap(columnIndex);
}
if (cmap == null) {
cmap = new DefaultColumnMap(tm, columnIndex);
}
cmap.setSelectionModel(getRowSelectionModel(tm));
maps.set(columnIndex,cmap);
}
}
return cmap;
}
public int getColumnIndex(ColumnMap cmap) {
return maps.indexOf(cmap);
}
public void tableChanged(TableModelEvent e) {
if (e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW) {
System.err.println(" >>>> ColumnMaps " + e.getSource());
destroyMaps();
maps.setSize(tm.getColumnCount());
System.err.println(" <<<< ColumnMaps " + e.getSource());
}
}
public void setSetOperator(int setop) {
for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
ColumnMap cmap = (ColumnMap)iter.next();
if (cmap != null) {
cmap.setSetOperator(setop);
}
}
}
private synchronized void destroyMaps() {
for (ListIterator li = maps.listIterator(); li.hasNext(); ) {
ColumnMap cmap = (ColumnMap)li.next();
if (cmap != null) {
cmap.cleanUp();
}
}
maps.clear();
}
};
ChangeListener socl = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof SetOperator) {
setColumnMapSetOperator(((SetOperator)e.getSource()).getSetOperator());
}
}
};
/** Comparator for Set of TableModels. */
Comparator objectComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return o1 == o2 ? 0 : o1 == null ? -1 : o2 == null ? 1 : o1.hashCode() < o2.hashCode() ? -1 : 1;
}
public boolean equals(Object obj) {
return this == obj;
}
};
private void setColumnMapSetOperator(int setop) {
for (Iterator iter = tblMapHash.values().iterator(); iter.hasNext(); ) {
ColumnMaps maps = (ColumnMaps)iter.next();
if (maps != null) {
maps.setSetOperator(setop);
}
}
}
/**
* Set the location and size of the given frame.
* @param f the frame to size and position
* @param x the default x location for the frame
* @param y the default y location for the frame
* @param w the default width for the frame
* @param h the default height for the frame
*/
private void setFrameBounds(Frame f, int x, int y, int w, int h) {
if (f != null) {
Point p = (Point)frameLoc.get(f.getTitle());
f.setLocation(p!=null?p:new Point(x,y));
Dimension d = (Dimension)frameDim.get(f.getTitle());
f.setSize(d!=null?d:new Dimension(w,h));
f.addComponentListener(ca);
}
}
/**
* Set the default view resources.
* The properties identifiers:
* identifiers=scatterplot cluster
*
* scatterplot.name=ScatterPlot
* scatterplot.class=edu.umn.genomics.table.ScatterPlotView
* scatterplot.icon24=edu/umn/genomics/table/Icons/scatterplot.gif
* scatterplot.icon16=edu/umn/genomics/table/Icons/scatterplot16.gif
*
* cluster.name=Cluster Rows
* cluster.class=edu.umn.genomics.table.cluster.ClusterView
* cluster.icon24=edu/umn/genomics/table/Icons/cluster.gif
* cluster.icon16=edu/umn/genomics/table/Icons/cluster16.gif
* cluster.classdependency=cern.colt.matrix.DoubleMatrix2D
*
* @param properties The list of view resources.
*/
public static void setDefaultViews(Properties properties) {
ClassLoader cl = DefaultTableContext.class.getClassLoader();
String ids = properties.getProperty("identifiers");
if (ids != null) {
StringTokenizer st = new StringTokenizer(ids);
while (st.hasMoreTokens()) {
String id = st.nextToken();
String className = properties.getProperty(id+".class");
String depends = properties.getProperty(id+".classdependency");
String libdepends = properties.getProperty(id+".libdependency");
if (depends != null) {
try {
for (StringTokenizer stk = new StringTokenizer(depends); stk.hasMoreTokens(); ) {
Class.forName(stk.nextToken());
}
} catch (ClassNotFoundException cnfex) {
continue;
}
}
if (libdepends != null) {
String libName = "";
try {
for (StringTokenizer stk = new StringTokenizer(libdepends); stk.hasMoreTokens(); ) {
libName = stk.nextToken();
System.loadLibrary(libName);
}
} catch (UnsatisfiedLinkError err) {
continue;
} catch (SecurityException ex) {
ExceptionHandler.popupException(""+ex);
continue;
} catch (Throwable t) {
ExceptionHandler.popupException(""+t);
continue;
}
}
if (className != null) {
String viewName = properties.getProperty(id+".name");
if (viewName == null || viewName.length() < 1) {
int idx = className.lastIndexOf('.');
viewName = idx < 0 ? className : className.substring(idx+1);
}
try {
Class theClass = Class.forName(className);
if (edu.umn.genomics.table.TableModelView.class.isAssignableFrom(theClass)) {
addDefaultViewClass(viewName, Class.forName(className));
}
String icon = properties.getProperty(id+".icon24");
if (icon != null) {
defaultViewIcons24.put(theClass, new ImageIcon(cl.getResource(icon)));
}
icon = properties.getProperty(id+".icon16");
if (icon != null) {
defaultViewIcons16.put(theClass, new ImageIcon(cl.getResource(icon)));
}
} catch (Exception ex) {
ExceptionHandler.popupException(""+ex);
} catch (NoClassDefFoundError err) {
ExceptionHandler.popupException(""+err);
}
}
}
}
}
/**
* Register the viewName for the viewClass.
* @param viewName The name this view is referred as.
* @param viewClass The viewing class.
*/
private static void addDefaultViewClass(String viewName, Class viewClass) {
defaultViewList.remove(viewName);
defaultViewList.add(viewName);
defaultViews.put(viewName,viewClass);
}
/**
* Register a TableModel viewing class. The view class must implement
* the edu.umn.genomics.table.TableModelView interface.
* @param viewName The name this view is referred as.
* @param className The fully qualified class name for the viewing class.
*/
public void addViewClass(String viewName, String className)
throws ClassNotFoundException, ClassCastException, NullPointerException {
addViewClass(viewName, Class.forName(className));
}
/**
* Register a TableModel viewing class. The view class must implement
* the edu.umn.genomics.table.TableModelView interface.
* @param viewName The name this view is referred as.
* @param viewClass The viewing class.
*/
public void addViewClass(String viewName, Class viewClass)
throws ClassCastException, NullPointerException {
if (viewClass == null) {
throw new NullPointerException();
}
if (edu.umn.genomics.table.TableModelView.class.isAssignableFrom(viewClass) ||
javax.swing.JTable.class.isAssignableFrom(viewClass)) {
viewList.remove(viewName);
viewList.add(viewName);
views.put(viewName,viewClass);
} else {
throw new ClassCastException(viewClass.toString() + " doesn't implement " +
edu.umn.genomics.table.TableModelView.class.toString());
}
}
/**
* Remove a registered view class.
* @param viewName The name for the view to be removed.
* @return the view class this name referred to.
*/
public TableModelView removeViewClass(String viewName) {
viewList.remove(viewName);
return (TableModelView)views.remove(viewName);
}
/**
* Remove all registered view classes.
*/
public void removeAllViewClasses() {
viewList.clear();
views.clear();
}
/**
* Register a view class icon 24x24 pixels.
* @param viewClass The viewing class.
* @param icon The icon for this viewing class.
*/
public void setViewIcon24(Class viewClass, Icon icon) {
viewIcons24.put(viewClass,icon);
}
/**
* Register a view class icon 16x16 pixels.
* @param viewClass The viewing class.
* @param icon The icon for this viewing class.
*/
public void setViewIcon16(Class viewClass, Icon icon) {
viewIcons16.put(viewClass,icon);
}
/**
* Get an icon for a view class.
* @param viewClass The viewing class.
* @return the icon for this view.
*/
public Icon getViewIcon16(Class viewClass){
Icon icon = getViewIcon(viewClass, viewIcons16);
return icon;
}
public Icon getViewIcon(Class viewClass) {
Icon icon = getViewIcon(viewClass, viewIcons24);
// if (icon == null)
// icon = defaultViewIcon;
return icon;
}
/**
* Get an icon for a view class.
* @param viewClass The viewing class.
* @param viewClass The hash of Icons
* @return the icon for this view.
*/
private Icon getViewIcon(Class viewClass, Hashtable iconHash) {
Icon icon = viewClass != null ? (Icon)iconHash.get(viewClass) : null;
return icon;
}
/**
* Get an icon for a view.
* @param viewName The name this view is referred as.
* @return the icon for this view.
*/
public Icon getViewIcon(String viewName) {
return getViewIcon((Class)views.get(viewName));
}
public Icon getViewIcon16(String viewName) {
return getViewIcon16((Class)views.get(viewName));
}
/**
* Get an icon for a view.
* @param treeNode The tree node for the view.
* @return the icon for this view.
*/
public Icon getViewIcon(DefaultMutableTreeNode treeNode) {
Object obj = node_objHt.get(treeNode);
if (obj instanceof JFrame) {
try {
return getViewIcon((((JFrame)obj).getContentPane().getComponent(0).getClass()),viewIcons16);
} catch (Exception ex) {
}
} else if (obj instanceof TableModel) {
TableModel tm = (TableModel)obj;
for (; tm instanceof VirtualTableModel; tm = ((VirtualTableModel)tm).getTableModel());
return getViewIcon(tm.getClass(),viewIcons16);
}
return getViewIcon(obj != null ? obj.getClass() : null,viewIcons16);
}
/**
* Get a list of all registered view class names.
* @return A list of all registered view class names.
*/
public String[] getViewNames() {
String viewNames[] = new String[viewList.size()];
try {
viewNames = (String[])viewList.toArray(viewNames);
} catch(Exception ex) {
}
return viewNames;
}
/**
* Return the View for the tree node, or null if the node does not represent a View.
* @param treeNode The tree node for the view.
* @return the view at this tree node.
*/
public TableModelView getTableModelView(DefaultMutableTreeNode treeNode) {
if (treeNode != null) {
Object obj = node_objHt.get(treeNode);
if (obj instanceof JFrame) {
try {
Component c = ((JFrame)obj).getContentPane().getComponent(0);
if (c instanceof TableModelView) {
return (TableModelView)c;
}
} catch (Exception ex) {
}
}
}
return null;
}
/**
* Create a DefaultTableContext.
*/
public DefaultTableContext() {
setOperator.addChangeListener(socl);
}
/**
* Retrieve the TreeNode for the given object, creating it
* if it doesn't already exist.
* @param obj The object for which to get a tree node.
* @return The tree node for the object.
*/
private DefaultMutableTreeNode getNode(Object obj) {
DefaultMutableTreeNode tn;
tn = (DefaultMutableTreeNode)obj_nodeHt.get(obj);
if (tn == null) {
tn = new DefaultMutableTreeNode(obj);
obj_nodeHt.put(obj,tn);
node_objHt.put(tn,obj);
}
return tn;
}
/**
* Add the child object as a child node to the parent object in the tree.
* @param parent The parent object, if null add the child to the root node.
* @param child The object to add as a child node in the tree.
* @return The tree node of the child object.
*/
private DefaultMutableTreeNode addNode(Object parent, Object child) {
DefaultMutableTreeNode pn = parent == null
? (DefaultMutableTreeNode)dtm.getRoot()
: getNode(parent);
DefaultMutableTreeNode cn = getNode(child);
//System.err.println("addNode " + pn + "\t" + cn);
dtm.insertNodeInto(cn,pn,dtm.getChildCount(pn));
return cn;
}
/**
* Remove the object from the tree.
* @param obj The object to remove from the tree.
*/
private void removeNode(Object obj) {
MutableTreeNode tn = (MutableTreeNode)obj_nodeHt.get(obj);
removeNode(tn);
}
/**
* Remove the node from the tree, destroying the object and all descendents.
* @param tn The tree node to remove and destroy.
*/
private void removeNode(MutableTreeNode tn) {
if (tn != null) {
if (!tn.isLeaf()) {
for(int i = tn.getChildCount()-1; i >= 0; i--) {
MutableTreeNode cn = (MutableTreeNode)tn.getChildAt(i);
removeNode(cn);
}
}
//System.err.println("removeNode " + tn);
Object obj = node_objHt.get(tn);
node_objHt.remove(tn);
if (obj != null) {
obj_nodeHt.remove(obj);
if (obj instanceof JFrame) {
((JFrame)obj).dispose();
} else if (obj instanceof TableModel) {
TableModel tm = (TableModel)obj;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
tm_vtm.remove(tm);
if (vtm.getTableModel() != tm && tm_vtm.containsKey(vtm.getTableModel())) {
if (tm_vtm.get(vtm.getTableModel()) == vtm) {
tm_vtm.remove(vtm.getTableModel());
}
}
rowSelHash.remove(vtm);
colSelHash.remove(vtm);
tblMapHash.remove(vtm);
}
}
dtm.removeNodeFromParent(tn);
}
}
/**
* Get a VirtualTableModelProxy for the given TableModel.
* If the given TableModel is a VirtualTableModelProxy, it will be
* registered and returned.
* This routine is used to guarantee that all references to a TableModel
* are the same.
* @param tm the TableModel for which to return a VirtualTableModelProxy.
* @return The VirtualTableModelProxy to which tm refers.
*/
private VirtualTableModelProxy getTableModelProxy(TableModel tm) {
if (tm == null)
return null;
VirtualTableModelProxy vtm = (VirtualTableModelProxy)tm_vtm.get(tm);
if (vtm == null) {
vtm = tm instanceof VirtualTableModelProxy ? (VirtualTableModelProxy)tm
: new VirtualTableModelProxy(tm);
tm_vtm.put(tm,vtm);
}
ColumnMaps maps = (ColumnMaps)tblMapHash.get(vtm);
if (maps == null) {
maps = new ColumnMaps(vtm);
tblMapHash.put(vtm,maps);
}
return vtm;
}
/**
* Get a VirtualTableModel for the given TableModel.
* If the given TableModel is a VirtualTableModel, it will be
* registered and returned.
* This routine is used to guarantee that all references to a TableModel
* are the same.
* @param tm the TableModel for which to return a VirtualTableModel.
* @return The VirtualTableModel for the given tm.
*/
public VirtualTableModel getVirtualTableModel(TableModel tm) {
return getTableModelProxy(tm);
}
/**
* Add a TableModel to the tree of managed tables.
* @param tm The TableModel to add.
*/
public void addTableModel(TableModel tm) {
if (tm == null)
return;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
DefaultMutableTreeNode tn = addNode(null, vtm);
tn.setAllowsChildren(true);
//System.err.println("addTableModel:" + "\n\t" + tm + "\n\t" + vtm );
}
/**
* Remove a TableModel from the tree of managed tables.
* @param tm The TableModel to remove.
*/
public void removeTableModel(TableModel tm) {
if (tm == null)
return;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
MutableTreeNode tn = getNode(vtm);
removeNode(tn);
rowSelHash.remove(vtm);
colSelHash.remove(vtm);
tblMapHash.remove(vtm);
tm_vtm.remove(tm);
}
/**
* Remove all TableModels from the tree of managed tables.
*/
public void removeAllTableModels() {
DefaultMutableTreeNode tn = (DefaultMutableTreeNode)dtm.getRoot();
for(int i = tn.getChildCount()-1; i >= 0; i--) {
MutableTreeNode cn = (MutableTreeNode)tn.getChildAt(i);
removeNode(cn);
}
}
/**
* Get a new TableModel that contains the selected rows in the given TableModel.
* The selections will be mapped so that the selection of rows for one
* TableModel will be reflected in the other TableModel.
* The new TableModel is added as a child tree node to the given TableModel.
* @param tm the TableModel from which to derive a new TableModel
* @param rows the selected rows of the given TableModel to include in the new TableModel
* @return The TableModel derived from the selected rows of the given TableModel.
*/
public TableModel getTableModel(TableModel tm, ListSelectionModel rows) {
if (tm == null || rows == null || rows.isSelectionEmpty())
return null;
VirtualTableModelProxy vtm = new VirtualTableModelProxy(tm);
boolean useSelection = false;
int count = tm.getRowCount();
// Check if the entire table is selected
if (rows.getMinSelectionIndex() == 0 &&
rows.getMaxSelectionIndex() == tm.getRowCount()-1) {
for (int i = tm.getRowCount()-1; i > 0; i--) {
if (!rows.isSelectedIndex(i)) {
useSelection = true;
break;
}
}
} else {
useSelection = true;
}
if (useSelection) {
count = 0;
for (int i = rows.getMinSelectionIndex(); i <= rows.getMaxSelectionIndex(); i++) {
if (rows.isSelectedIndex(i))
count++;
}
LSMIndexMap map = new LSMIndexMap(rows,true,false);
map.setSize(tm.getRowCount());
vtm.setName("Selected " + count + " Rows of " + getTableModelProxy(tm).getName());
vtm.setIndexMap(map);
ListSelectionModel lsm1 = getRowSelectionModel(tm);
ListSelectionModel lsm2 = getRowSelectionModel(vtm);
// need to store this somewhere
IndexMapSelection ims = new IndexMapSelection(lsm1,lsm2,map);
} else { // If the entire table is selected forget the mapping
rowSelHash.put(vtm,getRowSelectionModel(tm));
vtm.setName("All " + count + " Rows of " + getTableModelProxy(tm).getName());
}
DefaultMutableTreeNode tn = addNode(tm, vtm);
tn.setAllowsChildren(true);
return vtm;
}
@Override
public TableModel getTableModel(TableModel tm, Partition partition) {
if (tm == null || partition == null)
return null;
VirtualTableModelProxy vtm = new VirtualTableModelProxy(tm);
vtm.setIndexMap(partition.getPartitionIndexMap());
ListSelectionModel lsm1 = getRowSelectionModel(tm);
ListSelectionModel lsm2 = getRowSelectionModel(vtm);
IndexMapSelection ims = new IndexMapSelection(lsm1,lsm2,vtm.getIndexMap());
DefaultMutableTreeNode tn = addNode(tm, vtm);
tn.setAllowsChildren(true);
return vtm;
}
/**
* Display and manage a view of the given TableModel.
* This does a combination of getView and addView.
* @param tm
* @param viewName The name of the type of view to create.
* @return The view display component.
*/
public JFrame getTableModelView(TableModel tm, String viewName) {
if (tm == null)
return null;
JComponent jc = getView(tm, viewName);
JFrame jf = addView(tm, viewName, jc);
return jf;
}
/**
* Create a view for the given TableModel.
* @param tm The TableModel to view.
* @param viewName The name of the type of view to create.
* @return A view compenent for the given TableModel.
*/
public JComponent getView(TableModel tm, String viewName) {
if (tm == null)
return null;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
JComponent jc = null;
try {
Class vc = (Class)views.get(viewName);
try {
//Class pc[] = new Class[1];
//pc[0] = Class.forName("edu.umn.genomics.table.TableModel");
Constructor cons = vc.getConstructor((Class[])null);
Object po[] = null; // new Object[0];
jc = (JComponent)cons.newInstance((Object[])null);
if (jc instanceof TableModelView) {
((TableModelView)jc).setTableContext(this);
((TableModelView)jc).setSelectionModel(getRowSelectionModel(vtm));
((TableModelView)jc).setTableModel(vtm);
}
} catch (Exception exc) {
if (vc.isAssignableFrom(javax.swing.JTable.class)) {
Class pc[] = new Class[1];
pc[0] = Class.forName("javax.swing.table.TableModel");
Constructor cons = vc.getConstructor(pc);
Object po[] = new Object[1];
po[0] = vtm;
JTable jt = (JTable)cons.newInstance(po);
jt.setSelectionModel(getRowSelectionModel(vtm));
JScrollPane js = new JScrollPane(jt);
jc = js;
} else {
System.err.println(viewName + "\t" + exc);
exc.printStackTrace();
}
}
} catch (Exception ex) {
System.err.println(viewName + "\t" +ex);
}
return jc;
}
/**
* Display and manage the view component. The component is added to a Frame.
* The display frame is added as a child tree node of the TableModel.
* @param tm The TableModel for this view
* @param viewName The name of the type of view to create.
* @param jc The view compenent for the given TableModel.
* @return The view display component.
*/
public JFrame addView(TableModel tm, String viewName, JComponent jc) {
if (tm == null)
return null;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
JFrame jf = null;
try {
if (jc != null) {
jf = getViewFrame(viewName + " of " + vtm, jc);
setViewToolBar(jf, jc);
DefaultMutableTreeNode tn = addNode(vtm, jf);
tn.setAllowsChildren(false);
}
} catch (Exception ex) {
System.err.println(viewName + "\t" +ex);
}
return jf;
}
/**
* Get an editor for a TableModel.
* @param tm The TableModel to edit.
* @return A component that displays the editor.
*/
public JFrame getEditorFrame(TableModel tm) {
if (tm == null)
return null;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
JFrame jf = null;
if (vtm != null) {
VirtualTableModelView vtv = new VirtualTableModelView(vtm);
jf = getViewFrame("Edit " + vtm, vtv);
setViewToolBar(jf, vtv);
DefaultMutableTreeNode tn = addNode(tm, jf);
tn.setAllowsChildren(false);
}
return jf;
}
/**
* Place the given component into a frame, make it visible,
* track the frame's location and size, and listen for window
* events so that the tree can be maintained.
* @param title The title for the JFrame
* @param view The compenent to be placed in the frame to be viewed.
* @return The frame created.
*/
public JFrame getViewFrame(String title, final JComponent view) {
JFrame frame = new JFrame(title) {
public String toString() {
return getTitle();
}
};
frame.addWindowListener(new WindowAdapter() {
final JComponent _view = view;
private void doClose(WindowEvent e) {
removeNode(e.getSource());
if (_view instanceof CleanUp) {
((CleanUp)_view).cleanUp();
}
}
public void windowClosing(WindowEvent e) {
doClose(e);
}
public void windowClosed(WindowEvent e) {
doClose(e);
}
});
frame.getContentPane().add(view,BorderLayout.CENTER);
frame.pack();
Insets insets = frame.getInsets();
int sw = Toolkit.getDefaultToolkit().getScreenSize().width/10*8;
int sh = Toolkit.getDefaultToolkit().getScreenSize().height/10*8;
Dimension d = frame.getSize();
int pw = Math.min(sw,Math.max(d.width,sw/10*4))
- insets.left - insets.right;
int ph = Math.min(sh,Math.max(d.height,sh/10*4))
- insets.top - insets.bottom;
setFrameBounds(frame,(int)((sw-pw)/2),(int)((sh-ph)/2), pw, ph);
//System.err.println(frame + "\n" + sw + " " + sh + " " + pw + " " + ph + " " + insets);
frame.setVisible(true);
return frame;
}
/**
* Add a standard toolbar with close and saveimage buttons to the frame.
* The save button will create an image of the given view Component.
* The frame must have BorderLayout, as the toolbar placed in the
* BorderLayout.NORTH location.
* @param frame The frame to which the toolbar is to be added.
* @param view The view to be saved as an image.
*/
public static void setViewToolBar(Window frame, Component view) {
setViewToolBar(frame, view, null);
}
/**
* Add a standard toolbar with close and saveimage buttons to the frame.
* The save button will create an image of the given view Component.
* The frame must have BorderLayout, as the toolbar placed in the
* BorderLayout.NORTH location.
* @param frame The frame to which the toolbar is to be added.
* @param view The view to be saved as an image.
* @param extraButtons Extra buttons to be added to the toolbar.
*/
public static void setViewToolBar(Window frame, Component view, JComponent extraButtons[]) {
final Component comp = view;
final Window theframe = frame;
JButton jBtn;
JToolBar jtb = new JToolBar();
// Close
jBtn = new JButton("Close");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
WindowEvent we = new WindowEvent(theframe,WindowEvent.WINDOW_CLOSING);
WindowListener[] wl = theframe.getWindowListeners();
if (wl != null) {
for (int i = 0; i < wl.length; i++) {
wl[i].windowClosing(we);
}
}
theframe.dispose();
}
}
);
jBtn.setToolTipText("Close this view");
jtb.add(jBtn);
if (view != null) {
// Save Image
jBtn = new JButton("Save Image");
if (System.getProperty("java.specification.version").compareTo("1.4")>=0) {
jBtn.setToolTipText("Save this view as an image");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
SaveImage.saveImage(comp instanceof TableModelView ? ((TableModelView)comp).getCanvas() : comp);
} catch (IOException ioex) {
ExceptionHandler.popupException(""+ioex);
}
}
}
);
} else {
jBtn.setToolTipText("Save Image requires Java 1.4");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
// Save PDF
if (true) {
jBtn = new JButton("Save PDF");
try {
- Class.forName("com.lowagie.text.pdf.PdfWriter");
+ Class.forName("com.itextpdf.text.pdf.PdfWriter");
jBtn.setToolTipText("Save this view as a PDF file");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class[] paramClass = new Class[1];
paramClass[0] = java.awt.Component.class;
Object[] args = new Object[1];
args[0] = comp instanceof TableModelView
? ((TableModelView)comp).getCanvas()
: comp;
Class.forName("edu.umn.genomics.component.SavePDF").
getMethod("savePDF",paramClass).invoke(null,args);
} catch (Exception ex) {
ExceptionHandler.popupException(""+ex);
}
}
}
);
} catch(ClassNotFoundException cnfex) {
jBtn.setToolTipText("Save PDF requires the Lowagie iText package");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
}
}
if (extraButtons != null) {
for (int i = 0; i < extraButtons.length; i++) {
jtb.add(extraButtons[i]);
}
}
if (frame instanceof JFrame) {
((JFrame)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else if (frame instanceof JDialog) {
((JDialog)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else {
theframe.add( jtb, BorderLayout.NORTH);
}
theframe.validate();
}
/**
* Get the row selection model for the given TableModel.
* @param tm The TableModel for which to get the selection model.
* @return The selection model for this TableModel.
*/
public ListSelectionModel getRowSelectionModel(TableModel tm) {
return getSelectionModel(tm, rowSelHash);
}
/**
* Get the column selection model for the given TableModel.
* @param tm The TableModel for which to get the selection model.
* @return The selection model for this TableModel.
*/
public ListSelectionModel getColumnSelectionModel(TableModel tm) {
return getSelectionModel(tm, colSelHash);
}
/**
* Get the selection model for the given TableModel from the given Hashtable.
* @param tm The TableModel for which to get the selection model.
* @param ht The Hashtable in which to store the ListSelectionModel.
* @return The selection model for this TableModel.
*/
private ListSelectionModel getSelectionModel(TableModel tm, Hashtable ht) {
ListSelectionModel lsm = null;
if (tm != null) {
VirtualTableModelProxy vtm = getTableModelProxy(tm);
lsm = (ListSelectionModel)ht.get(vtm);
if (lsm == null) {
lsm = new DefaultListSelectionModel();
lsm.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ht.put(vtm,lsm);
}
}
return lsm;
}
/**
* Return a ColumnMap for the given TableModel column.
* @param tm The TableModel for which to get the map.
* @param columnIndex The index of the column to map.
* @return The ColumnMap for the given column of the TableModel
* @see edu.umn.genomics.table.ColumnMap
*/
public ColumnMap getColumnMap(TableModel tm, int columnIndex) {
if (tm == null)
return null;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
// Need a hashtable of these
ColumnMaps maps = (ColumnMaps)tblMapHash.get(vtm);
if (maps == null) {
maps = new ColumnMaps(vtm);
tblMapHash.put(vtm,maps);
}
return maps.getColumnMap(columnIndex);
// or TableModel provides them
};
/**
* Return the column index in the given TableModel that this ColumnMap represents.
* @param tm The TableModel for which to get the index.
* @param columnMap The ColumnMap for which to find the TableModel column index.
* @return The column index in the TableModel that ColumnMap represents.
* @see edu.umn.genomics.table.ColumnMap
*/
public int getColumnIndex(TableModel tm, ColumnMap columnMap) {
if (tm == null)
return -1;
VirtualTableModelProxy vtm = getTableModelProxy(tm);
// Need a hashtable of these
ColumnMaps maps = (ColumnMaps)tblMapHash.get(vtm);
if (maps != null) {
return maps.getColumnIndex(columnMap);
}
return -1;
};
/**
* Get a TreeModel representation of the TableModels and views managed.
* @return A tree of the managed TableModels and views.
*/
public TreeModel getTreeModel() {
return dtm;
}
/**
* Get an array of the TableModels being managed.
* @return An array of the managed TableModels.
*/
public TableModel[] getTableModels() {
Collection tms = tm_vtm.values();
TableModel tma[] = new TableModel[tms.size()];
return (TableModel[])tms.toArray(tma);
}
/**
* Get the Set of the TableModels, including VirtualTableModels, that are being managed.
* @return A Set of the managed TableModels.
*/
public Set getTableModelList() {
TreeSet ts = new TreeSet(objectComparator);
ts.addAll(tm_vtm.values());
ts.addAll(tm_vtm.keySet());
return ts;
}
/**
* Tests if the given TableModel is being managed.
* @return Whether the given TableModel is being managed.
*/
public boolean hasTableModel(TableModel tm) {
return tm == null ? false : tm_vtm.containsKey(tm) || tm_vtm.contains(tm);
}
/**
* Return the SetOperator context for set operations on selections.
* @param tm The TableModel for which to retrive the SetOperator.
* @return The selection SetOperator context for the TableModel.
*/
public SetOperator getSetOperator(TableModel tm) {
return setOperator;
}
}
class DbgDefaultListSelectionModel extends DefaultListSelectionModel {
public void addListSelectionListener(ListSelectionListener l) {
System.err.println(" +++ " + l + " >>> " + getListSelectionListeners().length + " " + this.hashCode());
// super.addListSelectionListener(ListenerRefFactory.getListener(l));
super.addListSelectionListener(l);
printList();
}
public void removeListSelectionListener(ListSelectionListener l) {
super.removeListSelectionListener(l);
System.err.println(" --- " + l + " <<< " + getListSelectionListeners().length + " " + this.hashCode());
printList();
}
public void printList() {
ListSelectionListener[] list = getListSelectionListeners();
for (int i = 0; i < list.length; i++) {
if (list[i] != null) {
System.err.println("\t" + i + "\t" + list[i]);
}
}
}
}
| true | true | public static void setViewToolBar(Window frame, Component view, JComponent extraButtons[]) {
final Component comp = view;
final Window theframe = frame;
JButton jBtn;
JToolBar jtb = new JToolBar();
// Close
jBtn = new JButton("Close");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
WindowEvent we = new WindowEvent(theframe,WindowEvent.WINDOW_CLOSING);
WindowListener[] wl = theframe.getWindowListeners();
if (wl != null) {
for (int i = 0; i < wl.length; i++) {
wl[i].windowClosing(we);
}
}
theframe.dispose();
}
}
);
jBtn.setToolTipText("Close this view");
jtb.add(jBtn);
if (view != null) {
// Save Image
jBtn = new JButton("Save Image");
if (System.getProperty("java.specification.version").compareTo("1.4")>=0) {
jBtn.setToolTipText("Save this view as an image");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
SaveImage.saveImage(comp instanceof TableModelView ? ((TableModelView)comp).getCanvas() : comp);
} catch (IOException ioex) {
ExceptionHandler.popupException(""+ioex);
}
}
}
);
} else {
jBtn.setToolTipText("Save Image requires Java 1.4");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
// Save PDF
if (true) {
jBtn = new JButton("Save PDF");
try {
Class.forName("com.lowagie.text.pdf.PdfWriter");
jBtn.setToolTipText("Save this view as a PDF file");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class[] paramClass = new Class[1];
paramClass[0] = java.awt.Component.class;
Object[] args = new Object[1];
args[0] = comp instanceof TableModelView
? ((TableModelView)comp).getCanvas()
: comp;
Class.forName("edu.umn.genomics.component.SavePDF").
getMethod("savePDF",paramClass).invoke(null,args);
} catch (Exception ex) {
ExceptionHandler.popupException(""+ex);
}
}
}
);
} catch(ClassNotFoundException cnfex) {
jBtn.setToolTipText("Save PDF requires the Lowagie iText package");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
}
}
if (extraButtons != null) {
for (int i = 0; i < extraButtons.length; i++) {
jtb.add(extraButtons[i]);
}
}
if (frame instanceof JFrame) {
((JFrame)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else if (frame instanceof JDialog) {
((JDialog)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else {
theframe.add( jtb, BorderLayout.NORTH);
}
theframe.validate();
}
| public static void setViewToolBar(Window frame, Component view, JComponent extraButtons[]) {
final Component comp = view;
final Window theframe = frame;
JButton jBtn;
JToolBar jtb = new JToolBar();
// Close
jBtn = new JButton("Close");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
WindowEvent we = new WindowEvent(theframe,WindowEvent.WINDOW_CLOSING);
WindowListener[] wl = theframe.getWindowListeners();
if (wl != null) {
for (int i = 0; i < wl.length; i++) {
wl[i].windowClosing(we);
}
}
theframe.dispose();
}
}
);
jBtn.setToolTipText("Close this view");
jtb.add(jBtn);
if (view != null) {
// Save Image
jBtn = new JButton("Save Image");
if (System.getProperty("java.specification.version").compareTo("1.4")>=0) {
jBtn.setToolTipText("Save this view as an image");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
SaveImage.saveImage(comp instanceof TableModelView ? ((TableModelView)comp).getCanvas() : comp);
} catch (IOException ioex) {
ExceptionHandler.popupException(""+ioex);
}
}
}
);
} else {
jBtn.setToolTipText("Save Image requires Java 1.4");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
// Save PDF
if (true) {
jBtn = new JButton("Save PDF");
try {
Class.forName("com.itextpdf.text.pdf.PdfWriter");
jBtn.setToolTipText("Save this view as a PDF file");
jBtn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class[] paramClass = new Class[1];
paramClass[0] = java.awt.Component.class;
Object[] args = new Object[1];
args[0] = comp instanceof TableModelView
? ((TableModelView)comp).getCanvas()
: comp;
Class.forName("edu.umn.genomics.component.SavePDF").
getMethod("savePDF",paramClass).invoke(null,args);
} catch (Exception ex) {
ExceptionHandler.popupException(""+ex);
}
}
}
);
} catch(ClassNotFoundException cnfex) {
jBtn.setToolTipText("Save PDF requires the Lowagie iText package");
jBtn.setEnabled(false);
}
jtb.add(jBtn);
}
}
if (extraButtons != null) {
for (int i = 0; i < extraButtons.length; i++) {
jtb.add(extraButtons[i]);
}
}
if (frame instanceof JFrame) {
((JFrame)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else if (frame instanceof JDialog) {
((JDialog)theframe).getContentPane().add( jtb, BorderLayout.NORTH);
} else {
theframe.add( jtb, BorderLayout.NORTH);
}
theframe.validate();
}
|
diff --git a/org.eclipse.riena.sample.snippets/src/org/eclipse/riena/sample/snippets/SnippetListRidget001.java b/org.eclipse.riena.sample.snippets/src/org/eclipse/riena/sample/snippets/SnippetListRidget001.java
index 6c11ef847..e1dc1f76d 100644
--- a/org.eclipse.riena.sample.snippets/src/org/eclipse/riena/sample/snippets/SnippetListRidget001.java
+++ b/org.eclipse.riena.sample.snippets/src/org/eclipse/riena/sample/snippets/SnippetListRidget001.java
@@ -1,72 +1,72 @@
/*******************************************************************************
* 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.sample.snippets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.riena.beans.common.DayPojo;
import org.eclipse.riena.beans.common.TypedBean;
import org.eclipse.riena.ui.ridgets.IListRidget;
import org.eclipse.riena.ui.ridgets.ISelectableRidget;
import org.eclipse.riena.ui.ridgets.swt.SwtRidgetFactory;
import org.eclipse.riena.ui.swt.utils.UIControlsFactory;
/**
* Demonstrates listening to selection changes on a list ridget.
*/
public class SnippetListRidget001 {
public SnippetListRidget001(final Shell shell) {
shell.setLayout(new FillLayout());
final org.eclipse.swt.widgets.List list = UIControlsFactory.createList(shell, false, true);
final IListRidget listRidget = (IListRidget) SwtRidgetFactory.createRidget(list);
listRidget.setSelectionType(ISelectableRidget.SelectionType.SINGLE);
final IObservableList input = new WritableList(DayPojo.createWeek(), DayPojo.class);
listRidget.bindToModel(input, DayPojo.class, "english"); //$NON-NLS-1$
listRidget.updateFromModel();
- final TypedBean<DayPojo> selection = new TypedBean<DayPojo>(null);
+ final TypedBean<DayPojo> selection = new TypedBean<DayPojo>(DayPojo.class);
selection.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
final DayPojo node = selection.getValue();
System.out.println("Selection: " + node.getEnglish()); //$NON-NLS-1$
}
});
listRidget.bindSingleSelectionToModel(selection, "value"); //$NON-NLS-1$
}
public static void main(final String[] args) {
final Display display = Display.getDefault();
try {
final Shell shell = new Shell();
shell.setText(SnippetListRidget001.class.getSimpleName());
new SnippetListRidget001(shell);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} finally {
display.dispose();
}
}
}
| true | true | public SnippetListRidget001(final Shell shell) {
shell.setLayout(new FillLayout());
final org.eclipse.swt.widgets.List list = UIControlsFactory.createList(shell, false, true);
final IListRidget listRidget = (IListRidget) SwtRidgetFactory.createRidget(list);
listRidget.setSelectionType(ISelectableRidget.SelectionType.SINGLE);
final IObservableList input = new WritableList(DayPojo.createWeek(), DayPojo.class);
listRidget.bindToModel(input, DayPojo.class, "english"); //$NON-NLS-1$
listRidget.updateFromModel();
final TypedBean<DayPojo> selection = new TypedBean<DayPojo>(null);
selection.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
final DayPojo node = selection.getValue();
System.out.println("Selection: " + node.getEnglish()); //$NON-NLS-1$
}
});
listRidget.bindSingleSelectionToModel(selection, "value"); //$NON-NLS-1$
}
| public SnippetListRidget001(final Shell shell) {
shell.setLayout(new FillLayout());
final org.eclipse.swt.widgets.List list = UIControlsFactory.createList(shell, false, true);
final IListRidget listRidget = (IListRidget) SwtRidgetFactory.createRidget(list);
listRidget.setSelectionType(ISelectableRidget.SelectionType.SINGLE);
final IObservableList input = new WritableList(DayPojo.createWeek(), DayPojo.class);
listRidget.bindToModel(input, DayPojo.class, "english"); //$NON-NLS-1$
listRidget.updateFromModel();
final TypedBean<DayPojo> selection = new TypedBean<DayPojo>(DayPojo.class);
selection.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(final PropertyChangeEvent evt) {
final DayPojo node = selection.getValue();
System.out.println("Selection: " + node.getEnglish()); //$NON-NLS-1$
}
});
listRidget.bindSingleSelectionToModel(selection, "value"); //$NON-NLS-1$
}
|
diff --git a/mpicbg/ij/blockmatching/BlockMatching.java b/mpicbg/ij/blockmatching/BlockMatching.java
index 92e23f7..d8d61ae 100644
--- a/mpicbg/ij/blockmatching/BlockMatching.java
+++ b/mpicbg/ij/blockmatching/BlockMatching.java
@@ -1,707 +1,707 @@
package mpicbg.ij.blockmatching;
import ij.IJ;
import ij.ImageStack;
import ij.process.FloatProcessor;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import mpicbg.ij.InverseMapping;
import mpicbg.ij.TransformMapping;
import mpicbg.ij.util.Filter;
import mpicbg.ij.util.Util;
import mpicbg.models.AbstractAffineModel2D;
import mpicbg.models.CoordinateTransform;
import mpicbg.models.CoordinateTransformList;
import mpicbg.models.ErrorStatistic;
import mpicbg.models.InvertibleCoordinateTransform;
import mpicbg.models.Model;
import mpicbg.models.MovingLeastSquaresTransform;
import mpicbg.models.Point;
import mpicbg.models.PointMatch;
import mpicbg.models.SimilarityModel2D;
import mpicbg.models.TransformMesh;
import mpicbg.models.TranslationModel2D;
/**
* Methods for establishing block-based correspondences for given sets of
* source {@link Point Points}.
*
* @author Stephan Saalfeld <[email protected]>
* @version 0.1b
*/
public class BlockMatching
{
/*
* σ of the Gaussian kernel required to make an image sampled at
* σ = 1.6 (as suggested by Lowe, 2004)
*/
final static private float minSigma = 1.6f;
final static private float minDiffSigma = ( float )Math.sqrt( minSigma * minSigma - 0.5f );
private BlockMatching(){}
/**
* Estimate the mean intensity of a block.
*
* <dl>
* <dt>Note:</dt>
* <dd>Make sure that the block is fully contained in the image, this will
* not be checked by the method for efficiency reasons.</dd>
* </dl>
*
* @param fp
* @param tx
* @param ty
* @param blockWidth
* @param blockHeight
* @return
*/
static protected float blockMean(
final FloatProcessor fp,
final int tx,
final int ty,
final int blockWidth,
final int blockHeight )
{
final int width = fp.getWidth();
final float[] pixels = ( float[] )fp.getPixels();
double sum = 0;
for ( int y = ty + blockHeight - 1; y >= ty; --y )
{
final int ry = y * width;
for ( int x = tx + blockWidth - 1; x >= tx; --x )
sum += pixels[ ry + x ];
}
return ( float )( sum / blockWidth / blockHeight );
}
/**
* Estimate the intensity variance of a block.
*
* <dl>
* <dt>Note:</dt>
* <dd>Make sure that the block is fully contained in the image, this will
* not be checked by the method for efficiency reasons.</dd>
* </dl>
*
* @param fp
* @param tx
* @param ty
* @param blockWidth
* @param blockHeight
* @return
*/
static protected float blockVariance(
final FloatProcessor fp,
final int tx,
final int ty,
final int blockWidth,
final int blockHeight,
final float mean )
{
final int width = fp.getWidth();
final float[] pixels = ( float[] )fp.getPixels();
double sum = 0;
for ( int y = ty + blockHeight - 1; y >= ty; --y )
{
final int ry = y * width;
for ( int x = tx + blockWidth - 1; x >= tx; --x )
{
final float a = pixels[ ry + x ] - mean;
sum += a * a;
}
}
return ( float )( sum / ( blockWidth * blockHeight - 1 ) );
}
/**
* Estimate {@linkplain PointMatch point correspondences} for a
* {@link Collection} of {@link Point Points} among two images that are
* approximately related by an {@link InvertibleCoordinateTransform} using
* the square difference of pixel intensities as a similarity measure.
*
* @param source
* @param target
* @param transform transfers source into target approximately
* @param blockRadiusX horizontal radius of a block
* @param blockRadiusY vertical radius of a block
* @param searchRadiusX horizontal search radius
* @param searchRadiusY vertical search radius
* @param sourcePoints
* @param sourceMatches
*/
static public void matchByMinimalSquareDifference(
final FloatProcessor source,
final FloatProcessor target,
final InvertibleCoordinateTransform transform,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final Collection< ? extends Point > sourcePoints,
final Collection< PointMatch > sourceMatches )
{
Util.normalizeContrast( source );
Util.normalizeContrast( target );
final FloatProcessor mappedTarget = new FloatProcessor( source.getWidth() + 2 * searchRadiusX, source.getHeight() + 2 * searchRadiusY );
Util.fillWithNaN( mappedTarget );
final TranslationModel2D tTarget = new TranslationModel2D();
tTarget.set( -searchRadiusX, -searchRadiusY );
final CoordinateTransformList< CoordinateTransform > lTarget = new CoordinateTransformList< CoordinateTransform >();
lTarget.add( tTarget );
lTarget.add( transform );
final InverseMapping< ? > targetMapping = new TransformMapping< CoordinateTransform >( lTarget );
targetMapping.mapInverseInterpolated( target, mappedTarget );
// mappedTarget.setMinAndMax( 0, 1 );
// new ImagePlus( "Mapped Target", mappedTarget ).show();
int k = 0;
for ( final Point p : sourcePoints )
{
final float[] s = p.getL();
final int px = Math.round( s[ 0 ] );
final int py = Math.round( s[ 1 ] );
if (
px - blockRadiusX >= 0 &&
px + blockRadiusX < source.getWidth() &&
py - blockRadiusY >= 0 &&
py + blockRadiusY < source.getHeight() )
{
IJ.showProgress( k++, sourcePoints.size() );
float tx = 0;
float ty = 0;
float dMin = Float.MAX_VALUE;
for ( int ity = -searchRadiusY; ity <= searchRadiusY; ++ity )
for ( int itx = -searchRadiusX; itx <= searchRadiusX; ++itx )
{
float d = 0;
float n = 0;
for ( int iy = -blockRadiusY; iy <= blockRadiusY; ++iy )
{
final int y = py + iy;
for ( int ix = -blockRadiusX; ix <= blockRadiusX; ++ix )
{
final int x = px + ix;
final float sf = source.getf( x, y );
final float tf = mappedTarget.getf( x + itx + searchRadiusX, y + ity + searchRadiusY );
if ( sf == Float.NaN || tf == Float.NaN )
continue;
else
{
final float a = sf - tf;
d += a * a;
++n;
}
}
}
if ( n > 0 )
{
d /= n;
if ( d < dMin )
{
dMin = d;
tx = itx;
ty = ity;
}
}
}
final float[] t = new float[]{ tx + s[ 0 ], ty + s[ 1 ] };
System.out.println( k + " : " + tx + ", " + ty );
transform.applyInPlace( t );
sourceMatches.add( new PointMatch( p, new Point( t ) ) );
}
}
}
static protected void matchByMaximalPMCC(
final FloatProcessor source,
final FloatProcessor target,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final float minR,
final float rod,
final float maxCurvature,
final Collection< PointMatch > query,
final Collection< PointMatch > results )
{
final float maxCurvatureRatio = ( maxCurvature + 1 ) * ( maxCurvature + 1 ) / maxCurvature;
final int blockWidth = 2 * blockRadiusX + 1;
final int blockHeight = 2 * blockRadiusY + 1;
/* Visualization of PMCC(x,y) */
/* <visualisation> */
final ImageStack rMapStack = new ImageStack( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
/* </visualisation> */
int k = 0;
int l = 0;
P: for ( final PointMatch pm : query )
{
IJ.showProgress( k++, query.size() );
final Point p = pm.getP1();
final Point q = pm.getP2();
final float[] s = p.getL();
final int px = Math.round( s[ 0 ] );
final int py = Math.round( s[ 1 ] );
final int ptx = px - blockRadiusX;
final int pty = py - blockRadiusY;
if ( ptx >= 0 && ptx + blockWidth < source.getWidth() && pty >= 0 && pty + blockHeight < source.getHeight() )
{
final float sourceBlockMean = blockMean( source, ptx, pty, blockWidth, blockHeight );
if ( Float.isNaN( sourceBlockMean ) ) continue P;
final float sourceBlockStd = ( float ) Math.sqrt( blockVariance( source, ptx, pty, blockWidth, blockHeight, sourceBlockMean ) );
if ( sourceBlockStd == 0 ) continue P;
float tx = 0;
float ty = 0;
float rMax = -Float.MAX_VALUE;
final FloatProcessor rMap = new FloatProcessor( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
for ( int ity = -searchRadiusY; ity <= searchRadiusY; ++ity )
{
final int ipty = ity + pty + searchRadiusY;
for ( int itx = -searchRadiusX; itx <= searchRadiusX; ++itx )
{
final int iptx = itx + ptx + searchRadiusX;
final float targetBlockMean = blockMean( target, iptx, ipty, blockWidth, blockHeight );
if ( Float.isNaN( targetBlockMean ) ) continue P;
final float targetBlockStd = ( float ) Math.sqrt( blockVariance( target, iptx, ipty, blockWidth, blockHeight, targetBlockMean ) );
if ( targetBlockStd == 0 ) continue P;
float r = 0;
- for ( int iy = 0; iy <= blockHeight; ++iy )
+ for ( int iy = 0; iy < blockHeight; ++iy )
{
final int ys = pty + iy;
final int yt = ipty + iy;
- for ( int ix = 0; ix <= blockWidth; ++ix )
+ for ( int ix = 0; ix < blockWidth; ++ix )
{
final int xs = ptx + ix;
final int xt = iptx + ix;
r += ( source.getf( xs, ys ) - sourceBlockMean ) * ( target.getf( xt, yt ) - targetBlockMean );
}
}
r /= sourceBlockStd * targetBlockStd * ( blockWidth * blockHeight - 1 );
if ( r > rMax )
{
rMax = r;
tx = itx;
ty = ity;
}
rMap.setf( itx + searchRadiusX, ity + searchRadiusY, r );
}
}
/* search and process maxima */
float bestR = -2.0f;
float secondBestR = -2.0f;
float dx = 0, dy = 0, dxx = 0, dyy = 0, dxy = 0;
for ( int y = 2 * searchRadiusY - 1; y > 0; --y )
for ( int x = 2 * searchRadiusX - 1; x > 0; --x )
{
final float c00, c01, c02, c10, c11, c12, c20, c21, c22;
c11 = rMap.getf( x, y );
c00 = rMap.getf( x - 1, y - 1 );
if ( c00 >= c11 ) continue;
c01 = rMap.getf( x, y - 1 );
if ( c01 >= c11 ) continue;
c02 = rMap.getf( x + 1, y - 1 );
if ( c02 >= c11 ) continue;
c10 = rMap.getf( x - 1, y );
if ( c10 >= c11 ) continue;
c12 = rMap.getf( x + 1, y );
if ( c12 >= c11 ) continue;
c20 = rMap.getf( x - 1, y + 1 );
if ( c20 >= c11 ) continue;
c21 = rMap.getf( x, y + 1 );
if ( c21 >= c11 ) continue;
c22 = rMap.getf( x + 1, y + 1 );
if ( c22 >= c11 ) continue;
/* is it better than what we had before? */
if ( c11 <= bestR )
{
if ( c11 > secondBestR ) secondBestR = c11;
continue;
}
secondBestR = bestR;
bestR = c11;
/* is it good enough? */
if ( c11 < minR ) continue;
/* estimate finite derivatives */
dx = ( c12 - c10 ) / 2.0f;
dy = ( c21 - c01 ) / 2.0f;
dxx = c10 - c11 - c11 + c12;
dyy = c01 - c11 - c11 + c21;
dxy = ( c22 - c20 - c02 + c00 ) / 4.0f;
}
// IJ.log( "maximum found" );
/* is it good enough? */
if ( bestR < minR ) continue;
// IJ.log( "minR test passed" );
/* is there more than one maximum of equal goodness? */
if ( secondBestR >= 0 && secondBestR / bestR > rod ) continue;
// IJ.log( "rod test passed" );
/* is it well localized in both x and y? */
final float det = dxx * dyy - dxy * dxy;
final float trace = dxx + dyy;
if ( det <= 0 || trace * trace / det > maxCurvatureRatio ) continue;
// IJ.log( "edge test passed" );
/* localize by Taylor expansion */
/* invert Hessian */
final float ixx = dyy / det;
final float ixy = -dxy / det;
final float iyy = dxx / det;
/* calculate offset */
final float ox = -ixx * dx - ixy * dy;
final float oy = -ixy * dx - iyy * dy;
if ( ox >= 1 || oy >= 1 || ox <= -1 || oy <= -1 ) continue;
// IJ.log( "localized" );
final float[] t = new float[] { tx + s[ 0 ] + ox, ty + s[ 1 ] + oy };
// System.out.println( k + " : " + ( tx + ox ) + ", " + ( ty +
// oy ) + " => " + rMax );
results.add( new PointMatch( p, new Point( t ) ) );
rMap.setMinAndMax( rMap.getMin(), rMap.getMax() );
rMapStack.addSlice( "" + ++l, rMap );
}
}
/* <visualisation> */
// if ( results.size() > 0 ) new ImagePlus( "r", rMapStack ).show();
/* </visualisation> */
}
/**
* Estimate {@linkplain PointMatch point correspondences} for a
* {@link Collection} of {@link Point Points} among two images that are
* approximately related by an {@link InvertibleCoordinateTransform} using
* the Pearson product-moment correlation coefficient (PMCC) <i>r</i> of
* pixel intensities as similarity measure. Only correspondence candidates
* with <i>r</i> >= a given threshold are accepted.
*
* @param scaledSource
* @param target
* @param scale
* [0,1]
* @param transform
* transfers source into target approximately
* @param blockRadiusX
* horizontal radius of a block
* @param blockRadiusY
* vertical radius of a block
* @param searchRadiusX
* horizontal search radius
* @param searchRadiusY
* vertical search radius
* @param minR
* minimal accepted Cross-Correlation coefficient
* @param sourcePoints
* @param sourceMatches
*/
static public void matchByMaximalPMCC(
final FloatProcessor source,
final FloatProcessor target,
final float scale,
final CoordinateTransform transform,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final float minR,
final float rod,
final float maxCurvature,
final Collection< ? extends Point > sourcePoints,
final Collection< PointMatch > sourceMatches,
final ErrorStatistic observer )
{
final int scaledBlockRadiusX = ( int )Math.ceil( scale * blockRadiusX );
final int scaledBlockRadiusY = ( int )Math.ceil( scale * blockRadiusY );
final int scaledSearchRadiusX = ( int )Math.ceil( scale * searchRadiusX ) + 1; // +1 for 3x3 maximum test
final int scaledSearchRadiusY = ( int )Math.ceil( scale * searchRadiusY ) + 1; // +1 for 3x3 maximum test
/* Scale source */
final FloatProcessor scaledSource = Filter.createDownsampled( source, scale, 0.5f, minSigma );
Util.normalizeContrast( scaledSource );
/* Smooth target with respect to the desired scale */
final FloatProcessor smoothedTarget = ( FloatProcessor )target.duplicate();
Filter.smoothForScale( smoothedTarget, scale, 0.5f, minSigma );
Util.normalizeContrast( smoothedTarget );
FloatProcessor mappedScaledTarget = new FloatProcessor( scaledSource.getWidth() + 2 * scaledSearchRadiusX, scaledSource.getHeight() + 2 * scaledSearchRadiusY );
Util.fillWithNaN( mappedScaledTarget );
/* Shift relative to the scaled search radius */
final TranslationModel2D tTarget = new TranslationModel2D();
tTarget.set( -scaledSearchRadiusX / scale, -scaledSearchRadiusY / scale );
/* Scale */
final SimilarityModel2D sTarget = new SimilarityModel2D();
sTarget.set( 1.0f / scale, 0, 0, 0 );
/* Combined transformation */
final CoordinateTransformList< CoordinateTransform > lTarget = new CoordinateTransformList< CoordinateTransform >();
lTarget.add( sTarget );
lTarget.add( tTarget );
lTarget.add( transform );
final InverseMapping< ? > targetMapping = new TransformMapping< CoordinateTransform >( lTarget );
targetMapping.mapInverseInterpolated( smoothedTarget, mappedScaledTarget );
// scaledSource.setMinAndMax( 0, 1 );
// mappedScaledTarget.setMinAndMax( 0, 1 );
// new ImagePlus( "Scaled Source", scaledSource ).show();
// new ImagePlus( "Mapped Target", mappedScaledTarget ).show();
final Map< Point, Point > scaledSourcePoints = new HashMap< Point, Point>();
final ArrayList< PointMatch > scaledSourceMatches = new ArrayList< PointMatch >();
for ( final Point p : sourcePoints )
{
final float[] l = p.getL().clone();
l[ 0 ] *= scale;
l[ 1 ] *= scale;
scaledSourcePoints.put( new Point( l ), p );
}
/* initialize source points and the expected place to search for them temporarily */
final Collection< PointMatch > query = new ArrayList< PointMatch >();
for ( final Point p : scaledSourcePoints.keySet() )
query.add( new PointMatch( p, p.clone()) );
matchByMaximalPMCC(
scaledSource,
mappedScaledTarget,
scaledBlockRadiusX,
scaledBlockRadiusY,
scaledSearchRadiusX,
scaledSearchRadiusY,
minR,
rod,
maxCurvature,
query,
scaledSourceMatches );
for ( final PointMatch p : scaledSourceMatches )
{
final float[] l1 = p.getP1().getL().clone();
final float[] l2 = p.getP2().getL().clone();
l1[ 0 ] /= scale;
l1[ 1 ] /= scale;
l2[ 0 ] /= scale;
l2[ 1 ] /= scale;
final float tx = l2[ 0 ] - l1[ 0 ];
final float ty = l2[ 1 ] - l1[ 1 ];
observer.add( Math.sqrt( tx * tx + ty * ty ) );
transform.applyInPlace( l2 );
sourceMatches.add( new PointMatch( scaledSourcePoints.get( p.getP1() ), new Point( l2 ) ) );
}
}
/**
* Estimate {@linkplain PointMatch point correspondences} for a
* {@link Collection} of {@link Point Points} among two images that are
* approximately related by an {@link InvertibleCoordinateTransform} using
* the Pearson product-moment correlation coefficient (PMCC) <i>r</i> of
* pixel intensities as similarity measure. Only correspondence candidates
* with <i>r</i> >= a given threshold are accepted.
*
* @param scaledSource
* @param target
* @param scale [0,1]
* @param transform transfers source into target approximately
* @param scaledBlockRadiusX horizontal radius of a block
* @param scaledBlockRadiusY vertical radius of a block
* @param scaledSearchRadiusX horizontal search radius
* @param scaledSearchRadiusY vertical search radius
* @param minR minimal accepted Cross-Correlation coefficient
* @param sourcePoints
* @param sourceMatches
*/
static public void matchByMaximalPMCC(
final FloatProcessor source,
final FloatProcessor target,
final float scale,
final CoordinateTransform transform,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final Collection< ? extends Point > sourcePoints,
final Collection< PointMatch > sourceMatches,
final ErrorStatistic observer )
{
matchByMaximalPMCC(
source,
target,
scale,
transform,
blockRadiusX,
blockRadiusY,
searchRadiusX,
searchRadiusY,
0.7f, // minR
0.9f, // rod
10.0f, // maxCurvature
sourcePoints,
sourceMatches,
observer );
}
public static void findMatches(
final FloatProcessor source,
final FloatProcessor target,
final Model< ? > initialModel,
final Class< ? extends AbstractAffineModel2D< ? > > localModelClass,
final float maxEpsilon,
final float maxScale,
final float minR,
final float rodR,
final float maxCurvatureR,
final int meshResolution,
final float alpha,
final Collection< PointMatch > sourceMatches )
{
CoordinateTransform ict = initialModel;
final Collection< Point > sourcePoints = new ArrayList< Point >();
final ErrorStatistic observer = new ErrorStatistic( 1 );
for ( int n = Math.max( 4, Math.min( ( int )meshResolution, ( int )Math.ceil( source.getWidth() / maxEpsilon / 4 ) ) ); n <= meshResolution; n *= 2 )
{
n = Math.min( meshResolution, n );
final MovingLeastSquaresTransform mlst = new MovingLeastSquaresTransform();
try
{
mlst.setModel( localModelClass );
}
catch ( Exception e )
{
IJ.error( "Invalid local model selected." );
return;
}
//if ( sourceMatches )
final int searchRadius = observer.n() < mlst.getModel().getMinNumMatches()
? ( int )Math.ceil( maxEpsilon )
: ( int )Math.ceil( observer.max );
final float scale = Math.min( maxScale, 16.0f / searchRadius );
final int blockRadius = ( int )Math.ceil( 32 / scale );
// final int blockRadius = Math.max( 16, 3 * p.imp1.getWidth() / n );
// final int searchRadius = ( int )( sourceMatches.size() >= mlst.getModel().getMinNumMatches() ? Math.min( p.maxEpsilon + 0.5f, blockRadius / 3 ) : p.maxEpsilon );
/* block match forward */
sourcePoints.clear();
sourceMatches.clear();
final TransformMesh mesh = new TransformMesh( n, source.getWidth(), source.getHeight() );
PointMatch.sourcePoints( mesh.getVA().keySet(), sourcePoints );
observer.clear();
BlockMatching.matchByMaximalPMCC(
source,
target,
//512.0f / p.imp1.getWidth(),
scale,
ict,
blockRadius,
blockRadius,
searchRadius,
searchRadius,
minR,
rodR,
maxCurvatureR,
sourcePoints,
sourceMatches,
observer );
IJ.log( "Blockmatching at n = " + n );
IJ.log( " average offset : " + observer.mean );
IJ.log( " minimal offset : " + observer.min );
IJ.log( " maximal offset : " + observer.max );
if ( sourceMatches.size() >= mlst.getModel().getMinNumMatches() )
{
mlst.setAlpha( alpha );
try
{
mlst.setMatches( sourceMatches );
ict = mlst;
}
catch ( Exception e ) {}
}
}
// TODO refine the search results by rematching at higher resolution with lower search radius
}
/**
* Create a Shape that illustrates a {@link Collection} of
* {@link PointMatch PointMatches}.
*
* @return the illustration
*/
static public Shape illustrateMatches( final Collection< PointMatch > matches)
{
GeneralPath path = new GeneralPath();
for ( final PointMatch m : matches )
{
final float[] w1 = m.getP1().getW();
final float[] w2 = m.getP2().getW();
path.moveTo( w1[ 0 ] - 1, w1[ 1 ] - 1 );
path.lineTo( w1[ 0 ] - 1, w1[ 1 ] + 1 );
path.lineTo( w1[ 0 ] + 1, w1[ 1 ] + 1 );
path.lineTo( w1[ 0 ] + 1, w1[ 1 ] - 1 );
path.closePath();
path.moveTo( w1[ 0 ], w1[ 1 ] );
path.lineTo( w2[ 0 ], w2[ 1 ] );
}
return path;
}
}
| false | true | static protected void matchByMaximalPMCC(
final FloatProcessor source,
final FloatProcessor target,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final float minR,
final float rod,
final float maxCurvature,
final Collection< PointMatch > query,
final Collection< PointMatch > results )
{
final float maxCurvatureRatio = ( maxCurvature + 1 ) * ( maxCurvature + 1 ) / maxCurvature;
final int blockWidth = 2 * blockRadiusX + 1;
final int blockHeight = 2 * blockRadiusY + 1;
/* Visualization of PMCC(x,y) */
/* <visualisation> */
final ImageStack rMapStack = new ImageStack( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
/* </visualisation> */
int k = 0;
int l = 0;
P: for ( final PointMatch pm : query )
{
IJ.showProgress( k++, query.size() );
final Point p = pm.getP1();
final Point q = pm.getP2();
final float[] s = p.getL();
final int px = Math.round( s[ 0 ] );
final int py = Math.round( s[ 1 ] );
final int ptx = px - blockRadiusX;
final int pty = py - blockRadiusY;
if ( ptx >= 0 && ptx + blockWidth < source.getWidth() && pty >= 0 && pty + blockHeight < source.getHeight() )
{
final float sourceBlockMean = blockMean( source, ptx, pty, blockWidth, blockHeight );
if ( Float.isNaN( sourceBlockMean ) ) continue P;
final float sourceBlockStd = ( float ) Math.sqrt( blockVariance( source, ptx, pty, blockWidth, blockHeight, sourceBlockMean ) );
if ( sourceBlockStd == 0 ) continue P;
float tx = 0;
float ty = 0;
float rMax = -Float.MAX_VALUE;
final FloatProcessor rMap = new FloatProcessor( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
for ( int ity = -searchRadiusY; ity <= searchRadiusY; ++ity )
{
final int ipty = ity + pty + searchRadiusY;
for ( int itx = -searchRadiusX; itx <= searchRadiusX; ++itx )
{
final int iptx = itx + ptx + searchRadiusX;
final float targetBlockMean = blockMean( target, iptx, ipty, blockWidth, blockHeight );
if ( Float.isNaN( targetBlockMean ) ) continue P;
final float targetBlockStd = ( float ) Math.sqrt( blockVariance( target, iptx, ipty, blockWidth, blockHeight, targetBlockMean ) );
if ( targetBlockStd == 0 ) continue P;
float r = 0;
for ( int iy = 0; iy <= blockHeight; ++iy )
{
final int ys = pty + iy;
final int yt = ipty + iy;
for ( int ix = 0; ix <= blockWidth; ++ix )
{
final int xs = ptx + ix;
final int xt = iptx + ix;
r += ( source.getf( xs, ys ) - sourceBlockMean ) * ( target.getf( xt, yt ) - targetBlockMean );
}
}
r /= sourceBlockStd * targetBlockStd * ( blockWidth * blockHeight - 1 );
if ( r > rMax )
{
rMax = r;
tx = itx;
ty = ity;
}
rMap.setf( itx + searchRadiusX, ity + searchRadiusY, r );
}
}
/* search and process maxima */
float bestR = -2.0f;
float secondBestR = -2.0f;
float dx = 0, dy = 0, dxx = 0, dyy = 0, dxy = 0;
for ( int y = 2 * searchRadiusY - 1; y > 0; --y )
for ( int x = 2 * searchRadiusX - 1; x > 0; --x )
{
final float c00, c01, c02, c10, c11, c12, c20, c21, c22;
c11 = rMap.getf( x, y );
c00 = rMap.getf( x - 1, y - 1 );
if ( c00 >= c11 ) continue;
c01 = rMap.getf( x, y - 1 );
if ( c01 >= c11 ) continue;
c02 = rMap.getf( x + 1, y - 1 );
if ( c02 >= c11 ) continue;
c10 = rMap.getf( x - 1, y );
if ( c10 >= c11 ) continue;
c12 = rMap.getf( x + 1, y );
if ( c12 >= c11 ) continue;
c20 = rMap.getf( x - 1, y + 1 );
if ( c20 >= c11 ) continue;
c21 = rMap.getf( x, y + 1 );
if ( c21 >= c11 ) continue;
c22 = rMap.getf( x + 1, y + 1 );
if ( c22 >= c11 ) continue;
/* is it better than what we had before? */
if ( c11 <= bestR )
{
if ( c11 > secondBestR ) secondBestR = c11;
continue;
}
secondBestR = bestR;
bestR = c11;
/* is it good enough? */
if ( c11 < minR ) continue;
/* estimate finite derivatives */
dx = ( c12 - c10 ) / 2.0f;
dy = ( c21 - c01 ) / 2.0f;
dxx = c10 - c11 - c11 + c12;
dyy = c01 - c11 - c11 + c21;
dxy = ( c22 - c20 - c02 + c00 ) / 4.0f;
}
// IJ.log( "maximum found" );
/* is it good enough? */
if ( bestR < minR ) continue;
// IJ.log( "minR test passed" );
/* is there more than one maximum of equal goodness? */
if ( secondBestR >= 0 && secondBestR / bestR > rod ) continue;
// IJ.log( "rod test passed" );
/* is it well localized in both x and y? */
final float det = dxx * dyy - dxy * dxy;
final float trace = dxx + dyy;
if ( det <= 0 || trace * trace / det > maxCurvatureRatio ) continue;
// IJ.log( "edge test passed" );
/* localize by Taylor expansion */
/* invert Hessian */
final float ixx = dyy / det;
final float ixy = -dxy / det;
final float iyy = dxx / det;
/* calculate offset */
final float ox = -ixx * dx - ixy * dy;
final float oy = -ixy * dx - iyy * dy;
if ( ox >= 1 || oy >= 1 || ox <= -1 || oy <= -1 ) continue;
// IJ.log( "localized" );
final float[] t = new float[] { tx + s[ 0 ] + ox, ty + s[ 1 ] + oy };
// System.out.println( k + " : " + ( tx + ox ) + ", " + ( ty +
// oy ) + " => " + rMax );
results.add( new PointMatch( p, new Point( t ) ) );
rMap.setMinAndMax( rMap.getMin(), rMap.getMax() );
rMapStack.addSlice( "" + ++l, rMap );
}
}
/* <visualisation> */
// if ( results.size() > 0 ) new ImagePlus( "r", rMapStack ).show();
/* </visualisation> */
}
| static protected void matchByMaximalPMCC(
final FloatProcessor source,
final FloatProcessor target,
final int blockRadiusX,
final int blockRadiusY,
final int searchRadiusX,
final int searchRadiusY,
final float minR,
final float rod,
final float maxCurvature,
final Collection< PointMatch > query,
final Collection< PointMatch > results )
{
final float maxCurvatureRatio = ( maxCurvature + 1 ) * ( maxCurvature + 1 ) / maxCurvature;
final int blockWidth = 2 * blockRadiusX + 1;
final int blockHeight = 2 * blockRadiusY + 1;
/* Visualization of PMCC(x,y) */
/* <visualisation> */
final ImageStack rMapStack = new ImageStack( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
/* </visualisation> */
int k = 0;
int l = 0;
P: for ( final PointMatch pm : query )
{
IJ.showProgress( k++, query.size() );
final Point p = pm.getP1();
final Point q = pm.getP2();
final float[] s = p.getL();
final int px = Math.round( s[ 0 ] );
final int py = Math.round( s[ 1 ] );
final int ptx = px - blockRadiusX;
final int pty = py - blockRadiusY;
if ( ptx >= 0 && ptx + blockWidth < source.getWidth() && pty >= 0 && pty + blockHeight < source.getHeight() )
{
final float sourceBlockMean = blockMean( source, ptx, pty, blockWidth, blockHeight );
if ( Float.isNaN( sourceBlockMean ) ) continue P;
final float sourceBlockStd = ( float ) Math.sqrt( blockVariance( source, ptx, pty, blockWidth, blockHeight, sourceBlockMean ) );
if ( sourceBlockStd == 0 ) continue P;
float tx = 0;
float ty = 0;
float rMax = -Float.MAX_VALUE;
final FloatProcessor rMap = new FloatProcessor( 2 * searchRadiusX + 1, 2 * searchRadiusY + 1 );
for ( int ity = -searchRadiusY; ity <= searchRadiusY; ++ity )
{
final int ipty = ity + pty + searchRadiusY;
for ( int itx = -searchRadiusX; itx <= searchRadiusX; ++itx )
{
final int iptx = itx + ptx + searchRadiusX;
final float targetBlockMean = blockMean( target, iptx, ipty, blockWidth, blockHeight );
if ( Float.isNaN( targetBlockMean ) ) continue P;
final float targetBlockStd = ( float ) Math.sqrt( blockVariance( target, iptx, ipty, blockWidth, blockHeight, targetBlockMean ) );
if ( targetBlockStd == 0 ) continue P;
float r = 0;
for ( int iy = 0; iy < blockHeight; ++iy )
{
final int ys = pty + iy;
final int yt = ipty + iy;
for ( int ix = 0; ix < blockWidth; ++ix )
{
final int xs = ptx + ix;
final int xt = iptx + ix;
r += ( source.getf( xs, ys ) - sourceBlockMean ) * ( target.getf( xt, yt ) - targetBlockMean );
}
}
r /= sourceBlockStd * targetBlockStd * ( blockWidth * blockHeight - 1 );
if ( r > rMax )
{
rMax = r;
tx = itx;
ty = ity;
}
rMap.setf( itx + searchRadiusX, ity + searchRadiusY, r );
}
}
/* search and process maxima */
float bestR = -2.0f;
float secondBestR = -2.0f;
float dx = 0, dy = 0, dxx = 0, dyy = 0, dxy = 0;
for ( int y = 2 * searchRadiusY - 1; y > 0; --y )
for ( int x = 2 * searchRadiusX - 1; x > 0; --x )
{
final float c00, c01, c02, c10, c11, c12, c20, c21, c22;
c11 = rMap.getf( x, y );
c00 = rMap.getf( x - 1, y - 1 );
if ( c00 >= c11 ) continue;
c01 = rMap.getf( x, y - 1 );
if ( c01 >= c11 ) continue;
c02 = rMap.getf( x + 1, y - 1 );
if ( c02 >= c11 ) continue;
c10 = rMap.getf( x - 1, y );
if ( c10 >= c11 ) continue;
c12 = rMap.getf( x + 1, y );
if ( c12 >= c11 ) continue;
c20 = rMap.getf( x - 1, y + 1 );
if ( c20 >= c11 ) continue;
c21 = rMap.getf( x, y + 1 );
if ( c21 >= c11 ) continue;
c22 = rMap.getf( x + 1, y + 1 );
if ( c22 >= c11 ) continue;
/* is it better than what we had before? */
if ( c11 <= bestR )
{
if ( c11 > secondBestR ) secondBestR = c11;
continue;
}
secondBestR = bestR;
bestR = c11;
/* is it good enough? */
if ( c11 < minR ) continue;
/* estimate finite derivatives */
dx = ( c12 - c10 ) / 2.0f;
dy = ( c21 - c01 ) / 2.0f;
dxx = c10 - c11 - c11 + c12;
dyy = c01 - c11 - c11 + c21;
dxy = ( c22 - c20 - c02 + c00 ) / 4.0f;
}
// IJ.log( "maximum found" );
/* is it good enough? */
if ( bestR < minR ) continue;
// IJ.log( "minR test passed" );
/* is there more than one maximum of equal goodness? */
if ( secondBestR >= 0 && secondBestR / bestR > rod ) continue;
// IJ.log( "rod test passed" );
/* is it well localized in both x and y? */
final float det = dxx * dyy - dxy * dxy;
final float trace = dxx + dyy;
if ( det <= 0 || trace * trace / det > maxCurvatureRatio ) continue;
// IJ.log( "edge test passed" );
/* localize by Taylor expansion */
/* invert Hessian */
final float ixx = dyy / det;
final float ixy = -dxy / det;
final float iyy = dxx / det;
/* calculate offset */
final float ox = -ixx * dx - ixy * dy;
final float oy = -ixy * dx - iyy * dy;
if ( ox >= 1 || oy >= 1 || ox <= -1 || oy <= -1 ) continue;
// IJ.log( "localized" );
final float[] t = new float[] { tx + s[ 0 ] + ox, ty + s[ 1 ] + oy };
// System.out.println( k + " : " + ( tx + ox ) + ", " + ( ty +
// oy ) + " => " + rMax );
results.add( new PointMatch( p, new Point( t ) ) );
rMap.setMinAndMax( rMap.getMin(), rMap.getMax() );
rMapStack.addSlice( "" + ++l, rMap );
}
}
/* <visualisation> */
// if ( results.size() > 0 ) new ImagePlus( "r", rMapStack ).show();
/* </visualisation> */
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java
index e730f596f..12b7a2932 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/artifactbrowser/FeedbackForm.java
@@ -1,158 +1,157 @@
/*
* FeedbackForm.java
*
* Version: $Revision: 1.4 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, 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.xmlui.aspect.artifactbrowser;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.List;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.TextArea;
import org.dspace.authorize.AuthorizeException;
import org.xml.sax.SAXException;
/**
* Display to the user a simple form letting the user give feedback.
*
* @author Scott Phillips
*/
public class FeedbackForm extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
private static final Message T_title =
message("xmlui.ArtifactBrowser.FeedbackForm.title");
private static final Message T_dspace_home =
message("xmlui.general.dspace_home");
private static final Message T_trail =
message("xmlui.ArtifactBrowser.FeedbackForm.trail");
private static final Message T_head =
message("xmlui.ArtifactBrowser.FeedbackForm.head");
private static final Message T_para1 =
message("xmlui.ArtifactBrowser.FeedbackForm.para1");
private static final Message T_email =
message("xmlui.ArtifactBrowser.FeedbackForm.email");
private static final Message T_email_help =
message("xmlui.ArtifactBrowser.FeedbackForm.email_help");
private static final Message T_comments =
message("xmlui.ArtifactBrowser.FeedbackForm.comments");
private static final Message T_submit =
message("xmlui.ArtifactBrowser.FeedbackForm.submit");
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey() {
String email = parameters.getParameter("email","");
String comments = parameters.getParameter("comments","");
String page = parameters.getParameter("page","unknown");
return HashUtil.hash(email + "-" + comments + "-" + page);
}
/**
* Generate the cache validity object.
*/
public SourceValidity getValidity()
{
return NOPValidity.SHARED_INSTANCE;
}
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Build the item viewer division.
Division feedback = body.addInteractiveDivision("feedback-form",
contextPath+"/feedback",Division.METHOD_POST,"primary");
feedback.setHead(T_head);
feedback.addPara(T_para1);
List form = feedback.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setLabel(T_email);
email.setHelp(T_email_help);
email.setValue(parameters.getParameter("email",""));
TextArea comments = form.addItem().addTextArea("comments");
comments.setLabel(T_comments);
- comments.setSize(5,60);
comments.setValue(parameters.getParameter("comments",""));
form.addItem().addButton("submit").setValue(T_submit);
feedback.addHidden("page").setValue(parameters.getParameter("page","unknown"));
}
}
| true | true | public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Build the item viewer division.
Division feedback = body.addInteractiveDivision("feedback-form",
contextPath+"/feedback",Division.METHOD_POST,"primary");
feedback.setHead(T_head);
feedback.addPara(T_para1);
List form = feedback.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setLabel(T_email);
email.setHelp(T_email_help);
email.setValue(parameters.getParameter("email",""));
TextArea comments = form.addItem().addTextArea("comments");
comments.setLabel(T_comments);
comments.setSize(5,60);
comments.setValue(parameters.getParameter("comments",""));
form.addItem().addButton("submit").setValue(T_submit);
feedback.addHidden("page").setValue(parameters.getParameter("page","unknown"));
}
| public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Build the item viewer division.
Division feedback = body.addInteractiveDivision("feedback-form",
contextPath+"/feedback",Division.METHOD_POST,"primary");
feedback.setHead(T_head);
feedback.addPara(T_para1);
List form = feedback.addList("form",List.TYPE_FORM);
Text email = form.addItem().addText("email");
email.setLabel(T_email);
email.setHelp(T_email_help);
email.setValue(parameters.getParameter("email",""));
TextArea comments = form.addItem().addTextArea("comments");
comments.setLabel(T_comments);
comments.setValue(parameters.getParameter("comments",""));
form.addItem().addButton("submit").setValue(T_submit);
feedback.addHidden("page").setValue(parameters.getParameter("page","unknown"));
}
|
diff --git a/src/main/java/com/anysoftkeyboard/ui/SendBugReportUiActivity.java b/src/main/java/com/anysoftkeyboard/ui/SendBugReportUiActivity.java
index 60911a1f..ea7190f7 100644
--- a/src/main/java/com/anysoftkeyboard/ui/SendBugReportUiActivity.java
+++ b/src/main/java/com/anysoftkeyboard/ui/SendBugReportUiActivity.java
@@ -1,94 +1,94 @@
/*
* Copyright (c) 2013 Menny Even-Danan
*
* 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.anysoftkeyboard.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.anysoftkeyboard.utils.Log;
import com.menny.android.anysoftkeyboard.BuildConfig;
import com.menny.android.anysoftkeyboard.R;
public class SendBugReportUiActivity extends Activity {
private static final String TAG = "ASK_BUG_SENDER";
public static final String CRASH_REPORT_TEXT = "CRASH_REPORT_TEXT";
public static final String CRASH_TYPE_STRING = "CRASH_TYPE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_crash_log_ui);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//this is a "singleInstance" activity, so we may get a "newIntent" call, with new crash data. I'll store the new intent.
setIntent(intent);
}
@Override
protected void onStart() {
super.onStart();
TextView crashType = (TextView) findViewById(R.id.ime_crash_type);
Intent callingIntent = getIntent();
String type = callingIntent.getStringExtra(CRASH_TYPE_STRING);
if (TextUtils.isEmpty(type) || (!BuildConfig.DEBUG)/*not showing the type of crash in RELEASE mode*/) {
crashType.setVisibility(View.GONE);
} else {
crashType.setText(type);
}
}
public void onCancelCrashReport(View v) {
finish();
}
public void onSendCrashReport(View v) {
String[] recipients = new String[]{BuildConfig.CRASH_REPORT_EMAIL_ADDRESS};
Intent callingIntent = getIntent();
Intent sendMail = new Intent();
sendMail.setAction(Intent.ACTION_SEND);
sendMail.setType("plain/text");
sendMail.putExtra(Intent.EXTRA_EMAIL, recipients);
sendMail.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.ime_crashed_title));
sendMail.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
try {
Intent sender = Intent.createChooser(sendMail, getString(R.string.ime_crashed_intent_selector_title));
- sender.putExtra(Intent.EXTRA_EMAIL, sendMail.getStringExtra(Intent.EXTRA_EMAIL));
+ sender.putExtra(Intent.EXTRA_EMAIL, sendMail.getStringArrayExtra(Intent.EXTRA_EMAIL));
sender.putExtra(Intent.EXTRA_SUBJECT, sendMail.getStringExtra(Intent.EXTRA_SUBJECT));
sender.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
Log.i(TAG, "Will send crash report using " + sender);
startActivity(sender);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "Unable to send bug report via e-mail!", Toast.LENGTH_LONG).show();
}
finish();
}
}
| true | true | public void onSendCrashReport(View v) {
String[] recipients = new String[]{BuildConfig.CRASH_REPORT_EMAIL_ADDRESS};
Intent callingIntent = getIntent();
Intent sendMail = new Intent();
sendMail.setAction(Intent.ACTION_SEND);
sendMail.setType("plain/text");
sendMail.putExtra(Intent.EXTRA_EMAIL, recipients);
sendMail.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.ime_crashed_title));
sendMail.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
try {
Intent sender = Intent.createChooser(sendMail, getString(R.string.ime_crashed_intent_selector_title));
sender.putExtra(Intent.EXTRA_EMAIL, sendMail.getStringExtra(Intent.EXTRA_EMAIL));
sender.putExtra(Intent.EXTRA_SUBJECT, sendMail.getStringExtra(Intent.EXTRA_SUBJECT));
sender.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
Log.i(TAG, "Will send crash report using " + sender);
startActivity(sender);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "Unable to send bug report via e-mail!", Toast.LENGTH_LONG).show();
}
finish();
}
| public void onSendCrashReport(View v) {
String[] recipients = new String[]{BuildConfig.CRASH_REPORT_EMAIL_ADDRESS};
Intent callingIntent = getIntent();
Intent sendMail = new Intent();
sendMail.setAction(Intent.ACTION_SEND);
sendMail.setType("plain/text");
sendMail.putExtra(Intent.EXTRA_EMAIL, recipients);
sendMail.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.ime_crashed_title));
sendMail.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
try {
Intent sender = Intent.createChooser(sendMail, getString(R.string.ime_crashed_intent_selector_title));
sender.putExtra(Intent.EXTRA_EMAIL, sendMail.getStringArrayExtra(Intent.EXTRA_EMAIL));
sender.putExtra(Intent.EXTRA_SUBJECT, sendMail.getStringExtra(Intent.EXTRA_SUBJECT));
sender.putExtra(Intent.EXTRA_TEXT, callingIntent.getStringExtra(CRASH_REPORT_TEXT));
Log.i(TAG, "Will send crash report using " + sender);
startActivity(sender);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "Unable to send bug report via e-mail!", Toast.LENGTH_LONG).show();
}
finish();
}
|
diff --git a/src/net/neoturbine/autolycus/BusShortcuts.java b/src/net/neoturbine/autolycus/BusShortcuts.java
index 145ffe7..7c718ec 100644
--- a/src/net/neoturbine/autolycus/BusShortcuts.java
+++ b/src/net/neoturbine/autolycus/BusShortcuts.java
@@ -1,91 +1,93 @@
/**
*
*/
package net.neoturbine.autolycus;
import net.neoturbine.autolycus.providers.Routes;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* @author Joseph Booker
*
*/
public class BusShortcuts extends Activity {
private static final int PICK_STOP = 1;
private String system;
private String route;
private String direction;
private String stopname;
private int stopid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final String action = intent.getAction();
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
Intent stopintent = new Intent(Intent.ACTION_PICK,Routes.CONTENT_URI);
startActivityForResult(stopintent, PICK_STOP);
} else {
setResult(RESULT_CANCELED);
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_STOP) {
if(resultCode == RESULT_OK) {
setContentView(R.layout.shortcut);
system = data.getStringExtra(SelectStop.EXTRA_SYSTEM);
route = data.getStringExtra(SelectStop.EXTRA_ROUTE);
direction = data.getStringExtra(SelectStop.EXTRA_DIRECTION);
stopid = data.getIntExtra(SelectStop.EXTRA_STOPID,-1);
stopname = data.getStringExtra(SelectStop.EXTRA_STOPNAME);
- ((TextView)findViewById(R.id.shortcut_stop)).setText(
- system + " Stop \"" + stopname +"\" (" + direction +") on Route "+route);
+ ((TextView)findViewById(R.id.shortcut_sys)).setText(system);
+ ((TextView)findViewById(R.id.shortcut_route)).setText("Route "+route);
+ ((TextView)findViewById(R.id.shortcut_direction)).setText(direction);
+ ((TextView)findViewById(R.id.shortcut_stpnm)).setText(stopname);
((EditText)findViewById(R.id.shortcut_stopname)).setText(stopname);
((Button)findViewById(R.id.shortcut_submit))
.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
returnShortcut();
}
});
}
}
}
public void returnShortcut() {
Intent shortcutIntent = new Intent();
shortcutIntent.setAction(StopPrediction.OPEN_STOP_ACTION);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent
.putExtra(SelectStop.EXTRA_SYSTEM, system)
.putExtra(SelectStop.EXTRA_ROUTE, route)
.putExtra(SelectStop.EXTRA_DIRECTION, direction)
.putExtra(SelectStop.EXTRA_STOPNAME, stopname)
.putExtra(SelectStop.EXTRA_STOPID, stopid);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
((TextView)findViewById(R.id.shortcut_stopname)).getText().toString());
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
this, R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent);
finish();
}
}
| true | true | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_STOP) {
if(resultCode == RESULT_OK) {
setContentView(R.layout.shortcut);
system = data.getStringExtra(SelectStop.EXTRA_SYSTEM);
route = data.getStringExtra(SelectStop.EXTRA_ROUTE);
direction = data.getStringExtra(SelectStop.EXTRA_DIRECTION);
stopid = data.getIntExtra(SelectStop.EXTRA_STOPID,-1);
stopname = data.getStringExtra(SelectStop.EXTRA_STOPNAME);
((TextView)findViewById(R.id.shortcut_stop)).setText(
system + " Stop \"" + stopname +"\" (" + direction +") on Route "+route);
((EditText)findViewById(R.id.shortcut_stopname)).setText(stopname);
((Button)findViewById(R.id.shortcut_submit))
.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
returnShortcut();
}
});
}
}
}
| protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_STOP) {
if(resultCode == RESULT_OK) {
setContentView(R.layout.shortcut);
system = data.getStringExtra(SelectStop.EXTRA_SYSTEM);
route = data.getStringExtra(SelectStop.EXTRA_ROUTE);
direction = data.getStringExtra(SelectStop.EXTRA_DIRECTION);
stopid = data.getIntExtra(SelectStop.EXTRA_STOPID,-1);
stopname = data.getStringExtra(SelectStop.EXTRA_STOPNAME);
((TextView)findViewById(R.id.shortcut_sys)).setText(system);
((TextView)findViewById(R.id.shortcut_route)).setText("Route "+route);
((TextView)findViewById(R.id.shortcut_direction)).setText(direction);
((TextView)findViewById(R.id.shortcut_stpnm)).setText(stopname);
((EditText)findViewById(R.id.shortcut_stopname)).setText(stopname);
((Button)findViewById(R.id.shortcut_submit))
.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
returnShortcut();
}
});
}
}
}
|
diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java
index 4c38f714b..26ec54051 100644
--- a/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java
+++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudfiles/CloudFilesClientLiveTest.java
@@ -1,397 +1,397 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <[email protected]>
*
* ====================================================================
* 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.jclouds.rackspace.cloudfiles;
import static org.jclouds.rackspace.cloudfiles.options.ListContainerOptions.Builder.underPath;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.jclouds.blobstore.ContainerNotFoundException;
import org.jclouds.blobstore.domain.PageSet;
import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;
import org.jclouds.encryption.EncryptionService;
import org.jclouds.encryption.internal.JCEEncryptionService;
import org.jclouds.http.HttpResponseException;
import org.jclouds.http.options.GetOptions;
import org.jclouds.rackspace.cloudfiles.domain.AccountMetadata;
import org.jclouds.rackspace.cloudfiles.domain.CFObject;
import org.jclouds.rackspace.cloudfiles.domain.ContainerCDNMetadata;
import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata;
import org.jclouds.rackspace.cloudfiles.domain.MutableObjectInfoWithMetadata;
import org.jclouds.rackspace.cloudfiles.domain.ObjectInfo;
import org.jclouds.rackspace.cloudfiles.options.ListCdnContainerOptions;
import org.jclouds.rackspace.cloudfiles.options.ListContainerOptions;
import org.jclouds.util.Utils;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
/**
* Tests behavior of {@code JaxrsAnnotationProcessor}
*
* @author Adrian Cole
*/
@Test(groups = "live", testName = "cloudfiles.CloudFilesClientLiveTest")
public class CloudFilesClientLiveTest extends BaseBlobStoreIntegrationTest {
private static final EncryptionService encryptionService = new JCEEncryptionService();
public CloudFilesClient getApi() {
return (CloudFilesClient) context.getProviderSpecificContext().getApi();
}
/**
* this method overrides containerName to ensure it isn't found
*/
@Test(groups = { "integration", "live" })
public void deleteContainerIfEmptyNotFound() throws Exception {
assert getApi().deleteContainerIfEmpty("dbienf");
}
@Test
public void testCDNOperations() throws Exception {
final long minimumTTL = 60 * 60; // The minimum TTL is 1 hour
// Create two new containers for testing
final String containerNameWithCDN = getContainerName();
final String containerNameWithoutCDN = getContainerName();
try {
try {
getApi().disableCDN(containerNameWithCDN);
getApi().disableCDN(containerNameWithoutCDN);
} catch (Exception e) {
}
ContainerCDNMetadata cdnMetadata = null;
// Enable CDN with PUT for one container
final URI cdnUri = getApi().enableCDN(containerNameWithCDN);
assertTrue(cdnUri != null);
// Confirm CDN is enabled via HEAD request and has default TTL
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getCDNUri(), cdnUri);
final long initialTTL = cdnMetadata.getTTL();
try {
cdnMetadata = getApi().getCDNMetadata(containerNameWithoutCDN);
assert cdnMetadata == null || !cdnMetadata.isCDNEnabled() : containerNameWithoutCDN
+ " should not have metadata";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
try {
cdnMetadata = getApi().getCDNMetadata("DoesNotExist");
assert false : "should not exist";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
// List CDN metadata for containers, and ensure all CDN info is available for enabled
// container
Set<ContainerCDNMetadata> cdnMetadataList = getApi().listCDNContainers();
assertTrue(cdnMetadataList.size() >= 1);
assertTrue(cdnMetadataList.contains(new ContainerCDNMetadata(containerNameWithCDN, true,
initialTTL, cdnUri)));
// Test listing with options
cdnMetadataList = getApi()
.listCDNContainers(ListCdnContainerOptions.Builder.enabledOnly());
assertTrue(Iterables.all(cdnMetadataList, new Predicate<ContainerCDNMetadata>() {
public boolean apply(ContainerCDNMetadata cdnMetadata) {
return cdnMetadata.isCDNEnabled();
}
}));
cdnMetadataList = getApi().listCDNContainers(
ListCdnContainerOptions.Builder.afterMarker(
containerNameWithCDN.substring(0, containerNameWithCDN.length() - 1))
.maxResults(1));
assertEquals(cdnMetadataList.size(), 1);
// Enable CDN with PUT for the same container, this time with a custom TTL
long ttl = 4000;
getApi().enableCDN(containerNameWithCDN, ttl);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), ttl);
// Check POST by updating TTL settings
ttl = minimumTTL;
getApi().updateCDN(containerNameWithCDN, minimumTTL);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), minimumTTL);
// Confirm that minimum allowed value for TTL is 3600, lower values are ignored.
getApi().updateCDN(containerNameWithCDN, 3599L);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
- assertEquals(cdnMetadata.getTTL(), minimumTTL); // Note that TTL is 3600 here, not 3599
+ assertEquals(cdnMetadata.getTTL(), 3599L);
// Disable CDN with POST
assertTrue(getApi().disableCDN(containerNameWithCDN));
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertEquals(cdnMetadata.isCDNEnabled(), false);
} finally {
recycleContainer(containerNameWithCDN);
recycleContainer(containerNameWithoutCDN);
}
}
@Test
public void testListOwnedContainers() throws Exception {
String containerPrefix = getContainerName();
try {
Set<ContainerMetadata> response = getApi().listContainers();
assertNotNull(response);
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
// Create test containers
String[] containerJsr330 = new String[] { containerPrefix + ".testListOwnedContainers1",
containerPrefix + ".testListOwnedContainers2" };
assertTrue(getApi().createContainer(containerJsr330[0]));
assertTrue(getApi().createContainer(containerJsr330[1]));
// Test default listing
response = getApi().listContainers();
// assertEquals(response.size(), initialContainerCount + 2);// if the containers already
// exist, this will fail
// Test listing with options
response = getApi().listContainers(
ListContainerOptions.Builder.afterMarker(
containerJsr330[0].substring(0, containerJsr330[0].length() - 1))
.maxResults(1));
assertEquals(response.size(), 1);
assertEquals(Iterables.get(response, 0).getName(), containerJsr330[0]);
response = getApi().listContainers(
ListContainerOptions.Builder.afterMarker(containerJsr330[0]).maxResults(1));
assertEquals(response.size(), 1);
assertEquals(Iterables.get(response, 0).getName(), containerJsr330[1]);
// Cleanup and test containers have been removed
assertTrue(getApi().deleteContainerIfEmpty(containerJsr330[0]));
assertTrue(getApi().deleteContainerIfEmpty(containerJsr330[1]));
response = getApi().listContainers();
// assertEquals(response.size(), initialContainerCount + 2);// if the containers already
// exist, this will fail
} finally {
returnContainer(containerPrefix);
}
}
@Test
public void testHeadAccountMetadata() throws Exception {
String containerPrefix = getContainerName();
String containerName = containerPrefix + ".testHeadAccountMetadata";
try {
AccountMetadata metadata = getApi().getAccountStatistics();
assertNotNull(metadata);
long initialContainerCount = metadata.getContainerCount();
assertTrue(getApi().createContainer(containerName));
metadata = getApi().getAccountStatistics();
assertNotNull(metadata);
assertTrue(metadata.getContainerCount() >= initialContainerCount);
assertTrue(getApi().deleteContainerIfEmpty(containerName));
} finally {
returnContainer(containerPrefix);
}
}
@Test
public void testPutContainers() throws Exception {
String containerName = getContainerName();
try {
String containerName1 = containerName + ".hello";
assertTrue(getApi().createContainer(containerName1));
// List only the container just created, using a marker with the container name less 1 char
Set<ContainerMetadata> response = getApi().listContainers(
ListContainerOptions.Builder.afterMarker(
containerName1.substring(0, containerName1.length() - 1)).maxResults(1));
assertNotNull(response);
assertEquals(response.size(), 1);
assertEquals(Iterables.get(response, 0).getName(), containerName + ".hello");
String containerName2 = containerName + "?should-be-illegal-question-char";
assert getApi().createContainer(containerName2);
// TODO: Should throw a specific exception, not UndeclaredThrowableException
try {
getApi().createContainer(containerName + "/illegal-slash-char");
fail("Should not be able to create container with illegal '/' character");
} catch (Exception e) {
}
assertTrue(getApi().deleteContainerIfEmpty(containerName1));
assertTrue(getApi().deleteContainerIfEmpty(containerName2));
} finally {
returnContainer(containerName);
}
}
public void testListContainerPath() throws InterruptedException, ExecutionException,
TimeoutException, IOException {
String containerName = getContainerName();
try {
String data = "foo";
getApi().putObject(containerName, newCFObject(data, "foo"));
getApi().putObject(containerName, newCFObject(data, "path/bar"));
PageSet<ObjectInfo> container = getApi().listObjects(containerName, underPath(""));
assert container.getNextMarker() == null;
assertEquals(container.size(), 1);
assertEquals(Iterables.get(container, 0).getName(), "foo");
container = getApi().listObjects(containerName, underPath("path"));
assert container.getNextMarker() == null;
assertEquals(container.size(), 1);
assertEquals(Iterables.get(container, 0).getName(), "path/bar");
} finally {
returnContainer(containerName);
}
}
@Test
public void testObjectOperations() throws Exception {
String containerName = getContainerName();
try {
// Test PUT with string data, ETag hash, and a piece of metadata
String data = "Here is my data";
String key = "object";
CFObject object = newCFObject(data, key);
byte[] md5 = object.getInfo().getHash();
String newEtag = getApi().putObject(containerName, object);
assertEquals(encryptionService.toHexString(md5), encryptionService.toHexString(object
.getInfo().getHash()));
// Test HEAD of missing object
assert getApi().getObjectInfo(containerName, "non-existent-object") == null;
// Test HEAD of object
MutableObjectInfoWithMetadata metadata = getApi().getObjectInfo(containerName,
object.getInfo().getName());
// TODO assertEquals(metadata.getName(), object.getMetadata().getName());
assertEquals(metadata.getBytes(), new Long(data.length()));
assertEquals(metadata.getContentType(), "text/plain");
assertEquals(encryptionService.toHexString(md5), encryptionService.toHexString(object
.getInfo().getHash()));
assertEquals(metadata.getHash(), encryptionService.fromHexString(newEtag));
assertEquals(metadata.getMetadata().entrySet().size(), 1);
assertEquals(metadata.getMetadata().get("metadata"), "metadata-value");
// // Test POST to update object's metadata
Map<String, String> userMetadata = Maps.newHashMap();
userMetadata.put("New-Metadata-1", "value-1");
userMetadata.put("New-Metadata-2", "value-2");
assertTrue(getApi().setObjectInfo(containerName, object.getInfo().getName(), userMetadata));
// Test GET of missing object
assert getApi().getObject(containerName, "non-existent-object") == null;
// Test GET of object (including updated metadata)
CFObject getBlob = getApi().getObject(containerName, object.getInfo().getName());
assertEquals(Utils.toStringAndClose(getBlob.getContent()), data);
// TODO assertEquals(getBlob.getName(), object.getMetadata().getName());
assertEquals(getBlob.getContentLength(), new Long(data.length()));
assertEquals(getBlob.getInfo().getContentType(), "text/plain");
assertEquals(encryptionService.toHexString(md5), encryptionService.toHexString(getBlob
.getInfo().getHash()));
assertEquals(encryptionService.fromHexString(newEtag), getBlob.getInfo().getHash());
assertEquals(getBlob.getInfo().getMetadata().entrySet().size(), 2);
assertEquals(getBlob.getInfo().getMetadata().get("new-metadata-1"), "value-1");
assertEquals(getBlob.getInfo().getMetadata().get("new-metadata-2"), "value-2");
// Test PUT with invalid ETag (as if object's data was corrupted in transit)
String correctEtag = newEtag;
String incorrectEtag = "0" + correctEtag.substring(1);
object.getInfo().setHash(encryptionService.fromHexString(incorrectEtag));
try {
getApi().putObject(containerName, object);
} catch (HttpResponseException e) {
assertEquals(e.getResponse().getStatusCode(), 422);
}
// Test PUT chunked/streamed upload with data of "unknown" length
ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes("UTF-8"));
CFObject blob = getApi().newCFObject();
blob.getInfo().setName("chunked-object");
blob.setPayload(bais);
newEtag = getApi().putObject(containerName, blob);
assertEquals(encryptionService.toHexString(md5), encryptionService.toHexString(getBlob
.getInfo().getHash()));
// Test GET with options
// Non-matching ETag
try {
getApi().getObject(containerName, object.getInfo().getName(),
GetOptions.Builder.ifETagDoesntMatch(newEtag));
} catch (HttpResponseException e) {
assertEquals(e.getResponse().getStatusCode(), 304);
}
// Matching ETag
getBlob = getApi().getObject(containerName, object.getInfo().getName(),
GetOptions.Builder.ifETagMatches(newEtag));
assertEquals(getBlob.getInfo().getHash(), encryptionService.fromHexString(newEtag));
getBlob = getApi().getObject(containerName, object.getInfo().getName(),
GetOptions.Builder.startAt(8));
assertEquals(Utils.toStringAndClose(getBlob.getContent()), data.substring(8));
} finally {
returnContainer(containerName);
}
}
private CFObject newCFObject(String data, String key) throws IOException {
CFObject object = getApi().newCFObject();
object.getInfo().setName(key);
object.setPayload(data);
object.generateMD5();
object.getInfo().setContentType("text/plain");
object.getInfo().getMetadata().put("Metadata", "metadata-value");
return object;
}
}
| true | true | public void testCDNOperations() throws Exception {
final long minimumTTL = 60 * 60; // The minimum TTL is 1 hour
// Create two new containers for testing
final String containerNameWithCDN = getContainerName();
final String containerNameWithoutCDN = getContainerName();
try {
try {
getApi().disableCDN(containerNameWithCDN);
getApi().disableCDN(containerNameWithoutCDN);
} catch (Exception e) {
}
ContainerCDNMetadata cdnMetadata = null;
// Enable CDN with PUT for one container
final URI cdnUri = getApi().enableCDN(containerNameWithCDN);
assertTrue(cdnUri != null);
// Confirm CDN is enabled via HEAD request and has default TTL
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getCDNUri(), cdnUri);
final long initialTTL = cdnMetadata.getTTL();
try {
cdnMetadata = getApi().getCDNMetadata(containerNameWithoutCDN);
assert cdnMetadata == null || !cdnMetadata.isCDNEnabled() : containerNameWithoutCDN
+ " should not have metadata";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
try {
cdnMetadata = getApi().getCDNMetadata("DoesNotExist");
assert false : "should not exist";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
// List CDN metadata for containers, and ensure all CDN info is available for enabled
// container
Set<ContainerCDNMetadata> cdnMetadataList = getApi().listCDNContainers();
assertTrue(cdnMetadataList.size() >= 1);
assertTrue(cdnMetadataList.contains(new ContainerCDNMetadata(containerNameWithCDN, true,
initialTTL, cdnUri)));
// Test listing with options
cdnMetadataList = getApi()
.listCDNContainers(ListCdnContainerOptions.Builder.enabledOnly());
assertTrue(Iterables.all(cdnMetadataList, new Predicate<ContainerCDNMetadata>() {
public boolean apply(ContainerCDNMetadata cdnMetadata) {
return cdnMetadata.isCDNEnabled();
}
}));
cdnMetadataList = getApi().listCDNContainers(
ListCdnContainerOptions.Builder.afterMarker(
containerNameWithCDN.substring(0, containerNameWithCDN.length() - 1))
.maxResults(1));
assertEquals(cdnMetadataList.size(), 1);
// Enable CDN with PUT for the same container, this time with a custom TTL
long ttl = 4000;
getApi().enableCDN(containerNameWithCDN, ttl);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), ttl);
// Check POST by updating TTL settings
ttl = minimumTTL;
getApi().updateCDN(containerNameWithCDN, minimumTTL);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), minimumTTL);
// Confirm that minimum allowed value for TTL is 3600, lower values are ignored.
getApi().updateCDN(containerNameWithCDN, 3599L);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertEquals(cdnMetadata.getTTL(), minimumTTL); // Note that TTL is 3600 here, not 3599
// Disable CDN with POST
assertTrue(getApi().disableCDN(containerNameWithCDN));
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertEquals(cdnMetadata.isCDNEnabled(), false);
} finally {
recycleContainer(containerNameWithCDN);
recycleContainer(containerNameWithoutCDN);
}
}
| public void testCDNOperations() throws Exception {
final long minimumTTL = 60 * 60; // The minimum TTL is 1 hour
// Create two new containers for testing
final String containerNameWithCDN = getContainerName();
final String containerNameWithoutCDN = getContainerName();
try {
try {
getApi().disableCDN(containerNameWithCDN);
getApi().disableCDN(containerNameWithoutCDN);
} catch (Exception e) {
}
ContainerCDNMetadata cdnMetadata = null;
// Enable CDN with PUT for one container
final URI cdnUri = getApi().enableCDN(containerNameWithCDN);
assertTrue(cdnUri != null);
// Confirm CDN is enabled via HEAD request and has default TTL
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getCDNUri(), cdnUri);
final long initialTTL = cdnMetadata.getTTL();
try {
cdnMetadata = getApi().getCDNMetadata(containerNameWithoutCDN);
assert cdnMetadata == null || !cdnMetadata.isCDNEnabled() : containerNameWithoutCDN
+ " should not have metadata";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
try {
cdnMetadata = getApi().getCDNMetadata("DoesNotExist");
assert false : "should not exist";
} catch (ContainerNotFoundException e) {
} catch (HttpResponseException e) {
}
// List CDN metadata for containers, and ensure all CDN info is available for enabled
// container
Set<ContainerCDNMetadata> cdnMetadataList = getApi().listCDNContainers();
assertTrue(cdnMetadataList.size() >= 1);
assertTrue(cdnMetadataList.contains(new ContainerCDNMetadata(containerNameWithCDN, true,
initialTTL, cdnUri)));
// Test listing with options
cdnMetadataList = getApi()
.listCDNContainers(ListCdnContainerOptions.Builder.enabledOnly());
assertTrue(Iterables.all(cdnMetadataList, new Predicate<ContainerCDNMetadata>() {
public boolean apply(ContainerCDNMetadata cdnMetadata) {
return cdnMetadata.isCDNEnabled();
}
}));
cdnMetadataList = getApi().listCDNContainers(
ListCdnContainerOptions.Builder.afterMarker(
containerNameWithCDN.substring(0, containerNameWithCDN.length() - 1))
.maxResults(1));
assertEquals(cdnMetadataList.size(), 1);
// Enable CDN with PUT for the same container, this time with a custom TTL
long ttl = 4000;
getApi().enableCDN(containerNameWithCDN, ttl);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), ttl);
// Check POST by updating TTL settings
ttl = minimumTTL;
getApi().updateCDN(containerNameWithCDN, minimumTTL);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertTrue(cdnMetadata.isCDNEnabled());
assertEquals(cdnMetadata.getTTL(), minimumTTL);
// Confirm that minimum allowed value for TTL is 3600, lower values are ignored.
getApi().updateCDN(containerNameWithCDN, 3599L);
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertEquals(cdnMetadata.getTTL(), 3599L);
// Disable CDN with POST
assertTrue(getApi().disableCDN(containerNameWithCDN));
cdnMetadata = getApi().getCDNMetadata(containerNameWithCDN);
assertEquals(cdnMetadata.isCDNEnabled(), false);
} finally {
recycleContainer(containerNameWithCDN);
recycleContainer(containerNameWithoutCDN);
}
}
|
diff --git a/src/com/android/phone/GsmUmtsOptions.java b/src/com/android/phone/GsmUmtsOptions.java
index 1a4de8dd..c75fff70 100644
--- a/src/com/android/phone/GsmUmtsOptions.java
+++ b/src/com/android/phone/GsmUmtsOptions.java
@@ -1,106 +1,107 @@
/*
* Copyright (C) 2008, 2011 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.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import static com.android.internal.telephony.MSimConstants.SUBSCRIPTION_KEY;
/**
* List of Network-specific settings screens.
*/
public class GsmUmtsOptions {
private static final String LOG_TAG = "GsmUmtsOptions";
private PreferenceScreen mButtonAPNExpand;
private PreferenceScreen mButtonOperatorSelectionExpand;
private CheckBoxPreference mButtonPrefer2g;
private static final String BUTTON_APN_EXPAND_KEY = "button_apn_key";
private static final String BUTTON_OPERATOR_SELECTION_EXPAND_KEY = "button_carrier_sel_key";
private static final String BUTTON_PREFER_2G_KEY = "button_prefer_2g_key";
private PreferenceActivity mPrefActivity;
private PreferenceScreen mPrefScreen;
private int mSubscription = 0;
private Phone mPhone;
public GsmUmtsOptions(PreferenceActivity prefActivity, PreferenceScreen prefScreen) {
this(prefActivity, prefScreen, 0);
}
public GsmUmtsOptions(PreferenceActivity prefActivity,
PreferenceScreen prefScreen, int subscription) {
mPrefActivity = prefActivity;
mPrefScreen = prefScreen;
mSubscription = subscription;
mPhone = PhoneApp.getInstance().getPhone(mSubscription);
create();
}
protected void create() {
mPrefActivity.addPreferencesFromResource(R.xml.gsm_umts_options);
mButtonAPNExpand = (PreferenceScreen) mPrefScreen.findPreference(BUTTON_APN_EXPAND_KEY);
mButtonAPNExpand.getIntent().putExtra(SUBSCRIPTION_KEY, mSubscription);
mButtonPrefer2g = (CheckBoxPreference) mPrefScreen.findPreference(BUTTON_PREFER_2G_KEY);
Use2GOnlyCheckBoxPreference.updatePhone(mPhone);
enableScreen();
}
public void enableScreen() {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
log("Not a GSM phone");
mButtonPrefer2g.setEnabled(false);
}
mButtonOperatorSelectionExpand =
(PreferenceScreen) mPrefScreen.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
+ mButtonOperatorSelectionExpand.getIntent().putExtra(SUBSCRIPTION_KEY, mSubscription);
if (mButtonOperatorSelectionExpand != null) {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (!mPhone.isManualNetSelAllowed()) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) {
if (mPhone.isCspPlmnEnabled()) {
log("[CSP] Enabling Operator Selection menu.");
mButtonOperatorSelectionExpand.setEnabled(true);
} else {
log("[CSP] Disabling Operator Selection menu.");
mPrefScreen.removePreference(mPrefScreen
.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY));
}
}
}
}
public boolean preferenceTreeClick(Preference preference) {
if (preference.getKey().equals(BUTTON_PREFER_2G_KEY)) {
log("preferenceTreeClick: return true");
return true;
}
log("preferenceTreeClick: return false");
return false;
}
protected void log(String s) {
android.util.Log.d(LOG_TAG, s);
}
}
| true | true | public void enableScreen() {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
log("Not a GSM phone");
mButtonPrefer2g.setEnabled(false);
}
mButtonOperatorSelectionExpand =
(PreferenceScreen) mPrefScreen.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
if (mButtonOperatorSelectionExpand != null) {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (!mPhone.isManualNetSelAllowed()) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) {
if (mPhone.isCspPlmnEnabled()) {
log("[CSP] Enabling Operator Selection menu.");
mButtonOperatorSelectionExpand.setEnabled(true);
} else {
log("[CSP] Disabling Operator Selection menu.");
mPrefScreen.removePreference(mPrefScreen
.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY));
}
}
}
}
| public void enableScreen() {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
log("Not a GSM phone");
mButtonPrefer2g.setEnabled(false);
}
mButtonOperatorSelectionExpand =
(PreferenceScreen) mPrefScreen.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
mButtonOperatorSelectionExpand.getIntent().putExtra(SUBSCRIPTION_KEY, mSubscription);
if (mButtonOperatorSelectionExpand != null) {
if (mPhone.getPhoneType() != Phone.PHONE_TYPE_GSM) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (!mPhone.isManualNetSelAllowed()) {
mButtonOperatorSelectionExpand.setEnabled(false);
} else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) {
if (mPhone.isCspPlmnEnabled()) {
log("[CSP] Enabling Operator Selection menu.");
mButtonOperatorSelectionExpand.setEnabled(true);
} else {
log("[CSP] Disabling Operator Selection menu.");
mPrefScreen.removePreference(mPrefScreen
.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY));
}
}
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/callbacks/QueryDoneReadDir.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/callbacks/QueryDoneReadDir.java
index 742e95d5d..84e7831a7 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/callbacks/QueryDoneReadDir.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/callbacks/QueryDoneReadDir.java
@@ -1,93 +1,90 @@
/*******************************************************************************
* Copyright (c) 2011 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.filesystem.internal.callbacks;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.services.IFileSystem;
import org.eclipse.tcf.services.IFileSystem.DirEntry;
import org.eclipse.tcf.services.IFileSystem.DoneClose;
import org.eclipse.tcf.services.IFileSystem.DoneReadDir;
import org.eclipse.tcf.services.IFileSystem.FileSystemException;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.tcf.filesystem.activator.UIPlugin;
import org.eclipse.tcf.te.tcf.filesystem.model.FSTreeNode;
/**
* The callback handler that handles the event when a directory is read.
*/
public class QueryDoneReadDir implements DoneReadDir {
// The tcf channel.
IChannel channel;
// The file system service.
IFileSystem service;
// The file handle of the parent directory.
IFileSystem.IFileHandle handle;
// The parent node being queried.
FSTreeNode parentNode;
// The callback object.
ICallback callback;
/**
* Create an instance with parameters to initialize the fields.
*
* @param channel The tcf channel.
* @param service The file system service.
* @param handle The directory's file handle.
* @param parentNode The parent directory.
*/
public QueryDoneReadDir(ICallback callback, IChannel channel, IFileSystem service, IFileSystem.IFileHandle handle, FSTreeNode parentNode) {
this.callback = callback;
this.channel = channel;
this.service = service;
this.handle = handle;
this.parentNode = parentNode;
}
/*
* (non-Javadoc)
* @see org.eclipse.tcf.services.IFileSystem.DoneReadDir#doneReadDir(org.eclipse.tcf.protocol.IToken, org.eclipse.tcf.services.IFileSystem.FileSystemException, org.eclipse.tcf.services.IFileSystem.DirEntry[], boolean)
*/
@Override
public void doneReadDir(IToken token, FileSystemException error, DirEntry[] entries, boolean eof) {
// Process the returned data
if (error == null) {
if (entries != null && entries.length > 0) {
for (DirEntry entry : entries) {
FSTreeNode node = new FSTreeNode(parentNode, entry, false);
parentNode.addChild(node);
}
}
- else {
- parentNode.clearChildren();
- }
if (eof) {
// Close the handle and channel if EOF is signaled or an error occurred.
service.close(handle, new DoneClose() {
@Override
public void doneClose(IToken token, FileSystemException error) {
if(callback != null) {
IStatus status = error == null ? Status.OK_STATUS : new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}});
}
else {
// And invoke ourself again
service.readdir(handle, new QueryDoneReadDir(callback, channel, service, handle, parentNode));
}
} else if(callback != null) {
Status status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}
}
| true | true | public void doneReadDir(IToken token, FileSystemException error, DirEntry[] entries, boolean eof) {
// Process the returned data
if (error == null) {
if (entries != null && entries.length > 0) {
for (DirEntry entry : entries) {
FSTreeNode node = new FSTreeNode(parentNode, entry, false);
parentNode.addChild(node);
}
}
else {
parentNode.clearChildren();
}
if (eof) {
// Close the handle and channel if EOF is signaled or an error occurred.
service.close(handle, new DoneClose() {
@Override
public void doneClose(IToken token, FileSystemException error) {
if(callback != null) {
IStatus status = error == null ? Status.OK_STATUS : new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}});
}
else {
// And invoke ourself again
service.readdir(handle, new QueryDoneReadDir(callback, channel, service, handle, parentNode));
}
} else if(callback != null) {
Status status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}
| public void doneReadDir(IToken token, FileSystemException error, DirEntry[] entries, boolean eof) {
// Process the returned data
if (error == null) {
if (entries != null && entries.length > 0) {
for (DirEntry entry : entries) {
FSTreeNode node = new FSTreeNode(parentNode, entry, false);
parentNode.addChild(node);
}
}
if (eof) {
// Close the handle and channel if EOF is signaled or an error occurred.
service.close(handle, new DoneClose() {
@Override
public void doneClose(IToken token, FileSystemException error) {
if(callback != null) {
IStatus status = error == null ? Status.OK_STATUS : new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}});
}
else {
// And invoke ourself again
service.readdir(handle, new QueryDoneReadDir(callback, channel, service, handle, parentNode));
}
} else if(callback != null) {
Status status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), error.getLocalizedMessage(), error);
callback.done(this, status);
}
}
|
diff --git a/src/com/freshbourne/thesis/Select.java b/src/com/freshbourne/thesis/Select.java
index 4248196..88b3a6d 100644
--- a/src/com/freshbourne/thesis/Select.java
+++ b/src/com/freshbourne/thesis/Select.java
@@ -1,19 +1,19 @@
package com.freshbourne.thesis;
public abstract class Select {
private int column;
public Select(int column){
this.column = column;
}
public boolean select(String[] a){
- if( a.length < column )
+ if( a.length <= column )
return false;
return select(a[column]);
}
public abstract boolean select(String s);
}
| true | true | public boolean select(String[] a){
if( a.length < column )
return false;
return select(a[column]);
}
| public boolean select(String[] a){
if( a.length <= column )
return false;
return select(a[column]);
}
|
diff --git a/src/plagiatssoftware/RabinKarpComparer.java b/src/plagiatssoftware/RabinKarpComparer.java
index fa014b9..d42ecfb 100644
--- a/src/plagiatssoftware/RabinKarpComparer.java
+++ b/src/plagiatssoftware/RabinKarpComparer.java
@@ -1,357 +1,358 @@
package plagiatssoftware;
import java.util.ArrayList;
import java.util.Random;
public class RabinKarpComparer
{
// Basis-Wert: 257 fuer Anzahl Buchstaben des Alphabets
private final int BASE = 257;
// initialer Modulo-Wert fuer die Hash-Funktion. Muss eine 2er Potenz sein
private int q = 1024;
// damit q-1 nicht bei jeder Moduloberechnung erneut berechnet werden muss
private int reducedQ = q - 1;
// ab wievielen false matches soll q neu gewaehlt werden? 0 = Zufallsmodus
// ausschalten
private final int MAX_FALSEMATCHES = 1000;
// Min und Max von q festlegen, z. b. 2^10 - 2^31 Integer: Max 2^31
private final int MIN_Q = 10;
private final int MAX_Q = 31;
private int _shiftFactor;
private int _falseMatches;
private int _minQResult;
private int _qDiff;
/**
* Beinhaltet Funktionen zum Durchsuchen von Strings mithilfe des RabinKarpAlgorithmus.
*
* @author Andreas Hahn
*/
public RabinKarpComparer()
{
// Minimum fuer q berechnen, pow ist relativ rechenzeitintensiv
_minQResult = (int) Math.pow(2, MIN_Q);
_qDiff = MAX_Q - MIN_Q + 1;
}
/**
* Wird ausgeloest wenn alle Suchen fertig sind.
*
* @author Andreas
*/
public interface OnSearchFinishedListener
{
abstract void onSearchFinished(ArrayList<String> searchStrings, ArrayList<ArrayList<String>> searchResults);
}
/**
* Die Funktion liefert alle SearchResults f�r die W�rter im searchText-Array.
*
* @param searchText
* Array mit allen zusammenh�ngenden Texte/W�rter die gefunden werden sollen.
* @param completeString
* Text der Durchsucht werden soll
* @return ArrayList mit den SearchResults
*/
public ArrayList<SearchResult> search(String[] searchText, StringBuilder completeString, String url)
{
return search(searchText, completeString, url, 0);
}
/**
* Die Funktion liefert alle SearchResults f�r die W�rter im searchText-Array.
*
* @param searchText
* Array mit allen zusammenh�ngenden Texte/W�rter die gefunden werden sollen.
* @param completeString
* Text der Durchsucht werden soll
* @return ArrayList mit den SearchResults
*/
public ArrayList<SearchResult> search(String[] searchText, StringBuilder completeString, String url, int startReihefolge)
{
ArrayList<SearchResult> result = new ArrayList<SearchResult>();
int minNumWords = 5;
SearchResult lastNegativSearchResult = null;
for (int passedWords = 0; passedWords < searchText.length; passedWords++)
{
String searchString = "";
int numWords;
for (numWords = 0; (numWords < minNumWords); numWords++)
{
if (passedWords + numWords < searchText.length)
{
searchString += " " + searchText[passedWords + numWords];
}
else
{
break;
}
}
+ searchString = searchString.trim();
int i = 0;
if (!searchString.equals(""))
{
SearchResult searchResult = new SearchResult(0, searchString, "", url, passedWords + startReihefolge);
while ((i = searchRabinKarb(searchString, completeString, i)) != 0)
{
searchResult.setplagiatsText(resultWithOverhead(completeString, i, searchString.length(), 0, 0));
searchResult.setorginalText(searchString);
if (passedWords + minNumWords >= searchText.length)
{
break;
}
else
{
searchString += " " + searchText[passedWords + minNumWords];
passedWords++;
}
}
if (searchResult.getplagiatsText().length() == 0)
{
if (lastNegativSearchResult == null)
{
// Legt ein neues Searchresult mit dem ersten nicht gefunden Wort an.
String firstString = "";
if (passedWords > 0)
{
firstString += searchText[passedWords - 1] + " ";
}
firstString += searchText[passedWords];
lastNegativSearchResult = new SearchResult(0, firstString, "", "", passedWords + startReihefolge);
}
else
{
// Baut das Searchresult mit nicht gefundenen Woertern zusammen. ([passedWords - numWords - 1] =
// 1. Wort im Suchstring)
lastNegativSearchResult.setorginalText(lastNegativSearchResult.getorginalText() + " " + searchText[passedWords]);
}
}
else
{
passedWords += (minNumWords - 1);
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
result.add(searchResult);
}
}
}
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
return result;
}
/**
* Schneidet einen Text aus dem gesamten String mit angegebenem Overhead aus.
*
* @param completeString
* Kompletter String
* @param position
* Startposition
* @param searchLength
* Laenge des String der ausgeschnitten werden soll
* @param overheadBefore
* Zeichen die vor dem String stehen bleiben sollen
* @param overheadAfter
* Zeichen die nach dem String stehen bleiben sollen
* @return Ausgeschnittener String mit angegebenem Overhead
*/
private String resultWithOverhead(StringBuilder completeString, int position, int searchLength, int overheadBefore, int overheadAfter)
{
String result = completeString.toString();
int start = position;
int after = position + searchLength;
boolean cuttedAfter = false;
boolean cuttedBefore = false;
if ((completeString.length() - (position + searchLength)) > overheadAfter)
{
after += overheadAfter;
cuttedAfter = true;
}
if (position > overheadBefore)
{
start -= overheadBefore;
cuttedBefore = true;
}
result = result.substring(start, after);
// Zeilenumbrueche entfernen
result = result.replace("\r\n", " ");
result = result.replace("\n", " ");
if (cuttedBefore)
{
result = "[..]" + result;
}
if (cuttedAfter)
{
result += "[..]";
}
return result;
}
/**
* Liefert die Position des ersten Vorkommens ab einer bestimmten Position.
*
* @param searchString
* String nach dem gesucht werden soll.
* @param completeString
* StringBuilder der durchsucht werden soll.
* @param startPosition
* Position ab der gesucht werden soll.
* @return Position des ersten Vorkommens
*/
private int searchRabinKarb(String searchString, StringBuilder completeString, int startPosition)
{
int result = 0;
int intRandomNumber = 0;
// Laenge des gesamten Textes
int intLengthComplete = completeString.length();
// Laenge des Suchtextes
int intLengthSearchString = searchString.length();
int intLengthDifference = intLengthComplete - intLengthSearchString;
if (intLengthComplete >= startPosition + intLengthSearchString)
{
// hash-Wert der ersten Zeichen des gesamten Textes
int intHashStringPart = hashFirst(completeString.substring(startPosition, startPosition + intLengthSearchString), intLengthSearchString);
// Wert des Musters
int intHashSearch = hashFirst(searchString, intLengthSearchString);
// da die Zufallszahlenerzeugung fuer die rand. RK-Algorithmus
// essentiell
// ist, messen wir die Instanziierung des Random-Objekts natuerlich
// jeweils mit
Random randomNumbers = new Random();
// in falseMatches werden die Anzahl "False Matches" gespeichert, also
// die Kollisionen
_falseMatches = 0;
// solange Text noch nicht komplett durchlaufen
for (int i = startPosition; i <= intLengthDifference; i++)
{
// wenn Hashwert des Musters mit dem Hashwert des Textausschnittes
// uebereinstimmt...
if (intHashStringPart == intHashSearch)
{
// und die Strings an der Stelle auch uebereinstimmen
if (completeString.substring(i, i + intLengthSearchString).equals(searchString))
{
// Ue�bereinstimmung gefunden
result = i;
break;
}
else
{
_falseMatches++;
if (MAX_FALSEMATCHES != 0)
{
if (_falseMatches == MAX_FALSEMATCHES)
{
// waehle q neu - eine Zweierpotenz zwischen 2^minQ
// bis 2^maxQ
intRandomNumber = randomNumbers.nextInt(_qDiff) + MIN_Q;
// Schiebeoperatoren sind schneller
q = _minQResult << (intRandomNumber - MIN_Q);
reducedQ = q - 1;
// false matches zuruecksetzen
_falseMatches = 0;
// mit neuem q muss Hash fuer Muster und
// Gesamtstring
// auch neu berechnet werden
intHashSearch = hashFirst(searchString, intLengthSearchString);
intHashStringPart = hashFirst(completeString.substring(i, i + intLengthSearchString), intLengthSearchString);
}
}
}
}
// Bereichsueberlaufsfehler abfangen
if ((i + intLengthSearchString + 1) > intLengthComplete) break;
// naechsten Hashwert bestimmen
intHashStringPart = hash(intHashStringPart, i + 1, intLengthSearchString, completeString);
}
}
return result;
}
/**
* Berechnung des 1. Hashwertes, von dem aus im Anschluss die neuen Hashes weitergerollt werden. Siehe {@link #hash}
*
* @param searchText
* @param patternLength
* @return
*/
private int hashFirst(String searchText, int patternLength)
{
int result = 0;
int reducedBase = 1;
for (int i = (patternLength - 1); i >= 0; i--)
{
if (i != (patternLength - 1)) reducedBase = bitModulo(reducedBase * BASE);
result += bitModulo(reducedBase * (int) searchText.charAt(i));
result = bitModulo(result);
}
_shiftFactor = reducedBase;
result = bitModulo(result);
return result;
}
/**
* Bitweise Moduloberechnung. Daher wird fuer q eine 2er Potenz benoetigt
*
* @param x
* @return
*/
private int bitModulo(int x)
{
return (x & reducedQ);
}
/**
* Rollende HashFunktion
*
* @param oldHashValue
* @param startPos
* @param patternLength
* @return
*/
private int hash(int oldHashValue, int startPos, int patternLength, StringBuilder completeString)
{
int result = 0;
// wenn die gesamte Stringlaenge kleiner als die des Musters ist, kann
// das Muster nicht vorkommen
if (completeString.length() >= patternLength)
{
int intValue;
int intValue2;
// das erste Zeichen von links bestimmen, das wegfaellt
intValue = (int) completeString.charAt(startPos - 1);
// das hinzukommende Zeichen von rechts bestimmen
intValue2 = (int) completeString.charAt(startPos + patternLength - 1);
result = ((oldHashValue - (intValue * _shiftFactor)) * BASE) + intValue2;
result = bitModulo(result);
}
return result;
}
}
| true | true | public ArrayList<SearchResult> search(String[] searchText, StringBuilder completeString, String url, int startReihefolge)
{
ArrayList<SearchResult> result = new ArrayList<SearchResult>();
int minNumWords = 5;
SearchResult lastNegativSearchResult = null;
for (int passedWords = 0; passedWords < searchText.length; passedWords++)
{
String searchString = "";
int numWords;
for (numWords = 0; (numWords < minNumWords); numWords++)
{
if (passedWords + numWords < searchText.length)
{
searchString += " " + searchText[passedWords + numWords];
}
else
{
break;
}
}
int i = 0;
if (!searchString.equals(""))
{
SearchResult searchResult = new SearchResult(0, searchString, "", url, passedWords + startReihefolge);
while ((i = searchRabinKarb(searchString, completeString, i)) != 0)
{
searchResult.setplagiatsText(resultWithOverhead(completeString, i, searchString.length(), 0, 0));
searchResult.setorginalText(searchString);
if (passedWords + minNumWords >= searchText.length)
{
break;
}
else
{
searchString += " " + searchText[passedWords + minNumWords];
passedWords++;
}
}
if (searchResult.getplagiatsText().length() == 0)
{
if (lastNegativSearchResult == null)
{
// Legt ein neues Searchresult mit dem ersten nicht gefunden Wort an.
String firstString = "";
if (passedWords > 0)
{
firstString += searchText[passedWords - 1] + " ";
}
firstString += searchText[passedWords];
lastNegativSearchResult = new SearchResult(0, firstString, "", "", passedWords + startReihefolge);
}
else
{
// Baut das Searchresult mit nicht gefundenen Woertern zusammen. ([passedWords - numWords - 1] =
// 1. Wort im Suchstring)
lastNegativSearchResult.setorginalText(lastNegativSearchResult.getorginalText() + " " + searchText[passedWords]);
}
}
else
{
passedWords += (minNumWords - 1);
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
result.add(searchResult);
}
}
}
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
return result;
}
| public ArrayList<SearchResult> search(String[] searchText, StringBuilder completeString, String url, int startReihefolge)
{
ArrayList<SearchResult> result = new ArrayList<SearchResult>();
int minNumWords = 5;
SearchResult lastNegativSearchResult = null;
for (int passedWords = 0; passedWords < searchText.length; passedWords++)
{
String searchString = "";
int numWords;
for (numWords = 0; (numWords < minNumWords); numWords++)
{
if (passedWords + numWords < searchText.length)
{
searchString += " " + searchText[passedWords + numWords];
}
else
{
break;
}
}
searchString = searchString.trim();
int i = 0;
if (!searchString.equals(""))
{
SearchResult searchResult = new SearchResult(0, searchString, "", url, passedWords + startReihefolge);
while ((i = searchRabinKarb(searchString, completeString, i)) != 0)
{
searchResult.setplagiatsText(resultWithOverhead(completeString, i, searchString.length(), 0, 0));
searchResult.setorginalText(searchString);
if (passedWords + minNumWords >= searchText.length)
{
break;
}
else
{
searchString += " " + searchText[passedWords + minNumWords];
passedWords++;
}
}
if (searchResult.getplagiatsText().length() == 0)
{
if (lastNegativSearchResult == null)
{
// Legt ein neues Searchresult mit dem ersten nicht gefunden Wort an.
String firstString = "";
if (passedWords > 0)
{
firstString += searchText[passedWords - 1] + " ";
}
firstString += searchText[passedWords];
lastNegativSearchResult = new SearchResult(0, firstString, "", "", passedWords + startReihefolge);
}
else
{
// Baut das Searchresult mit nicht gefundenen Woertern zusammen. ([passedWords - numWords - 1] =
// 1. Wort im Suchstring)
lastNegativSearchResult.setorginalText(lastNegativSearchResult.getorginalText() + " " + searchText[passedWords]);
}
}
else
{
passedWords += (minNumWords - 1);
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
result.add(searchResult);
}
}
}
if (lastNegativSearchResult != null)
{
result.add(lastNegativSearchResult);
lastNegativSearchResult = null;
}
return result;
}
|
diff --git a/src/main/java/com/google/gerrit/client/patches/AbstractPatchContentTable.java b/src/main/java/com/google/gerrit/client/patches/AbstractPatchContentTable.java
index 438d7a22e..5f5236d7b 100644
--- a/src/main/java/com/google/gerrit/client/patches/AbstractPatchContentTable.java
+++ b/src/main/java/com/google/gerrit/client/patches/AbstractPatchContentTable.java
@@ -1,576 +1,577 @@
// 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.google.gerrit.client.patches;
import com.google.gerrit.client.FormatUtil;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.PatchTable;
import com.google.gerrit.client.changes.PublishCommentScreen;
import com.google.gerrit.client.changes.Util;
import com.google.gerrit.client.data.AccountInfoCache;
import com.google.gerrit.client.data.PatchScript;
import com.google.gerrit.client.data.SparseFileContent;
import com.google.gerrit.client.reviewdb.Patch;
import com.google.gerrit.client.reviewdb.PatchLineComment;
import com.google.gerrit.client.reviewdb.PatchSet;
import com.google.gerrit.client.ui.ComplexDisclosurePanel;
import com.google.gerrit.client.ui.NavigationTable;
import com.google.gerrit.client.ui.NeedsSignInKeyCommand;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.shared.HandlerRegistration;
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.FlexTable;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwtexpui.globalkey.client.GlobalKey;
import com.google.gwtexpui.globalkey.client.KeyCommand;
import com.google.gwtexpui.globalkey.client.KeyCommandSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractPatchContentTable extends NavigationTable<Object> {
private static final long AGE = 7 * 24 * 60 * 60 * 1000L;
protected PatchTable fileList;
protected AccountInfoCache accountCache = AccountInfoCache.empty();
protected Patch.Key patchKey;
protected PatchSet.Id idSideA;
protected PatchSet.Id idSideB;
protected boolean onlyOneHunk;
protected String formatLanguage;
private final Timestamp aged =
new Timestamp(System.currentTimeMillis() - AGE);
private final KeyCommandSet keysComment;
private HandlerRegistration regComment;
protected AbstractPatchContentTable() {
keysNavigation.add(new PrevKeyCommand(0, 'k', PatchUtil.C.linePrev()));
keysNavigation.add(new NextKeyCommand(0, 'j', PatchUtil.C.lineNext()));
keysNavigation.add(new PrevChunkKeyCmd(0, 'p', PatchUtil.C.chunkPrev()));
keysNavigation.add(new NextChunkKeyCmd(0, 'n', PatchUtil.C.chunkNext()));
if (Gerrit.isSignedIn()) {
keysAction.add(new InsertCommentCommand(0, 'c', PatchUtil.C
.commentInsert()));
keysAction.add(new PublishCommentsKeyCommand(0, 'r', Util.C
.keyPublishComments()));
// See CommentEditorPanel
//
keysComment = new KeyCommandSet(PatchUtil.C.commentEditorSet());
keysComment.add(new NoOpKeyCommand(KeyCommand.M_CTRL, 's', PatchUtil.C
.commentSaveDraft()));
keysComment.add(new NoOpKeyCommand(KeyCommand.M_CTRL, 'd', PatchUtil.C
.commentDiscard()));
keysComment.add(new NoOpKeyCommand(0, KeyCodes.KEY_ESCAPE, PatchUtil.C
.commentCancelEdit()));
} else {
keysComment = null;
}
table.setStyleName("gerrit-PatchContentTable");
}
void notifyDraftDelta(final int delta) {
if (fileList != null) {
fileList.notifyDraftDelta(patchKey, delta);
}
}
@Override
public void setRegisterKeys(final boolean on) {
super.setRegisterKeys(on);
if (on && keysComment != null && regComment == null) {
regComment = GlobalKey.add(this, keysComment);
} else if (!on && regComment != null) {
regComment.removeHandler();
regComment = null;
}
}
public void display(final Patch.Key k, final PatchSet.Id a,
final PatchSet.Id b, final PatchScript s) {
patchKey = k;
idSideA = a;
idSideB = b;
final String pathName = patchKey.get();
int ext = pathName.lastIndexOf('.');
formatLanguage = ext > 0 ? pathName.substring(ext + 1).toLowerCase() : null;
render(s);
}
protected abstract void render(PatchScript script);
protected abstract void onInsertComment(PatchLine pl);
public abstract void display(CommentDetail comments);
@Override
protected MyFlexTable createFlexTable() {
return new DoubleClickFlexTable();
}
@Override
protected Object getRowItemKey(final Object item) {
return null;
}
protected void initScript(final PatchScript script) {
if (script.getEdits().size() == 1) {
final SparseFileContent a = script.getA();
final SparseFileContent b = script.getB();
onlyOneHunk = a.size() == 0 || b.size() == 0;
} else {
onlyOneHunk = false;
}
}
private boolean isChunk(final int row) {
final Object o = getRowItem(row);
if (!onlyOneHunk && o instanceof PatchLine) {
final PatchLine pl = (PatchLine) o;
switch (pl.getType()) {
case DELETE:
case INSERT:
case REPLACE:
return true;
}
} else if (o instanceof CommentList) {
return true;
}
return false;
}
private int findChunkStart(int row) {
while (0 <= row && isChunk(row)) {
row--;
}
return row + 1;
}
private int findChunkEnd(int row) {
final int max = table.getRowCount();
while (row < max && isChunk(row)) {
row++;
}
return row - 1;
}
private static int oneBefore(final int begin) {
return 1 <= begin ? begin - 1 : begin;
}
private int oneAfter(final int end) {
return end + 1 < table.getRowCount() ? end + 1 : end;
}
private void moveToPrevChunk(int row) {
while (0 <= row && isChunk(row)) {
row--;
}
for (; 0 <= row; row--) {
if (isChunk(row)) {
final int start = findChunkStart(row);
movePointerTo(start, false);
scrollIntoView(oneBefore(start), oneAfter(row));
return;
}
}
// No prior hunk found? Try to hit the first line in the file.
//
for (row = 0; row < table.getRowCount(); row++) {
if (getRowItem(row) != null) {
movePointerTo(row);
break;
}
}
}
private void moveToNextChunk(int row) {
final int max = table.getRowCount();
while (row < max && isChunk(row)) {
row++;
}
for (; row < max; row++) {
if (isChunk(row)) {
movePointerTo(row, false);
scrollIntoView(oneBefore(row), oneAfter(findChunkEnd(row)));
return;
}
}
// No next hunk found? Try to hit the last line in the file.
//
for (row = max - 1; row >= 0; row--) {
if (getRowItem(row) != null) {
movePointerTo(row);
break;
}
}
}
/** Invoked when the user clicks on a table cell. */
protected abstract void onCellDoubleClick(int row, int column);
/**
* Invokes createCommentEditor() with an empty string as value for the comment
* parent UUID. This method is invoked by callers that want to create an
* editor for a comment that is not a reply.
*/
protected void createCommentEditor(final int suggestRow, final int column,
final int line, final short file) {
createCommentEditor(suggestRow, column, line, file, null /* no parent */);
}
protected void createReplyEditor(final LineCommentPanel currentPanel) {
final int row = rowOf(currentPanel.getElement());
if (row >= 0) {
final int column = columnOf(currentPanel.getElement());
final PatchLineComment c = currentPanel.comment;
final PatchLineComment.Key k = c.getKey();
createCommentEditor(row, column, c.getLine(), c.getSide(), k.get());
}
}
private void createCommentEditor(final int suggestRow, final int column,
final int line, final short file, final String parentUuid) {
int row = suggestRow;
int spans[] = new int[column + 1];
OUTER: while (row < table.getRowCount()) {
int col = 0;
- for (int cell = 0; cell < table.getCellCount(row); cell++) {
+ for (int cell = 0; row < table.getRowCount()
+ && cell < table.getCellCount(row); cell++) {
while (col < column && 0 < spans[col]) {
spans[col++]--;
}
spans[col] = table.getFlexCellFormatter().getRowSpan(row, cell);
if (col == column) {
if (table.getWidget(row, cell) instanceof ComplexDisclosurePanel) {
row++;
} else {
break OUTER;
}
}
}
}
if (row < table.getRowCount() && column < table.getCellCount(row)
&& table.getWidget(row, column) instanceof CommentEditorPanel) {
// Don't insert two editors on the same position, it doesn't make
// any sense to the user.
//
((CommentEditorPanel) table.getWidget(row, column)).setFocus(true);
return;
}
if (!Gerrit.isSignedIn()) {
Gerrit.doSignIn();
return;
}
final Patch.Key parentKey;
final short side;
switch (file) {
case 0:
if (idSideA == null) {
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 0;
} else {
parentKey = new Patch.Key(idSideA, patchKey.get());
side = (short) 1;
}
break;
case 1:
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 1;
break;
default:
throw new RuntimeException("unexpected file id " + file);
}
final PatchLineComment newComment =
new PatchLineComment(new PatchLineComment.Key(parentKey, null), line,
Gerrit.getUserAccount().getId(), parentUuid);
newComment.setSide(side);
newComment.setMessage("");
final CommentEditorPanel ed = new CommentEditorPanel(newComment);
boolean needInsert = true;
if (row < table.getRowCount()) {
for (int cell = 0; cell < table.getCellCount(row); cell++) {
final Widget w = table.getWidget(row, cell);
if (w instanceof CommentEditorPanel
|| w instanceof ComplexDisclosurePanel) {
needInsert = false;
break;
}
}
}
if (needInsert) {
table.insertRow(row);
table.getCellFormatter().setStyleName(row, 0, S_ICON_CELL);
}
table.setWidget(row, column, ed);
table.getFlexCellFormatter().setStyleName(row, column, "Comment");
int span = 1;
for (int r = row + 1; r < table.getRowCount(); r++) {
boolean hasComment = false;
for (int c = 0; c < table.getCellCount(r); c++) {
final Widget w = table.getWidget(r, c);
if (w instanceof ComplexDisclosurePanel
|| w instanceof CommentEditorPanel) {
hasComment = true;
break;
}
}
if (hasComment) {
table.removeCell(r, column);
span++;
} else {
break;
}
}
if (span > 1) {
table.getFlexCellFormatter().setRowSpan(row, column, span);
}
for (int r = row - 1; r > 0; r--) {
if (getRowItem(r) instanceof CommentList) {
continue;
} else if (getRowItem(r) != null) {
movePointerTo(r);
break;
}
}
ed.setFocus(true);
}
@Override
protected void onOpenRow(final int row) {
final Object item = getRowItem(row);
if (item instanceof CommentList) {
for (final ComplexDisclosurePanel p : ((CommentList) item).panels) {
p.setOpen(!p.isOpen());
}
}
}
public void setAccountInfoCache(final AccountInfoCache aic) {
assert aic != null;
accountCache = aic;
}
static void destroyEditor(final FlexTable table, final int row, final int col) {
table.clearCell(row, col);
final int span = table.getFlexCellFormatter().getRowSpan(row, col);
boolean removeRow = true;
final int nCells = table.getCellCount(row);
for (int cell = 0; cell < nCells; cell++) {
if (table.getWidget(row, cell) != null) {
removeRow = false;
break;
}
}
if (removeRow) {
for (int r = row - 1; 0 <= r; r--) {
boolean data = false;
for (int c = 0; c < table.getCellCount(r); c++) {
data |= table.getWidget(r, c) != null;
final int s = table.getFlexCellFormatter().getRowSpan(r, c) - 1;
if (r + s == row) {
table.getFlexCellFormatter().setRowSpan(r, c, s);
}
}
if (!data) {
break;
}
}
table.removeRow(row);
} else if (span != 1) {
table.getFlexCellFormatter().setRowSpan(row, col, 1);
for (int r = row + 1; r < row + span; r++) {
table.insertCell(r, col + 1);
}
}
}
protected void bindComment(final int row, final int col,
final PatchLineComment line, final boolean isLast) {
if (line.getStatus() == PatchLineComment.Status.DRAFT) {
final CommentEditorPanel plc = new CommentEditorPanel(line);
table.setWidget(row, col, plc);
table.getFlexCellFormatter().setStyleName(row, col, "Comment");
return;
}
final LineCommentPanel mp;
if (isLast) {
// Create a panel with a Reply button if we are looking at the
// last comment for this line.
mp = new LineCommentPanel(line, this);
} else {
mp = new LineCommentPanel(line);
}
String panelHeader;
final ComplexDisclosurePanel panel;
if (line.getAuthor() != null) {
panelHeader = FormatUtil.nameEmail(accountCache.get(line.getAuthor()));
} else {
panelHeader = Util.C.messageNoAuthor();
}
if (isLast) {
mp.isRecent = true;
} else {
// TODO Instead of opening messages by strict age, do it by "unread"?
mp.isRecent = line.getWrittenOn().after(aged);
}
panel = new ComplexDisclosurePanel(panelHeader, mp.isRecent);
panel.getHeader().add(
new InlineLabel(Util.M.messageWrittenOn(FormatUtil.mediumFormat(line
.getWrittenOn()))));
panel.setContent(mp);
table.setWidget(row, col, panel);
table.getFlexCellFormatter().setStyleName(row, col, "Comment");
CommentList l = (CommentList) getRowItem(row);
if (l == null) {
l = new CommentList();
setRowItem(row, l);
}
l.comments.add(line);
l.panels.add(panel);
}
protected static class CommentList {
final List<PatchLineComment> comments = new ArrayList<PatchLineComment>();
final List<ComplexDisclosurePanel> panels =
new ArrayList<ComplexDisclosurePanel>();
}
protected class DoubleClickFlexTable extends MyFlexTable {
public DoubleClickFlexTable() {
sinkEvents(Event.ONDBLCLICK | Event.ONCLICK);
}
@Override
public void onBrowserEvent(final Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONCLICK: {
// Find out which cell was actually clicked.
final Element td = getEventTargetCell(event);
if (td == null) {
break;
}
final int row = rowOf(td);
if (getRowItem(row) != null) {
movePointerTo(row);
return;
}
break;
}
case Event.ONDBLCLICK: {
// Find out which cell was actually clicked.
Element td = getEventTargetCell(event);
if (td == null) {
return;
}
onCellDoubleClick(rowOf(td), columnOf(td));
return;
}
}
super.onBrowserEvent(event);
}
}
public static class NoOpKeyCommand extends NeedsSignInKeyCommand {
public NoOpKeyCommand(int mask, int key, String help) {
super(mask, key, help);
}
@Override
public void onKeyPress(final KeyPressEvent event) {
}
}
public class InsertCommentCommand extends NeedsSignInKeyCommand {
public InsertCommentCommand(int mask, int key, String help) {
super(mask, key, help);
}
@Override
public void onKeyPress(final KeyPressEvent event) {
ensurePointerVisible();
for (int row = getCurrentRow(); 0 <= row; row--) {
final Object item = getRowItem(row);
if (item instanceof PatchLine) {
onInsertComment((PatchLine) item);
return;
} else if (item instanceof CommentList) {
continue;
} else {
return;
}
}
}
}
public class PublishCommentsKeyCommand extends NeedsSignInKeyCommand {
public PublishCommentsKeyCommand(int mask, char key, String help) {
super(mask, key, help);
}
@Override
public void onKeyPress(final KeyPressEvent event) {
final PatchSet.Id id = patchKey.getParentKey();
Gerrit.display("change,publish," + id.toString(),
new PublishCommentScreen(id));
}
}
public class PrevChunkKeyCmd extends KeyCommand {
public PrevChunkKeyCmd(int mask, int key, String help) {
super(mask, key, help);
}
@Override
public void onKeyPress(final KeyPressEvent event) {
ensurePointerVisible();
moveToPrevChunk(getCurrentRow());
}
}
public class NextChunkKeyCmd extends KeyCommand {
public NextChunkKeyCmd(int mask, int key, String help) {
super(mask, key, help);
}
@Override
public void onKeyPress(final KeyPressEvent event) {
ensurePointerVisible();
moveToNextChunk(getCurrentRow());
}
}
}
| true | true | private void createCommentEditor(final int suggestRow, final int column,
final int line, final short file, final String parentUuid) {
int row = suggestRow;
int spans[] = new int[column + 1];
OUTER: while (row < table.getRowCount()) {
int col = 0;
for (int cell = 0; cell < table.getCellCount(row); cell++) {
while (col < column && 0 < spans[col]) {
spans[col++]--;
}
spans[col] = table.getFlexCellFormatter().getRowSpan(row, cell);
if (col == column) {
if (table.getWidget(row, cell) instanceof ComplexDisclosurePanel) {
row++;
} else {
break OUTER;
}
}
}
}
if (row < table.getRowCount() && column < table.getCellCount(row)
&& table.getWidget(row, column) instanceof CommentEditorPanel) {
// Don't insert two editors on the same position, it doesn't make
// any sense to the user.
//
((CommentEditorPanel) table.getWidget(row, column)).setFocus(true);
return;
}
if (!Gerrit.isSignedIn()) {
Gerrit.doSignIn();
return;
}
final Patch.Key parentKey;
final short side;
switch (file) {
case 0:
if (idSideA == null) {
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 0;
} else {
parentKey = new Patch.Key(idSideA, patchKey.get());
side = (short) 1;
}
break;
case 1:
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 1;
break;
default:
throw new RuntimeException("unexpected file id " + file);
}
final PatchLineComment newComment =
new PatchLineComment(new PatchLineComment.Key(parentKey, null), line,
Gerrit.getUserAccount().getId(), parentUuid);
newComment.setSide(side);
newComment.setMessage("");
final CommentEditorPanel ed = new CommentEditorPanel(newComment);
boolean needInsert = true;
if (row < table.getRowCount()) {
for (int cell = 0; cell < table.getCellCount(row); cell++) {
final Widget w = table.getWidget(row, cell);
if (w instanceof CommentEditorPanel
|| w instanceof ComplexDisclosurePanel) {
needInsert = false;
break;
}
}
}
if (needInsert) {
table.insertRow(row);
table.getCellFormatter().setStyleName(row, 0, S_ICON_CELL);
}
table.setWidget(row, column, ed);
table.getFlexCellFormatter().setStyleName(row, column, "Comment");
int span = 1;
for (int r = row + 1; r < table.getRowCount(); r++) {
boolean hasComment = false;
for (int c = 0; c < table.getCellCount(r); c++) {
final Widget w = table.getWidget(r, c);
if (w instanceof ComplexDisclosurePanel
|| w instanceof CommentEditorPanel) {
hasComment = true;
break;
}
}
if (hasComment) {
table.removeCell(r, column);
span++;
} else {
break;
}
}
if (span > 1) {
table.getFlexCellFormatter().setRowSpan(row, column, span);
}
for (int r = row - 1; r > 0; r--) {
if (getRowItem(r) instanceof CommentList) {
continue;
} else if (getRowItem(r) != null) {
movePointerTo(r);
break;
}
}
ed.setFocus(true);
}
| private void createCommentEditor(final int suggestRow, final int column,
final int line, final short file, final String parentUuid) {
int row = suggestRow;
int spans[] = new int[column + 1];
OUTER: while (row < table.getRowCount()) {
int col = 0;
for (int cell = 0; row < table.getRowCount()
&& cell < table.getCellCount(row); cell++) {
while (col < column && 0 < spans[col]) {
spans[col++]--;
}
spans[col] = table.getFlexCellFormatter().getRowSpan(row, cell);
if (col == column) {
if (table.getWidget(row, cell) instanceof ComplexDisclosurePanel) {
row++;
} else {
break OUTER;
}
}
}
}
if (row < table.getRowCount() && column < table.getCellCount(row)
&& table.getWidget(row, column) instanceof CommentEditorPanel) {
// Don't insert two editors on the same position, it doesn't make
// any sense to the user.
//
((CommentEditorPanel) table.getWidget(row, column)).setFocus(true);
return;
}
if (!Gerrit.isSignedIn()) {
Gerrit.doSignIn();
return;
}
final Patch.Key parentKey;
final short side;
switch (file) {
case 0:
if (idSideA == null) {
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 0;
} else {
parentKey = new Patch.Key(idSideA, patchKey.get());
side = (short) 1;
}
break;
case 1:
parentKey = new Patch.Key(idSideB, patchKey.get());
side = (short) 1;
break;
default:
throw new RuntimeException("unexpected file id " + file);
}
final PatchLineComment newComment =
new PatchLineComment(new PatchLineComment.Key(parentKey, null), line,
Gerrit.getUserAccount().getId(), parentUuid);
newComment.setSide(side);
newComment.setMessage("");
final CommentEditorPanel ed = new CommentEditorPanel(newComment);
boolean needInsert = true;
if (row < table.getRowCount()) {
for (int cell = 0; cell < table.getCellCount(row); cell++) {
final Widget w = table.getWidget(row, cell);
if (w instanceof CommentEditorPanel
|| w instanceof ComplexDisclosurePanel) {
needInsert = false;
break;
}
}
}
if (needInsert) {
table.insertRow(row);
table.getCellFormatter().setStyleName(row, 0, S_ICON_CELL);
}
table.setWidget(row, column, ed);
table.getFlexCellFormatter().setStyleName(row, column, "Comment");
int span = 1;
for (int r = row + 1; r < table.getRowCount(); r++) {
boolean hasComment = false;
for (int c = 0; c < table.getCellCount(r); c++) {
final Widget w = table.getWidget(r, c);
if (w instanceof ComplexDisclosurePanel
|| w instanceof CommentEditorPanel) {
hasComment = true;
break;
}
}
if (hasComment) {
table.removeCell(r, column);
span++;
} else {
break;
}
}
if (span > 1) {
table.getFlexCellFormatter().setRowSpan(row, column, span);
}
for (int r = row - 1; r > 0; r--) {
if (getRowItem(r) instanceof CommentList) {
continue;
} else if (getRowItem(r) != null) {
movePointerTo(r);
break;
}
}
ed.setFocus(true);
}
|
diff --git a/tools/sos-boot/src/main/java/sorcer/com/sun/jini/start/ServiceStarter.java b/tools/sos-boot/src/main/java/sorcer/com/sun/jini/start/ServiceStarter.java
index e2aeafc8..9ff0fc63 100644
--- a/tools/sos-boot/src/main/java/sorcer/com/sun/jini/start/ServiceStarter.java
+++ b/tools/sos-boot/src/main/java/sorcer/com/sun/jini/start/ServiceStarter.java
@@ -1,367 +1,370 @@
/*
* 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 sorcer.com.sun.jini.start;
import com.sun.jini.start.NonActivatableServiceDescriptor;
import com.sun.jini.start.ServiceDescriptor;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import java.net.URL;
import java.rmi.RMISecurityManager;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.MissingResourceException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.Subject;
import net.jini.config.ConfigurationProvider;
/**
* @author Rafał Krupiński
*/
public class ServiceStarter {
/**
* Component name for service starter configuration entries
*/
static final String START_PACKAGE = "com.sun.jini.start";
/**
* Configure logger
*/
static /*final*/ Logger logger = null;
static {
try {
logger =
Logger.getLogger(
START_PACKAGE + ".service.starter",
START_PACKAGE + ".resources.service");
} catch (Exception e) {
logger =
Logger.getLogger(START_PACKAGE + ".service.starter");
if (e instanceof MissingResourceException) {
logger.info("Could not load logger's ResourceBundle: "
+ e);
} else if (e instanceof IllegalArgumentException) {
logger.info("Logger exists and uses another resource bundle: "
+ e);
}
logger.info("Defaulting to existing logger");
}
}
/**
* Array of strong references to transient services
*/
private ArrayList transient_service_refs;
/**
* Utility routine that sets a security manager if one isn't already
* present.
*/
synchronized static void ensureSecurityManager() {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
}
/**
* Generic service creation method that attempts to login via
* the provided <code>LoginContext</code> and then call the
* <code>create</code> overload without a login context argument.
*
* @param descs The <code>ServiceDescriptor[]</code> that contains
* the descriptors for the services to start.
* @param config The associated <code>Configuration</code> object
* used to customize the service creation process.
* @param loginContext The associated <code>LoginContext</code> object
* used to login/logout.
* @return Returns a <code>Result[]</code> that is the same length as
* <code>descs</code>, which contains the details for each
* service creation attempt.
* @throws Exception If there was a problem logging in/out or
* a problem creating the service.
* @see Service
* @see ServiceDescriptor
* @see net.jini.config.Configuration
* @see javax.security.auth.login.LoginContext
*/
private Service[] createWithLogin(
final ServiceDescriptor[] descs, final Configuration config,
final LoginContext loginContext)
throws Exception {
logger.entering(ServiceStarter.class.getName(),
"createWithLogin", new Object[]{descs, config, loginContext});
loginContext.login();
Service[] results = null;
try {
results = (Service[]) Subject.doAsPrivileged(
loginContext.getSubject(),
new PrivilegedExceptionAction() {
public Object run()
throws Exception {
return create(descs, config);
}
},
null);
} catch (PrivilegedActionException pae) {
throw pae.getException();
} finally {
try {
loginContext.logout();
} catch (LoginException le) {
logger.log(Level.FINE, "service.logout.exception", le);
}
}
logger.exiting(ServiceStarter.class.getName(),
"createWithLogin", results);
return results;
}
/**
* Generic service creation method that attempts to start the
* services defined by the provided <code>ServiceDescriptor[]</code>
* argument.
*
* @param descs The <code>ServiceDescriptor[]</code> that contains
* the descriptors for the services to start.
* @param config The associated <code>Configuration</code> object
* used to customize the service creation process.
* @return Returns a <code>Result[]</code> that is the same length as
* <code>descs</code>, which contains the details for each
* service creation attempt.
* @throws Exception If there was a problem creating the service.
* @see Service
* @see ServiceDescriptor
* @see net.jini.config.Configuration
*/
private Service[] create(final ServiceDescriptor[] descs,
final Configuration config)
throws Exception {
logger.entering(ServiceStarter.class.getName(), "create",
new Object[]{descs, config});
ArrayList proxies = new ArrayList();
Object result = null;
Exception problem = null;
ServiceDescriptor desc = null;
for (int i = 0; i < descs.length; i++) {
desc = descs[i];
result = null;
problem = null;
try {
if (desc != null) {
result = desc.create(config);
}
} catch (Exception e) {
problem = e;
} finally {
proxies.add(new Service(desc, result, problem));
}
}
logger.exiting(ServiceStarter.class.getName(), "create", proxies);
return (Service[]) proxies.toArray(new Service[proxies.size()]);
}
/**
* Utility routine that maintains strong references to any
* transient services in the provided <code>Result[]</code>.
* This prevents the transient services from getting garbage
* collected.
*/
private void maintainNonActivatableReferences(Service[] results) {
logger.entering(ServiceStarter.class.getName(),
"maintainNonActivatableReferences", (Object[]) results);
if (results.length == 0)
return;
transient_service_refs = new ArrayList();
for (int i = 0; i < results.length; i++) {
if (results[i] != null &&
results[i].result != null &&
NonActivatableServiceDescriptor.class.equals(
results[i].descriptor.getClass())) {
logger.log(Level.FINEST, "Storing ref to: {0}",
results[i].result);
transient_service_refs.add(results[i].result);
}
}
//TODO - kick off daemon thread to maintain refs via LifeCycle object
logger.exiting(ServiceStarter.class.getName(),
"maintainNonActivatableReferences");
return;
}
/**
* Utility routine that prints out warning messages for each service
* descriptor that produced an exception or that was null.
*/
private static void checkResultFailures(Service[] results) {
logger.entering(ServiceStarter.class.getName(),
"checkResultFailures", (Object[]) results);
if (results.length == 0)
return;
for (int i = 0; i < results.length; i++) {
if (results[i].exception != null) {
logger.log(Level.WARNING,
"service.creation.unknown",
results[i].exception);
logger.log(Level.WARNING,
"service.creation.unknown.detail",
new Object[]{new Integer(i),
results[i].descriptor});
} else if (results[i].descriptor == null) {
logger.log(Level.WARNING,
"service.creation.null", new Integer(i));
}
}
logger.exiting(ServiceStarter.class.getName(),
"checkResultFailures");
}
/**
* Workhorse function for both main() entrypoints.
*/
private Service[] processServiceDescriptors(Configuration... configs) throws Exception {
List<Service> resultList = new LinkedList<Service>();
+ ServiceDescriptor[][] descriptors = new ServiceDescriptor[configs.length][];
- Map<Configuration, ServiceDescriptor[]>serviceDescriptors = new HashMap<Configuration, ServiceDescriptor[]>();
- for (Configuration config : configs) {
+ for (int i = 0; i < configs.length; i++) {
+ Configuration config = configs[i];
ServiceDescriptor[] descs = (ServiceDescriptor[])
config.getEntry(START_PACKAGE, "serviceDescriptors",
ServiceDescriptor[].class, null);
if (descs == null || descs.length == 0) {
logger.warning("service.config.empty");
continue;
}
- serviceDescriptors.put(config, descs);
+ descriptors[i] = descs;
}
- for (Map.Entry<Configuration, ServiceDescriptor[]> e : serviceDescriptors.entrySet()) {
- Configuration config = e.getKey();
- ServiceDescriptor[] descs = e.getValue();
+ for (int i = 0; i < configs.length; i++) {
+ Configuration config = configs[i];
+ ServiceDescriptor[] descs = descriptors[i];
+ if(descs == null)
+ continue;
LoginContext loginContext = (LoginContext)
config.getEntry(START_PACKAGE, "loginContext",
LoginContext.class, null);
Service[] results;
if (loginContext != null) {
results = createWithLogin(descs, config, loginContext);
} else {
results = create(descs, config);
}
resultList.addAll(Arrays.asList(results));
}
Service[] results = resultList.toArray(new Service[resultList.size()]);
checkResultFailures(results);
maintainNonActivatableReferences(results);
return results;
}
/**
* The main method for embidding the <code>ServiceStarter</code> application.
* The <code>config</code> argument is queried for the
* <code>com.sun.jini.start.serviceDescriptors</code> entry, which
* is assumed to be a <code>ServiceDescriptor[]</code>.
* The <code>create()</code> method is then called on each of the array
* elements.
*
* @param config the <code>Configuration</code> object.
* @see ServiceDescriptor
* @see com.sun.jini.start.SharedActivatableServiceDescriptor
* @see com.sun.jini.start.SharedActivationGroupDescriptor
* @see NonActivatableServiceDescriptor
* @see net.jini.config.Configuration
*/
public void main(Configuration config) {
ensureSecurityManager();
try {
logger.entering(ServiceStarter.class.getName(),
"main", config);
processServiceDescriptors(config);
} catch (ConfigurationException cex) {
logger.log(Level.SEVERE, "service.config.exception", cex);
} catch (Exception e) {
logger.log(Level.SEVERE, "service.creation.exception", e);
}
logger.exiting(ServiceStarter.class.getName(),
"main");
}
/**
* Create a Configuration object from each path in args and create service for each entry.
*
* @param args config file paths
* @throws ConfigurationException
* @return list ofcreated services
*/
public Service[] startServicesFromPaths(String[] args) throws ConfigurationException {
logger.info("Loading from " + Arrays.deepToString(args));
Collection<Configuration> configs = new ArrayList<Configuration>(args.length);
for (String arg : args) {
if (arg == null) continue;
URL resource = getClass().getClassLoader().getResource(arg);
String options;
if (resource == null) {
options = arg;
} else {
options = resource.toExternalForm();
}
configs.add(ConfigurationProvider.getInstance(new String[]{options}));
}
try {
return processServiceDescriptors(configs.toArray(new Configuration[configs.size()]));
} catch (Exception e) {
throw new IllegalArgumentException("Error while parsing configuration", e);
}
}
public Service[] startServices(String[] args) {
ServiceStarter.ensureSecurityManager();
try {
Configuration config = ConfigurationProvider.getInstance(args);
return processServiceDescriptors(config);
} catch (ConfigurationException cex) {
logger.log(Level.SEVERE, "service.config.exception", cex);
} catch (Exception e) {
logger.log(Level.SEVERE, "service.creation.exception", e);
} finally {
logger.exiting(ServiceStarter.class.getName(),
"main");
}
return new Service[0];
}
}//end class ServiceStarter
| false | true | private Service[] processServiceDescriptors(Configuration... configs) throws Exception {
List<Service> resultList = new LinkedList<Service>();
Map<Configuration, ServiceDescriptor[]>serviceDescriptors = new HashMap<Configuration, ServiceDescriptor[]>();
for (Configuration config : configs) {
ServiceDescriptor[] descs = (ServiceDescriptor[])
config.getEntry(START_PACKAGE, "serviceDescriptors",
ServiceDescriptor[].class, null);
if (descs == null || descs.length == 0) {
logger.warning("service.config.empty");
continue;
}
serviceDescriptors.put(config, descs);
}
for (Map.Entry<Configuration, ServiceDescriptor[]> e : serviceDescriptors.entrySet()) {
Configuration config = e.getKey();
ServiceDescriptor[] descs = e.getValue();
LoginContext loginContext = (LoginContext)
config.getEntry(START_PACKAGE, "loginContext",
LoginContext.class, null);
Service[] results;
if (loginContext != null) {
results = createWithLogin(descs, config, loginContext);
} else {
results = create(descs, config);
}
resultList.addAll(Arrays.asList(results));
}
Service[] results = resultList.toArray(new Service[resultList.size()]);
checkResultFailures(results);
maintainNonActivatableReferences(results);
return results;
}
| private Service[] processServiceDescriptors(Configuration... configs) throws Exception {
List<Service> resultList = new LinkedList<Service>();
ServiceDescriptor[][] descriptors = new ServiceDescriptor[configs.length][];
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
ServiceDescriptor[] descs = (ServiceDescriptor[])
config.getEntry(START_PACKAGE, "serviceDescriptors",
ServiceDescriptor[].class, null);
if (descs == null || descs.length == 0) {
logger.warning("service.config.empty");
continue;
}
descriptors[i] = descs;
}
for (int i = 0; i < configs.length; i++) {
Configuration config = configs[i];
ServiceDescriptor[] descs = descriptors[i];
if(descs == null)
continue;
LoginContext loginContext = (LoginContext)
config.getEntry(START_PACKAGE, "loginContext",
LoginContext.class, null);
Service[] results;
if (loginContext != null) {
results = createWithLogin(descs, config, loginContext);
} else {
results = create(descs, config);
}
resultList.addAll(Arrays.asList(results));
}
Service[] results = resultList.toArray(new Service[resultList.size()]);
checkResultFailures(results);
maintainNonActivatableReferences(results);
return results;
}
|
diff --git a/LifeTrack/src/com/lostmiracle/lifetrack/MainActivity.java b/LifeTrack/src/com/lostmiracle/lifetrack/MainActivity.java
index 36fddf4..1eacafd 100644
--- a/LifeTrack/src/com/lostmiracle/lifetrack/MainActivity.java
+++ b/LifeTrack/src/com/lostmiracle/lifetrack/MainActivity.java
@@ -1,82 +1,83 @@
package com.lostmiracle.lifetrack;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int counter;
Button add1, add5, sub1, sub5, bReset;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 20;
add1 = (Button) findViewById(R.id.add_one);
add5 = (Button) findViewById(R.id.add_five);
sub1 = (Button) findViewById(R.id.minus_one);
sub5 = (Button) findViewById(R.id.minus_five);
bReset = (Button) findViewById(R.id.bReset);
display = (TextView) findViewById(R.id.tvCounter);
bReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
+ counter = 20;
display.setText("" + 20);
}
});
add1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("" + counter);
}
});
add5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter += 5;
display.setText("" + counter);
}
});
sub1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("" + counter);
}
});
sub5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter -= 5;
display.setText("" + counter);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 20;
add1 = (Button) findViewById(R.id.add_one);
add5 = (Button) findViewById(R.id.add_five);
sub1 = (Button) findViewById(R.id.minus_one);
sub5 = (Button) findViewById(R.id.minus_five);
bReset = (Button) findViewById(R.id.bReset);
display = (TextView) findViewById(R.id.tvCounter);
bReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("" + 20);
}
});
add1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("" + counter);
}
});
add5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter += 5;
display.setText("" + counter);
}
});
sub1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("" + counter);
}
});
sub5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter -= 5;
display.setText("" + counter);
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 20;
add1 = (Button) findViewById(R.id.add_one);
add5 = (Button) findViewById(R.id.add_five);
sub1 = (Button) findViewById(R.id.minus_one);
sub5 = (Button) findViewById(R.id.minus_five);
bReset = (Button) findViewById(R.id.bReset);
display = (TextView) findViewById(R.id.tvCounter);
bReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter = 20;
display.setText("" + 20);
}
});
add1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("" + counter);
}
});
add5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter += 5;
display.setText("" + counter);
}
});
sub1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("" + counter);
}
});
sub5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter -= 5;
display.setText("" + counter);
}
});
}
|
diff --git a/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java b/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java
index 1a6503b..60de722 100644
--- a/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java
+++ b/TheAdventure/src/se/chalmers/kangaroo/view/KangarooAnimation.java
@@ -1,51 +1,52 @@
package se.chalmers.kangaroo.view;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
/**
* A class representing the animation of the Kangaroo.
* @author simonal
*
*/
public class KangarooAnimation implements Animation {
private Image rightSheet;
private Image leftSheet;
private int widthPerFrame;
private int height;
private int tick;
private int currentFrame;
/**
* Constructor taking the pathname and width and height of the animation.
* @param pathName
* @param width
* @param height
*/
public KangarooAnimation(int width, int height) {
rightSheet = Toolkit.getDefaultToolkit().getImage("resources/sheets/kangaroo_58x64_right.png");
leftSheet = Toolkit.getDefaultToolkit().getImage("resources/sheets/kangaroo_58x64_right.png");
currentFrame = 0;
this.widthPerFrame = width;
this.height = height;
tick = 0;
}
/**
* Draws the animation once every halv second if the game is running in 60 ups.
*/
@Override
public void drawSprite(Graphics g, int x, int y) {
- if (tick == 30) {
+ if (tick == 15) {
tick = 0;
- currentFrame = (currentFrame % 3) + 1;
+ currentFrame++;
+ currentFrame = (currentFrame % 3);
}
g.drawImage(leftSheet, x-widthPerFrame/2, y-height, x+widthPerFrame/2, y,
(currentFrame * widthPerFrame), 1,
(currentFrame * widthPerFrame) + widthPerFrame,
height, null, null);
tick++;
}
}
| false | true | public void drawSprite(Graphics g, int x, int y) {
if (tick == 30) {
tick = 0;
currentFrame = (currentFrame % 3) + 1;
}
g.drawImage(leftSheet, x-widthPerFrame/2, y-height, x+widthPerFrame/2, y,
(currentFrame * widthPerFrame), 1,
(currentFrame * widthPerFrame) + widthPerFrame,
height, null, null);
tick++;
}
| public void drawSprite(Graphics g, int x, int y) {
if (tick == 15) {
tick = 0;
currentFrame++;
currentFrame = (currentFrame % 3);
}
g.drawImage(leftSheet, x-widthPerFrame/2, y-height, x+widthPerFrame/2, y,
(currentFrame * widthPerFrame), 1,
(currentFrame * widthPerFrame) + widthPerFrame,
height, null, null);
tick++;
}
|
diff --git a/web/src/main/java/org/openmrs/web/controller/user/UserFormController.java b/web/src/main/java/org/openmrs/web/controller/user/UserFormController.java
index 945ea38d..cdadc0a9 100644
--- a/web/src/main/java/org/openmrs/web/controller/user/UserFormController.java
+++ b/web/src/main/java/org/openmrs/web/controller/user/UserFormController.java
@@ -1,280 +1,280 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.user;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Person;
import org.openmrs.PersonName;
import org.openmrs.Role;
import org.openmrs.User;
import org.openmrs.api.PasswordException;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.openmrs.messagesource.MessageSourceService;
import org.openmrs.propertyeditor.RoleEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.validator.UserValidator;
import org.openmrs.web.WebConstants;
import org.openmrs.web.user.UserProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
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.context.request.WebRequest;
/**
* Used for creating/editing User
*/
@Controller
public class UserFormController {
protected static final Log log = LogFactory.getLog(UserFormController.class);
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Role.class, new RoleEditor());
}
// the personId attribute is called person_id so that spring MVC doesn't try to bind it to the personId property of user
@ModelAttribute("user")
public User formBackingObject(WebRequest request,
@RequestParam(required=false, value="person_id") Integer personId) {
String userId = request.getParameter("userId");
User u = null;
try {
u = Context.getUserService().getUser(Integer.valueOf(userId));
} catch (Exception ex) { }
if (u == null) {
u = new User();
}
if (personId != null) {
u.setPerson(Context.getPersonService().getPerson(personId));
} else if (u.getPerson() == null) {
Person p = new Person();
p.addName(new PersonName());
u.setPerson(p);
}
return u;
}
@ModelAttribute("allRoles")
public List<Role> getRoles(WebRequest request) {
List<Role> roles = Context.getUserService().getAllRoles();
if (roles == null)
roles = new Vector<Role>();
for (String s : OpenmrsConstants.AUTO_ROLES()) {
Role r = new Role(s);
roles.remove(r);
}
return roles;
}
@RequestMapping(value="/admin/users/user.form", method=RequestMethod.GET)
public String showForm(@RequestParam(required=false, value="userId") Integer userId,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user,
ModelMap model) {
// the formBackingObject method above sets up user, depending on userId and personId parameters
model.addAttribute("isNewUser", isNewUser(user));
if (isNewUser(user) || Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS))
model.addAttribute("modifyPasswords", true);
if (createNewPerson != null)
model.addAttribute("createNewPerson", createNewPerson);
if(!isNewUser(user))
model.addAttribute("changePassword",new UserProperties(user.getUserProperties()).isSupposedToChangePassword());
// not using the default view name because I'm converting from an existing form
return "admin/users/userForm";
}
/**
* @should work for an example
*/
@RequestMapping(value="/admin/users/user.form", method=RequestMethod.POST)
public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
- return "redirect:/admin/users/user.list";
+ return "redirect:users.list";
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
log.error("Failed to delete user", ex);
return "redirect:/admin/users/user.form?userId="+request.getParameter("userId");
}
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "User.disableReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
- return "redirect:user.list";
+ return "redirect:users.list";
}
/**
* Superficially determines if this form is being filled out for a new user (basically just
* looks for a primary key (user_id)
*
* @param user
* @return true/false if this user is new
*/
private Boolean isNewUser(User user) {
return user == null ? true : user.getUserId() == null;
}
}
| false | true | public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
return "redirect:/admin/users/user.list";
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
log.error("Failed to delete user", ex);
return "redirect:/admin/users/user.form?userId="+request.getParameter("userId");
}
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "User.disableReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
return "redirect:user.list";
}
| public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
return "redirect:users.list";
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
log.error("Failed to delete user", ex);
return "redirect:/admin/users/user.form?userId="+request.getParameter("userId");
}
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "User.disableReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
return "redirect:users.list";
}
|
diff --git a/minerva/src/main/java/org/opentools/minerva/connector/jdbc/JDBCManagedConnectionFactory.java b/minerva/src/main/java/org/opentools/minerva/connector/jdbc/JDBCManagedConnectionFactory.java
index a95257fbd..ea593c961 100644
--- a/minerva/src/main/java/org/opentools/minerva/connector/jdbc/JDBCManagedConnectionFactory.java
+++ b/minerva/src/main/java/org/opentools/minerva/connector/jdbc/JDBCManagedConnectionFactory.java
@@ -1,173 +1,173 @@
/*
* 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.
*/
/*
* Licensed under the X license (see http://www.x.org/terms.htm)
*/
package org.opentools.minerva.connector.jdbc;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import javax.resource.ResourceException;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ManagedConnection;
import javax.security.auth.Subject;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.security.PasswordCredential;
/**
* ManagedConnectionFactory implementation for JDBC connections. You give it
* a driver, URL, user, and password and it generated connections. Matches
* connections based on JDBC user and JDBC URL. Currently supports managed
* mode only.
* <p>To initialize this ResourceAdapter, use the following properties:</p>
* <table>
* <tr><th align="right">Driver</th><td>The driver class name</td></tr>
* <tr><th align="right">ConnectionUrl</th><td>The JDBC URL</td></tr>
* <tr><th align="right">UserName</th><td>The default JDBC UserName</td></tr>
* <tr><th align="right">Password</th><td>The default JDBC Password</td></tr>
* </table>
*
* @author Aaron Mulder <[email protected]>
* @version $Revision: 4 $
*/
public class JDBCManagedConnectionFactory implements ManagedConnectionFactory {
private static final long serialVersionUID = 2366364114324427978L;
private String driver;
private String url;
private String username;
private String password;
private transient PrintWriter logger;
public JDBCManagedConnectionFactory() {
}
public Object createConnectionFactory(ConnectionManager mgr) throws ResourceException {
return new JDBCDataSource(mgr, this);
}
public Object createConnectionFactory() throws ResourceException {
throw new java.lang.UnsupportedOperationException("Must be used in managed mode");
}
public ManagedConnection createManagedConnection(Subject sub, ConnectionRequestInfo info) throws ResourceException {
// Set user and password to default
String user = username;
String pw = password;
// Check passed Subject and ConnectionRequestInfo for user/password overrides
if(sub != null) {
Set creds = sub.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
for(Iterator it = creds.iterator(); it.hasNext(); ) {
PasswordCredential pc = (PasswordCredential)it.next();
user = pc.getUserName();
pw = new String(pc.getPassword());
break;
}
} else {
if(info != null) {
JDBCConnectionRequestInfo jdbcInfo = (JDBCConnectionRequestInfo)info;
user = jdbcInfo.user;
pw = jdbcInfo.password;
}
}
// Create the connection
try {
Connection con = DriverManager.getConnection(url, user, pw);
con.setAutoCommit(false);
ManagedConnection mc = new JDBCManagedConnection(con, user, url);
mc.setLogWriter(logger);
return mc;
} catch(SQLException e) {
throw new ResourceException("Unable to create DB connection: "+e);
}
}
public ManagedConnection matchManagedConnections(Set cons, Subject sub, ConnectionRequestInfo info) throws ResourceException {
// Set user and password to default
String user = username;
// Check passed Subject and ConnectionRequestInfo for user/password overrides
if(sub != null) {
Set creds = sub.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
for(Iterator it = creds.iterator(); it.hasNext(); ) {
PasswordCredential pc = (PasswordCredential)it.next();
user = pc.getUserName();
break;
}
} else {
if(info != null) {
if(!(info instanceof JDBCConnectionRequestInfo)) {
throw new ResourceException("Passed ConnectionRequestInfo class '"+info.getClass().getName()+"' to JDBCManagedConnectionFactory!");
}
JDBCConnectionRequestInfo jdbcInfo = (JDBCConnectionRequestInfo)info;
user = jdbcInfo.user;
}
}
// Check the connections in the Set
for(Iterator it = cons.iterator(); it.hasNext(); ) {
Object unknown = it.next();
if(!(unknown instanceof JDBCManagedConnection)) {
continue;
}
JDBCManagedConnection con = (JDBCManagedConnection)unknown;
- if(con.getUser().equals(user) && con.getURL().equals(url)) {
+ if( (user == null || con.getUser() == null || con.getUser().equals(user)) && con.getURL().equals(url)) {
return con;
}
}
return null;
}
public void setLogWriter(PrintWriter writer) throws ResourceException {
logger = writer;
}
public PrintWriter getLogWriter() throws ResourceException {
return logger;
}
public void setDriver(String driver) {
this.driver = driver;
try {
Class.forName(driver);
} catch(Exception e) {
if(logger != null) {
logger.println("Unable to load JDBC driver '"+driver+"'");
e.printStackTrace(logger);
} else {
System.err.println("Unable to load JDBC driver '"+driver+"'");
e.printStackTrace();
}
}
}
public String getDriver() {return driver;}
public void setConnectionURL(String url) {this.url = url;}
public String getConnectionURL() {return url;}
public void setUserName(String username) {this.username = username;}
public String getUserName() {return username;}
public void setPassword(String password) {this.password = password;}
public String getPassword() {return password;}
}
| true | true | public ManagedConnection matchManagedConnections(Set cons, Subject sub, ConnectionRequestInfo info) throws ResourceException {
// Set user and password to default
String user = username;
// Check passed Subject and ConnectionRequestInfo for user/password overrides
if(sub != null) {
Set creds = sub.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
for(Iterator it = creds.iterator(); it.hasNext(); ) {
PasswordCredential pc = (PasswordCredential)it.next();
user = pc.getUserName();
break;
}
} else {
if(info != null) {
if(!(info instanceof JDBCConnectionRequestInfo)) {
throw new ResourceException("Passed ConnectionRequestInfo class '"+info.getClass().getName()+"' to JDBCManagedConnectionFactory!");
}
JDBCConnectionRequestInfo jdbcInfo = (JDBCConnectionRequestInfo)info;
user = jdbcInfo.user;
}
}
// Check the connections in the Set
for(Iterator it = cons.iterator(); it.hasNext(); ) {
Object unknown = it.next();
if(!(unknown instanceof JDBCManagedConnection)) {
continue;
}
JDBCManagedConnection con = (JDBCManagedConnection)unknown;
if(con.getUser().equals(user) && con.getURL().equals(url)) {
return con;
}
}
return null;
}
| public ManagedConnection matchManagedConnections(Set cons, Subject sub, ConnectionRequestInfo info) throws ResourceException {
// Set user and password to default
String user = username;
// Check passed Subject and ConnectionRequestInfo for user/password overrides
if(sub != null) {
Set creds = sub.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
for(Iterator it = creds.iterator(); it.hasNext(); ) {
PasswordCredential pc = (PasswordCredential)it.next();
user = pc.getUserName();
break;
}
} else {
if(info != null) {
if(!(info instanceof JDBCConnectionRequestInfo)) {
throw new ResourceException("Passed ConnectionRequestInfo class '"+info.getClass().getName()+"' to JDBCManagedConnectionFactory!");
}
JDBCConnectionRequestInfo jdbcInfo = (JDBCConnectionRequestInfo)info;
user = jdbcInfo.user;
}
}
// Check the connections in the Set
for(Iterator it = cons.iterator(); it.hasNext(); ) {
Object unknown = it.next();
if(!(unknown instanceof JDBCManagedConnection)) {
continue;
}
JDBCManagedConnection con = (JDBCManagedConnection)unknown;
if( (user == null || con.getUser() == null || con.getUser().equals(user)) && con.getURL().equals(url)) {
return con;
}
}
return null;
}
|
diff --git a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
index fcbac09..c5b6292 100644
--- a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
+++ b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
@@ -1,361 +1,361 @@
package com.araeosia.ArcherGames;
import com.araeosia.ArcherGames.utils.Archer;
import com.araeosia.ArcherGames.utils.BookItem;
import com.araeosia.ArcherGames.utils.Kit;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.inventory.ItemStack;
public class CommandHandler implements CommandExecutor, Listener {
public ArcherGames plugin;
public CommandHandler(ArcherGames plugin) {
this.plugin = plugin;
}
public HashMap<String, Integer> chunkReloads;
/**
*
* @param sender
* @param cmd
* @param commandLabel
* @param args
* @return
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + "");
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0]));
return true;
}
} else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) {
String outputAlive = "";
int alive = 0;
String outputSpec = "";
int spec = 0;
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (Archer.getByName(p.getName()).isAlive()) {
outputAlive += p.getDisplayName() + ", ";
alive++;
} else {
spec++;
outputSpec += p.getDisplayName() + ", ";
}
}
sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: ");
sender.sendMessage(outputAlive);
sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: ");
sender.sendMessage(outputSpec);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) {
if (args.length != 0) {
if (ScheduledTasks.gameStatus != 1) {
sender.sendMessage(plugin.strings.get("alreadystartedkits"));
} else {
Kit selectedKit = new Kit();
Boolean isOkay = false;
for (Kit kit : plugin.kits) {
if (args[0].equalsIgnoreCase(kit.getName())) {
isOkay = true;
selectedKit = kit;
}
}
if (isOkay) {
if (Archer.getByName(sender.getName()).isReady()) {
sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), Archer.getByName(sender.getName()).getKit().getName()));
}
if (sender.hasPermission(selectedKit.getPermission())) {
plugin.serverwide.joinGame(sender.getName(), selectedKit);
sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName()));
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
}
} else {
sender.sendMessage(ChatColor.GREEN + "Use /kit (kitname) to select a kit.");
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
String kitsNo = "";
for (Kit kit : plugin.kits) {
if (sender.hasPermission(kit.getPermission())) {
kits += kit.getName() + ", ";
} else {
kitsNo += kit.getName() + ", ";
}
}
sender.sendMessage(ChatColor.GREEN + kits);
sender.sendMessage(plugin.strings.get("kitnoaccessible"));
sender.sendMessage("§c" + kitsNo);
}
return true;
} else if (cmd.getName().equalsIgnoreCase("chunk")) {
if (!(ScheduledTasks.gameStatus == 1)) {
if (sender instanceof Player) {
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
return true;
} else {
return false;
}
} else {
sender.sendMessage(ChatColor.RED + "You may not use this command yet.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("pay")) {
if (args.length != 0) {
if (args.length != 1) {
try {
if (Double.parseDouble(args[1]) > 0) {
if(plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))){
plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1]));
plugin.db.addMoney(args[0], Double.parseDouble(args[1]));
} else {
sender.sendMessage("You cannot afford to send this amount of money!");
}
- sender.sendMessage(ChatColor.GREEN + "$" + args[0] + " paid to " + args[0]);
+ sender.sendMessage(ChatColor.GREEN + "$" + args[1] + " paid to " + args[0]);
}
} catch (Exception e) {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("time")) {
if (!(ScheduledTasks.gameStatus >= 2)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 3)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 4)) {
sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts."));
} else {
sender.sendMessage(ChatColor.RED + "Nothing to time!");
}
return true;
} else if (cmd.getName().equalsIgnoreCase("timer")) {
if (args.length != 0) {
if (sender.hasPermission("ArcherGames.admin")) {
try {
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left.");
return true;
} catch (Exception e) {
sender.sendMessage(ChatColor.RED + "Time could not be set.");
return true;
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")) {
if (sender.hasPermission("archergames.admin")) {
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("credtop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:");
HashMap<String, Integer> credits = plugin.db.getTopPoints();
int i = 1;
for(String playerName : credits.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("baltop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:");
HashMap<String, Integer> balances = plugin.db.getTopPoints();
int i = 1;
for(String playerName : balances.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("wintop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:");
HashMap<String, Integer> wins = plugin.db.getTopWinners();
int i = 1;
for(String playerName : wins.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("stats")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:");
sender.sendMessage( ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup));
sender.sendMessage( ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup));
sender.sendMessage( ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup));
sender.sendMessage( ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup));
sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup));
return true;
} else if (cmd.getName().equalsIgnoreCase("credits")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits.");
return true;
} else if (cmd.getName().equalsIgnoreCase("track")){
if(sender.hasPermission("ArcherGames.donor.track")){
if(sender instanceof Player){
if(args.length != 0){
Player player = (Player) sender;
if(!player.getInventory().contains(Material.COMPASS)){
player.getInventory().addItem(new ItemStack(Material.COMPASS));
}
player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation());
player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]);
} else {
sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("ride")){
if(sender instanceof Player){
if(!plugin.serverwide.ridingPlayers.contains(sender.getName())){
plugin.serverwide.ridingPlayers.add(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players.");
} else {
plugin.serverwide.ridingPlayers.remove(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players.");
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("help")){
if(sender instanceof Player){
Player player = (Player) sender;
if (!player.getInventory().contains(Material.BOOK)) {
BookItem bi = new BookItem(new ItemStack(387, 1));
bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author"));
bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title"));
String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]);
bi.setPages(pages);
player.getInventory().addItem(bi.getItemStack());
return true;
} else {
sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("commands")) {
sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements.");
sendHelp(sender, "vote", "List the sites you can vote for the server on.");
sendHelp(sender, "money [player]", "Show either your or another player's money balance.");
sendHelp(sender, "stats [player]", "Show either your or another player's stats.");
sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue");
sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money");
sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)");
sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game.");
sendHelp(sender, "who/online/players", "See the players online and who is alive.");
sendHelp(sender, "credtop", "Show the top players for credits earned.");
sendHelp(sender, "baltop", "Show the top players for money earned.");
sendHelp(sender, "wintop", "Show the top players for games won.");
sendHelp(sender, "stats [player]", "Show the specified player, or your, stats.");
sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)");
sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them");
sendHelp(sender, "help", "Give yourself a help book.");
sendHelp(sender, "commands", "Show this help page.");
sendHelp(sender, "goto (player)", "Teleport to another player while spectating.");
return true;
} else if(cmd.getName().equalsIgnoreCase("goto")){
if(args.length != 0){
Player p = null;
for(Player player : plugin.getServer().getOnlinePlayers()){
if(player.getName().contains(args[0])){
p = player;
}
}
if(p != null){
if(sender instanceof Player){
if(!Archer.getByName(sender.getName()).isAlive){
((Player) sender).teleport(p);
sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName());
return true;
} else {
sender.sendMessage("You must be dead to use that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid player!");
return true;
}
}
}
return false;
}
/**
*
* @param event
*/
@EventHandler
public void onCommandPreProccessEvent(final PlayerCommandPreprocessEvent event) {
if (!(plugin.serverwide.getArcher(event.getPlayer()).kit == null) || !event.getPlayer().hasPermission("archergames.overrides.command")) {
if (!event.getMessage().contains("kit") && false) { // Needs fixing.
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.strings.get("nocommand"));
}
}
}
private void sendHelp(CommandSender sender, String command, String description) {
sender.sendMessage(ChatColor.GOLD + "/" + command + ": " + ChatColor.YELLOW + description);
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + "");
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0]));
return true;
}
} else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) {
String outputAlive = "";
int alive = 0;
String outputSpec = "";
int spec = 0;
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (Archer.getByName(p.getName()).isAlive()) {
outputAlive += p.getDisplayName() + ", ";
alive++;
} else {
spec++;
outputSpec += p.getDisplayName() + ", ";
}
}
sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: ");
sender.sendMessage(outputAlive);
sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: ");
sender.sendMessage(outputSpec);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) {
if (args.length != 0) {
if (ScheduledTasks.gameStatus != 1) {
sender.sendMessage(plugin.strings.get("alreadystartedkits"));
} else {
Kit selectedKit = new Kit();
Boolean isOkay = false;
for (Kit kit : plugin.kits) {
if (args[0].equalsIgnoreCase(kit.getName())) {
isOkay = true;
selectedKit = kit;
}
}
if (isOkay) {
if (Archer.getByName(sender.getName()).isReady()) {
sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), Archer.getByName(sender.getName()).getKit().getName()));
}
if (sender.hasPermission(selectedKit.getPermission())) {
plugin.serverwide.joinGame(sender.getName(), selectedKit);
sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName()));
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
}
} else {
sender.sendMessage(ChatColor.GREEN + "Use /kit (kitname) to select a kit.");
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
String kitsNo = "";
for (Kit kit : plugin.kits) {
if (sender.hasPermission(kit.getPermission())) {
kits += kit.getName() + ", ";
} else {
kitsNo += kit.getName() + ", ";
}
}
sender.sendMessage(ChatColor.GREEN + kits);
sender.sendMessage(plugin.strings.get("kitnoaccessible"));
sender.sendMessage("§c" + kitsNo);
}
return true;
} else if (cmd.getName().equalsIgnoreCase("chunk")) {
if (!(ScheduledTasks.gameStatus == 1)) {
if (sender instanceof Player) {
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
return true;
} else {
return false;
}
} else {
sender.sendMessage(ChatColor.RED + "You may not use this command yet.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("pay")) {
if (args.length != 0) {
if (args.length != 1) {
try {
if (Double.parseDouble(args[1]) > 0) {
if(plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))){
plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1]));
plugin.db.addMoney(args[0], Double.parseDouble(args[1]));
} else {
sender.sendMessage("You cannot afford to send this amount of money!");
}
sender.sendMessage(ChatColor.GREEN + "$" + args[0] + " paid to " + args[0]);
}
} catch (Exception e) {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("time")) {
if (!(ScheduledTasks.gameStatus >= 2)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 3)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 4)) {
sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts."));
} else {
sender.sendMessage(ChatColor.RED + "Nothing to time!");
}
return true;
} else if (cmd.getName().equalsIgnoreCase("timer")) {
if (args.length != 0) {
if (sender.hasPermission("ArcherGames.admin")) {
try {
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left.");
return true;
} catch (Exception e) {
sender.sendMessage(ChatColor.RED + "Time could not be set.");
return true;
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")) {
if (sender.hasPermission("archergames.admin")) {
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("credtop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:");
HashMap<String, Integer> credits = plugin.db.getTopPoints();
int i = 1;
for(String playerName : credits.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("baltop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:");
HashMap<String, Integer> balances = plugin.db.getTopPoints();
int i = 1;
for(String playerName : balances.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("wintop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:");
HashMap<String, Integer> wins = plugin.db.getTopWinners();
int i = 1;
for(String playerName : wins.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("stats")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:");
sender.sendMessage( ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup));
sender.sendMessage( ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup));
sender.sendMessage( ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup));
sender.sendMessage( ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup));
sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup));
return true;
} else if (cmd.getName().equalsIgnoreCase("credits")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits.");
return true;
} else if (cmd.getName().equalsIgnoreCase("track")){
if(sender.hasPermission("ArcherGames.donor.track")){
if(sender instanceof Player){
if(args.length != 0){
Player player = (Player) sender;
if(!player.getInventory().contains(Material.COMPASS)){
player.getInventory().addItem(new ItemStack(Material.COMPASS));
}
player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation());
player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]);
} else {
sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("ride")){
if(sender instanceof Player){
if(!plugin.serverwide.ridingPlayers.contains(sender.getName())){
plugin.serverwide.ridingPlayers.add(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players.");
} else {
plugin.serverwide.ridingPlayers.remove(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players.");
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("help")){
if(sender instanceof Player){
Player player = (Player) sender;
if (!player.getInventory().contains(Material.BOOK)) {
BookItem bi = new BookItem(new ItemStack(387, 1));
bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author"));
bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title"));
String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]);
bi.setPages(pages);
player.getInventory().addItem(bi.getItemStack());
return true;
} else {
sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("commands")) {
sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements.");
sendHelp(sender, "vote", "List the sites you can vote for the server on.");
sendHelp(sender, "money [player]", "Show either your or another player's money balance.");
sendHelp(sender, "stats [player]", "Show either your or another player's stats.");
sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue");
sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money");
sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)");
sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game.");
sendHelp(sender, "who/online/players", "See the players online and who is alive.");
sendHelp(sender, "credtop", "Show the top players for credits earned.");
sendHelp(sender, "baltop", "Show the top players for money earned.");
sendHelp(sender, "wintop", "Show the top players for games won.");
sendHelp(sender, "stats [player]", "Show the specified player, or your, stats.");
sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)");
sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them");
sendHelp(sender, "help", "Give yourself a help book.");
sendHelp(sender, "commands", "Show this help page.");
sendHelp(sender, "goto (player)", "Teleport to another player while spectating.");
return true;
} else if(cmd.getName().equalsIgnoreCase("goto")){
if(args.length != 0){
Player p = null;
for(Player player : plugin.getServer().getOnlinePlayers()){
if(player.getName().contains(args[0])){
p = player;
}
}
if(p != null){
if(sender instanceof Player){
if(!Archer.getByName(sender.getName()).isAlive){
((Player) sender).teleport(p);
sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName());
return true;
} else {
sender.sendMessage("You must be dead to use that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid player!");
return true;
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + "");
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0]));
return true;
}
} else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) {
String outputAlive = "";
int alive = 0;
String outputSpec = "";
int spec = 0;
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (Archer.getByName(p.getName()).isAlive()) {
outputAlive += p.getDisplayName() + ", ";
alive++;
} else {
spec++;
outputSpec += p.getDisplayName() + ", ";
}
}
sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: ");
sender.sendMessage(outputAlive);
sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: ");
sender.sendMessage(outputSpec);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) {
if (args.length != 0) {
if (ScheduledTasks.gameStatus != 1) {
sender.sendMessage(plugin.strings.get("alreadystartedkits"));
} else {
Kit selectedKit = new Kit();
Boolean isOkay = false;
for (Kit kit : plugin.kits) {
if (args[0].equalsIgnoreCase(kit.getName())) {
isOkay = true;
selectedKit = kit;
}
}
if (isOkay) {
if (Archer.getByName(sender.getName()).isReady()) {
sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), Archer.getByName(sender.getName()).getKit().getName()));
}
if (sender.hasPermission(selectedKit.getPermission())) {
plugin.serverwide.joinGame(sender.getName(), selectedKit);
sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName()));
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
}
} else {
sender.sendMessage(ChatColor.GREEN + "Use /kit (kitname) to select a kit.");
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
String kitsNo = "";
for (Kit kit : plugin.kits) {
if (sender.hasPermission(kit.getPermission())) {
kits += kit.getName() + ", ";
} else {
kitsNo += kit.getName() + ", ";
}
}
sender.sendMessage(ChatColor.GREEN + kits);
sender.sendMessage(plugin.strings.get("kitnoaccessible"));
sender.sendMessage("§c" + kitsNo);
}
return true;
} else if (cmd.getName().equalsIgnoreCase("chunk")) {
if (!(ScheduledTasks.gameStatus == 1)) {
if (sender instanceof Player) {
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
return true;
} else {
return false;
}
} else {
sender.sendMessage(ChatColor.RED + "You may not use this command yet.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("pay")) {
if (args.length != 0) {
if (args.length != 1) {
try {
if (Double.parseDouble(args[1]) > 0) {
if(plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))){
plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1]));
plugin.db.addMoney(args[0], Double.parseDouble(args[1]));
} else {
sender.sendMessage("You cannot afford to send this amount of money!");
}
sender.sendMessage(ChatColor.GREEN + "$" + args[1] + " paid to " + args[0]);
}
} catch (Exception e) {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("time")) {
if (!(ScheduledTasks.gameStatus >= 2)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 3)) {
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if (!(ScheduledTasks.gameStatus >= 4)) {
sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts."));
} else {
sender.sendMessage(ChatColor.RED + "Nothing to time!");
}
return true;
} else if (cmd.getName().equalsIgnoreCase("timer")) {
if (args.length != 0) {
if (sender.hasPermission("ArcherGames.admin")) {
try {
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left.");
return true;
} catch (Exception e) {
sender.sendMessage(ChatColor.RED + "Time could not be set.");
return true;
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")) {
if (sender.hasPermission("archergames.admin")) {
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
} else {
return false;
}
} else if (cmd.getName().equalsIgnoreCase("credtop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:");
HashMap<String, Integer> credits = plugin.db.getTopPoints();
int i = 1;
for(String playerName : credits.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("baltop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:");
HashMap<String, Integer> balances = plugin.db.getTopPoints();
int i = 1;
for(String playerName : balances.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("wintop")){
sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:");
HashMap<String, Integer> wins = plugin.db.getTopWinners();
int i = 1;
for(String playerName : wins.keySet()){
sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName));
i++;
}
return true;
} else if (cmd.getName().equalsIgnoreCase("stats")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:");
sender.sendMessage( ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup));
sender.sendMessage( ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup));
sender.sendMessage( ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup));
sender.sendMessage( ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup));
sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup));
return true;
} else if (cmd.getName().equalsIgnoreCase("credits")){
String lookup = args.length == 0 ? sender.getName() : args[0];
sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits.");
return true;
} else if (cmd.getName().equalsIgnoreCase("track")){
if(sender.hasPermission("ArcherGames.donor.track")){
if(sender instanceof Player){
if(args.length != 0){
Player player = (Player) sender;
if(!player.getInventory().contains(Material.COMPASS)){
player.getInventory().addItem(new ItemStack(Material.COMPASS));
}
player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation());
player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]);
} else {
sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("ride")){
if(sender instanceof Player){
if(!plugin.serverwide.ridingPlayers.contains(sender.getName())){
plugin.serverwide.ridingPlayers.add(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players.");
} else {
plugin.serverwide.ridingPlayers.remove(sender.getName());
sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players.");
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command.");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("help")){
if(sender instanceof Player){
Player player = (Player) sender;
if (!player.getInventory().contains(Material.BOOK)) {
BookItem bi = new BookItem(new ItemStack(387, 1));
bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author"));
bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title"));
String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]);
bi.setPages(pages);
player.getInventory().addItem(bi.getItemStack());
return true;
} else {
sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else if (cmd.getName().equalsIgnoreCase("commands")) {
sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements.");
sendHelp(sender, "vote", "List the sites you can vote for the server on.");
sendHelp(sender, "money [player]", "Show either your or another player's money balance.");
sendHelp(sender, "stats [player]", "Show either your or another player's stats.");
sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue");
sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money");
sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)");
sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game.");
sendHelp(sender, "who/online/players", "See the players online and who is alive.");
sendHelp(sender, "credtop", "Show the top players for credits earned.");
sendHelp(sender, "baltop", "Show the top players for money earned.");
sendHelp(sender, "wintop", "Show the top players for games won.");
sendHelp(sender, "stats [player]", "Show the specified player, or your, stats.");
sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)");
sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them");
sendHelp(sender, "help", "Give yourself a help book.");
sendHelp(sender, "commands", "Show this help page.");
sendHelp(sender, "goto (player)", "Teleport to another player while spectating.");
return true;
} else if(cmd.getName().equalsIgnoreCase("goto")){
if(args.length != 0){
Player p = null;
for(Player player : plugin.getServer().getOnlinePlayers()){
if(player.getName().contains(args[0])){
p = player;
}
}
if(p != null){
if(sender instanceof Player){
if(!Archer.getByName(sender.getName()).isAlive){
((Player) sender).teleport(p);
sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName());
return true;
} else {
sender.sendMessage("You must be dead to use that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!");
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid player!");
return true;
}
}
}
return false;
}
|
diff --git a/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/RSEExecEnvironment.java b/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/RSEExecEnvironment.java
index 3d0b1005d..558c16215 100644
--- a/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/RSEExecEnvironment.java
+++ b/rse/plugins/org.eclipse.dltk.rse.core/src/org/eclipse/dltk/core/internal/rse/RSEExecEnvironment.java
@@ -1,226 +1,227 @@
package org.eclipse.dltk.core.internal.rse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.environment.IDeployment;
import org.eclipse.dltk.core.environment.IEnvironment;
import org.eclipse.dltk.core.environment.IExecutionEnvironment;
import org.eclipse.dltk.internal.launching.execution.EFSDeployment;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.core.subsystems.ISubSystem;
import org.eclipse.rse.internal.efs.RSEFileSystem;
import org.eclipse.rse.services.shells.IHostShell;
import org.eclipse.rse.services.shells.IShellService;
import org.eclipse.rse.subsystems.shells.core.subsystems.servicesubsystem.IShellServiceSubSystem;
public class RSEExecEnvironment implements IExecutionEnvironment {
private final static String EXIT_CMD = "exit"; //$NON-NLS-1$
private final static String CMD_DELIMITER = " ;"; //$NON-NLS-1$
private RSEEnvironment environment;
private static int counter = -1;
private Map environmentVariables = null;
public RSEExecEnvironment(RSEEnvironment env) {
this.environment = env;
}
public IDeployment createDeployment() {
try {
String rootPath = getTempDir() + environment.getSeparator()
+ getTempName("dltk", ".tmp");
URI rootUri = createRemoteURI(environment.getHost(), rootPath);
return new EFSDeployment(environment, rootUri);
} catch (CoreException e) {
if (DLTKCore.DEBUG)
e.printStackTrace();
}
return null;
}
private URI createRemoteURI(IHost host, String rootPath) {
return RSEFileSystem.getURIFor(host.getHostName(), rootPath);
}
private IShellServiceSubSystem getShellServiceSubSystem(IHost host) {
ISubSystem[] subsys = host.getSubSystems();
for (int i = 0; i < subsys.length; i++) {
if (subsys[i] instanceof IShellServiceSubSystem)
return (IShellServiceSubSystem) subsys[i];
}
return null;
}
private String getTempName(String prefix, String suffix) {
if (counter == -1) {
counter = new Random().nextInt() & 0xffff;
}
counter++;
return prefix + Integer.toString(counter) + suffix;
}
private String getTempDir() {
IShellServiceSubSystem system = getShellServiceSubSystem(environment
.getHost());
try {
system.connect(false, null);
} catch (Exception e) {
e.printStackTrace();
}
String temp = system.getConnectorService().getTempDirectory();
if (temp.length() == 0) {
temp = "/tmp";
}
return temp;
}
public Process exec(String[] cmdLine, IPath workingDir, String[] environment)
throws CoreException {
IShellServiceSubSystem shell = getShellServiceSubSystem(this.environment
.getHost());
try {
shell.connect(false, null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (!shell.isConnected()) {
return null;
}
IShellService shellService = shell.getShellService();
IHostShell hostShell = null;
hostShell = shellService.runCommand(workingDir.toPortableString(),
"bash", environment, new NullProgressMonitor());
// Sometimes environment variables aren't set, so use export.
if (environment != null) {
for (int i = 0; i < environment.length; i++) {
hostShell.writeToShell("export "
+ toShellArguments(environment[i]));
}
}
String pattern = "DLTK_INITIAL_PREFIX_EXECUTION_STRING:"
+ String.valueOf(System.currentTimeMillis());
String echoCommand = "echo \"" + pattern + "\"";
// hostShell.writeToShell(echoCommand);
String command = createCommand(cmdLine);
hostShell.writeToShell(echoCommand + " ;" + command + " ;"
+ echoCommand + " ;" + EXIT_CMD);
// hostShell.writeToShell(echoCommand);
// hostShell.writeToShell(EXIT_CMD);
Process p = null;
try {
p = new MyHostShellProcessAdapter(hostShell, pattern);
} catch (Exception e) {
if (p != null) {
p.destroy();
}
throw new RuntimeException("Failed to run remote command");
}
return p;
}
private String toShellArguments(String cmd) {
String replaceAll = cmd.replaceAll(" ", "\\\\ ");
return replaceAll;
}
private String createWorkingDir(IPath workingDir) {
if (workingDir == null)
return ".";
return workingDir.toPortableString();
}
private String createCommand(String[] cmdLine) {
StringBuffer cmd = new StringBuffer();
for (int i = 1; i < cmdLine.length; i++) {
cmd.append(cmdLine[i]);
if (i != cmdLine.length - 1) {
cmd.append(" ");
}
}
return cmdLine[0] + " " + /* toShellArguments( */cmd.toString()/* ) */;
}
public Map getEnvironmentVariables() {
if (this.environmentVariables != null) {
return this.environmentVariables;
}
final Map result = new HashMap();
try {
Process process = this.exec(new String[] { "set" }, new Path(""),
null);
if (process != null) {
final BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (true) {
String line;
line = input.readLine();
if (line == null) {
break;
}
line = line.trim();
int pos = line.indexOf("=");
if (pos != -1) {
String varName = line.substring(0, pos);
String varValue = line.substring(pos + 1);
result.put(varName, varValue);
}
}
} catch (IOException e) {
DLTKRSEPlugin.log(e);
}
}
});
t.start();
try {
t.join(5000);// No more than 5 seconds
} catch (InterruptedException e) {
DLTKRSEPlugin.log(e);
}
+ process.destroy();
}
} catch (CoreException e) {
DLTKRSEPlugin.log(e);
}
if (result.size() > 0) {
environmentVariables = result;
}
return result;
}
public IEnvironment getEnvironment() {
return environment;
}
public boolean isValidExecutableAndEquals(String possibleName, IPath path) {
if (environment.getHost().getSystemType().isWindows()) {
possibleName = possibleName.toLowerCase();
String fName = path.removeFileExtension().toString().toLowerCase();
String ext = path.getFileExtension();
if (possibleName.equals(fName)
&& ("exe".equalsIgnoreCase(ext) || "bat".equalsIgnoreCase(ext))) { //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
} else {
String fName = path.lastSegment();
if (fName.equals(possibleName)) {
return true;
}
}
return false;
}
}
| true | true | public Map getEnvironmentVariables() {
if (this.environmentVariables != null) {
return this.environmentVariables;
}
final Map result = new HashMap();
try {
Process process = this.exec(new String[] { "set" }, new Path(""),
null);
if (process != null) {
final BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (true) {
String line;
line = input.readLine();
if (line == null) {
break;
}
line = line.trim();
int pos = line.indexOf("=");
if (pos != -1) {
String varName = line.substring(0, pos);
String varValue = line.substring(pos + 1);
result.put(varName, varValue);
}
}
} catch (IOException e) {
DLTKRSEPlugin.log(e);
}
}
});
t.start();
try {
t.join(5000);// No more than 5 seconds
} catch (InterruptedException e) {
DLTKRSEPlugin.log(e);
}
}
} catch (CoreException e) {
DLTKRSEPlugin.log(e);
}
if (result.size() > 0) {
environmentVariables = result;
}
return result;
}
public IEnvironment getEnvironment() {
return environment;
}
public boolean isValidExecutableAndEquals(String possibleName, IPath path) {
if (environment.getHost().getSystemType().isWindows()) {
possibleName = possibleName.toLowerCase();
String fName = path.removeFileExtension().toString().toLowerCase();
String ext = path.getFileExtension();
if (possibleName.equals(fName)
&& ("exe".equalsIgnoreCase(ext) || "bat".equalsIgnoreCase(ext))) { //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
} else {
String fName = path.lastSegment();
if (fName.equals(possibleName)) {
return true;
}
}
return false;
}
}
| public Map getEnvironmentVariables() {
if (this.environmentVariables != null) {
return this.environmentVariables;
}
final Map result = new HashMap();
try {
Process process = this.exec(new String[] { "set" }, new Path(""),
null);
if (process != null) {
final BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (true) {
String line;
line = input.readLine();
if (line == null) {
break;
}
line = line.trim();
int pos = line.indexOf("=");
if (pos != -1) {
String varName = line.substring(0, pos);
String varValue = line.substring(pos + 1);
result.put(varName, varValue);
}
}
} catch (IOException e) {
DLTKRSEPlugin.log(e);
}
}
});
t.start();
try {
t.join(5000);// No more than 5 seconds
} catch (InterruptedException e) {
DLTKRSEPlugin.log(e);
}
process.destroy();
}
} catch (CoreException e) {
DLTKRSEPlugin.log(e);
}
if (result.size() > 0) {
environmentVariables = result;
}
return result;
}
public IEnvironment getEnvironment() {
return environment;
}
public boolean isValidExecutableAndEquals(String possibleName, IPath path) {
if (environment.getHost().getSystemType().isWindows()) {
possibleName = possibleName.toLowerCase();
String fName = path.removeFileExtension().toString().toLowerCase();
String ext = path.getFileExtension();
if (possibleName.equals(fName)
&& ("exe".equalsIgnoreCase(ext) || "bat".equalsIgnoreCase(ext))) { //$NON-NLS-1$ //$NON-NLS-2$
return true;
}
} else {
String fName = path.lastSegment();
if (fName.equals(possibleName)) {
return true;
}
}
return false;
}
}
|
diff --git a/src/libbitster/Janitor.java b/src/libbitster/Janitor.java
index 4ec0f72..f1f976d 100644
--- a/src/libbitster/Janitor.java
+++ b/src/libbitster/Janitor.java
@@ -1,69 +1,69 @@
package libbitster;
import java.util.HashSet;
import java.util.Iterator;
/**
* Singleton. Cleans up the program when shutting down.
* @author Martin Miralles-Cordal
*/
public class Janitor extends Actor {
private static Janitor instance;
private String state;
// Hash set of all running managers
private HashSet<Manager> managers;
protected Janitor() {
super();
this.state = "init";
managers = new HashSet<Manager>();
}
@Override
protected void receive (Memo memo) {
// Memo sent when manager is done shutting down
if(memo.getType().equals("done")) {
managers.remove(memo.getSender());
}
}
/**
* Register a {@link Manager} with the {@link Janitor}
* @param m the {@link Manager} to register
*/
public void register(Manager m)
{
managers.add(m);
}
/**
* When thread starts, send halt message to Managers
*/
protected void idle () {
if(state.equals("init")) {
- state.equals("normal");
+ state = "normal";
Iterator<Manager> it = managers.iterator();
while(it.hasNext()) {
Log.info("Sending halt memo to manager.");
it.next().post(new Memo("halt", null, this));
}
}
if(managers.isEmpty()) {
Log.info("All managers report done. Shutting down...");
shutdown();
}
try { Thread.sleep(50); } catch (InterruptedException e) { /* don't care */ }
}
public static Janitor getInstance() {
if(instance == null) {
instance = new Janitor();
}
return instance;
}
}
| true | true | protected void idle () {
if(state.equals("init")) {
state.equals("normal");
Iterator<Manager> it = managers.iterator();
while(it.hasNext()) {
Log.info("Sending halt memo to manager.");
it.next().post(new Memo("halt", null, this));
}
}
if(managers.isEmpty()) {
Log.info("All managers report done. Shutting down...");
shutdown();
}
try { Thread.sleep(50); } catch (InterruptedException e) { /* don't care */ }
}
| protected void idle () {
if(state.equals("init")) {
state = "normal";
Iterator<Manager> it = managers.iterator();
while(it.hasNext()) {
Log.info("Sending halt memo to manager.");
it.next().post(new Memo("halt", null, this));
}
}
if(managers.isEmpty()) {
Log.info("All managers report done. Shutting down...");
shutdown();
}
try { Thread.sleep(50); } catch (InterruptedException e) { /* don't care */ }
}
|
diff --git a/jsf-ri/src/com/sun/faces/component/ComponentResourceContainer.java b/jsf-ri/src/com/sun/faces/component/ComponentResourceContainer.java
index e2f38245c..1eca9b971 100644
--- a/jsf-ri/src/com/sun/faces/component/ComponentResourceContainer.java
+++ b/jsf-ri/src/com/sun/faces/component/ComponentResourceContainer.java
@@ -1,54 +1,54 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.component;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
import java.io.IOException;
public class ComponentResourceContainer extends UIPanel {
/**
* Take no action to prevent component resources from inadvertantly
* being rendered.
*/
@Override
public void encodeAll(FacesContext context) throws IOException {
- super.encodeAll(context); //To change body of overridden methods use File | Settings | File Templates.
+ // no-op
}
}
| true | true | public void encodeAll(FacesContext context) throws IOException {
super.encodeAll(context); //To change body of overridden methods use File | Settings | File Templates.
}
| public void encodeAll(FacesContext context) throws IOException {
// no-op
}
|
diff --git a/src/java/org/lwjgl/test/devil/BasicTest.java b/src/java/org/lwjgl/test/devil/BasicTest.java
index cbeb990d..ce7f9242 100644
--- a/src/java/org/lwjgl/test/devil/BasicTest.java
+++ b/src/java/org/lwjgl/test/devil/BasicTest.java
@@ -1,126 +1,128 @@
/*
* Copyright (c) 2002-2004 LWJGL Project
* 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 'LWJGL' 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 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 org.lwjgl.test.devil;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.devil.IL;
import org.lwjgl.devil.ILU;
import org.lwjgl.devil.ILUT;
import org.lwjgl.devil.ILinfo;
/**
* <p>The core DevIL and ILU API.</p>
*
* @author Mark Bernard <[email protected]>
* @version $Revision$
* $Id$
*/
public class BasicTest {
public static void main(String args[]) {
try {
+ org.lwjgl.opengl.Display.create();
IL.create();
ILU.create();
ILUT.create();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ilGenImages");
IntBuffer im = BufferUtils.createIntBuffer(1);
IL.ilGenImages(im);
System.out.println("ilBindImage");
IL.ilBindImage(im.get(0));
IL.ilEnable(IL.IL_ORIGIN_SET);
IL.ilOriginFunc(IL.IL_ORIGIN_UPPER_LEFT);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
URL imageURL = BasicTest.class.getResource("/res/ILtest.tga");
System.out.println("ilLoadFromURL " + imageURL);
try {
System.out.println("load lump = " + IL.ilLoadFromURL(imageURL));
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int newIm = IL.ilCloneCurImage();
IL.ilCopyImage(im.get(0));
IL.ilBindImage(newIm);
ByteBuffer buf = IL.ilGetData();
System.out.println("ilGetData");
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int limit = buf.limit();
System.out.println("limit = " + limit);
for (int i = 0; i < buf.limit(); i += 3) {
System.out.println(buf.get(i) + " " + buf.get(i + 1) + " " + buf.get(i + 2));
}
System.out.println("current image = " + im.get(0) + " IL.ilGetInteger(IL.IL_ACTIVE_IMAGE) = "
+ IL.ilGetInteger(IL.IL_ACTIVE_IMAGE));
System.out.println("Version: " + IL.ilGetInteger(IL.IL_VERSION_NUM));
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
ILinfo info = new ILinfo();
ILU.iluGetImageInfo(info);
System.out.println("info.id = " + info.id);
System.out.println("info.width = " + info.width);
System.out.println("info.height = " + info.height);
System.out.println("info.depth = " + info.depth);
System.out.println("info.bpp = " + info.bpp);
System.out.println("info.sizeOfData = " + info.sizeOfData);
System.out.println("info.format = " + info.format);
System.out.println("info.type = " + info.type);
System.out.println("info.origin = " + info.origin);
System.out.println("info.palType = " + info.palType);
System.out.println("info.palSize = " + info.palSize);
System.out.println("info.numNext = " + info.numNext);
System.out.println("info.numMips = " + info.numMips);
System.out.println("info.numLayers = " + info.numLayers);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ILUT Vendor: " + ILUT.ilutGetString(ILUT.ILUT_VENDOR));
try {
ILUT.destroy();
ILU.destroy();
IL.destroy();
+ org.lwjgl.opengl.Display.destroy();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
| false | true | public static void main(String args[]) {
try {
IL.create();
ILU.create();
ILUT.create();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ilGenImages");
IntBuffer im = BufferUtils.createIntBuffer(1);
IL.ilGenImages(im);
System.out.println("ilBindImage");
IL.ilBindImage(im.get(0));
IL.ilEnable(IL.IL_ORIGIN_SET);
IL.ilOriginFunc(IL.IL_ORIGIN_UPPER_LEFT);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
URL imageURL = BasicTest.class.getResource("/res/ILtest.tga");
System.out.println("ilLoadFromURL " + imageURL);
try {
System.out.println("load lump = " + IL.ilLoadFromURL(imageURL));
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int newIm = IL.ilCloneCurImage();
IL.ilCopyImage(im.get(0));
IL.ilBindImage(newIm);
ByteBuffer buf = IL.ilGetData();
System.out.println("ilGetData");
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int limit = buf.limit();
System.out.println("limit = " + limit);
for (int i = 0; i < buf.limit(); i += 3) {
System.out.println(buf.get(i) + " " + buf.get(i + 1) + " " + buf.get(i + 2));
}
System.out.println("current image = " + im.get(0) + " IL.ilGetInteger(IL.IL_ACTIVE_IMAGE) = "
+ IL.ilGetInteger(IL.IL_ACTIVE_IMAGE));
System.out.println("Version: " + IL.ilGetInteger(IL.IL_VERSION_NUM));
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
ILinfo info = new ILinfo();
ILU.iluGetImageInfo(info);
System.out.println("info.id = " + info.id);
System.out.println("info.width = " + info.width);
System.out.println("info.height = " + info.height);
System.out.println("info.depth = " + info.depth);
System.out.println("info.bpp = " + info.bpp);
System.out.println("info.sizeOfData = " + info.sizeOfData);
System.out.println("info.format = " + info.format);
System.out.println("info.type = " + info.type);
System.out.println("info.origin = " + info.origin);
System.out.println("info.palType = " + info.palType);
System.out.println("info.palSize = " + info.palSize);
System.out.println("info.numNext = " + info.numNext);
System.out.println("info.numMips = " + info.numMips);
System.out.println("info.numLayers = " + info.numLayers);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ILUT Vendor: " + ILUT.ilutGetString(ILUT.ILUT_VENDOR));
try {
ILUT.destroy();
ILU.destroy();
IL.destroy();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
| public static void main(String args[]) {
try {
org.lwjgl.opengl.Display.create();
IL.create();
ILU.create();
ILUT.create();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ilGenImages");
IntBuffer im = BufferUtils.createIntBuffer(1);
IL.ilGenImages(im);
System.out.println("ilBindImage");
IL.ilBindImage(im.get(0));
IL.ilEnable(IL.IL_ORIGIN_SET);
IL.ilOriginFunc(IL.IL_ORIGIN_UPPER_LEFT);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
URL imageURL = BasicTest.class.getResource("/res/ILtest.tga");
System.out.println("ilLoadFromURL " + imageURL);
try {
System.out.println("load lump = " + IL.ilLoadFromURL(imageURL));
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int newIm = IL.ilCloneCurImage();
IL.ilCopyImage(im.get(0));
IL.ilBindImage(newIm);
ByteBuffer buf = IL.ilGetData();
System.out.println("ilGetData");
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
int limit = buf.limit();
System.out.println("limit = " + limit);
for (int i = 0; i < buf.limit(); i += 3) {
System.out.println(buf.get(i) + " " + buf.get(i + 1) + " " + buf.get(i + 2));
}
System.out.println("current image = " + im.get(0) + " IL.ilGetInteger(IL.IL_ACTIVE_IMAGE) = "
+ IL.ilGetInteger(IL.IL_ACTIVE_IMAGE));
System.out.println("Version: " + IL.ilGetInteger(IL.IL_VERSION_NUM));
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
ILinfo info = new ILinfo();
ILU.iluGetImageInfo(info);
System.out.println("info.id = " + info.id);
System.out.println("info.width = " + info.width);
System.out.println("info.height = " + info.height);
System.out.println("info.depth = " + info.depth);
System.out.println("info.bpp = " + info.bpp);
System.out.println("info.sizeOfData = " + info.sizeOfData);
System.out.println("info.format = " + info.format);
System.out.println("info.type = " + info.type);
System.out.println("info.origin = " + info.origin);
System.out.println("info.palType = " + info.palType);
System.out.println("info.palSize = " + info.palSize);
System.out.println("info.numNext = " + info.numNext);
System.out.println("info.numMips = " + info.numMips);
System.out.println("info.numLayers = " + info.numLayers);
System.out.println("error = " + ILU.iluErrorString(IL.ilGetError()));
System.out.println("ILUT Vendor: " + ILUT.ilutGetString(ILUT.ILUT_VENDOR));
try {
ILUT.destroy();
ILU.destroy();
IL.destroy();
org.lwjgl.opengl.Display.destroy();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
|
diff --git a/httpasyncclient/src/main/java/org/apache/http/impl/nio/client/NHttpClientProtocolHandler.java b/httpasyncclient/src/main/java/org/apache/http/impl/nio/client/NHttpClientProtocolHandler.java
index 03cdfe2..cf13240 100644
--- a/httpasyncclient/src/main/java/org/apache/http/impl/nio/client/NHttpClientProtocolHandler.java
+++ b/httpasyncclient/src/main/java/org/apache/http/impl/nio/client/NHttpClientProtocolHandler.java
@@ -1,408 +1,409 @@
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.client;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpInetConnection;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.client.HttpAsyncExchangeHandler;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HttpContext;
/**
* Fully asynchronous HTTP client side protocol handler that implements the
* essential requirements of the HTTP protocol for the server side message
* processing as described by RFC 2616. It is capable of executing HTTP requests
* with nearly constant memory footprint. Only HTTP message heads are stored in
* memory, while content of message bodies is streamed directly from the entity
* to the underlying channel (and vice versa) using {@link ConsumingNHttpEntity}
* and {@link ProducingNHttpEntity} interfaces.
*/
class NHttpClientProtocolHandler implements NHttpClientHandler {
private final Log log = LogFactory.getLog(getClass());
private static final String HTTP_EXCHNAGE = "http.nio.exchange";
public NHttpClientProtocolHandler() {
super();
}
private void closeConnection(final NHttpClientConnection conn) {
try {
conn.close();
} catch (IOException ex) {
try {
conn.shutdown();
} catch (IOException ignore) {
this.log.debug("I/O error terminating connection: " + ex.getMessage(), ex);
}
}
}
protected void shutdownConnection(final NHttpClientConnection conn) {
try {
conn.shutdown();
} catch (IOException ex) {
this.log.debug("I/O error terminating connection: " + ex.getMessage(), ex);
}
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
HttpExchange httpexchange = new HttpExchange();
HttpContext context = conn.getContext();
if (this.log.isDebugEnabled()) {
this.log.debug("Connected " + formatState(conn, httpexchange));
}
context.setAttribute(HTTP_EXCHNAGE, httpexchange);
requestReady(conn);
}
public void closed(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Disconnected " + formatState(conn, httpexchange));
}
if (handler != null) {
handler.cancel();
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
HttpContext context = conn.getContext();
HttpAsyncExchangeHandler<?> handler = getHandler(context);
this.log.error("HTTP protocol exception: " + ex.getMessage(), ex);
if (handler != null) {
handler.failed(ex);
}
closeConnection(conn);
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
HttpContext context = conn.getContext();
HttpAsyncExchangeHandler<?> handler = getHandler(context);
this.log.error("I/O error: " + ex.getMessage(), ex);
if (handler != null) {
handler.failed(ex);
}
shutdownConnection(conn);
}
public void requestReady(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Request ready " + formatState(conn, httpexchange));
}
if (httpexchange.getRequestState() != MessageState.READY) {
return;
}
if (handler == null || handler.isDone()) {
if (this.log.isDebugEnabled()) {
this.log.debug("No request submitted " + formatState(conn, httpexchange));
}
return;
}
try {
HttpRequest request = handler.generateRequest();
httpexchange.setRequest(request);
HttpEntityEnclosingRequest entityReq = null;
if (request instanceof HttpEntityEnclosingRequest) {
entityReq = (HttpEntityEnclosingRequest) request;
}
conn.submitRequest(request);
if (entityReq != null) {
if (entityReq.expectContinue()) {
int timeout = conn.getSocketTimeout();
httpexchange.setTimeout(timeout);
timeout = request.getParams().getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
conn.setSocketTimeout(timeout);
httpexchange.setRequestState(MessageState.ACK);
} else {
httpexchange.setRequestState(MessageState.BODY_STREAM);
}
} else {
httpexchange.setRequestState(MessageState.COMPLETED);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
} catch (HttpException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP protocol exception: " + ex.getMessage(), ex);
}
closeConnection(conn);
handler.failed(ex);
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Input ready " + formatState(conn, httpexchange));
}
try {
handler.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
processResponse(conn, httpexchange, handler);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Output ready " + formatState(conn, httpexchange));
}
try {
if (httpexchange.getRequestState() == MessageState.ACK) {
conn.suspendOutput();
return;
}
handler.produceContent(encoder, conn);
if (encoder.isCompleted()) {
httpexchange.setRequestState(MessageState.COMPLETED);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Response received " + formatState(conn, httpexchange));
}
try {
HttpResponse response = conn.getHttpResponse();
HttpRequest request = httpexchange.getRequest();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
httpexchange.setRequestState(MessageState.BODY_STREAM);
}
return;
} else {
httpexchange.setResponse(response);
if (httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
httpexchange.setRequestState(MessageState.COMPLETED);
} else if (httpexchange.getRequestState() == MessageState.BODY_STREAM) {
// Early response
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.suspendOutput();
conn.resetOutput();
httpexchange.invalidate();
}
}
handler.responseReceived(response);
if (!canResponseHaveBody(request, response)) {
+ conn.resetInput();
processResponse(conn, httpexchange, handler);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
} catch (HttpException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP protocol exception: " + ex.getMessage(), ex);
}
closeConnection(conn);
handler.failed(ex);
}
}
public void timeout(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Timeout " + formatState(conn, httpexchange));
}
try {
if (httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
httpexchange.setRequestState(MessageState.BODY_STREAM);
} else {
if (conn.getStatus() == NHttpConnection.ACTIVE) {
conn.close();
if (conn.getStatus() == NHttpConnection.CLOSING) {
// Give the connection some grace time to
// close itself nicely
conn.setSocketTimeout(250);
}
} else {
conn.shutdown();
}
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
}
}
private HttpExchange getHttpExchange(final HttpContext context) {
return (HttpExchange) context.getAttribute(HTTP_EXCHNAGE);
}
private HttpAsyncExchangeHandler<?> getHandler(final HttpContext context) {
return (HttpAsyncExchangeHandler<?>) context.getAttribute(
DefaultAsyncRequestDirector.HTTP_EXCHANGE_HANDLER);
}
private void processResponse(
final NHttpClientConnection conn,
final HttpExchange httpexchange,
final HttpAsyncExchangeHandler<?> handler) throws IOException {
if (!httpexchange.isValid()) {
conn.close();
}
HttpRequest request = httpexchange.getRequest();
HttpResponse response = httpexchange.getResponse();
String method = request.getRequestLine().getMethod();
int status = response.getStatusLine().getStatusCode();
if (method.equalsIgnoreCase("CONNECT") && status == HttpStatus.SC_OK) {
this.log.debug("CONNECT method succeeded");
conn.resetInput();
} else {
if (!handler.keepAlive(response)) {
this.log.debug("Connection cannot be kept alive");
conn.close();
}
}
if (this.log.isDebugEnabled()) {
this.log.debug("Response processed " + formatState(conn, httpexchange));
}
handler.responseCompleted();
httpexchange.reset();
}
private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) {
String method = request.getRequestLine().getMethod();
int status = response.getStatusLine().getStatusCode();
if (method.equalsIgnoreCase("HEAD")) {
return false;
}
if (method.equalsIgnoreCase("CONNECT") && status == HttpStatus.SC_OK) {
return false;
}
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
private String formatState(final NHttpConnection conn, final HttpExchange httpexchange) {
StringBuilder buf = new StringBuilder();
buf.append("[");
if (conn.isOpen() && (conn instanceof HttpInetConnection)) {
HttpInetConnection inetconn = (HttpInetConnection) conn;
buf.append(inetconn.getRemoteAddress());
buf.append(":");
buf.append(inetconn.getRemotePort());
}
buf.append("(");
buf.append(conn.isOpen() ? "open" : "closed");
buf.append("),request=");
buf.append(httpexchange.getRequestState());
if (httpexchange.getRequest() != null) {
buf.append("(");
buf.append(httpexchange.getRequest().getRequestLine());
buf.append(")");
}
buf.append(",response=");
buf.append(httpexchange.getResponseState());
if (httpexchange.getResponse() != null) {
buf.append("(");
buf.append(httpexchange.getResponse().getStatusLine());
buf.append(")");
}
buf.append(",valid=");
buf.append(httpexchange.isValid());
buf.append("]");
return buf.toString();
}
}
| true | true | public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Response received " + formatState(conn, httpexchange));
}
try {
HttpResponse response = conn.getHttpResponse();
HttpRequest request = httpexchange.getRequest();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
httpexchange.setRequestState(MessageState.BODY_STREAM);
}
return;
} else {
httpexchange.setResponse(response);
if (httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
httpexchange.setRequestState(MessageState.COMPLETED);
} else if (httpexchange.getRequestState() == MessageState.BODY_STREAM) {
// Early response
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.suspendOutput();
conn.resetOutput();
httpexchange.invalidate();
}
}
handler.responseReceived(response);
if (!canResponseHaveBody(request, response)) {
processResponse(conn, httpexchange, handler);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
} catch (HttpException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP protocol exception: " + ex.getMessage(), ex);
}
closeConnection(conn);
handler.failed(ex);
}
}
| public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
HttpExchange httpexchange = getHttpExchange(context);
HttpAsyncExchangeHandler<?> handler = getHandler(context);
if (this.log.isDebugEnabled()) {
this.log.debug("Response received " + formatState(conn, httpexchange));
}
try {
HttpResponse response = conn.getHttpResponse();
HttpRequest request = httpexchange.getRequest();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
httpexchange.setRequestState(MessageState.BODY_STREAM);
}
return;
} else {
httpexchange.setResponse(response);
if (httpexchange.getRequestState() == MessageState.ACK) {
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
httpexchange.setRequestState(MessageState.COMPLETED);
} else if (httpexchange.getRequestState() == MessageState.BODY_STREAM) {
// Early response
int timeout = httpexchange.getTimeout();
conn.setSocketTimeout(timeout);
conn.suspendOutput();
conn.resetOutput();
httpexchange.invalidate();
}
}
handler.responseReceived(response);
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
processResponse(conn, httpexchange, handler);
}
} catch (IOException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("I/O error: " + ex.getMessage(), ex);
}
shutdownConnection(conn);
handler.failed(ex);
} catch (HttpException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug("HTTP protocol exception: " + ex.getMessage(), ex);
}
closeConnection(conn);
handler.failed(ex);
}
}
|
diff --git a/uk.ac.gda.common.rcp/src/uk/ac/gda/common/rcp/util/GridUtils.java b/uk.ac.gda.common.rcp/src/uk/ac/gda/common/rcp/util/GridUtils.java
index d1b849c..896d452 100644
--- a/uk.ac.gda.common.rcp/src/uk/ac/gda/common/rcp/util/GridUtils.java
+++ b/uk.ac.gda.common.rcp/src/uk/ac/gda/common/rcp/util/GridUtils.java
@@ -1,208 +1,211 @@
/*-
* Copyright © 2009 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.gda.common.rcp.util;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* Class to deal with setting items in a grid layout invisible. Allows batch updating of controls to reduce flicker
*/
public class GridUtils {
private static int depthCount = 0;
/** FIXME - static collections with widgets in are a bad idea, causes memory leaks **/
private static Set<Control> controlsToLayout = new HashSet<Control>();
/** FIXME - static collections with widgets in are a bad idea, causes memory leaks **/
private static Stack<Control> controlsToRedraw = new Stack<Control>();
/**
* Start a batch layout update. Wrap multiple calls to setVisibleAndLayout or layout with start/end MultLayout.
* <p>
* Calls to startMultiLayout can be nested as a stack is used internally. The last call to endMultiLayout causes all
* the layouts to happen at once.
* </p>
*
* @param parent
* a suitable control that encompasses all the controls that may have their visibility changed. parent is
* optional and can be null. If parent is "wrong" or null the effect is simply to have slightly more
* flicker in the UI that optimal
*/
public static void startMultiLayout(Control parent) {
if (parent != null)
parent.setRedraw(false);
controlsToRedraw.push(parent);
depthCount++;
}
/**
* End a batch layout update. If the stack is empty, the all the controls that have had layout updated will now be
* laid out and redrawn.
*/
public static void endMultiLayout() {
depthCount--;
if (depthCount == 0 && controlsToLayout.size() > 0) {
Control[] controls = controlsToLayout.toArray(new Control[controlsToLayout.size()]);
controls[0].getShell().layout(controls);
for (Control control : controls) {
control.setRedraw(true);
}
controlsToLayout.clear();
}
Control parent = controlsToRedraw.pop();
if (parent != null)
parent.setRedraw(true);
}
/**
* Changes visibility and layout of a control. Takes into consideration excluding the control from the GridData
* layout manager.
* <p>
* If this function is called within the scope of startMultiLayout, the final steps of layout will not take effect
* until endMultiLayout is called.
* </p>
*
* @param widget
* the widget to make visible or invisible
* @param isVisible
* is true to make widget visible, false to hide it
*/
public static void setVisibleAndLayout(final Control widget, final boolean isVisible) {
if (widget == null) return;
if (!(widget.getLayoutData() instanceof GridData)) {
throw new IllegalArgumentException("Widget must have GridData layout data applied");
}
final GridData data = (GridData) widget.getLayoutData();
if (data.exclude != !isVisible || widget.getVisible() != isVisible) {
data.exclude = !isVisible;
if (depthCount == 0) {
// perform update immediately
widget.setVisible(isVisible);
try {
- widget.getShell().layout(new Control[] { widget });
+ //changed from widget.getShell() to widget.getParent() as the former
+ //led to views not laying out correctly when opened in running workbench despite working
+ //ok if view is opened during workbench initialisation
+ widget.getParent().layout(new Control[] { widget });
} catch (Exception ignored) {
// If we cannot layout parent then not a problem.
}
} else {
// defer update until endMultiUpdate is called
// don't turn off redraw multiple times for the same
// widget because we only turn it back on once.
// This is important since setRedraw is stacked
if (!controlsToLayout.contains(widget)) {
widget.setRedraw(false);
}
widget.setVisible(isVisible);
controlsToLayout.add(widget);
}
}
}
/**
* Simplified version of setVisibleAndLayout(...) which cannot cause
* a memory leak. Does not work with startMultiLayout() and endMultiLayout()
*
* You need to call layout once on the parent widget after using this method. For instance:
*
*
GridUtils.setVisible(wLabel, wVisible);
GridUtils.setVisible(w, wVisible);
GridUtils.setVisible(kLabel, kVisible);
GridUtils.setVisible(kStart, kVisible);
getShell().layout();
*
* @param widget
* @param isVisible
*/
public static void setVisible(final Control widget, final boolean isVisible) {
if (widget == null) return;
if (widget.getLayoutData() instanceof GridData) {
final GridData data = (GridData) widget.getLayoutData();
data.exclude = !isVisible;
}
widget.setVisible(isVisible);
}
/**
* Calls layout on the control, deferring the call if within a start/endMultiLayout call. Use this version of layout
* only when you are sure that the bounding box has not changed, otherwise, use layoutFull
*
* @param control
* is the widget to re-layout
*/
public static void layout(Composite control) {
if (depthCount == 0) {
control.layout();
} else {
controlsToLayout.add(control);
controlsToLayout.addAll(Arrays.asList(control.getChildren()));
}
}
/**
* Calls layout on the control, deferring the call if within a start/endMultiLayout call. As opposed to layout(),
* this forces a full layout.
*
* @param control
* is the widget to re-layout
*/
public static void layoutFull(Composite control) {
if (depthCount == 0) {
try {
control.setRedraw(false);
control.getShell().layout(new Control[] { control });
control.layout();
} finally {
control.setRedraw(true);
}
} else {
controlsToLayout.add(control);
controlsToLayout.addAll(Arrays.asList(control.getChildren()));
}
}
/**
*
* @param area
*/
public static void removeMargins(Composite area) {
final GridLayout layout = (GridLayout)area.getLayout();
layout.horizontalSpacing=0;
layout.verticalSpacing =0;
layout.marginBottom =0;
layout.marginTop =0;
layout.marginLeft =0;
layout.marginRight =0;
layout.marginHeight =0;
layout.marginWidth =0;
}
}
| true | true | public static void setVisibleAndLayout(final Control widget, final boolean isVisible) {
if (widget == null) return;
if (!(widget.getLayoutData() instanceof GridData)) {
throw new IllegalArgumentException("Widget must have GridData layout data applied");
}
final GridData data = (GridData) widget.getLayoutData();
if (data.exclude != !isVisible || widget.getVisible() != isVisible) {
data.exclude = !isVisible;
if (depthCount == 0) {
// perform update immediately
widget.setVisible(isVisible);
try {
widget.getShell().layout(new Control[] { widget });
} catch (Exception ignored) {
// If we cannot layout parent then not a problem.
}
} else {
// defer update until endMultiUpdate is called
// don't turn off redraw multiple times for the same
// widget because we only turn it back on once.
// This is important since setRedraw is stacked
if (!controlsToLayout.contains(widget)) {
widget.setRedraw(false);
}
widget.setVisible(isVisible);
controlsToLayout.add(widget);
}
}
}
| public static void setVisibleAndLayout(final Control widget, final boolean isVisible) {
if (widget == null) return;
if (!(widget.getLayoutData() instanceof GridData)) {
throw new IllegalArgumentException("Widget must have GridData layout data applied");
}
final GridData data = (GridData) widget.getLayoutData();
if (data.exclude != !isVisible || widget.getVisible() != isVisible) {
data.exclude = !isVisible;
if (depthCount == 0) {
// perform update immediately
widget.setVisible(isVisible);
try {
//changed from widget.getShell() to widget.getParent() as the former
//led to views not laying out correctly when opened in running workbench despite working
//ok if view is opened during workbench initialisation
widget.getParent().layout(new Control[] { widget });
} catch (Exception ignored) {
// If we cannot layout parent then not a problem.
}
} else {
// defer update until endMultiUpdate is called
// don't turn off redraw multiple times for the same
// widget because we only turn it back on once.
// This is important since setRedraw is stacked
if (!controlsToLayout.contains(widget)) {
widget.setRedraw(false);
}
widget.setVisible(isVisible);
controlsToLayout.add(widget);
}
}
}
|
diff --git a/d2s-platform/src/main/java/org/data2semantics/platform/reporting/HTMLReporter.java b/d2s-platform/src/main/java/org/data2semantics/platform/reporting/HTMLReporter.java
index 06a6468..49f7315 100644
--- a/d2s-platform/src/main/java/org/data2semantics/platform/reporting/HTMLReporter.java
+++ b/d2s-platform/src/main/java/org/data2semantics/platform/reporting/HTMLReporter.java
@@ -1,652 +1,652 @@
package org.data2semantics.platform.reporting;
import static org.data2semantics.platform.reporting.ReporterTools.safe;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.data2semantics.platform.Global;
import org.data2semantics.platform.core.Module;
import org.data2semantics.platform.core.ModuleInstance;
import org.data2semantics.platform.core.Workflow;
import org.data2semantics.platform.core.data.Input;
import org.data2semantics.platform.core.data.InstanceInput;
import org.data2semantics.platform.core.data.InstanceOutput;
import org.data2semantics.platform.core.data.MultiInput;
import org.data2semantics.platform.core.data.Output;
import org.data2semantics.platform.core.data.ReferenceInput;
import org.data2semantics.platform.util.FrequencyModel;
import org.data2semantics.platform.util.Functions;
import de.neuland.jade4j.Jade4J;
import de.neuland.jade4j.JadeConfiguration;
import de.neuland.jade4j.template.JadeTemplate;
public class HTMLReporter implements Reporter
{
public static List<Parser> parsers = new ArrayList<Parser>();
static {
parsers.add(new ImageParser());
parsers.add(new ToStringParser());
}
private Workflow workflow;
private File root;
public HTMLReporter(Workflow workflow, File root)
{
this.workflow = workflow;
this.root = root;
}
@Override
public void report() throws IOException
{
new ReportWriter();
}
@Override
public Workflow workflow()
{
return workflow;
}
/**
* A singular environment for the purpose of writing a report.
*
* @author Peter
*
*/
private class ReportWriter
{
private final File temp = new File("./tmp/");
JadeConfiguration config = new JadeConfiguration();
public ReportWriter() throws IOException
{
config.setPrettyPrint(true);
// * Copy the templates to a temporary directory
temp.mkdirs();
ReporterTools.copy("html/templates", temp);
for (Module module : workflow.modules())
{
// * Output module information
File moduleDir = new File(root, "/modules/"
+ ReporterTools.safe(module.name()));
if (module.ready())
{
int i = 0;
for (ModuleInstance instance : module.instances())
{
// * Output the instance information
int padding = 1 + (int) Math.log10(module.instances()
.size());
File instanceDir = new File(moduleDir, String.format(
"./%0" + padding + "d/", i));
instanceOutput(instance, instanceDir, i);
i++;
}
}
moduleOutput(module, moduleDir);
}
// * Output the workflow information
workflowOutput(workflow, root);
// Problems deleting template in windows
FileUtils.deleteQuietly(temp);
}
public JadeConfiguration jadeConfig()
{
return config;
}
private String produceDotString()
{
StringBuffer result = new StringBuffer();
result.append("digraph{");
for (Module module : workflow.modules())
{
for (Input inp : module.inputs())
{
if (inp instanceof ReferenceInput)
{
ReferenceInput ri = (ReferenceInput) inp;
result.append(ri.reference().module().name() + "->"
+ module.name() + "[label=\""
+ ri.reference().name() + "\"]");
} else if (inp instanceof MultiInput)
{
for (Input i : ((MultiInput) inp).inputs())
{
if (i instanceof ReferenceInput)
{
ReferenceInput ri = (ReferenceInput) i;
result.append(ri.reference().module().name()
+ "->" + module.name() + "[label=\""
+ ri.reference().name() + "\"]");
}
}
}
}
}
result.append("}");
return result.toString();
}
private void workflowOutput(Workflow workflow, File root)
throws IOException
{
// copy the static files
ReporterTools.copy("html/static", root);
// * The data we will pass to the template
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("name", workflow.name());
templateData.put("short_name", workflow.name());
templateData.put("tags", "");
templateData.put("dotstring", produceDotString());
List<Map<String, Object>> modules = new ArrayList<Map<String, Object>>();
for (Module module : workflow.modules())
{
Map<String, Object> moduleMap = new LinkedHashMap<String, Object>();
moduleMap.put("name", module.name());
moduleMap.put("url",
"./modules/" + ReporterTools.safe(module.name())
+ "/index.html");
moduleMap.put("instances", module.instances().size());
modules.add(moduleMap);
}
templateData.put("modules", modules);
// * Load the template
JadeTemplate tpl = getTemplate("workflow");
root.mkdirs();
// * Process the template
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(root, "index.html")));
config.renderTemplate(tpl, templateData, out);
out.flush();
} catch (IOException e)
{
Global.log()
.warning(
"Failed to write to workflow directory. Continuing without writing report. IOException: "
+ e.getMessage()
+ " - "
+ Arrays.toString(e.getStackTrace()));
return;
}
}
private void moduleOutput(Module module, File moduleDir)
throws IOException
{
// * The data we will pass to the template
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("name", module.name());
templateData.put("short_name", module.name());
templateData.put("tags", "");
templateData.put("workflow_name", module.workflow().name());
templateData.put("instantiated", module.instantiated());
List<Map<String, Object>> instances = new ArrayList<Map<String, Object>>();
if (module.instantiated())
{
// * Collect the input names
List<String> inputNames = new ArrayList<String>();
for (Input input : module.inputs())
if(input.print())
inputNames.add(input.name());
templateData.put("input_names", inputNames);
int i = 0;
int padding = 1 + (int) Math.log10(module.instances().size());
for (ModuleInstance instance : module.instances())
{
// * Collect the instance inputs
List<String> instanceInputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
instanceInputs.add(input.value().toString());
// * Collect the instance information
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
instanceMap
.put("url",
String.format("./%0" + padding
+ "d/index.html", i));
instanceMap.put("inputs", instanceInputs);
instances.add(instanceMap);
i++;
}
}
templateData.put("instances", instances);
List<Map<String, Object>> outputs = new ArrayList<Map<String, Object>>();
for (Output output : module.outputs())
if(output.print())
{
Map<String, Object> outputMap = new LinkedHashMap<String, Object>();
outputMap.put("name", output.name());
- outputMap.put("safe-name", safe(output.name()));
+ outputMap.put("safe_name", safe(output.name()));
outputMap.put("description", output.description());
List<Map<String, Object>> outputInstances = new ArrayList<Map<String, Object>>();
// * Collect values for all instances
List<Object> values = new ArrayList<Object>();
for (ModuleInstance instance : module.instances())
{
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
List<String> inputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
inputs.add(input.value().toString());
instanceMap.put("inputs", inputs);
Object value = instance.output(output.name()).value();
instanceMap.put("output", Functions.toString(value));
values.add(value);
outputInstances.add(instanceMap);
}
outputMap.put("instances", outputInstances);
// * Collect summary info
boolean isNumeric = isNumeric(values);
outputMap.put("is_numeric", isNumeric);
FrequencyModel<Object> fm = new FrequencyModel<Object>(values);
outputMap.put("mode", (fm.distinct() > 0) ? Functions.toString(fm.sorted().get(0)) : "");
outputMap.put("mode_frequency",
(fm.distinct()>0) ? fm.frequency(fm.sorted().get(0)) : 0);
outputMap.put("num_instances", values.size());
outputMap.put("entropy", fm.entropy());
if (isNumeric)
{
List<Number> numbers = numbers(values);
outputMap.put("mean", mean(numbers));
outputMap.put("dev", standardDeviation(numbers));
outputMap.put("median", median(numbers));
}
outputs.add(outputMap);
}
templateData.put("outputs", outputs);
List<Map<String, Object>> inputs = new ArrayList<Map<String, Object>>();
for (Input input : module.inputs())
if(input.print())
{
Map<String, Object> inputMap = new LinkedHashMap<String, Object>();
inputMap.put("name", input.name());
inputMap.put("description", input.description());
List<String> values = new ArrayList<String>();
for (ModuleInstance instance : module.instances())
values.add(Functions.toString(instance.input(input.name())
.value()));
inputMap.put("values", values);
inputs.add(inputMap);
}
templateData.put("inputs", inputs);
// * Load the template
JadeTemplate tpl = getTemplate("module");
moduleDir.mkdirs();
// * Process the template
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(moduleDir, "index.html")));
config.renderTemplate(tpl, templateData, out);
out.flush();
} catch (IOException e)
{
Global.log()
.warning(
"Failed to write to workflow directory. Continuing without writing report. IOException: "
+ e.getMessage()
+ " - "
+ Arrays.toString(e.getStackTrace()));
return;
}
}
/**
* Prepare and write a specific module instance to an HTML page.
*
* @param instance
* @param instanceDir
*/
private void instanceOutput(
ModuleInstance instance, File instanceDir, int i) throws IOException
{
// * The data we will pass to the template
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("workflow_name", instance.module().workflow()
.name());
templateData.put("name", instance.module().name());
templateData.put("short_name", instance.module().name() + "(" + i
+ ")");
templateData.put("tags", "");
templateData.put("instance", i);
List<Map<String, Object>> inputs = new ArrayList<Map<String, Object>>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
{
Map<String, Object> inputMap = new LinkedHashMap<String, Object>();
inputMap.put("name", input.name());
inputMap.put("description", input.description());
inputMap.put("value",
parse(input.value(), input.name(), instanceDir)
);
inputs.add(inputMap);
}
templateData.put("inputs", inputs);
List<Map<String, Object>> outputs = new ArrayList<Map<String, Object>>();
for (InstanceOutput output : instance.outputs())
if(output.original().print())
{
Map<String, Object> outputMap = new LinkedHashMap<String, Object>();
outputMap.put("name", output.name());
outputMap.put("description", output.description());
outputMap.put("value",
parse(output.value(), output.name(), instanceDir)
);
outputs.add(outputMap);
}
templateData.put("outputs", outputs);
// * Load the template
JadeTemplate tpl = getTemplate("instance");
instanceDir.mkdirs();
// * Process the template
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(instanceDir, "index.html")));
config.renderTemplate(tpl, templateData, out);
out.flush();
} catch (IOException e)
{
Global.log()
.warning(
"Failed to write to workflow directory. Continuing without writing report. IOException: "
+ e.getMessage()
+ " - "
+ Arrays.toString(e.getStackTrace()));
return;
}
}
private JadeTemplate getTemplate(String string) throws IOException
{
String raw = temp.getAbsolutePath() + File.separator + string;
// String uri = URLEncoder.encode(raw, "UTF-8");
// String uri = raw.replace(" ", "%20");
return config.getTemplate(raw);
}
public String parse(Object value, String name, File dir)
{
for(Parser parser : parsers)
if(parser.accept(value))
return parser.parse(value, name, this, dir);
throw new RuntimeException("No parser found for value: "+ value);
}
}
/**
* Whether all result values represent numbers
*
* @return
*/
public static boolean isNumeric(List<?> values)
{
for (Object value : values)
if (!(value instanceof Number))
return false;
return true;
}
public static double mean(List<? extends Number> values)
{
double sum = 0.0;
double num = 0.0;
for (Object value : values)
{
double v = ((Number) value).doubleValue();
if (!(Double.isNaN(v) || Double.isNaN(v)))
{
sum += v;
num++;
}
}
return sum / num;
}
public static double standardDeviation(List<? extends Number> values)
{
double mean = mean(values);
double num = 0.0;
double varSum = 0.0;
for (Object value : values)
{
double v = ((Number) value).doubleValue();
if (!(Double.isNaN(v) || Double.isNaN(v)))
{
double diff = mean - v;
varSum += diff * diff;
num++;
}
}
double variance = varSum / (num - 1);
return Math.sqrt(variance);
}
public static double median(List<? extends Number> values)
{
List<Double> vs = new ArrayList<Double>(values.size());
for (Object value : values)
{
double v = ((Number) value).doubleValue();
if (!(Double.isNaN(v) || Double.isNaN(v)))
{
vs.add(v);
}
}
if (vs.isEmpty())
return -1.0;
Collections.sort(vs);
if (vs.size() % 2 == 1)
return vs.get(vs.size() / 2); // element s/2+1, but index s/2
return (vs.get(vs.size() / 2 - 1) + vs.get(vs.size() / 2)) / 2.0;
}
public static <T> T mode(List<T> values)
{
FrequencyModel<T> model = new FrequencyModel<T>(values);
return model.sorted().get(0);
}
public static List<Number> numbers(List<Object> values)
{
List<Number> numbers = new ArrayList<Number>(values.size());
for (Object value : values)
try
{
numbers.add((Number) value);
} catch (ClassCastException e)
{
throw new RuntimeException("Non-number object (type: "
+ value.getClass() + ", toString: " + value
+ ") found in list. Cannot convert to list of numbers.");
}
return numbers;
}
public static interface Parser
{
/**
* Whether thiw parser accepts this value
* @return
*/
public boolean accept(Object value);
public String parse(Object value, String name, ReportWriter writer, File dir);
}
public static class ToStringParser implements Parser
{
@Override
public boolean accept(Object value)
{
return true;
}
@Override
public String parse(Object value, String name, ReportWriter writer, File dir)
{
return Functions.toString(value);
}
}
public static class ImageParser implements Parser {
@Override
public boolean accept(Object value)
{
return value instanceof RenderedImage;
}
@Override
public String parse(Object value, String name, ReportWriter writer, File dir)
{
RenderedImage image = (RenderedImage) value;
// * Write the image
File imageDir = new File(dir, "images/");
imageDir.mkdirs();
String filename = name + "-" + Functions.randomString(5) + ".png";
File imageFile = new File(imageDir, filename);
try
{
ImageIO.write(image, "PNG", imageFile);
} catch (IOException e)
{
throw new RuntimeException(e);
}
// * Collate the data
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("name", name);
templateData.put("url", imageFile.toString());
// * Load the template
JadeTemplate tpl;
try
{
tpl = writer.getTemplate("parser.image.jade");
} catch (IOException e)
{
throw new RuntimeException(e);
}
// * Process the template
return writer.jadeConfig().renderTemplate(tpl, templateData);
}
}
}
| true | true | private void moduleOutput(Module module, File moduleDir)
throws IOException
{
// * The data we will pass to the template
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("name", module.name());
templateData.put("short_name", module.name());
templateData.put("tags", "");
templateData.put("workflow_name", module.workflow().name());
templateData.put("instantiated", module.instantiated());
List<Map<String, Object>> instances = new ArrayList<Map<String, Object>>();
if (module.instantiated())
{
// * Collect the input names
List<String> inputNames = new ArrayList<String>();
for (Input input : module.inputs())
if(input.print())
inputNames.add(input.name());
templateData.put("input_names", inputNames);
int i = 0;
int padding = 1 + (int) Math.log10(module.instances().size());
for (ModuleInstance instance : module.instances())
{
// * Collect the instance inputs
List<String> instanceInputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
instanceInputs.add(input.value().toString());
// * Collect the instance information
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
instanceMap
.put("url",
String.format("./%0" + padding
+ "d/index.html", i));
instanceMap.put("inputs", instanceInputs);
instances.add(instanceMap);
i++;
}
}
templateData.put("instances", instances);
List<Map<String, Object>> outputs = new ArrayList<Map<String, Object>>();
for (Output output : module.outputs())
if(output.print())
{
Map<String, Object> outputMap = new LinkedHashMap<String, Object>();
outputMap.put("name", output.name());
outputMap.put("safe-name", safe(output.name()));
outputMap.put("description", output.description());
List<Map<String, Object>> outputInstances = new ArrayList<Map<String, Object>>();
// * Collect values for all instances
List<Object> values = new ArrayList<Object>();
for (ModuleInstance instance : module.instances())
{
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
List<String> inputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
inputs.add(input.value().toString());
instanceMap.put("inputs", inputs);
Object value = instance.output(output.name()).value();
instanceMap.put("output", Functions.toString(value));
values.add(value);
outputInstances.add(instanceMap);
}
outputMap.put("instances", outputInstances);
// * Collect summary info
boolean isNumeric = isNumeric(values);
outputMap.put("is_numeric", isNumeric);
FrequencyModel<Object> fm = new FrequencyModel<Object>(values);
outputMap.put("mode", (fm.distinct() > 0) ? Functions.toString(fm.sorted().get(0)) : "");
outputMap.put("mode_frequency",
(fm.distinct()>0) ? fm.frequency(fm.sorted().get(0)) : 0);
outputMap.put("num_instances", values.size());
outputMap.put("entropy", fm.entropy());
if (isNumeric)
{
List<Number> numbers = numbers(values);
outputMap.put("mean", mean(numbers));
outputMap.put("dev", standardDeviation(numbers));
outputMap.put("median", median(numbers));
}
outputs.add(outputMap);
}
templateData.put("outputs", outputs);
List<Map<String, Object>> inputs = new ArrayList<Map<String, Object>>();
for (Input input : module.inputs())
if(input.print())
{
Map<String, Object> inputMap = new LinkedHashMap<String, Object>();
inputMap.put("name", input.name());
inputMap.put("description", input.description());
List<String> values = new ArrayList<String>();
for (ModuleInstance instance : module.instances())
values.add(Functions.toString(instance.input(input.name())
.value()));
inputMap.put("values", values);
inputs.add(inputMap);
}
templateData.put("inputs", inputs);
// * Load the template
JadeTemplate tpl = getTemplate("module");
moduleDir.mkdirs();
// * Process the template
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(moduleDir, "index.html")));
config.renderTemplate(tpl, templateData, out);
out.flush();
} catch (IOException e)
{
Global.log()
.warning(
"Failed to write to workflow directory. Continuing without writing report. IOException: "
+ e.getMessage()
+ " - "
+ Arrays.toString(e.getStackTrace()));
return;
}
}
| private void moduleOutput(Module module, File moduleDir)
throws IOException
{
// * The data we will pass to the template
Map<String, Object> templateData = new LinkedHashMap<String, Object>();
templateData.put("name", module.name());
templateData.put("short_name", module.name());
templateData.put("tags", "");
templateData.put("workflow_name", module.workflow().name());
templateData.put("instantiated", module.instantiated());
List<Map<String, Object>> instances = new ArrayList<Map<String, Object>>();
if (module.instantiated())
{
// * Collect the input names
List<String> inputNames = new ArrayList<String>();
for (Input input : module.inputs())
if(input.print())
inputNames.add(input.name());
templateData.put("input_names", inputNames);
int i = 0;
int padding = 1 + (int) Math.log10(module.instances().size());
for (ModuleInstance instance : module.instances())
{
// * Collect the instance inputs
List<String> instanceInputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
instanceInputs.add(input.value().toString());
// * Collect the instance information
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
instanceMap
.put("url",
String.format("./%0" + padding
+ "d/index.html", i));
instanceMap.put("inputs", instanceInputs);
instances.add(instanceMap);
i++;
}
}
templateData.put("instances", instances);
List<Map<String, Object>> outputs = new ArrayList<Map<String, Object>>();
for (Output output : module.outputs())
if(output.print())
{
Map<String, Object> outputMap = new LinkedHashMap<String, Object>();
outputMap.put("name", output.name());
outputMap.put("safe_name", safe(output.name()));
outputMap.put("description", output.description());
List<Map<String, Object>> outputInstances = new ArrayList<Map<String, Object>>();
// * Collect values for all instances
List<Object> values = new ArrayList<Object>();
for (ModuleInstance instance : module.instances())
{
Map<String, Object> instanceMap = new LinkedHashMap<String, Object>();
List<String> inputs = new ArrayList<String>();
for (InstanceInput input : instance.inputs())
if(input.original().print())
inputs.add(input.value().toString());
instanceMap.put("inputs", inputs);
Object value = instance.output(output.name()).value();
instanceMap.put("output", Functions.toString(value));
values.add(value);
outputInstances.add(instanceMap);
}
outputMap.put("instances", outputInstances);
// * Collect summary info
boolean isNumeric = isNumeric(values);
outputMap.put("is_numeric", isNumeric);
FrequencyModel<Object> fm = new FrequencyModel<Object>(values);
outputMap.put("mode", (fm.distinct() > 0) ? Functions.toString(fm.sorted().get(0)) : "");
outputMap.put("mode_frequency",
(fm.distinct()>0) ? fm.frequency(fm.sorted().get(0)) : 0);
outputMap.put("num_instances", values.size());
outputMap.put("entropy", fm.entropy());
if (isNumeric)
{
List<Number> numbers = numbers(values);
outputMap.put("mean", mean(numbers));
outputMap.put("dev", standardDeviation(numbers));
outputMap.put("median", median(numbers));
}
outputs.add(outputMap);
}
templateData.put("outputs", outputs);
List<Map<String, Object>> inputs = new ArrayList<Map<String, Object>>();
for (Input input : module.inputs())
if(input.print())
{
Map<String, Object> inputMap = new LinkedHashMap<String, Object>();
inputMap.put("name", input.name());
inputMap.put("description", input.description());
List<String> values = new ArrayList<String>();
for (ModuleInstance instance : module.instances())
values.add(Functions.toString(instance.input(input.name())
.value()));
inputMap.put("values", values);
inputs.add(inputMap);
}
templateData.put("inputs", inputs);
// * Load the template
JadeTemplate tpl = getTemplate("module");
moduleDir.mkdirs();
// * Process the template
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(moduleDir, "index.html")));
config.renderTemplate(tpl, templateData, out);
out.flush();
} catch (IOException e)
{
Global.log()
.warning(
"Failed to write to workflow directory. Continuing without writing report. IOException: "
+ e.getMessage()
+ " - "
+ Arrays.toString(e.getStackTrace()));
return;
}
}
|
diff --git a/src/main/java/org/dynmap/MapManager.java b/src/main/java/org/dynmap/MapManager.java
index d5dd3621..e43ad101 100644
--- a/src/main/java/org/dynmap/MapManager.java
+++ b/src/main/java/org/dynmap/MapManager.java
@@ -1,938 +1,941 @@
package org.dynmap;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.command.CommandSender;
import org.dynmap.DynmapWorld.AutoGenerateOption;
import org.dynmap.debug.Debug;
import org.dynmap.hdmap.HDMapManager;
import org.dynmap.utils.LegacyMapChunkCache;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.NewMapChunkCache;
import org.dynmap.utils.SnapshotCache;
import org.dynmap.utils.TileFlags;
public class MapManager {
public AsynchronousQueue<MapTile> tileQueue;
private static final int DEFAULT_CHUNKS_PER_TICK = 200;
private static final int DEFAULT_ZOOMOUT_PERIOD = 60;
public List<DynmapWorld> worlds = new ArrayList<DynmapWorld>();
public Map<String, DynmapWorld> worldsLookup = new HashMap<String, DynmapWorld>();
private BukkitScheduler scheduler;
private DynmapPlugin plug_in;
private long timeslice_int = 0; /* In milliseconds */
private int max_chunk_loads_per_tick = DEFAULT_CHUNKS_PER_TICK;
private int parallelrendercnt = 0;
private int progressinterval = 100;
private int zoomout_period = DEFAULT_ZOOMOUT_PERIOD; /* Zoom-out tile processing period, in seconds */
/* Which fullrenders are active */
private HashMap<String, FullWorldRenderState> active_renders = new HashMap<String, FullWorldRenderState>();
/* Chunk load handling */
private Object loadlock = new Object();
private int chunks_in_cur_tick = 0;
private long cur_tick;
/* Tile hash manager */
public TileHashManager hashman;
/* lock for our data structures */
public static final Object lock = new Object();
public static MapManager mapman; /* Our singleton */
public HDMapManager hdmapman;
public SnapshotCache sscache;
/* Thread pool for processing renders */
private DynmapScheduledThreadPoolExecutor render_pool;
private static final int POOL_SIZE = 3;
private HashMap<String, MapStats> mapstats = new HashMap<String, MapStats>();
private static class MapStats {
int loggedcnt;
int renderedcnt;
int updatedcnt;
int transparentcnt;
}
public DynmapWorld getWorld(String name) {
DynmapWorld world = worldsLookup.get(name);
return world;
}
public Collection<DynmapWorld> getWorlds() {
return worlds;
}
private static class OurThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setPriority(Thread.MIN_PRIORITY);
t.setName("Dynmap Render Thread");
return t;
}
}
private class DynmapScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
DynmapScheduledThreadPoolExecutor() {
super(POOL_SIZE + parallelrendercnt);
this.setThreadFactory(new OurThreadFactory());
/* Set shutdown policy to stop everything */
setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}
protected void afterExecute(Runnable r, Throwable x) {
if(r instanceof FullWorldRenderState) {
((FullWorldRenderState)r).cleanup();
}
if(x != null) {
Log.severe("Exception during render job: " + r);
x.printStackTrace();
}
}
@Override
public void execute(final Runnable r) {
try {
super.execute(new Runnable() {
public void run() {
try {
r.run();
} catch (Exception x) {
Log.severe("Exception during render job: " + r);
x.printStackTrace();
}
}
});
} catch (RejectedExecutionException rxe) { /* Pool shutdown - nominal for reload or unload */
}
}
@Override
public ScheduledFuture<?> schedule(final Runnable command, long delay, TimeUnit unit) {
try {
return super.schedule(new Runnable() {
public void run() {
try {
command.run();
} catch (Exception x) {
Log.severe("Exception during render job: " + command);
x.printStackTrace();
}
}
}, delay, unit);
} catch (RejectedExecutionException rxe) {
return null; /* Pool shut down when we reload or unload */
}
}
}
/* This always runs on render pool threads - no bukkit calls from here */
private class FullWorldRenderState implements Runnable {
DynmapWorld world; /* Which world are we rendering */
Location loc;
int map_index = -1; /* Which map are we on */
MapType map;
TileFlags found = null;
TileFlags rendered = null;
LinkedList<MapTile> renderQueue = null;
MapTile tile0 = null;
int rendercnt = 0;
CommandSender sender;
long timeaccum;
HashSet<MapType> renderedmaps = new HashSet<MapType>();
String activemaps;
List<String> activemaplist;
/* Min and max limits for chunk coords (for radius limit) */
int cxmin, cxmax, czmin, czmax;
String rendertype;
boolean cancelled;
String mapname;
/* Full world, all maps render */
FullWorldRenderState(DynmapWorld dworld, Location l, CommandSender sender, String mapname) {
this(dworld, l, sender, mapname, -1);
rendertype = "Full render";
}
/* Full world, all maps render, with optional render radius */
FullWorldRenderState(DynmapWorld dworld, Location l, CommandSender sender, String mapname, int radius) {
world = dworld;
loc = l;
found = new TileFlags();
rendered = new TileFlags();
renderQueue = new LinkedList<MapTile>();
this.sender = sender;
if(radius < 0) {
cxmin = czmin = Integer.MIN_VALUE;
cxmax = czmax = Integer.MAX_VALUE;
rendertype = "Full render";
}
else {
cxmin = (l.getBlockX() - radius)>>4;
czmin = (l.getBlockZ() - radius)>>4;
cxmax = (l.getBlockX() + radius+15)>>4;
czmax = (l.getBlockZ() + radius+15)>>4;
rendertype = "Radius render";
}
this.mapname = mapname;
}
/* Single tile render - used for incremental renders */
FullWorldRenderState(MapTile t) {
world = getWorld(t.getWorld().getName());
tile0 = t;
cxmin = czmin = Integer.MIN_VALUE;
cxmax = czmax = Integer.MAX_VALUE;
}
public String toString() {
return "world=" + world.world.getName() + ", map=" + map;
}
public void cleanup() {
if(tile0 == null) {
synchronized(lock) {
active_renders.remove(world.world.getName());
}
}
}
public void run() {
long tstart = System.currentTimeMillis();
MapTile tile = null;
List<MapTile> tileset = null;
if(cancelled) {
cleanup();
return;
}
if(tile0 == null) { /* Not single tile render */
/* If render queue is empty, start next map */
if(renderQueue.isEmpty()) {
if(map_index >= 0) { /* Finished a map? */
double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size();
if(activemaplist.size() > 1)
sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile).");
else
sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile).");
}
found.clear();
rendered.clear();
rendercnt = 0;
timeaccum = 0;
/* Advance to next unrendered map */
while(map_index < world.maps.size()) {
map_index++; /* Move to next one */
if(map_index >= world.maps.size()) break;
/* If single map render, see if this is our target */
if(mapname != null) {
if(world.maps.get(map_index).getName().equals(mapname)) {
break;
}
}
else {
if(renderedmaps.contains(world.maps.get(map_index)) == false)
break;
}
}
if(map_index >= world.maps.size()) { /* Last one done? */
sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished.");
cleanup();
return;
}
map = world.maps.get(map_index);
activemaplist = map.getMapNamesSharingRender(world);
/* Build active map list */
activemaps = "";
- for(String n : activemaplist) {
- if((mapname != null) && (!mapname.equals(n)))
- continue;
- if(activemaps.length() > 0)
- activemaps += ",";
- activemaps += n;
+ if(mapname != null) {
+ activemaps = mapname;
+ }
+ else {
+ for(String n : activemaplist) {
+ if(activemaps.length() > 0)
+ activemaps += ",";
+ activemaps += n;
+ }
}
/* Mark all the concurrently rendering maps rendered */
renderedmaps.addAll(map.getMapsSharingRender(world));
/* Now, prime the render queue */
for (MapTile mt : map.getTiles(loc)) {
if (!found.getFlag(mt.tileOrdinalX(), mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(), mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
if(world.seedloc != null) {
for(Location seed : world.seedloc) {
for (MapTile mt : map.getTiles(seed)) {
if (!found.getFlag(mt.tileOrdinalX(),mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(),mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
}
}
}
if(parallelrendercnt > 1) { /* Doing parallel renders? */
tileset = new ArrayList<MapTile>();
for(int i = 0; i < parallelrendercnt; i++) {
tile = renderQueue.pollFirst();
if(tile != null)
tileset.add(tile);
}
}
else {
tile = renderQueue.pollFirst();
}
}
else { /* Else, single tile render */
tile = tile0;
}
World w = world.world;
boolean notdone = true;
if(tileset != null) {
long save_timeaccum = timeaccum;
List<Future<Boolean>> rslt = new ArrayList<Future<Boolean>>();
final int cnt = tileset.size();
for(int i = 1; i < cnt; i++) { /* Do all but first on other threads */
final MapTile mt = tileset.get(i);
if((mapman != null) && (mapman.render_pool != null)) {
final long ts = tstart;
Future<Boolean> future = mapman.render_pool.submit(new Callable<Boolean>() {
public Boolean call() {
return processTile(mt, mt.world.world, ts, cnt);
}
});
rslt.add(future);
}
}
/* Now, do our render (first one) */
notdone = processTile(tileset.get(0), w, tstart, cnt);
/* Now, join with others */
for(int i = 0; i < rslt.size(); i++) {
try {
notdone = notdone && rslt.get(i).get();
} catch (ExecutionException xx) {
Log.severe(xx);
notdone = false;
} catch (InterruptedException ix) {
notdone = false;
}
}
timeaccum = save_timeaccum + System.currentTimeMillis() - tstart;
}
else {
notdone = processTile(tile, w, tstart, 1);
}
if(notdone) {
if(tile0 == null) { /* fullrender */
long tend = System.currentTimeMillis();
if(timeslice_int > (tend-tstart)) { /* We were fast enough */
scheduleDelayedJob(this, timeslice_int - (tend-tstart));
}
else { /* Schedule to run ASAP */
scheduleDelayedJob(this, 0);
}
}
else {
cleanup();
}
}
else {
cleanup();
}
}
private boolean processTile(MapTile tile, World w, long tstart, int parallelcnt) {
/* Get list of chunks required for tile */
List<DynmapChunk> requiredChunks = tile.getRequiredChunks();
/* If we are doing radius limit render, see if any are inside limits */
if(cxmin != Integer.MIN_VALUE) {
boolean good = false;
for(DynmapChunk c : requiredChunks) {
if((c.x >= cxmin) && (c.x <= cxmax) && (c.z >= czmin) && (c.z <= czmax)) {
good = true;
break;
}
}
if(!good) requiredChunks = Collections.emptyList();
}
/* Fetch chunk cache from server thread */
MapChunkCache cache = createMapChunkCache(world, requiredChunks, tile.isBlockTypeDataNeeded(),
tile.isHightestBlockYDataNeeded(), tile.isBiomeDataNeeded(),
tile.isRawBiomeDataNeeded());
if(cache == null) {
return false; /* Cancelled/aborted */
}
if(tile0 != null) { /* Single tile? */
if(cache.isEmpty() == false)
tile.render(cache, null);
}
else {
/* Switch to not checking if rendered tile is blank - breaks us on skylands, where tiles can be nominally blank - just work off chunk cache empty */
if (cache.isEmpty() == false) {
tile.render(cache, mapname);
synchronized(lock) {
// found.setFlag(tile.tileOrdinalX(),tile.tileOrdinalY(),false);
rendered.setFlag(tile.tileOrdinalX(), tile.tileOrdinalY(), true);
for (MapTile adjTile : map.getAdjecentTiles(tile)) {
if (!found.getFlag(adjTile.tileOrdinalX(),adjTile.tileOrdinalY()) &&
!rendered.getFlag(adjTile.tileOrdinalX(),adjTile.tileOrdinalY())) {
found.setFlag(adjTile.tileOrdinalX(), adjTile.tileOrdinalY(), true);
renderQueue.add(adjTile);
}
}
}
}
synchronized(lock) {
// found.setFlag(tile.tileOrdinalX(), tile.tileOrdinalY(), false);
if(!cache.isEmpty()) {
rendercnt++;
timeaccum += System.currentTimeMillis() - tstart;
if((rendercnt % progressinterval) == 0) {
double msecpertile = (double)timeaccum / (double)rendercnt / (double)activemaplist.size();
if(activemaplist.size() > 1)
sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" +
w.getName() + "' in progress - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile).");
else
sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" +
w.getName() + "' in progress - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile).");
}
}
}
}
/* And unload what we loaded */
cache.unloadChunks();
return true;
}
public void cancelRender() {
cancelled = true;
}
}
private class CheckWorldTimes implements Runnable {
public void run() {
Future<Integer> f = scheduler.callSyncMethod(plug_in, new Callable<Integer>() {
public Integer call() throws Exception {
for(DynmapWorld w : worlds) {
int new_servertime = (int)(w.world.getTime() % 24000);
/* Check if we went from night to day */
boolean wasday = w.servertime >= 0 && w.servertime < 13700;
boolean isday = new_servertime >= 0 && new_servertime < 13700;
w.servertime = new_servertime;
if(wasday != isday) {
pushUpdate(w.world, new Client.DayNight(isday));
}
}
return 0;
}
});
try {
f.get();
} catch (Exception ix) {
Log.severe(ix);
}
scheduleDelayedJob(this, 5000);
}
}
private class DoZoomOutProcessing implements Runnable {
public void run() {
Debug.debug("DoZoomOutProcessing started");
ArrayList<DynmapWorld> wl = new ArrayList<DynmapWorld>(worlds);
for(DynmapWorld w : wl) {
w.freshenZoomOutFiles();
}
scheduleDelayedJob(this, zoomout_period*1000);
Debug.debug("DoZoomOutProcessing finished");
}
}
public MapManager(DynmapPlugin plugin, ConfigurationNode configuration) {
plug_in = plugin;
mapman = this;
/* Clear color scheme */
ColorScheme.reset();
/* Initialize HD map manager */
hdmapman = new HDMapManager();
hdmapman.loadHDShaders(plugin);
hdmapman.loadHDPerspectives(plugin);
hdmapman.loadHDLightings(plugin);
sscache = new SnapshotCache(configuration.getInteger("snapshotcachesize", 500));
parallelrendercnt = configuration.getInteger("parallelrendercnt", 0);
progressinterval = configuration.getInteger("progressloginterval", 100);
if(progressinterval < 100) progressinterval = 100;
this.tileQueue = new AsynchronousQueue<MapTile>(
new Handler<MapTile>() {
@Override
public void handle(MapTile t) {
scheduleDelayedJob(new FullWorldRenderState(t), 0);
}
},
(int) (configuration.getDouble("renderinterval", 0.5) * 1000),
configuration.getInteger("renderacceleratethreshold", 30),
(int)(configuration.getDouble("renderaccelerateinterval", 0.2) * 1000));
/* On dedicated thread, so default to no delays */
timeslice_int = (long)(configuration.getDouble("timesliceinterval", 0.0) * 1000);
max_chunk_loads_per_tick = configuration.getInteger("maxchunkspertick", DEFAULT_CHUNKS_PER_TICK);
if(max_chunk_loads_per_tick < 5) max_chunk_loads_per_tick = 5;
/* Get zoomout processing periond in seconds */
zoomout_period = configuration.getInteger("zoomoutperiod", DEFAULT_ZOOMOUT_PERIOD);
if(zoomout_period < 5) zoomout_period = 5;
scheduler = plugin.getServer().getScheduler();
hashman = new TileHashManager(DynmapPlugin.tilesDirectory, configuration.getBoolean("enabletilehash", true));
tileQueue.start();
for (World world : plug_in.getServer().getWorlds()) {
activateWorld(world);
}
}
void renderFullWorld(Location l, CommandSender sender, String mapname) {
DynmapWorld world = getWorld(l.getWorld().getName());
if (world == null) {
sender.sendMessage("Could not render: world '" + l.getWorld().getName() + "' not defined in configuration.");
return;
}
String wname = l.getWorld().getName();
FullWorldRenderState rndr;
synchronized(lock) {
rndr = active_renders.get(wname);
if(rndr != null) {
sender.sendMessage(rndr.rendertype + " of world '" + wname + "' already active.");
return;
}
rndr = new FullWorldRenderState(world,l,sender, mapname); /* Make new activation record */
active_renders.put(wname, rndr); /* Add to active table */
}
/* Schedule first tile to be worked */
scheduleDelayedJob(rndr, 0);
sender.sendMessage("Full render starting on world '" + wname + "'...");
}
void renderWorldRadius(Location l, CommandSender sender, String mapname, int radius) {
DynmapWorld world = getWorld(l.getWorld().getName());
if (world == null) {
sender.sendMessage("Could not render: world '" + l.getWorld().getName() + "' not defined in configuration.");
return;
}
String wname = l.getWorld().getName();
FullWorldRenderState rndr;
synchronized(lock) {
rndr = active_renders.get(wname);
if(rndr != null) {
sender.sendMessage(rndr.rendertype + " of world '" + wname + "' already active.");
return;
}
rndr = new FullWorldRenderState(world,l,sender, mapname, radius); /* Make new activation record */
active_renders.put(wname, rndr); /* Add to active table */
}
/* Schedule first tile to be worked */
scheduleDelayedJob(rndr, 0);
sender.sendMessage("Render of " + radius + " block radius starting on world '" + wname + "'...");
}
void cancelRender(World w, CommandSender sender) {
synchronized(lock) {
if(w != null) {
FullWorldRenderState rndr;
rndr = active_renders.get(w.getName());
if(rndr != null) {
rndr.cancelRender(); /* Cancel render */
if(sender != null) {
sender.sendMessage("Cancelled render for '" + w.getName() + "'");
}
}
}
else { /* Else, cancel all */
for(String wid : active_renders.keySet()) {
FullWorldRenderState rnd = active_renders.get(wid);
rnd.cancelRender();
if(sender != null) {
sender.sendMessage("Cancelled render for '" + wid + "'");
}
}
}
}
}
public void activateWorld(World w) {
ConfigurationNode worldConfiguration = plug_in.getWorldConfiguration(w);
if (!worldConfiguration.getBoolean("enabled", false)) {
Log.info("World '" + w.getName() + "' disabled");
return;
}
String worldName = w.getName();
DynmapWorld dynmapWorld = new DynmapWorld();
dynmapWorld.world = w;
dynmapWorld.configuration = worldConfiguration;
Log.verboseinfo("Loading maps of world '" + worldName + "'...");
for(MapType map : worldConfiguration.<MapType>createInstances("maps", new Class<?>[0], new Object[0])) {
if(map.getName() != null)
dynmapWorld.maps.add(map);
}
Log.info("Loaded " + dynmapWorld.maps.size() + " maps of world '" + worldName + "'.");
List<ConfigurationNode> loclist = worldConfiguration.getNodes("fullrenderlocations");
dynmapWorld.seedloc = new ArrayList<Location>();
dynmapWorld.servertime = (int)(w.getTime() % 24000);
dynmapWorld.sendposition = worldConfiguration.getBoolean("sendposition", true);
dynmapWorld.sendhealth = worldConfiguration.getBoolean("sendhealth", true);
dynmapWorld.bigworld = worldConfiguration.getBoolean("bigworld", false);
dynmapWorld.setExtraZoomOutLevels(worldConfiguration.getInteger("extrazoomout", 0));
dynmapWorld.worldtilepath = new File(DynmapPlugin.tilesDirectory, w.getName());
if(loclist != null) {
for(ConfigurationNode loc : loclist) {
Location lx = new Location(w, loc.getDouble("x", 0), loc.getDouble("y", 64), loc.getDouble("z", 0));
dynmapWorld.seedloc.add(lx);
}
}
/* Load visibility limits, if any are defined */
List<ConfigurationNode> vislimits = worldConfiguration.getNodes("visibilitylimits");
if(vislimits != null) {
dynmapWorld.visibility_limits = new ArrayList<MapChunkCache.VisibilityLimit>();
for(ConfigurationNode vis : vislimits) {
MapChunkCache.VisibilityLimit lim = new MapChunkCache.VisibilityLimit();
lim.x0 = vis.getInteger("x0", 0);
lim.x1 = vis.getInteger("x1", 0);
lim.z0 = vis.getInteger("z0", 0);
lim.z1 = vis.getInteger("z1", 0);
dynmapWorld.visibility_limits.add(lim);
/* Also, add a seed location for the middle of each visible area */
dynmapWorld.seedloc.add(new Location(w, (lim.x0+lim.x1)/2, 64, (lim.z0+lim.z1)/2));
}
}
/* Load hidden limits, if any are defined */
List<ConfigurationNode> hidelimits = worldConfiguration.getNodes("hiddenlimits");
if(hidelimits != null) {
dynmapWorld.hidden_limits = new ArrayList<MapChunkCache.VisibilityLimit>();
for(ConfigurationNode vis : hidelimits) {
MapChunkCache.VisibilityLimit lim = new MapChunkCache.VisibilityLimit();
lim.x0 = vis.getInteger("x0", 0);
lim.x1 = vis.getInteger("x1", 0);
lim.z0 = vis.getInteger("z0", 0);
lim.z1 = vis.getInteger("z1", 0);
dynmapWorld.hidden_limits.add(lim);
}
}
String autogen = worldConfiguration.getString("autogenerate-to-visibilitylimits", "none");
if(autogen.equals("permanent")) {
dynmapWorld.do_autogenerate = AutoGenerateOption.PERMANENT;
}
else if(autogen.equals("map-only")) {
dynmapWorld.do_autogenerate = AutoGenerateOption.FORMAPONLY;
}
else {
dynmapWorld.do_autogenerate = AutoGenerateOption.NONE;
}
if((dynmapWorld.do_autogenerate != AutoGenerateOption.NONE) && (dynmapWorld.visibility_limits == null)) {
Log.info("Warning: Automatic world generation to visible limits option requires that visibitylimits be set - option disabled");
dynmapWorld.do_autogenerate = AutoGenerateOption.NONE;
}
String hiddenchunkstyle = worldConfiguration.getString("hidestyle", "stone");
if(hiddenchunkstyle.equals("air"))
dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_AIR;
else if(hiddenchunkstyle.equals("ocean"))
dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_OCEAN;
else
dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_STONE_PLAIN;
// TODO: Make this less... weird...
// Insert the world on the same spot as in the configuration.
HashMap<String, Integer> indexLookup = new HashMap<String, Integer>();
List<ConfigurationNode> nodes = plug_in.configuration.getNodes("worlds");
for (int i = 0; i < nodes.size(); i++) {
ConfigurationNode node = nodes.get(i);
indexLookup.put(node.getString("name"), i);
}
Integer worldIndex = indexLookup.get(worldName);
if(worldIndex == null) {
worlds.add(dynmapWorld); /* Put at end if no world section */
}
else {
int insertIndex;
for(insertIndex = 0; insertIndex < worlds.size(); insertIndex++) {
Integer nextWorldIndex = indexLookup.get(worlds.get(insertIndex).world.getName());
if (nextWorldIndex == null || worldIndex < nextWorldIndex.intValue()) {
break;
}
}
worlds.add(insertIndex, dynmapWorld);
}
worldsLookup.put(w.getName(), dynmapWorld);
plug_in.events.trigger("worldactivated", dynmapWorld);
}
public int touch(Location l) {
DynmapWorld world = getWorld(l.getWorld().getName());
if (world == null)
return 0;
int invalidates = 0;
for (int i = 0; i < world.maps.size(); i++) {
MapTile[] tiles = world.maps.get(i).getTiles(l);
for (int j = 0; j < tiles.length; j++) {
invalidateTile(tiles[j]);
invalidates++;
}
}
return invalidates;
}
public int touchVolume(Location l0, Location l1) {
DynmapWorld world = getWorld(l0.getWorld().getName());
if (world == null)
return 0;
int invalidates = 0;
for (int i = 0; i < world.maps.size(); i++) {
MapTile[] tiles = world.maps.get(i).getTiles(l0, l1);
for (int j = 0; j < tiles.length; j++) {
invalidateTile(tiles[j]);
invalidates++;
}
}
return invalidates;
}
public void invalidateTile(MapTile tile) {
if(tileQueue.push(tile))
Debug.debug("Invalidating tile " + tile.getFilename());
}
public static void scheduleDelayedJob(Runnable job, long delay_in_msec) {
if((mapman != null) && (mapman.render_pool != null)) {
if(delay_in_msec > 0)
mapman.render_pool.schedule(job, delay_in_msec, TimeUnit.MILLISECONDS);
else
mapman.render_pool.execute(job);
}
}
public void startRendering() {
tileQueue.start();
render_pool = new DynmapScheduledThreadPoolExecutor();
scheduleDelayedJob(new DoZoomOutProcessing(), 60000);
scheduleDelayedJob(new CheckWorldTimes(), 5000);
}
public void stopRendering() {
/* Tell all worlds to cancel any zoom out processing */
for(DynmapWorld w: worlds)
w.cancelZoomOutFreshen();
render_pool.shutdown();
try {
render_pool.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException ix) {
}
tileQueue.stop();
mapman = null;
hdmapman = null;
}
private HashMap<World, File> worldTileDirectories = new HashMap<World, File>();
public File getTileFile(MapTile tile) {
World world = tile.getWorld();
File worldTileDirectory = worldTileDirectories.get(world);
if (worldTileDirectory == null) {
worldTileDirectory = new File(DynmapPlugin.tilesDirectory, tile.getWorld().getName());
worldTileDirectories.put(world, worldTileDirectory);
}
if (!worldTileDirectory.isDirectory() && !worldTileDirectory.mkdirs()) {
Log.warning("Could not create directory for tiles ('" + worldTileDirectory + "').");
}
return new File(worldTileDirectory, tile.getFilename());
}
public void pushUpdate(Object update) {
for(DynmapWorld world : getWorlds()) {
world.updates.pushUpdate(update);
}
}
public void pushUpdate(World world, Object update) {
pushUpdate(world.getName(), update);
}
public void pushUpdate(String worldName, Object update) {
DynmapWorld world = getWorld(worldName);
if(world != null)
world.updates.pushUpdate(update);
}
public Object[] getWorldUpdates(String worldName, long since) {
DynmapWorld world = getWorld(worldName);
if (world == null)
return new Object[0];
return world.updates.getUpdatedObjects(since);
}
private static boolean use_legacy = false;
/**
* Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread
*/
public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks,
boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) {
MapChunkCache c = null;
try {
if(!use_legacy)
c = new NewMapChunkCache();
} catch (NoClassDefFoundError ncdfe) {
use_legacy = true;
}
if(c == null)
c = new LegacyMapChunkCache();
if(w.visibility_limits != null) {
for(MapChunkCache.VisibilityLimit limit: w.visibility_limits) {
c.setVisibleRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
c.setAutoGenerateVisbileRanges(w.do_autogenerate);
}
if(w.hidden_limits != null) {
for(MapChunkCache.VisibilityLimit limit: w.hidden_limits) {
c.setHiddenRange(limit);
}
c.setHiddenFillStyle(w.hiddenchunkstyle);
}
c.setChunks(w.world, chunks);
if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false)
Log.severe("CraftBukkit build does not support biome APIs");
if(chunks.size() == 0) { /* No chunks to get? */
return c;
}
final MapChunkCache cc = c;
while(!cc.isDoneLoading()) {
synchronized(loadlock) {
long now = System.currentTimeMillis();
if(cur_tick != (now/50)) { /* New tick? */
chunks_in_cur_tick = max_chunk_loads_per_tick;
cur_tick = now/50;
}
}
Future<Boolean> f = scheduler.callSyncMethod(plug_in, new Callable<Boolean>() {
public Boolean call() throws Exception {
boolean exhausted;
synchronized(loadlock) {
if(chunks_in_cur_tick > 0)
chunks_in_cur_tick -= cc.loadChunks(chunks_in_cur_tick);
exhausted = (chunks_in_cur_tick == 0);
}
return exhausted;
}
});
boolean delay;
try {
delay = f.get();
} catch (Exception ix) {
Log.severe(ix);
return null;
}
if(delay)
try { Thread.sleep(50); } catch (InterruptedException ix) {}
}
return c;
}
/**
* Update map tile statistics
*/
public void updateStatistics(MapTile tile, String subtype, boolean rendered, boolean updated, boolean transparent) {
synchronized(lock) {
String k = tile.getKey();
if(subtype != null)
k += "." + subtype;
MapStats ms = mapstats.get(k);
if(ms == null) {
ms = new MapStats();
mapstats.put(k, ms);
}
ms.loggedcnt++;
if(rendered)
ms.renderedcnt++;
if(updated)
ms.updatedcnt++;
if(transparent)
ms.transparentcnt++;
}
}
/**
* Print statistics command
*/
public void printStats(CommandSender sender, String prefix) {
sender.sendMessage("Tile Render Statistics:");
MapStats tot = new MapStats();
synchronized(lock) {
for(String k: new TreeSet<String>(mapstats.keySet())) {
if((prefix != null) && !k.startsWith(prefix))
continue;
MapStats ms = mapstats.get(k);
sender.sendMessage(" " + k + ": processed=" + ms.loggedcnt + ", rendered=" + ms.renderedcnt +
", updated=" + ms.updatedcnt + ", transparent=" + ms.transparentcnt);
tot.loggedcnt += ms.loggedcnt;
tot.renderedcnt += ms.renderedcnt;
tot.updatedcnt += ms.updatedcnt;
tot.transparentcnt += ms.transparentcnt;
}
}
sender.sendMessage(" TOTALS: processed=" + tot.loggedcnt + ", rendered=" + tot.renderedcnt +
", updated=" + tot.updatedcnt + ", transparent=" + tot.transparentcnt);
sender.sendMessage(" Cache hit rate: " + sscache.getHitRate() + "%");
sender.sendMessage(" Triggered update queue size: " + tileQueue.size());
}
/**
* Reset statistics
*/
public void resetStats(CommandSender sender, String prefix) {
synchronized(lock) {
for(String k : mapstats.keySet()) {
if((prefix != null) && !k.startsWith(prefix))
continue;
MapStats ms = mapstats.get(k);
ms.loggedcnt = 0;
ms.renderedcnt = 0;
ms.updatedcnt = 0;
ms.transparentcnt = 0;
}
}
sscache.resetStats();
sender.sendMessage("Tile Render Statistics reset");
}
}
| true | true | public void run() {
long tstart = System.currentTimeMillis();
MapTile tile = null;
List<MapTile> tileset = null;
if(cancelled) {
cleanup();
return;
}
if(tile0 == null) { /* Not single tile render */
/* If render queue is empty, start next map */
if(renderQueue.isEmpty()) {
if(map_index >= 0) { /* Finished a map? */
double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size();
if(activemaplist.size() > 1)
sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile).");
else
sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile).");
}
found.clear();
rendered.clear();
rendercnt = 0;
timeaccum = 0;
/* Advance to next unrendered map */
while(map_index < world.maps.size()) {
map_index++; /* Move to next one */
if(map_index >= world.maps.size()) break;
/* If single map render, see if this is our target */
if(mapname != null) {
if(world.maps.get(map_index).getName().equals(mapname)) {
break;
}
}
else {
if(renderedmaps.contains(world.maps.get(map_index)) == false)
break;
}
}
if(map_index >= world.maps.size()) { /* Last one done? */
sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished.");
cleanup();
return;
}
map = world.maps.get(map_index);
activemaplist = map.getMapNamesSharingRender(world);
/* Build active map list */
activemaps = "";
for(String n : activemaplist) {
if((mapname != null) && (!mapname.equals(n)))
continue;
if(activemaps.length() > 0)
activemaps += ",";
activemaps += n;
}
/* Mark all the concurrently rendering maps rendered */
renderedmaps.addAll(map.getMapsSharingRender(world));
/* Now, prime the render queue */
for (MapTile mt : map.getTiles(loc)) {
if (!found.getFlag(mt.tileOrdinalX(), mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(), mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
if(world.seedloc != null) {
for(Location seed : world.seedloc) {
for (MapTile mt : map.getTiles(seed)) {
if (!found.getFlag(mt.tileOrdinalX(),mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(),mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
}
}
}
if(parallelrendercnt > 1) { /* Doing parallel renders? */
tileset = new ArrayList<MapTile>();
for(int i = 0; i < parallelrendercnt; i++) {
tile = renderQueue.pollFirst();
if(tile != null)
tileset.add(tile);
}
}
else {
tile = renderQueue.pollFirst();
}
}
else { /* Else, single tile render */
tile = tile0;
}
World w = world.world;
boolean notdone = true;
if(tileset != null) {
long save_timeaccum = timeaccum;
List<Future<Boolean>> rslt = new ArrayList<Future<Boolean>>();
final int cnt = tileset.size();
for(int i = 1; i < cnt; i++) { /* Do all but first on other threads */
final MapTile mt = tileset.get(i);
if((mapman != null) && (mapman.render_pool != null)) {
final long ts = tstart;
Future<Boolean> future = mapman.render_pool.submit(new Callable<Boolean>() {
public Boolean call() {
return processTile(mt, mt.world.world, ts, cnt);
}
});
rslt.add(future);
}
}
/* Now, do our render (first one) */
notdone = processTile(tileset.get(0), w, tstart, cnt);
/* Now, join with others */
for(int i = 0; i < rslt.size(); i++) {
try {
notdone = notdone && rslt.get(i).get();
} catch (ExecutionException xx) {
Log.severe(xx);
notdone = false;
} catch (InterruptedException ix) {
notdone = false;
}
}
timeaccum = save_timeaccum + System.currentTimeMillis() - tstart;
}
else {
notdone = processTile(tile, w, tstart, 1);
}
if(notdone) {
if(tile0 == null) { /* fullrender */
long tend = System.currentTimeMillis();
if(timeslice_int > (tend-tstart)) { /* We were fast enough */
scheduleDelayedJob(this, timeslice_int - (tend-tstart));
}
else { /* Schedule to run ASAP */
scheduleDelayedJob(this, 0);
}
}
else {
cleanup();
}
}
else {
cleanup();
}
}
| public void run() {
long tstart = System.currentTimeMillis();
MapTile tile = null;
List<MapTile> tileset = null;
if(cancelled) {
cleanup();
return;
}
if(tile0 == null) { /* Not single tile render */
/* If render queue is empty, start next map */
if(renderQueue.isEmpty()) {
if(map_index >= 0) { /* Finished a map? */
double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size();
if(activemaplist.size() > 1)
sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile).");
else
sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" +
world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile).");
}
found.clear();
rendered.clear();
rendercnt = 0;
timeaccum = 0;
/* Advance to next unrendered map */
while(map_index < world.maps.size()) {
map_index++; /* Move to next one */
if(map_index >= world.maps.size()) break;
/* If single map render, see if this is our target */
if(mapname != null) {
if(world.maps.get(map_index).getName().equals(mapname)) {
break;
}
}
else {
if(renderedmaps.contains(world.maps.get(map_index)) == false)
break;
}
}
if(map_index >= world.maps.size()) { /* Last one done? */
sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished.");
cleanup();
return;
}
map = world.maps.get(map_index);
activemaplist = map.getMapNamesSharingRender(world);
/* Build active map list */
activemaps = "";
if(mapname != null) {
activemaps = mapname;
}
else {
for(String n : activemaplist) {
if(activemaps.length() > 0)
activemaps += ",";
activemaps += n;
}
}
/* Mark all the concurrently rendering maps rendered */
renderedmaps.addAll(map.getMapsSharingRender(world));
/* Now, prime the render queue */
for (MapTile mt : map.getTiles(loc)) {
if (!found.getFlag(mt.tileOrdinalX(), mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(), mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
if(world.seedloc != null) {
for(Location seed : world.seedloc) {
for (MapTile mt : map.getTiles(seed)) {
if (!found.getFlag(mt.tileOrdinalX(),mt.tileOrdinalY())) {
found.setFlag(mt.tileOrdinalX(),mt.tileOrdinalY(), true);
renderQueue.add(mt);
}
}
}
}
}
if(parallelrendercnt > 1) { /* Doing parallel renders? */
tileset = new ArrayList<MapTile>();
for(int i = 0; i < parallelrendercnt; i++) {
tile = renderQueue.pollFirst();
if(tile != null)
tileset.add(tile);
}
}
else {
tile = renderQueue.pollFirst();
}
}
else { /* Else, single tile render */
tile = tile0;
}
World w = world.world;
boolean notdone = true;
if(tileset != null) {
long save_timeaccum = timeaccum;
List<Future<Boolean>> rslt = new ArrayList<Future<Boolean>>();
final int cnt = tileset.size();
for(int i = 1; i < cnt; i++) { /* Do all but first on other threads */
final MapTile mt = tileset.get(i);
if((mapman != null) && (mapman.render_pool != null)) {
final long ts = tstart;
Future<Boolean> future = mapman.render_pool.submit(new Callable<Boolean>() {
public Boolean call() {
return processTile(mt, mt.world.world, ts, cnt);
}
});
rslt.add(future);
}
}
/* Now, do our render (first one) */
notdone = processTile(tileset.get(0), w, tstart, cnt);
/* Now, join with others */
for(int i = 0; i < rslt.size(); i++) {
try {
notdone = notdone && rslt.get(i).get();
} catch (ExecutionException xx) {
Log.severe(xx);
notdone = false;
} catch (InterruptedException ix) {
notdone = false;
}
}
timeaccum = save_timeaccum + System.currentTimeMillis() - tstart;
}
else {
notdone = processTile(tile, w, tstart, 1);
}
if(notdone) {
if(tile0 == null) { /* fullrender */
long tend = System.currentTimeMillis();
if(timeslice_int > (tend-tstart)) { /* We were fast enough */
scheduleDelayedJob(this, timeslice_int - (tend-tstart));
}
else { /* Schedule to run ASAP */
scheduleDelayedJob(this, 0);
}
}
else {
cleanup();
}
}
else {
cleanup();
}
}
|
diff --git a/communicator-client/src/main/java/com/outr/net/communicator/client/connection/AJAXConnection.java b/communicator-client/src/main/java/com/outr/net/communicator/client/connection/AJAXConnection.java
index 6d5114d..9957f6c 100644
--- a/communicator-client/src/main/java/com/outr/net/communicator/client/connection/AJAXConnection.java
+++ b/communicator-client/src/main/java/com/outr/net/communicator/client/connection/AJAXConnection.java
@@ -1,166 +1,166 @@
package com.outr.net.communicator.client.connection;
import com.google.gwt.http.client.*;
import com.outr.net.communicator.client.GWTCommunicator;
import com.outr.net.communicator.client.JSONConverter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Matt Hicks <[email protected]>
*/
public class AJAXConnection implements Connection {
private final ConnectionManager manager;
private final RequestBuilder pollBuilder;
private final RequestBuilder sendBuilder;
private Request pollRequest;
private Request sendRequest;
private RequestCallback pollCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
try {
if (response.getStatusCode() == 200) {
pollRequest = null;
// GWTCommunicator.log("Received: " + response.getText());
AJAXResponse r = (AJAXResponse)JSONConverter.fromString(response.getText());
if (r.status) {
for (int i = 0; i < r.data.size(); i++) {
Message message = r.data.get(i);
manager.received(message);
}
connectPolling(); // Reconnect polling
} else {
pollError("Status was failure: " + r.failure, r);
}
} else {
String message = null;
if (response.getStatusCode() != 0) {
message = "Bad Response: " + response.getStatusText() + " (" + response.getStatusCode() + ")";
}
pollError(message, null);
if (response.getStatusCode() == 404) { // Resource not found, so reload the browser
manager.communicator.reload(true, true, 0);
}
}
} catch(Throwable t) {
- pollError("Exception thrown on poll receive. Status: " + response.getStatusText() + " (" + response.getStatusCode() + "). Message: " + response.getText(), null);
+ pollError("Exception thrown on poll receive (" + t.getMessage() + "). Status: " + response.getStatusText() + " (" + response.getStatusCode() + "). Message: " + response.getText(), null);
}
}
@Override
public void onError(Request request, Throwable exception) {
pollError(exception.getMessage(), null);
}
};
private RequestCallback sendCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
try {
if (response.getStatusCode() == 200) {
AJAXResponse r = (AJAXResponse)JSONConverter.fromString(response.getText());
if (r.status) { // Successful, lets check the queue for more to send
sendRequest = null;
manager.queue.confirm(); // Messages sent successfully
sendData();
} else {
sendError("Status was failure: " + r.failure, r);
}
} else {
sendError("Bad Response: " + response.getStatusText() + " (" + response.getStatusCode() + ")", null);
}
} catch(Throwable t) {
sendError("Exception thrown on send. Status: " + response.getStatusText() + " (" + response.getStatusCode() + "). Message: " + response.getText(), null);
}
}
@Override
public void onError(Request request, Throwable exception) {
sendError(exception.getMessage(), null);
}
};
public AJAXConnection(ConnectionManager manager, String ajaxURL) {
this.manager = manager;
pollBuilder = new RequestBuilder(RequestBuilder.POST, ajaxURL);
pollBuilder.setTimeoutMillis(60000);
sendBuilder = new RequestBuilder(RequestBuilder.POST, ajaxURL);
sendBuilder.setTimeoutMillis(10000);
}
@Override
public void connect() {
connectPolling();
sendData();
}
private void connectPolling() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", manager.uuid);
map.put("type", "receive");
map.put("lastReceiveId", manager.getLastReceiveId());
String json = JSONConverter.toJSONValue(map).toString();
try {
pollRequest = pollBuilder.sendRequest(json, pollCallback);
} catch(RequestException exc) {
log("PollingRequestError: " + exc.getMessage());
}
}
private void sendData() {
if (sendRequest == null && manager.queue.hasNext()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", manager.uuid);
map.put("type", "send");
List<Message> messages = new ArrayList<Message>(manager.queue.waiting());
while (manager.queue.hasNext()) {
messages.add(manager.queue.next());
}
map.put("messages", messages);
String json = JSONConverter.toJSONValue(map).toString();
try {
sendRequest = sendBuilder.sendRequest(json, sendCallback);
} catch(RequestException exc) {
log("SendRequestError: " + exc.getMessage());
}
}
}
@Override
public void messageReady() {
sendData();
}
private void pollError(String error, AJAXResponse response) {
if (error != null) {
log("Error received from poll: " + error);
}
manager.disconnected();
responseError(response);
}
private void sendError(String error, AJAXResponse response) {
log("Error received from send: " + error);
manager.queue.failed();
manager.disconnected();
responseError(response);
}
private void responseError(AJAXResponse response) {
if (response != null && response.failure != null) {
manager.handleError(response.failure.error);
}
}
public void update(int delta) {
}
private void log(String message) {
GWTCommunicator.log(message);
}
}
| true | true | public void onResponseReceived(Request request, Response response) {
try {
if (response.getStatusCode() == 200) {
pollRequest = null;
// GWTCommunicator.log("Received: " + response.getText());
AJAXResponse r = (AJAXResponse)JSONConverter.fromString(response.getText());
if (r.status) {
for (int i = 0; i < r.data.size(); i++) {
Message message = r.data.get(i);
manager.received(message);
}
connectPolling(); // Reconnect polling
} else {
pollError("Status was failure: " + r.failure, r);
}
} else {
String message = null;
if (response.getStatusCode() != 0) {
message = "Bad Response: " + response.getStatusText() + " (" + response.getStatusCode() + ")";
}
pollError(message, null);
if (response.getStatusCode() == 404) { // Resource not found, so reload the browser
manager.communicator.reload(true, true, 0);
}
}
} catch(Throwable t) {
pollError("Exception thrown on poll receive. Status: " + response.getStatusText() + " (" + response.getStatusCode() + "). Message: " + response.getText(), null);
}
}
| public void onResponseReceived(Request request, Response response) {
try {
if (response.getStatusCode() == 200) {
pollRequest = null;
// GWTCommunicator.log("Received: " + response.getText());
AJAXResponse r = (AJAXResponse)JSONConverter.fromString(response.getText());
if (r.status) {
for (int i = 0; i < r.data.size(); i++) {
Message message = r.data.get(i);
manager.received(message);
}
connectPolling(); // Reconnect polling
} else {
pollError("Status was failure: " + r.failure, r);
}
} else {
String message = null;
if (response.getStatusCode() != 0) {
message = "Bad Response: " + response.getStatusText() + " (" + response.getStatusCode() + ")";
}
pollError(message, null);
if (response.getStatusCode() == 404) { // Resource not found, so reload the browser
manager.communicator.reload(true, true, 0);
}
}
} catch(Throwable t) {
pollError("Exception thrown on poll receive (" + t.getMessage() + "). Status: " + response.getStatusText() + " (" + response.getStatusCode() + "). Message: " + response.getText(), null);
}
}
|
diff --git a/src/main/java/jnr/constants/ConstantSet.java b/src/main/java/jnr/constants/ConstantSet.java
index b3f2bfa..26ddfc9 100644
--- a/src/main/java/jnr/constants/ConstantSet.java
+++ b/src/main/java/jnr/constants/ConstantSet.java
@@ -1,232 +1,233 @@
/*
* 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 jnr.constants;
import java.lang.reflect.Field;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Provides forward and reverse lookup for platform constants
*/
public class ConstantSet extends AbstractSet<Constant> {
private final ConcurrentMap<String, Constant> nameToConstant;
private final ConcurrentMap<Long, Constant> valueToConstant;
private final Set<Enum> constants;
private final Class<Enum> enumClass;
private volatile Long minValue;
private volatile Long maxValue;
private static final ConcurrentMap<String, ConstantSet> constantSets
= new ConcurrentHashMap<String, ConstantSet>();
private static final Object lock = new Object();
/**
* Gets a <tt>ConstantSet</tt>
*
* @param name The name of the constant set to get.
* @return A <tt>ConstantSet</tt>.
*/
public static ConstantSet getConstantSet(String name) {
ConstantSet constants = constantSets.get(name);
if (constants == null) {
synchronized (lock) {
- if (!constantSets.containsKey(name)) {
+ constants = constantSets.get(name);
+ if (constants == null) {
Class<Enum> enumClass = getEnumClass(name);
if (enumClass == null) {
return null;
}
if (!Constant.class.isAssignableFrom(enumClass)) {
throw new ClassCastException("class for " + name
+ " does not implement Constant interface");
}
constants = new ConstantSet(enumClass);
constantSets.put(name, constants);
}
}
}
return constants;
}
/**
* Gets the {@link Enum} class for the constant name space.
*
* @param name The name of the constants to locate.
* @return A Class.
*/
@SuppressWarnings("unchecked")
private static final Class<Enum> getEnumClass(String name) {
String[] prefixes = Platform.getPlatform().getPackagePrefixes();
for (String prefix : prefixes) {
try {
return (Class<Enum>) Class.forName(prefix + "." + name).asSubclass(Enum.class);
} catch (ClassNotFoundException ex) {
}
}
return null;
}
/**
* Creates a new instance of <tt>ConstantSet</tt>
*
* @param enumClass The Enum subclass to load constants from.
*/
@SuppressWarnings("unchecked")
private ConstantSet(Class<Enum> enumClass) {
this.enumClass = enumClass;
nameToConstant = new ConcurrentHashMap<String, Constant>();
valueToConstant = new ConcurrentHashMap<Long, Constant>();
constants = EnumSet.allOf(enumClass);
}
/**
* Gets the constant for a name.
*
* @param name The name of the system constant (e.g. "EINVAL").
* @return A {@link Constant} instance.
*/
@SuppressWarnings("unchecked")
public Constant getConstant(String name) {
Constant c = nameToConstant.get(name);
if (c == null) {
try {
nameToConstant.put(name, c = Constant.class.cast(Enum.valueOf(enumClass, name)));
} catch (IllegalArgumentException ex) {
return null;
}
}
return c;
}
/**
* Gets the constant for a name.
*
* @param value A system constant value.
* @return A {@link Constant} instance.
*/
@SuppressWarnings("unchecked")
public Constant getConstant(long value) {
Constant c = valueToConstant.get(value);
if (c == null) {
for (Enum e : constants) {
if (e instanceof Constant && ((Constant) e).longValue() == value) {
c = (Constant) e;
break;
}
}
if (c != null) {
valueToConstant.put(value, c);
}
}
return c;
}
/**
* Gets the integer value of a platform constant.
*
* @param name The name of the platform constant to look up (e.g. "EINVAL").
* @return The integer value of the constant.
*/
public long getValue(String name) {
Constant c = getConstant(name);
return c != null ? c.longValue() : 0;
}
/**
* Gets the name of a platform constant value.
*
* @param value The integer value to look up.
* @return The name of the constant.
*/
public String getName(int value) {
Constant c = getConstant(value);
return c != null ? c.name() : "unknown";
}
private Long getLongField(String name, long defaultValue) {
try {
Field f = enumClass.getField("MIN_VALUE");
return (Long) f.get(enumClass);
} catch (NoSuchFieldException ex) {
return defaultValue;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public long minValue() {
if (minValue == null) {
minValue = getLongField("MIN_VALUE", Integer.MIN_VALUE);
}
return minValue.intValue();
}
public long maxValue() {
if (maxValue == null) {
maxValue = getLongField("MAX_VALUE", Integer.MAX_VALUE);
}
return maxValue.intValue();
}
private final class ConstantIterator implements Iterator<Constant> {
private final Iterator<Enum> it;
private Constant next = null;
ConstantIterator(Collection<Enum> constants) {
this.it = constants.iterator();
next = it.hasNext() ? (Constant) it.next() : null;
}
public boolean hasNext() {
return next != null && !next.name().equals("__UNKNOWN_CONSTANT__");
}
public void remove() {
throw new UnsupportedOperationException();
}
public Constant next() {
Constant prev = next;
next = it.hasNext() ? (Constant) it.next() : null;
return prev;
}
}
@Override
public Iterator<Constant> iterator() {
return new ConstantIterator(constants);
}
@Override
public int size() {
return constants.size();
}
@Override
public boolean contains(Object o) {
return o != null && o.getClass().equals(enumClass);
}
}
| true | true | public static ConstantSet getConstantSet(String name) {
ConstantSet constants = constantSets.get(name);
if (constants == null) {
synchronized (lock) {
if (!constantSets.containsKey(name)) {
Class<Enum> enumClass = getEnumClass(name);
if (enumClass == null) {
return null;
}
if (!Constant.class.isAssignableFrom(enumClass)) {
throw new ClassCastException("class for " + name
+ " does not implement Constant interface");
}
constants = new ConstantSet(enumClass);
constantSets.put(name, constants);
}
}
}
return constants;
}
| public static ConstantSet getConstantSet(String name) {
ConstantSet constants = constantSets.get(name);
if (constants == null) {
synchronized (lock) {
constants = constantSets.get(name);
if (constants == null) {
Class<Enum> enumClass = getEnumClass(name);
if (enumClass == null) {
return null;
}
if (!Constant.class.isAssignableFrom(enumClass)) {
throw new ClassCastException("class for " + name
+ " does not implement Constant interface");
}
constants = new ConstantSet(enumClass);
constantSets.put(name, constants);
}
}
}
return constants;
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/decoration/JIDCombo.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/decoration/JIDCombo.java
index 610f6b5d7..aaf6923da 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/decoration/JIDCombo.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/decoration/JIDCombo.java
@@ -1,110 +1,112 @@
package de.fu_berlin.inf.dpp.ui.widgets.decoration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.SarosPluginContext;
import de.fu_berlin.inf.dpp.accountManagement.XMPPAccountStore;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.preferences.PreferenceUtils;
/**
* Extend's an {@link JID} displaying {@link Combo}.<br/>
* The {@link Combo} is pre-filled with the domains as defined in
* {@link XMPPAccountStore}.<br/>
* When the user edits the user portion of the selected {@link JID} all
* {@link Combo} elements are updated in order to reflect the user portion
* accordingly.
*/
public class JIDCombo {
@Inject
PreferenceUtils preferenceUtils;
@Inject
XMPPAccountStore xmppAccountStore;
protected Combo control;
public JIDCombo(Combo control) {
this.control = control;
SarosPluginContext.initComponent(this);
fill();
update();
registerListeners();
}
protected void fill() {
JIDComboUtils.fillJIDCombo(this.control, this.preferenceUtils,
this.xmppAccountStore);
}
protected void update() {
JIDComboUtils.updateJIDCombo(this.control);
}
protected void registerListeners() {
this.control.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
switch (e.keyCode) {
+ case SWT.HOME:
+ case SWT.END:
case SWT.ARROW_UP:
case SWT.ARROW_RIGHT:
case SWT.ARROW_DOWN:
case SWT.ARROW_LEFT:
// no need to update
break;
default:
update();
}
}
});
}
/**
* Returns the underlying {@link Combo} {@link Control}.
*
* @return
*/
public Combo getControl() {
return this.control;
}
/**
* @see Combo#getText()
*/
public String getText() {
return this.control.getText();
}
/**
* @see Combo#setText(String)
*/
public void setText(String string) {
this.control.setText(string);
update();
}
/**
* @see Combo#setEnabled(boolean)
*/
public void setEnabled(boolean enabled) {
this.control.setEnabled(enabled);
}
/**
* @return
* @see Combo#setFocus()
*/
public boolean setFocus() {
this.control.setSelection(new Point(0, 0));
return this.control.setFocus();
}
}
| true | true | protected void registerListeners() {
this.control.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
switch (e.keyCode) {
case SWT.ARROW_UP:
case SWT.ARROW_RIGHT:
case SWT.ARROW_DOWN:
case SWT.ARROW_LEFT:
// no need to update
break;
default:
update();
}
}
});
}
| protected void registerListeners() {
this.control.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
switch (e.keyCode) {
case SWT.HOME:
case SWT.END:
case SWT.ARROW_UP:
case SWT.ARROW_RIGHT:
case SWT.ARROW_DOWN:
case SWT.ARROW_LEFT:
// no need to update
break;
default:
update();
}
}
});
}
|
diff --git a/HelloGit/src/main.java b/HelloGit/src/main.java
index f8cbe46..8eaae7c 100644
--- a/HelloGit/src/main.java
+++ b/HelloGit/src/main.java
@@ -1,11 +1,10 @@
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.format("Hello Git %d!\n", 4);
- //sdsasadsadsdasda
}
}
| true | true | public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.format("Hello Git %d!\n", 4);
//sdsasadsadsdasda
}
| public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.format("Hello Git %d!\n", 4);
}
|
diff --git a/guiPanel.java b/guiPanel.java
index 026dbdb..e03a345 100644
--- a/guiPanel.java
+++ b/guiPanel.java
@@ -1,1062 +1,1060 @@
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.io.FileWriter.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Stack;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.JToolTip;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.*;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Highlighter.Highlight;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.UndoManager;
public class guiPanel extends JPanel implements UndoableEditListener {
// C++ source file this application has the focus on currently
// When tab focus changes this variable should refer to the file the tab contains
String currentCppSourceFile;
private static final long serialVersionUID = 1L;
//JMenuItems for File
// private JMenuItem newFile;
// private JMenuItem openFile;
// private JMenuItem saveFile;
// private JMenuItem saveAsFile;
// private JMenuItem run;
// private JMenuItem exit;
//Menu items for Edit
private JMenuItem undo;
private JMenuItem redo;
// private JButton pasteButton;
private DataDisplay tabbedPane3;
private Editor editor;
private JButton jb_undo, jb_redo;
// private JTextArea area;
private UndoManager undoredo;
private Controller controller;
//TODO: need functionality to keep track of what action was just done
//Menu Items for Help
private JMenuItem tutorial;
private TextLineNumber tln;
// highlight history
private Stack<Object> highlightStack = new Stack<Object>();
//constructor
public guiPanel(){
JMenuBar topBar = new JMenuBar(); //menu bar to hold the menus
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
//JMenu styleMenu = new JMenu("Style");
JMenu helpMenu = new JMenu("Help");
JMenu runMenu = new JMenu("Run");
currentCppSourceFile = null;
//menu items for "Edit"
undoredo = new UndoManager();
//help menu
tutorial = new JMenuItem("Tutorial");
//add the menus to the menu bar
topBar.add(fileMenu);
topBar.add(editMenu);
topBar.add(runMenu);
//topBar.add(styleMenu);
topBar.add(helpMenu);
helpMenu.add(tutorial);
JPanel myPanel = new JPanel();
JTextArea area = new JTextArea();
JTextArea area2 = new JTextArea();
JTextArea area3 = new JTextArea();
//set up the area to be put into the scroll pane
area.setColumns(30);
area.setRows(10);
area.setEditable(true);
JToolBar editToolBar = new JToolBar();
//add edit buttons to menu
// TODO: get undo/redo working, need undomanager and listner; look at swing.undo
editMenu.add(new UndoAction("Undo"));
editMenu.add(new RedoAction("Redo"));
editMenu.addSeparator();
editMenu.add(area.getActionMap().get(DefaultEditorKit.cutAction));
editMenu.add(area.getActionMap().get(DefaultEditorKit.copyAction));
editMenu.add(area.getActionMap().get(DefaultEditorKit.pasteAction));
editMenu.addSeparator();
editMenu.add(area.getActionMap().get(DefaultEditorKit.selectAllAction));
// Make buttons look nicer
Action a;
a = area.getActionMap().get(DefaultEditorKit.cutAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("Images/edit_cut.png"));
a.putValue(Action.NAME, "Cut");
a = area.getActionMap().get(DefaultEditorKit.copyAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("Images/copy.png"));
a.putValue(Action.NAME, "Copy");
a = area.getActionMap().get(DefaultEditorKit.pasteAction);
a.putValue(Action.SMALL_ICON, new ImageIcon("Images/paste.png"));
a.putValue(Action.NAME, "Paste");
a = area.getActionMap().get(DefaultEditorKit.selectAllAction);
a.putValue(Action.NAME, "Select All");
Action copyAction = new DefaultEditorKit.CopyAction();
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("Images/copy.png"));
copyAction.putValue(Action.NAME, "");
Action pasteAction = new DefaultEditorKit.PasteAction();
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("Images/paste.png"));
pasteAction.putValue(Action.NAME, "");
Action cutAction = new DefaultEditorKit.CutAction();
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("Images/edit_cut.png"));
cutAction.putValue(Action.NAME, "");
// To Do: Get style menu working
/*Action action = new StyledEditorKit.BoldAction();
action.putValue(Action.NAME, "Bold");
styleMenu.add(action);
action = new StyledEditorKit.ItalicAction();
action.putValue(Action.NAME, "Italic");
styleMenu.add(action);
action = new StyledEditorKit.UnderlineAction();
action.putValue(Action.NAME, "Underline");
styleMenu.add(action);*/
// -------------------------------------------------------------------
// 3 main gui components of citrin
JTabbedPane program = new JTabbedPane();
JTabbedPane tabbedPane2 = new JTabbedPane();
// JTabbedPane tabbedPane3 = new JTabbedPane();
tabbedPane3 = new DataDisplay(new Dimension(125,93) );
area2.setColumns(30);
area2.setRows(10);
area2.setEditable(true);
area3.setColumns(30);
area3.setRows(10);
area3.setEditable(false);
Console console = new Console();
console.setEditable(false);
editor = new Editor();
JScrollPane scrollPane = new JScrollPane(editor);
//add line numbers to editor
tln = new TextLineNumber(editor);
scrollPane.setRowHeaderView(tln);
JScrollPane scrollPane2 = new JScrollPane(console);
JScrollPane scrollPane3 = new JScrollPane(area3);
JScrollPane scrollPane4 = new JScrollPane(tabbedPane3);
//tabbedPane.addTab("Program", null);
program.add("Program", scrollPane);
// program.setName("*Program");
//tabbedPane2.addTab("Console", null);
tabbedPane2.add("Console", scrollPane2);
//tabbedPane2.add("copy.gif", new ImageIcon("copy.gif"), 0);
// tabbedPane3.addTab("States", null);
// tabbedPane3.add("States", scrollPane3);
fileMenu.add(new OpenAction("Open", editor));
fileMenu.addSeparator();
fileMenu.add(new SaveAction("Save", editor, true));
fileMenu.add(new SaveAction("SaveAs", editor, false));
fileMenu.addSeparator();
fileMenu.add(new ExitAction());
runMenu.add(new RunAllAction("RunAll", console));
runMenu.add(new StepAction("RunStep", console));
runMenu.add(new RunNumOfStepsAction(console));
runMenu.add(new RunBreakPoint(console));
JButton open = new JButton(new OpenAction("", editor));
open.setToolTipText("Open");
//buttons for cut, copy, paste
JButton cut = new JButton(cutAction);
cut.setToolTipText("Cut (Ctrl+X)");
JButton copy = new JButton(copyAction);
copy.setToolTipText("Copy (Ctrl+C)");
JButton paste = new JButton(pasteAction);
paste.setToolTipText("Paste (Ctrl+V)");
//button to stop the interpreter
Action stopAction = new StopRunAction();
JButton stopRunButton = new JButton(stopAction);
stopRunButton.setToolTipText("Terminate");
//button for runAll
Action runAllAction = new RunAllAction("", console);
JButton runAll = new JButton(runAllAction);
runAll.setToolTipText("Run All (F11)");
runAllAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F11"));
runAll.getActionMap().put("runAll", runAllAction);
runAll.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) runAllAction.getValue(Action.ACCELERATOR_KEY), "runAll")
;
//button for runStep
Action runStepAction = new StepAction("", console);
JButton runStep = new JButton(runStepAction);
runStep.setToolTipText("Run Step (F1)");
runStepAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F1"));
runStep.getActionMap().put("runStep", runStepAction);
runStep.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) runStepAction.getValue(Action.ACCELERATOR_KEY), "runStep")
;
//button for save
Action saveAction = new SaveAction("", editor,true);
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
JButton save = new JButton(saveAction);
save.getActionMap().put("save", saveAction);
save.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) saveAction.getValue(Action.ACCELERATOR_KEY), "save")
;
save.setToolTipText("Save (Ctrl+S)");
Action undoAction = new UndoAction("");
undoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Z"));
jb_undo = new JButton(undoAction);
jb_undo.getActionMap().put("undo", undoAction);
jb_undo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) undoAction.getValue(Action.ACCELERATOR_KEY), "undo")
;
jb_undo.setToolTipText("Undo (Ctrl+Z)");
Action redoAction = new RedoAction("");
redoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Y"));
jb_redo = new JButton(redoAction);
jb_redo.getActionMap().put("redo", redoAction);
jb_redo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put((KeyStroke) redoAction.getValue(Action.ACCELERATOR_KEY), "redo")
;
jb_redo.setToolTipText("Redo (Ctrl+Y)");
editToolBar.add(open);
editToolBar.add(cut);
editToolBar.add(copy);
editToolBar.add(paste);
editToolBar.add(runAll);
editToolBar.add(runStep);
editToolBar.add(save);
editToolBar.add(jb_undo);
editToolBar.add(jb_redo);
editToolBar.add(stopRunButton);
JSplitPane splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane4, tabbedPane2);
splitPane2.setOneTouchExpandable(true);
splitPane2.setDividerLocation(400);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tabbedPane, splitPane2);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, program, splitPane2);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(450);
//Provide minimum sizes for the two components in the split pane
Dimension minimumSize = new Dimension(200, 10);
scrollPane.setMinimumSize(minimumSize);
scrollPane2.setMinimumSize(minimumSize);
scrollPane3.setMinimumSize(new Dimension(10, 10));
myPanel.setLayout(new BorderLayout());
myPanel.setPreferredSize(new Dimension(500, 600));
setLayout(new BorderLayout());
setPreferredSize(new Dimension(800, 650));
myPanel.add("Center",splitPane);
myPanel.add("North", editToolBar);
//myPanel.setLocation(0, 0); //This line doesn't seem to be necessary.
add("Center", myPanel);
add("North", topBar);
//setLocation(0,0); //This line doesn't seem to be necessary.
controller = new Controller(console, this);
editor.getDocument().addUndoableEditListener(this);
//undo.addActionListener(this);
//redo.addActionListener(this);
//jb_undo.addActionListener(this);
//jb_redo.addActionListener(this);
runMenu.add(new RunTimed("RunTimed", console));
}
private static void createAndShowGUI(){
// Create the container
JFrame frame = new JFrame("CITRIN", null);
// Quit the application when this frame is closed:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and add the content
guiPanel panel = new guiPanel();
frame.setLayout(new BorderLayout());
frame.add(panel);
// Display the window
frame.pack(); // adapt the frame size to its content
frame.setLocation(300, 20); // in pixels
frame.setVisible(true); // Now the frame will appear on screen
// Quit the application when this frame is closed:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add a window listener
frame.addWindowListener(new WindowAdapter(){
//save the user preferences as the window closes
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]){
// Set the look and feel to that of the system
try {
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
}
catch ( Exception e ) {
System.err.println( e );
}
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("serial")
class RunTimed extends AbstractAction{
JTextComponent display;
String interpretation = "";
long now;
long mTimeElapsed = System.currentTimeMillis();
public RunTimed(String label, JTextComponent display) {
super("RunTimed", new ImageIcon("Images/run.png"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
save(editor, true);
runstep s = new runstep();
Thread thr = new Thread(s);
thr.start();
}
}
class runstep implements Runnable{
public void run(long time) {
// TODO Auto-generated method stub
boolean firstRun = false;
do{
if(firstRun){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized(controller) {
if(!controller.isInterpreting() && !firstRun){
resetCitrin(null);
firstRun = true;
}
else {
if(controller.isInterpreting()){
controller.addSteps(1);
}
}
}
}while(controller.isInterpreting());
Thread.currentThread().interrupt();
}
@Override
public void run() {
//String s = JOptionPane.showInputDialog("Enter number of seconds:");
//if(s.contains(".")){
//}
double time = Double.parseDouble(JOptionPane.showInputDialog("Enter number of seconds:"));
time = time*1000;
long s = (long) time;
run(s);
}
}
@Override
public void undoableEditHappened(UndoableEditEvent edit) {
undoredo.addEdit(edit.getEdit());
}
//highlights one line
public void HighlightLine(int lineNumber, Color c){
DefaultHighlightPainter color = new DefaultHighlightPainter(c);
int beginning = 0;
int end = 0;
try {
beginning = editor.getLineStartOffset(lineNumber-1);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
end = editor.getLineEndOffset(lineNumber-1);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Object tag = editor.getHighlighter().addHighlight(beginning, end, color);
highlightStack.add(tag);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clearHighlight(){
editor.getHighlighter().removeAllHighlights();
highlightStack.clear();
}
public void clearMostRecentHighlight(){
if(highlightStack.size()>0){
editor.getHighlighter().removeHighlight(highlightStack.lastElement());
highlightStack.pop();
}
}
public void centerOnLine(int lineNum){
int beginning;
try {
beginning = editor.getLineStartOffset(lineNum-1);
editor.setCaretPosition(beginning);
centerLineInScrollPane(editor);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void centerLineInScrollPane(JTextComponent component)
{
Container container = SwingUtilities.getAncestorOfClass(JViewport.class, component);
if (container == null) return;
try{
Rectangle r = component.modelToView(component.getCaretPosition());
JViewport viewport = (JViewport)container;
int extentWidth = viewport.getExtentSize().width;
int viewWidth = viewport.getViewSize().width;
int x = Math.max(0, r.x - (extentWidth / 2));
x = Math.min(x, viewWidth - extentWidth);
int extentHeight = viewport.getExtentSize().height;
int viewHeight = viewport.getViewSize().height;
int y = Math.max(0, r.y - (extentHeight / 2));
y = Math.min(y, viewHeight - extentHeight);
viewport.setViewPosition(new Point(x, y));
}
catch(BadLocationException ble) {}
}
// @Override
/* public void actionPerformed(ActionEvent e) {
if(e.getSource() == undo || e.getSource() == jb_undo){
if(undoredo.canUndo()){
undoredo.undo();
}
}
else if(e.getSource() == redo || e.getSource() == jb_redo){
if(undoredo.canRedo()){
undoredo.redo();
}
}
}*/
class UndoAction extends AbstractAction{
/**
*
*/
private static final long serialVersionUID = 1L;
public UndoAction(String label){
super(label, new ImageIcon("Images/undo.png"));
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
undoredo.undo();
}
}
class RedoAction extends AbstractAction{
/**
*
*/
private static final long serialVersionUID = 1L;
public RedoAction(String label){
super(label, new ImageIcon("Images/redo.png"));
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
undoredo.redo();
}
}
/*
public void saveFileAs() throws IOException {
String saveFileName = JOptionPane.showInputDialog("Save File As");
System.out.print(saveFileName);
}
*/
/*@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == exit){
System.exit(0);
}
}*/
// ----------------------------------------------------------------------------
// Callback Classes
//
// TODO :
//
// - NewFile Action
// - Error checking such as making sure the file exists before saving
//
// ToConsider :
//
// SaveAction and OpenAction should resides in a different class since
// those actions should be more related to some editing session type class
// rather than this main application class
//
// All these functions are using currentCppSourceFile. Hard to keep track
// of if multiple editing session should be implemented.
// An action to simply exit the app
@SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
}
public void actionPerformed(ActionEvent ev) {
System.exit(0);
}
}
// An action that saves the document to a file : Supports Save and SaveAs actoins
/*class SaveActionButton extends AbstractAction {
// PossibleBugSource : Saving to class member variable currentCppSourceFile
JTextComponent textComponent;
//boolean saveToCurrentFile;
// label ... label to show on the view
// textComponent ... the view and model that keeps and show the text data
// saveToCurrentFile ... false => prompts the user for the file, true => save to curent file
public SaveActionButton(String label, JTextComponent textComponent){//, boolean saveToCurrentFile) {
super("", new ImageIcon("saved.gif"));
this.textComponent = textComponent;
// this.saveToCurrentFile = saveToCurrentFile;
}
public void actionPerformed(ActionEvent ev) {
undoredo.discardAllEdits();
File file;
/* if ( ! saveToCurrentFile ) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
else {*/
/* if(currentCppSourceFile != null){
file = new File(currentCppSourceFile);
}
else{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
//}
// }
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComponent.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
}*/
// An action that saves the document to a file : Supports Save and SaveAs actions
@SuppressWarnings("serial")
class SaveAction extends AbstractAction {
// PossibleBugSource : Saving to class member variable currentCppSourceFile
JTextComponent textComponent;
boolean saveToCurrentFile;
// label ... label to show on the view
// textComponent ... the view and model that keeps and show the text data
// saveToCurrentFile ... false => prompts the user for the file, true => save to curent file
public SaveAction(String label, JTextComponent textComponent, boolean saveAs){//, boolean saveToCurrentFile) {
super(label, new ImageIcon("Images/save.png"));
this.textComponent = textComponent;
saveToCurrentFile = saveAs;
// this.saveToCurrentFile = saveToCurrentFile;
}
public void actionPerformed(ActionEvent ev) {
File file;
/* if ( ! saveToCurrentFile ) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
else {*/
if(currentCppSourceFile != null && saveToCurrentFile){
file = new File(currentCppSourceFile);
}
else{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
currentCppSourceFile = file.toString();
undoredo.discardAllEdits();
}
//}
// }
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComponent.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
}
public void save(JTextComponent textComponent, boolean saveAs){//, boolean saveToCurrentFile) {
File file;
/* if ( ! saveToCurrentFile ) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
else {*/
if(currentCppSourceFile != null && saveAs){
file = new File(currentCppSourceFile);
}
else{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
currentCppSourceFile = file.toString();
undoredo.discardAllEdits();
}
//}
// }
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComponent.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
// An action that opens an existing file
public class OpenAction extends AbstractAction implements UndoableEditListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextComponent textComponent;
// textComponent ... this action opens a file into this textComponent
public OpenAction(String label, JTextComponent textComponent) {
super(label, new ImageIcon("Images/open_folder_green.png"));
this.textComponent = textComponent;
}
// Query user for a filename and attempt to open and read the file into
// the text component.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;
FileReader reader = null;
try {
reader = new FileReader(file);
textComponent.read(reader, null);
currentCppSourceFile = file.getPath();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {
}
//Set text component to focus
textComponent.requestFocus();
//hack to update line numbers
textComponent.setCaretPosition(textComponent.getDocument().getLength());
textComponent.setCaretPosition(0);
textComponent.getDocument().addUndoableEditListener(this);
//textComponent.getDocument().addUndoableEditListener( this);
}
}
}
@Override
public void undoableEditHappened(UndoableEditEvent edit) {
// TODO Auto-generated method stub
undoredo.addEdit(edit.getEdit());
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class RunAllAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunAllAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/run.png"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
save(editor, true);
// run interpreter on currentCppSourceFile
// Start interpreter in new thread
// TODO: hmmmm is this the best way
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.continueRun();
}
}
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class StepAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public StepAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/step.gif"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.addSteps(1);
}
}
}
}
@SuppressWarnings("serial")
class RunNumOfStepsAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunNumOfStepsAction(JTextComponent display) {
super("Run Multiple Steps");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
int steps;
- JOptionPane dialog = new JOptionPane();
- int input = Integer.parseInt(dialog.showInputDialog("Enter number of steps to run"));
+ int input = Integer.parseInt(JOptionPane.showInputDialog("Enter number of steps to run"));
input = input-1;
synchronized(controller){
Interpreter i;
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
new Thread(i = new Interpreter(controller,currentCppSourceFile,1, stab)).start();
controller.addInterpreter(i);
controller.addSteps(input);
}
}
}
@SuppressWarnings("serial")
class RunBreakPoint extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunBreakPoint(JTextComponent display) {
super("Run to Breakpoint");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
- JOptionPane dialog = new JOptionPane();
- int input = Integer.parseInt(dialog.showInputDialog("Run to which line"));
+ int input = Integer.parseInt(JOptionPane.showInputDialog("Run to which line"));
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(input);
}
else{
controller.runToBreak(input);
}
}
}
}
@SuppressWarnings("serial")
class StopRunAction extends AbstractAction {
public StopRunAction() {
super("", new ImageIcon("Images/stop.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
//stop interpreter
synchronized(controller){
controller.stopInterpreter();
}
}
}
void resetCitrin(Integer breakPoint)
{
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
Interpreter i = new Interpreter(controller,currentCppSourceFile,-1, stab);
controller.addInterpreter(i);
Thread t = new Thread(i);
CitrinInterrupter.getInstance().addThread(t);
t.start();
if (breakPoint!=null)
i.setBreakPoint(breakPoint);
}
}
| false | true | public void save(JTextComponent textComponent, boolean saveAs){//, boolean saveToCurrentFile) {
File file;
/* if ( ! saveToCurrentFile ) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
else {*/
if(currentCppSourceFile != null && saveAs){
file = new File(currentCppSourceFile);
}
else{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
currentCppSourceFile = file.toString();
undoredo.discardAllEdits();
}
//}
// }
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComponent.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
// An action that opens an existing file
public class OpenAction extends AbstractAction implements UndoableEditListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextComponent textComponent;
// textComponent ... this action opens a file into this textComponent
public OpenAction(String label, JTextComponent textComponent) {
super(label, new ImageIcon("Images/open_folder_green.png"));
this.textComponent = textComponent;
}
// Query user for a filename and attempt to open and read the file into
// the text component.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;
FileReader reader = null;
try {
reader = new FileReader(file);
textComponent.read(reader, null);
currentCppSourceFile = file.getPath();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {
}
//Set text component to focus
textComponent.requestFocus();
//hack to update line numbers
textComponent.setCaretPosition(textComponent.getDocument().getLength());
textComponent.setCaretPosition(0);
textComponent.getDocument().addUndoableEditListener(this);
//textComponent.getDocument().addUndoableEditListener( this);
}
}
}
@Override
public void undoableEditHappened(UndoableEditEvent edit) {
// TODO Auto-generated method stub
undoredo.addEdit(edit.getEdit());
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class RunAllAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunAllAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/run.png"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
save(editor, true);
// run interpreter on currentCppSourceFile
// Start interpreter in new thread
// TODO: hmmmm is this the best way
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.continueRun();
}
}
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class StepAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public StepAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/step.gif"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.addSteps(1);
}
}
}
}
@SuppressWarnings("serial")
class RunNumOfStepsAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunNumOfStepsAction(JTextComponent display) {
super("Run Multiple Steps");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
int steps;
JOptionPane dialog = new JOptionPane();
int input = Integer.parseInt(dialog.showInputDialog("Enter number of steps to run"));
input = input-1;
synchronized(controller){
Interpreter i;
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
new Thread(i = new Interpreter(controller,currentCppSourceFile,1, stab)).start();
controller.addInterpreter(i);
controller.addSteps(input);
}
}
}
@SuppressWarnings("serial")
class RunBreakPoint extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunBreakPoint(JTextComponent display) {
super("Run to Breakpoint");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
JOptionPane dialog = new JOptionPane();
int input = Integer.parseInt(dialog.showInputDialog("Run to which line"));
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(input);
}
else{
controller.runToBreak(input);
}
}
}
}
@SuppressWarnings("serial")
class StopRunAction extends AbstractAction {
public StopRunAction() {
super("", new ImageIcon("Images/stop.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
//stop interpreter
synchronized(controller){
controller.stopInterpreter();
}
}
}
void resetCitrin(Integer breakPoint)
{
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
Interpreter i = new Interpreter(controller,currentCppSourceFile,-1, stab);
controller.addInterpreter(i);
Thread t = new Thread(i);
CitrinInterrupter.getInstance().addThread(t);
t.start();
if (breakPoint!=null)
i.setBreakPoint(breakPoint);
}
}
| public void save(JTextComponent textComponent, boolean saveAs){//, boolean saveToCurrentFile) {
File file;
/* if ( ! saveToCurrentFile ) {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
if (file == null)
return;
}
else {*/
if(currentCppSourceFile != null && saveAs){
file = new File(currentCppSourceFile);
}
else{
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
currentCppSourceFile = file.toString();
undoredo.discardAllEdits();
}
//}
// }
FileWriter writer = null;
try {
writer = new FileWriter(file);
textComponent.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException x) {
}
}
}
}
// An action that opens an existing file
public class OpenAction extends AbstractAction implements UndoableEditListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextComponent textComponent;
// textComponent ... this action opens a file into this textComponent
public OpenAction(String label, JTextComponent textComponent) {
super(label, new ImageIcon("Images/open_folder_green.png"));
this.textComponent = textComponent;
}
// Query user for a filename and attempt to open and read the file into
// the text component.
public void actionPerformed(ActionEvent ev) {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
if (file == null)
return;
FileReader reader = null;
try {
reader = new FileReader(file);
textComponent.read(reader, null);
currentCppSourceFile = file.getPath();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException x) {
}
//Set text component to focus
textComponent.requestFocus();
//hack to update line numbers
textComponent.setCaretPosition(textComponent.getDocument().getLength());
textComponent.setCaretPosition(0);
textComponent.getDocument().addUndoableEditListener(this);
//textComponent.getDocument().addUndoableEditListener( this);
}
}
}
@Override
public void undoableEditHappened(UndoableEditEvent edit) {
// TODO Auto-generated method stub
undoredo.addEdit(edit.getEdit());
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class RunAllAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunAllAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/run.png"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
save(editor, true);
// run interpreter on currentCppSourceFile
// Start interpreter in new thread
// TODO: hmmmm is this the best way
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.continueRun();
}
}
}
}
// An action that runs the interpreter on all the contents of the current cpp source file
@SuppressWarnings("serial")
class StepAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public StepAction(String label, JTextComponent display) {
super(label, new ImageIcon("Images/step.gif"));
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(null);
}
else{
controller.addSteps(1);
}
}
}
}
@SuppressWarnings("serial")
class RunNumOfStepsAction extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunNumOfStepsAction(JTextComponent display) {
super("Run Multiple Steps");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
int steps;
int input = Integer.parseInt(JOptionPane.showInputDialog("Enter number of steps to run"));
input = input-1;
synchronized(controller){
Interpreter i;
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
new Thread(i = new Interpreter(controller,currentCppSourceFile,1, stab)).start();
controller.addInterpreter(i);
controller.addSteps(input);
}
}
}
@SuppressWarnings("serial")
class RunBreakPoint extends AbstractAction {
JTextComponent display;
String interpretation = "";
public RunBreakPoint(JTextComponent display) {
super("Run to Breakpoint");
this.display = display;
}
@Override
public void actionPerformed(ActionEvent e) {
// run interpreter on currentCppSourceFile
save(editor, true);
int input = Integer.parseInt(JOptionPane.showInputDialog("Run to which line"));
synchronized(controller){
if(!controller.isInterpreting()){
resetCitrin(input);
}
else{
controller.runToBreak(input);
}
}
}
}
@SuppressWarnings("serial")
class StopRunAction extends AbstractAction {
public StopRunAction() {
super("", new ImageIcon("Images/stop.png"));
}
@Override
public void actionPerformed(ActionEvent e) {
//stop interpreter
synchronized(controller){
controller.stopInterpreter();
}
}
}
void resetCitrin(Integer breakPoint)
{
SymbolTableNotifier stab = new SymbolTableNotifier();
stab.addObserver( tabbedPane3 );
controller.clearConsole();
controller.setInterpretingStart();
Interpreter i = new Interpreter(controller,currentCppSourceFile,-1, stab);
controller.addInterpreter(i);
Thread t = new Thread(i);
CitrinInterrupter.getInstance().addThread(t);
t.start();
if (breakPoint!=null)
i.setBreakPoint(breakPoint);
}
}
|
diff --git a/tests/src/org/jboss/messaging/tests/integration/security/NettySecurityClientTest.java b/tests/src/org/jboss/messaging/tests/integration/security/NettySecurityClientTest.java
index e7cd9310c..24a3619d8 100644
--- a/tests/src/org/jboss/messaging/tests/integration/security/NettySecurityClientTest.java
+++ b/tests/src/org/jboss/messaging/tests/integration/security/NettySecurityClientTest.java
@@ -1,140 +1,144 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005-2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.messaging.tests.integration.security;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import org.jboss.messaging.core.config.TransportConfiguration;
import org.jboss.messaging.core.config.impl.ConfigurationImpl;
import org.jboss.messaging.core.logging.Logger;
import org.jboss.messaging.core.server.Messaging;
import org.jboss.messaging.core.server.MessagingService;
import org.jboss.messaging.integration.transports.netty.NettyAcceptorFactory;
import org.jboss.messaging.integration.transports.netty.NettyConnectorFactory;
import org.jboss.messaging.tests.util.SpawnedVMSupport;
import org.jboss.messaging.tests.util.UnitTestCase;
/**
* A NettySecurityClientTest
*
* @author <a href="[email protected]">Jeff Mesnil</a>
*/
public class NettySecurityClientTest extends UnitTestCase
{
// Constants -----------------------------------------------------
private static final Logger log = Logger.getLogger(NettySecurityClientTest.class);
// Attributes ----------------------------------------------------
private MessagingService messagingService;
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
public void testProducerConsumerClientWithoutSecurityManager() throws Exception
{
doTestProducerConsumerClient(false);
}
public void testProducerConsumerClientWithSecurityManager() throws Exception
{
doTestProducerConsumerClient(true);
}
// SecurityManagerClientTestBase overrides -----------------------
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
@Override
protected void setUp() throws Exception
{
super.setUp();
ConfigurationImpl config = new ConfigurationImpl();
config.setSecurityEnabled(false);
config.getAcceptorConfigurations().add(new TransportConfiguration(NettyAcceptorFactory.class.getName()));
messagingService = Messaging.newNullStorageMessagingService(config);
messagingService.start();
}
@Override
protected void tearDown() throws Exception
{
messagingService.stop();
super.tearDown();
}
// Private -------------------------------------------------------
private void doTestProducerConsumerClient(boolean withSecurityManager) throws Exception
{
String[] vmargs = new String[0];
if (withSecurityManager)
{
URL securityPolicyURL = Thread.currentThread().getContextClassLoader().getResource("restricted-security-client.policy");
vmargs = new String[] { "-Djava.security.manager", "-Djava.security.policy=" + securityPolicyURL.getPath() };
}
// spawn a JVM that creates a client withor without a security manager which sends and receives a test message
Process p = SpawnedVMSupport.spawnVM(SimpleClient.class.getName(),
vmargs,
false,
new String[] { NettyConnectorFactory.class.getName() });
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.replace('|', '\n');
- if ("OK".equals(line.trim()))
+ if (line.startsWith("Listening"))
+ {
+ continue;
+ }
+ else if ("OK".equals(line.trim()))
{
break;
} else
{
fail("Exception when starting the client: " + line);
}
}
// the client VM should exit by itself. If it doesn't, that means we have a problem
// and the test will timeout
log.debug("waiting for the client VM to exit ...");
p.waitFor();
assertEquals("client VM did not exit cleanly", 0, p.exitValue());
}
// Inner classes -------------------------------------------------
}
| true | true | private void doTestProducerConsumerClient(boolean withSecurityManager) throws Exception
{
String[] vmargs = new String[0];
if (withSecurityManager)
{
URL securityPolicyURL = Thread.currentThread().getContextClassLoader().getResource("restricted-security-client.policy");
vmargs = new String[] { "-Djava.security.manager", "-Djava.security.policy=" + securityPolicyURL.getPath() };
}
// spawn a JVM that creates a client withor without a security manager which sends and receives a test message
Process p = SpawnedVMSupport.spawnVM(SimpleClient.class.getName(),
vmargs,
false,
new String[] { NettyConnectorFactory.class.getName() });
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.replace('|', '\n');
if ("OK".equals(line.trim()))
{
break;
} else
{
fail("Exception when starting the client: " + line);
}
}
// the client VM should exit by itself. If it doesn't, that means we have a problem
// and the test will timeout
log.debug("waiting for the client VM to exit ...");
p.waitFor();
assertEquals("client VM did not exit cleanly", 0, p.exitValue());
}
| private void doTestProducerConsumerClient(boolean withSecurityManager) throws Exception
{
String[] vmargs = new String[0];
if (withSecurityManager)
{
URL securityPolicyURL = Thread.currentThread().getContextClassLoader().getResource("restricted-security-client.policy");
vmargs = new String[] { "-Djava.security.manager", "-Djava.security.policy=" + securityPolicyURL.getPath() };
}
// spawn a JVM that creates a client withor without a security manager which sends and receives a test message
Process p = SpawnedVMSupport.spawnVM(SimpleClient.class.getName(),
vmargs,
false,
new String[] { NettyConnectorFactory.class.getName() });
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
line = line.replace('|', '\n');
if (line.startsWith("Listening"))
{
continue;
}
else if ("OK".equals(line.trim()))
{
break;
} else
{
fail("Exception when starting the client: " + line);
}
}
// the client VM should exit by itself. If it doesn't, that means we have a problem
// and the test will timeout
log.debug("waiting for the client VM to exit ...");
p.waitFor();
assertEquals("client VM did not exit cleanly", 0, p.exitValue());
}
|
diff --git a/solr/core/src/java/org/apache/solr/core/RequestHandlers.java b/solr/core/src/java/org/apache/solr/core/RequestHandlers.java
index 80c7c04d7..93def2997 100644
--- a/solr/core/src/java/org/apache/solr/core/RequestHandlers.java
+++ b/solr/core/src/java/org/apache/solr/core/RequestHandlers.java
@@ -1,337 +1,337 @@
/**
* 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.solr.core;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.CommonParams.EchoParamStyle;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.handler.component.SearchHandler;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.plugin.PluginInfoInitialized;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
final class RequestHandlers {
public static Logger log = LoggerFactory.getLogger(RequestHandlers.class);
public static final String DEFAULT_HANDLER_NAME="standard";
protected final SolrCore core;
// Use a synchronized map - since the handlers can be changed at runtime,
// the map implementation should be thread safe
private final Map<String, SolrRequestHandler> handlers =
new ConcurrentHashMap<String,SolrRequestHandler>() ;
/**
* Trim the trailing '/' if its there, and convert null to empty string.
*
* we want:
* /update/csv and
* /update/csv/
* to map to the same handler
*
*/
private static String normalize( String p )
{
if(p == null) return "";
if( p.endsWith( "/" ) && p.length() > 1 )
return p.substring( 0, p.length()-1 );
return p;
}
public RequestHandlers(SolrCore core) {
this.core = core;
}
/**
* @return the RequestHandler registered at the given name
*/
public SolrRequestHandler get(String handlerName) {
return handlers.get(normalize(handlerName));
}
/**
* @return a Map of all registered handlers of the specified type.
*/
public Map<String,SolrRequestHandler> getAll(Class clazz) {
Map<String,SolrRequestHandler> result
= new HashMap<String,SolrRequestHandler>(7);
for (Map.Entry<String,SolrRequestHandler> e : handlers.entrySet()) {
if(clazz.isInstance(e.getValue())) result.put(e.getKey(), e.getValue());
}
return result;
}
/**
* Handlers must be initialized before calling this function. As soon as this is
* called, the handler can immediately accept requests.
*
* This call is thread safe.
*
* @return the previous handler at the given path or null
*/
public SolrRequestHandler register( String handlerName, SolrRequestHandler handler ) {
String norm = normalize( handlerName );
if( handler == null ) {
return handlers.remove( norm );
}
SolrRequestHandler old = handlers.put(norm, handler);
if (0 != norm.length() && handler instanceof SolrInfoMBean) {
core.getInfoRegistry().put(handlerName, handler);
}
return old;
}
/**
* Returns an unmodifiable Map containing the registered handlers
*/
public Map<String,SolrRequestHandler> getRequestHandlers() {
return Collections.unmodifiableMap( handlers );
}
/**
* Read solrconfig.xml and register the appropriate handlers
*
* This function should <b>only</b> be called from the SolrCore constructor. It is
* not intended as a public API.
*
* While the normal runtime registration contract is that handlers MUST be initialized
* before they are registered, this function does not do that exactly.
*
* This function registers all handlers first and then calls init() for each one.
*
* This is OK because this function is only called at startup and there is no chance that
* a handler could be asked to handle a request before it is initialized.
*
* The advantage to this approach is that handlers can know what path they are registered
* to and what other handlers are available at startup.
*
* Handlers will be registered and initialized in the order they appear in solrconfig.xml
*/
void initHandlersFromConfig(SolrConfig config ){
// use link map so we iterate in the same order
Map<PluginInfo,SolrRequestHandler> handlers = new LinkedHashMap<PluginInfo,SolrRequestHandler>();
for (PluginInfo info : config.getPluginInfos(SolrRequestHandler.class.getName())) {
try {
SolrRequestHandler requestHandler;
String startup = info.attributes.get("startup") ;
if( startup != null ) {
if( "lazy".equals(startup) ) {
log.info("adding lazy requestHandler: " + info.className);
requestHandler = new LazyRequestHandlerWrapper( core, info.className, info.initArgs );
} else {
throw new Exception( "Unknown startup value: '"+startup+"' for: "+info.className );
}
} else {
requestHandler = core.createRequestHandler(info.className);
}
handlers.put(info,requestHandler);
SolrRequestHandler old = register(info.name, requestHandler);
if(old != null) {
log.warn("Multiple requestHandler registered to the same name: " + info.name + " ignoring: " + old.getClass().getName());
}
if(info.isDefault()){
old = register("",requestHandler);
if(old != null)
log.warn("Multiple default requestHandler registered" + " ignoring: " + old.getClass().getName());
}
log.info("created "+info.name+": " + info.className);
} catch (Exception ex) {
SolrConfig.severeErrors.add( ex );
SolrException e = new SolrException
(ErrorCode.SERVER_ERROR, "RequestHandler init failure", ex);
SolrException.logOnce(log,null,e);
throw e;
}
}
- // we've now registered all handlers, time ot init them in the same order
+ // we've now registered all handlers, time to init them in the same order
for (Map.Entry<PluginInfo,SolrRequestHandler> entry : handlers.entrySet()) {
PluginInfo info = entry.getKey();
SolrRequestHandler requestHandler = entry.getValue();
if (requestHandler instanceof PluginInfoInitialized) {
((PluginInfoInitialized) requestHandler).init(info);
} else{
requestHandler.init(info.initArgs);
}
}
if(get("") == null) register("", get(DEFAULT_HANDLER_NAME));
}
/**
* The <code>LazyRequestHandlerWrapper</core> wraps any {@link SolrRequestHandler}.
* Rather then instanciate and initalize the handler on startup, this wrapper waits
* until it is actually called. This should only be used for handlers that are
* unlikely to be used in the normal lifecycle.
*
* You can enable lazy loading in solrconfig.xml using:
*
* <pre>
* <requestHandler name="..." class="..." startup="lazy">
* ...
* </requestHandler>
* </pre>
*
* This is a private class - if there is a real need for it to be public, it could
* move
*
* @since solr 1.2
*/
private static final class LazyRequestHandlerWrapper implements SolrRequestHandler, SolrInfoMBean
{
private final SolrCore core;
private String _className;
private NamedList _args;
private SolrRequestHandler _handler;
public LazyRequestHandlerWrapper( SolrCore core, String className, NamedList args )
{
this.core = core;
_className = className;
_args = args;
_handler = null; // don't initialize
}
/**
* In normal use, this function will not be called
*/
public void init(NamedList args) {
// do nothing
}
/**
* Wait for the first request before initializing the wrapped handler
*/
public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {
SolrRequestHandler handler = _handler;
if (handler == null) {
handler = getWrappedHandler();
}
handler.handleRequest( req, rsp );
}
public synchronized SolrRequestHandler getWrappedHandler()
{
if( _handler == null ) {
try {
SolrRequestHandler handler = core.createRequestHandler(_className);
handler.init( _args );
if( handler instanceof SolrCoreAware ) {
((SolrCoreAware)handler).inform( core );
}
_handler = handler;
}
catch( Exception ex ) {
throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "lazy loading error", ex );
}
}
return _handler;
}
public String getHandlerClass()
{
return _className;
}
//////////////////////// SolrInfoMBeans methods //////////////////////
public String getName() {
return "Lazy["+_className+"]";
}
public String getDescription()
{
if( _handler == null ) {
return getName();
}
return _handler.getDescription();
}
public String getVersion() {
String rev = "$Revision$";
if( _handler != null ) {
rev += " :: " + _handler.getVersion();
}
return rev;
}
public String getSourceId() {
String rev = "$Id$";
if( _handler != null ) {
rev += " :: " + _handler.getSourceId();
}
return rev;
}
public String getSource() {
String rev = "$URL$";
if( _handler != null ) {
rev += "\n" + _handler.getSource();
}
return rev;
}
public URL[] getDocs() {
if( _handler == null ) {
return null;
}
return _handler.getDocs();
}
public Category getCategory()
{
return Category.QUERYHANDLER;
}
public NamedList getStatistics() {
if( _handler != null ) {
return _handler.getStatistics();
}
NamedList<String> lst = new SimpleOrderedMap<String>();
lst.add("note", "not initialized yet" );
return lst;
}
}
}
| true | true | void initHandlersFromConfig(SolrConfig config ){
// use link map so we iterate in the same order
Map<PluginInfo,SolrRequestHandler> handlers = new LinkedHashMap<PluginInfo,SolrRequestHandler>();
for (PluginInfo info : config.getPluginInfos(SolrRequestHandler.class.getName())) {
try {
SolrRequestHandler requestHandler;
String startup = info.attributes.get("startup") ;
if( startup != null ) {
if( "lazy".equals(startup) ) {
log.info("adding lazy requestHandler: " + info.className);
requestHandler = new LazyRequestHandlerWrapper( core, info.className, info.initArgs );
} else {
throw new Exception( "Unknown startup value: '"+startup+"' for: "+info.className );
}
} else {
requestHandler = core.createRequestHandler(info.className);
}
handlers.put(info,requestHandler);
SolrRequestHandler old = register(info.name, requestHandler);
if(old != null) {
log.warn("Multiple requestHandler registered to the same name: " + info.name + " ignoring: " + old.getClass().getName());
}
if(info.isDefault()){
old = register("",requestHandler);
if(old != null)
log.warn("Multiple default requestHandler registered" + " ignoring: " + old.getClass().getName());
}
log.info("created "+info.name+": " + info.className);
} catch (Exception ex) {
SolrConfig.severeErrors.add( ex );
SolrException e = new SolrException
(ErrorCode.SERVER_ERROR, "RequestHandler init failure", ex);
SolrException.logOnce(log,null,e);
throw e;
}
}
// we've now registered all handlers, time ot init them in the same order
for (Map.Entry<PluginInfo,SolrRequestHandler> entry : handlers.entrySet()) {
PluginInfo info = entry.getKey();
SolrRequestHandler requestHandler = entry.getValue();
if (requestHandler instanceof PluginInfoInitialized) {
((PluginInfoInitialized) requestHandler).init(info);
} else{
requestHandler.init(info.initArgs);
}
}
if(get("") == null) register("", get(DEFAULT_HANDLER_NAME));
}
| void initHandlersFromConfig(SolrConfig config ){
// use link map so we iterate in the same order
Map<PluginInfo,SolrRequestHandler> handlers = new LinkedHashMap<PluginInfo,SolrRequestHandler>();
for (PluginInfo info : config.getPluginInfos(SolrRequestHandler.class.getName())) {
try {
SolrRequestHandler requestHandler;
String startup = info.attributes.get("startup") ;
if( startup != null ) {
if( "lazy".equals(startup) ) {
log.info("adding lazy requestHandler: " + info.className);
requestHandler = new LazyRequestHandlerWrapper( core, info.className, info.initArgs );
} else {
throw new Exception( "Unknown startup value: '"+startup+"' for: "+info.className );
}
} else {
requestHandler = core.createRequestHandler(info.className);
}
handlers.put(info,requestHandler);
SolrRequestHandler old = register(info.name, requestHandler);
if(old != null) {
log.warn("Multiple requestHandler registered to the same name: " + info.name + " ignoring: " + old.getClass().getName());
}
if(info.isDefault()){
old = register("",requestHandler);
if(old != null)
log.warn("Multiple default requestHandler registered" + " ignoring: " + old.getClass().getName());
}
log.info("created "+info.name+": " + info.className);
} catch (Exception ex) {
SolrConfig.severeErrors.add( ex );
SolrException e = new SolrException
(ErrorCode.SERVER_ERROR, "RequestHandler init failure", ex);
SolrException.logOnce(log,null,e);
throw e;
}
}
// we've now registered all handlers, time to init them in the same order
for (Map.Entry<PluginInfo,SolrRequestHandler> entry : handlers.entrySet()) {
PluginInfo info = entry.getKey();
SolrRequestHandler requestHandler = entry.getValue();
if (requestHandler instanceof PluginInfoInitialized) {
((PluginInfoInitialized) requestHandler).init(info);
} else{
requestHandler.init(info.initArgs);
}
}
if(get("") == null) register("", get(DEFAULT_HANDLER_NAME));
}
|
diff --git a/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/compatibility/PluginCompatibilityTests.java b/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/compatibility/PluginCompatibilityTests.java
index 48124edb1..0796489e8 100644
--- a/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/compatibility/PluginCompatibilityTests.java
+++ b/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/compatibility/PluginCompatibilityTests.java
@@ -1,52 +1,52 @@
/*******************************************************************************
* Copyright (c) 2004 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.core.tests.runtime.compatibility;
import java.io.IOException;
import junit.framework.*;
import org.eclipse.core.internal.plugins.InternalPlatform;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.PluginVersionIdentifier;
import org.eclipse.core.tests.harness.BundleTestingHelper;
import org.eclipse.core.tests.runtime.RuntimeTestsPlugin;
import org.osgi.framework.*;
public class PluginCompatibilityTests extends TestCase {
public PluginCompatibilityTests(String name) {
super(name);
}
// see bug 59013
public void testPluginWithNoRuntimeLibrary() throws BundleException, IOException {
assertNull("0.0", BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0"));
BundleTestingHelper.runWithBundles("0.1", new Runnable() {
public void run() {
Bundle[] installed = BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0");
assertEquals("1.0", 1, installed.length);
assertEquals("1.0", "bundle01", installed[0].getSymbolicName());
- assertEquals("1.1", "1.0", installed[0].getHeaders().get(Constants.BUNDLE_VERSION));
+ assertEquals("1.1", new Version("1.0"), new Version((String) installed[0].getHeaders().get(Constants.BUNDLE_VERSION)));
assertEquals("1.2", Bundle.RESOLVED, installed[0].getState());
IPluginDescriptor descriptor = InternalPlatform.getPluginRegistry().getPluginDescriptor("bundle01", new PluginVersionIdentifier("1.0"));
assertNotNull("2.0", descriptor);
assertNotNull("2.1", descriptor.getRuntimeLibraries());
// see bug 89845. Changed in 3.1...even bundles with no libraries have "dot"
// on the classpath
assertEquals("2.2", 1, descriptor.getRuntimeLibraries().length);
assertEquals("2.3", ".", descriptor.getRuntimeLibraries()[0].getPath().toString());
}
}, RuntimeTestsPlugin.getContext(), new String[] {RuntimeTestsPlugin.TEST_FILES_ROOT + "compatibility/bundle01"}, null);
}
public static Test suite() {
return new TestSuite(PluginCompatibilityTests.class);
}
}
| true | true | public void testPluginWithNoRuntimeLibrary() throws BundleException, IOException {
assertNull("0.0", BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0"));
BundleTestingHelper.runWithBundles("0.1", new Runnable() {
public void run() {
Bundle[] installed = BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0");
assertEquals("1.0", 1, installed.length);
assertEquals("1.0", "bundle01", installed[0].getSymbolicName());
assertEquals("1.1", "1.0", installed[0].getHeaders().get(Constants.BUNDLE_VERSION));
assertEquals("1.2", Bundle.RESOLVED, installed[0].getState());
IPluginDescriptor descriptor = InternalPlatform.getPluginRegistry().getPluginDescriptor("bundle01", new PluginVersionIdentifier("1.0"));
assertNotNull("2.0", descriptor);
assertNotNull("2.1", descriptor.getRuntimeLibraries());
// see bug 89845. Changed in 3.1...even bundles with no libraries have "dot"
// on the classpath
assertEquals("2.2", 1, descriptor.getRuntimeLibraries().length);
assertEquals("2.3", ".", descriptor.getRuntimeLibraries()[0].getPath().toString());
}
}, RuntimeTestsPlugin.getContext(), new String[] {RuntimeTestsPlugin.TEST_FILES_ROOT + "compatibility/bundle01"}, null);
}
| public void testPluginWithNoRuntimeLibrary() throws BundleException, IOException {
assertNull("0.0", BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0"));
BundleTestingHelper.runWithBundles("0.1", new Runnable() {
public void run() {
Bundle[] installed = BundleTestingHelper.getBundles(RuntimeTestsPlugin.getContext(), "bundle01", "1.0");
assertEquals("1.0", 1, installed.length);
assertEquals("1.0", "bundle01", installed[0].getSymbolicName());
assertEquals("1.1", new Version("1.0"), new Version((String) installed[0].getHeaders().get(Constants.BUNDLE_VERSION)));
assertEquals("1.2", Bundle.RESOLVED, installed[0].getState());
IPluginDescriptor descriptor = InternalPlatform.getPluginRegistry().getPluginDescriptor("bundle01", new PluginVersionIdentifier("1.0"));
assertNotNull("2.0", descriptor);
assertNotNull("2.1", descriptor.getRuntimeLibraries());
// see bug 89845. Changed in 3.1...even bundles with no libraries have "dot"
// on the classpath
assertEquals("2.2", 1, descriptor.getRuntimeLibraries().length);
assertEquals("2.3", ".", descriptor.getRuntimeLibraries()[0].getPath().toString());
}
}, RuntimeTestsPlugin.getContext(), new String[] {RuntimeTestsPlugin.TEST_FILES_ROOT + "compatibility/bundle01"}, null);
}
|
diff --git a/src/org/apache/xerces/parsers/XMLGrammarCachingConfiguration.java b/src/org/apache/xerces/parsers/XMLGrammarCachingConfiguration.java
index a7e76074..f4aeb7c6 100644
--- a/src/org/apache/xerces/parsers/XMLGrammarCachingConfiguration.java
+++ b/src/org/apache/xerces/parsers/XMLGrammarCachingConfiguration.java
@@ -1,406 +1,409 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001, 2002 The Apache Software Foundation.
* 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.parsers;
import java.io.IOException;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.util.XMLGrammarPoolImpl;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.SchemaGrammar;
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.impl.xs.XSMessageFormatter;
import org.apache.xerces.impl.dtd.XMLDTDLoader;
import org.apache.xerces.impl.dtd.DTDGrammar;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.SynchronizedSymbolTable;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLInputSource;
/**
* <p> This configuration provides a generic way of using
* Xerces's grammar caching facilities. It extends the
* StandardParserConfiguration and thus may validate documents
* according to XML schemas or DTD's. It also allows the user to
* preparse a grammar, and to lock the grammar pool
* implementation such that no more grammars will be added.</p>
* <p> Using the org.apache.xerces.xni.parser property, an
* application may instantiate a Xerces SAX or DOM parser with
* this configuration. When invoked in this manner, the default
* behaviour will be elicited; to use this configuration's
* specific facilities, the user will need to reference it
* directly.</p>
* <p>
* In addition to the features and properties recognized by the base
* parser configuration, this class recognizes these additional
* features and properties:
* <ul>
* </ul>
*
* @author Neil Graham, IBM
*
* @version $Id$
*/
public class XMLGrammarCachingConfiguration
extends StandardParserConfiguration {
//
// Constants
//
// a larg(ish) prime to use for a symbol table to be shared
// among
// potentially man parsers. Start one as close to 2K (20
// times larger than normal) and see what happens...
public static final int BIG_PRIME = 2039;
// the static symbol table to be shared amongst parsers
protected static final SynchronizedSymbolTable fStaticSymbolTable =
new SynchronizedSymbolTable(BIG_PRIME);
// the Grammar Pool to be shared similarly
protected static final XMLGrammarPoolImpl fStaticGrammarPool =
new XMLGrammarPoolImpl();
// schema full checking constant
protected static final String SCHEMA_FULL_CHECKING =
Constants.XERCES_FEATURE_PREFIX+Constants.SCHEMA_FULL_CHECKING;
// Data
// some constants that need to be added into the symbol table
String XMLNS = null;
String URI_XSI = null;
String XSI_SCHEMALOCATION = null;
String XSI_NONAMESPACESCHEMALOCATION = null;
String XSI_TYPE = null;
String XSI_NIL = null;
String URI_SCHEMAFORSCHEMA = null;
// variables needed for caching schema grammars.
protected XMLSchemaLoader fSchemaLoader;
// the DTD grammar loader
protected XMLDTDLoader fDTDLoader;
//
// Constructors
//
/** Default constructor. */
public XMLGrammarCachingConfiguration() {
this(fStaticSymbolTable, fStaticGrammarPool, null);
} // <init>()
/**
* Constructs a parser configuration using the specified symbol table.
*
* @param symbolTable The symbol table to use.
*/
public XMLGrammarCachingConfiguration(SymbolTable symbolTable) {
this(symbolTable, fStaticGrammarPool, null);
} // <init>(SymbolTable)
/**
* Constructs a parser configuration using the specified symbol table and
* grammar pool.
* <p>
* <strong>REVISIT:</strong>
* Grammar pool will be updated when the new validation engine is
* implemented.
*
* @param symbolTable The symbol table to use.
* @param grammarPool The grammar pool to use.
*/
public XMLGrammarCachingConfiguration(SymbolTable symbolTable,
XMLGrammarPool grammarPool) {
this(symbolTable, grammarPool, null);
} // <init>(SymbolTable,XMLGrammarPool)
/**
* Constructs a parser configuration using the specified symbol table,
* grammar pool, and parent settings.
* <p>
* <strong>REVISIT:</strong>
* Grammar pool will be updated when the new validation engine is
* implemented.
*
* @param symbolTable The symbol table to use.
* @param grammarPool The grammar pool to use.
* @param parentSettings The parent settings.
*/
public XMLGrammarCachingConfiguration(SymbolTable symbolTable,
XMLGrammarPool grammarPool,
XMLComponentManager parentSettings) {
super(symbolTable, grammarPool, parentSettings);
// symbolTable is assumed to be static here...
XMLNS = fSymbolTable.addSymbol(SchemaSymbols.O_XMLNS);
URI_XSI = fSymbolTable.addSymbol(SchemaSymbols.URI_XSI);
XSI_SCHEMALOCATION = fSymbolTable.addSymbol(SchemaSymbols.OXSI_SCHEMALOCATION);
XSI_NONAMESPACESCHEMALOCATION = fSymbolTable.addSymbol(SchemaSymbols.OXSI_NONAMESPACESCHEMALOCATION);
XSI_TYPE = fSymbolTable.addSymbol(SchemaSymbols.OXSI_TYPE);
XSI_NIL = fSymbolTable.addSymbol(SchemaSymbols.OXSI_NIL);
URI_SCHEMAFORSCHEMA = fSymbolTable.addSymbol(SchemaSymbols.OURI_SCHEMAFORSCHEMA);
// REVISIT: may need to add some features/properties
// specific to this configuration at some point...
// add default recognized features
// set state for default features
// add default recognized properties
// create and register missing components
fSchemaLoader = new XMLSchemaLoader(fSymbolTable);
fSchemaLoader.setProperty(XMLGRAMMAR_POOL, fGrammarPool);
// and set up the DTD loader too:
fDTDLoader = new XMLDTDLoader(fSymbolTable, fGrammarPool);
} // <init>(SymbolTable,XMLGrammarPool, XMLComponentManager)
//
// Public methods
//
/*
* lock the XMLGrammarPoolImpl object so that it does not
* accept any more grammars from the validators.
*/
public void lockGrammarPool() {
fGrammarPool.lockPool();
} // lockGrammarPool()
/*
* clear the XMLGrammarPoolImpl object so that it does not
* contain any more grammars.
*/
public void clearGrammarPool() {
fGrammarPool.clear();
} // clearGrammarPool()
/*
* unlock the XMLGrammarPoolImpl object so that it
* accepts more grammars from the validators.
*/
public void unlockGrammarPool() {
fGrammarPool.unlockPool();
} // unlockGrammarPool()
/**
* Parse a grammar from a location identified by an URI.
* This method also adds this grammar to the XMLGrammarPool
*
* @param type The type of the grammar to be constructed
* @param uri The location of the grammar to be constructed.
* <strong>The parser will not expand this URI or make it
* available to the EntityResolver</strong>
* @return The newly created <code>Grammar</code>.
* @exception XNIException thrown on an error in grammar
* construction
* @exception IOException thrown if an error is encountered
* in reading the file
*/
public Grammar parseGrammar(String type, String uri)
throws XNIException, IOException {
XMLInputSource source = new XMLInputSource(null, uri, null);
return parseGrammar(type, source);
}
/**
* Parse a grammar from a location identified by an
* XMLInputSource.
* This method also adds this grammar to the XMLGrammarPool
*
* @param type The type of the grammar to be constructed
* @param source The XMLInputSource containing this grammar's
* information
* <strong>If a URI is included in the systemId field, the parser will not expand this URI or make it
* available to the EntityResolver</strong>
* @return The newly created <code>Grammar</code>.
* @exception XNIException thrown on an error in grammar
* construction
* @exception IOException thrown if an error is encountered
* in reading the file
*/
public Grammar parseGrammar(String type, XMLInputSource
is) throws XNIException, IOException {
if(type.equals(XMLGrammarDescription.XML_SCHEMA)) {
// by default, make all XMLGrammarPoolImpl's schema grammars available to fSchemaHandler
return parseXMLSchema(is);
} else if(type.equals(XMLGrammarDescription.XML_DTD)) {
return parseDTD(is);
}
// don't know this grammar...
return null;
} // parseGrammar(String, XMLInputSource): Grammar
//
// Protected methods
//
// features and properties
/**
* Check a feature. If feature is known and supported, this method simply
* returns. Otherwise, the appropriate exception is thrown.
*
* @param featureId The unique identifier (URI) of the feature.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
protected void checkFeature(String featureId)
throws XMLConfigurationException {
super.checkFeature(featureId);
} // checkFeature(String)
/**
* Check a property. If the property is known and supported, this method
* simply returns. Otherwise, the appropriate exception is thrown.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
protected void checkProperty(String propertyId)
throws XMLConfigurationException {
super.checkProperty(propertyId);
} // checkProperty(String)
// package-protected methods
/* This method parses an XML Schema document.
* It requires a GrammarBucket parameter so that DOMASBuilder can
* extract the info it needs.
* Therefore, bucket must not be null!
*/
SchemaGrammar parseXMLSchema(XMLInputSource is)
throws IOException {
XMLEntityResolver resolver = getEntityResolver();
if(resolver != null) {
fSchemaLoader.setEntityResolver(resolver);
}
+ if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) {
+ fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter());
+ }
fSchemaLoader.setProperty(ERROR_REPORTER, fErrorReporter);
String propPrefix = Constants.XERCES_PROPERTY_PREFIX;
String propName = propPrefix + Constants.SCHEMA_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = propPrefix + Constants.SCHEMA_NONS_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = Constants.JAXP_PROPERTY_PREFIX+Constants.SCHEMA_SOURCE;
fSchemaLoader.setProperty(propName, getProperty(propName));
fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, getFeature(SCHEMA_FULL_CHECKING));
// Should check whether the grammar with this namespace is already in
// the grammar resolver. But since we don't know the target namespace
// of the document here, we leave such check to XSDHandler
SchemaGrammar grammar = (SchemaGrammar)fSchemaLoader.loadGrammar(is);
// by default, hand it off to the grammar pool
if (grammar != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA,
new Grammar[]{grammar});
}
return grammar;
} // parseXMLSchema(XMLInputSource) : SchemaGrammar
/* This method parses an external DTD entity.
*/
DTDGrammar parseDTD(XMLInputSource is)
throws IOException {
XMLEntityResolver resolver = getEntityResolver();
if(resolver != null) {
fDTDLoader.setEntityResolver(resolver);
}
fDTDLoader.setProperty(ERROR_REPORTER, fErrorReporter);
// Should check whether the grammar with this namespace is already in
// the grammar resolver. But since we don't know the target namespace
// of the document here, we leave such check to the application...
DTDGrammar grammar = (DTDGrammar)fDTDLoader.loadGrammar(is);
// by default, hand it off to the grammar pool
if (grammar != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_DTD,
new Grammar[]{grammar});
}
return grammar;
} // parseXMLDTD(XMLInputSource) : DTDGrammar
} // class XMLGrammarCachingConfiguration
| true | true | SchemaGrammar parseXMLSchema(XMLInputSource is)
throws IOException {
XMLEntityResolver resolver = getEntityResolver();
if(resolver != null) {
fSchemaLoader.setEntityResolver(resolver);
}
fSchemaLoader.setProperty(ERROR_REPORTER, fErrorReporter);
String propPrefix = Constants.XERCES_PROPERTY_PREFIX;
String propName = propPrefix + Constants.SCHEMA_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = propPrefix + Constants.SCHEMA_NONS_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = Constants.JAXP_PROPERTY_PREFIX+Constants.SCHEMA_SOURCE;
fSchemaLoader.setProperty(propName, getProperty(propName));
fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, getFeature(SCHEMA_FULL_CHECKING));
// Should check whether the grammar with this namespace is already in
// the grammar resolver. But since we don't know the target namespace
// of the document here, we leave such check to XSDHandler
SchemaGrammar grammar = (SchemaGrammar)fSchemaLoader.loadGrammar(is);
// by default, hand it off to the grammar pool
if (grammar != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA,
new Grammar[]{grammar});
}
return grammar;
} // parseXMLSchema(XMLInputSource) : SchemaGrammar
| SchemaGrammar parseXMLSchema(XMLInputSource is)
throws IOException {
XMLEntityResolver resolver = getEntityResolver();
if(resolver != null) {
fSchemaLoader.setEntityResolver(resolver);
}
if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) {
fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter());
}
fSchemaLoader.setProperty(ERROR_REPORTER, fErrorReporter);
String propPrefix = Constants.XERCES_PROPERTY_PREFIX;
String propName = propPrefix + Constants.SCHEMA_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = propPrefix + Constants.SCHEMA_NONS_LOCATION;
fSchemaLoader.setProperty(propName, getProperty(propName));
propName = Constants.JAXP_PROPERTY_PREFIX+Constants.SCHEMA_SOURCE;
fSchemaLoader.setProperty(propName, getProperty(propName));
fSchemaLoader.setFeature(SCHEMA_FULL_CHECKING, getFeature(SCHEMA_FULL_CHECKING));
// Should check whether the grammar with this namespace is already in
// the grammar resolver. But since we don't know the target namespace
// of the document here, we leave such check to XSDHandler
SchemaGrammar grammar = (SchemaGrammar)fSchemaLoader.loadGrammar(is);
// by default, hand it off to the grammar pool
if (grammar != null) {
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA,
new Grammar[]{grammar});
}
return grammar;
} // parseXMLSchema(XMLInputSource) : SchemaGrammar
|
diff --git a/java/src/edu/umich/insoar/language/AgentMessageParser.java b/java/src/edu/umich/insoar/language/AgentMessageParser.java
index 054269ef..f0af77c6 100644
--- a/java/src/edu/umich/insoar/language/AgentMessageParser.java
+++ b/java/src/edu/umich/insoar/language/AgentMessageParser.java
@@ -1,298 +1,302 @@
package edu.umich.insoar.language;
import java.util.Iterator;
import java.util.Set;
import sml.Identifier;
import edu.umich.insoar.language.Patterns.LingObject;
import edu.umich.insoar.world.WMUtil;
public class AgentMessageParser
{
public static String translateAgentMessage(Identifier id){
String message = null;
String type = WMUtil.getValueOfAttribute(id, "type");
System.out.println(type);
Identifier fieldsId = WMUtil.getIdentifierOfAttribute(id, "fields");
if(type == null){
return null;
} else if(type.equals("different-attribute-question")){
message = translateDifferentAttributeQuestion(fieldsId);
} else if(type.equals("value-question")){
message = translateValueQuestion(fieldsId);
} else if(type.equals("common-attribute-question")){
message = translateCommonAttributeQuestion(fieldsId);
} else if(type.equals("attribute-presence-question")){
message = translateAttributePresenceQuestion(fieldsId);
} else if(type.equals("ask-property-name")){
message = translateCategoryQuestion(fieldsId);
} else if(type.equals("category-of-property")){
message = translateCategoryPropertyQuestion(fieldsId);
} else if(type.equals("how-to-measure")){
message = String.format("How do I measure %s?", WMUtil.getValueOfAttribute(fieldsId, "property"));
} else if(type.equals("ambiguous-category")){
message = translateAmbiguousCategory(fieldsId);
} else if(type.equals("describe-object")){
message = translateDescription(fieldsId);
} else if(type.equals("dont-know")){
message = "I don't know";
} else if(type.equals("no-prep")){
message = "I don't know that preposition.";
} else if(type.equals("single-word-response")){
message = WMUtil.getValueOfAttribute(fieldsId, "word");
} else if(type.equals("no-object")){
message = "I do not see the object you are talking about";
} else if(type.equals("count-response")){
int count = Integer.parseInt(WMUtil.getValueOfAttribute(fieldsId, "count"));
message = "There " + (count == 1 ? "is" : "are") + " " + count;
} else if(type.equals("unknown-message")){
message = "I was not able to understand your last message";
} else if(type.equals("teaching-request")){
message = translateTeachingRequest(fieldsId);
} else if(type.equals("which-question")){
message = translateWhichQuestion(fieldsId);
} else if(type.equals("get-next-task")){
message = "Waiting for next command...";
} else if(type.equals("get-next-subaction")){
message = "What action should I take next?";
} else if(type.equals("confirmation")){
message = "Okay.";
} else if (type.equals("get-goal")){
message = "What is the goal of the action?";
} else if (type.equals("restart-task-instruction")){
message = "The provided instruction sequence does not lead to the provided goal. Please give the instructions again.";
} else if(type.equals("request-index-confirmation")){
message = translateRequestIndexConfirmation(fieldsId);
} else if(type.equals("describe-scene")){
message = translateSceneQuestion(fieldsId);
} else if(type.equals("describe-scene-objects")){
message = translateSceneObjectsQuestion(fieldsId);
} else if(type.equals("list-objects")){
message = translateObjectsQuestion(fieldsId);
} else if(type.equals("location-unknown")){
message = "Relative location of object unknown";
} else if(type.equals("play-game")){
message = "Shall we play a game?";
} else if(type.equals("game-start")){
message = "Ok I know that game. Tell me \"your turn\" when it's my turn.";
} else if(type.equals("game-new-params")){
message = "Tell me the name of an action, failure state, or goal of the game, or finished.";
} else if(type.equals("game-new-action2")){
message = "Ok tell me the name of a legal action in this game, or finished.";
} else if(type.equals("game-new-action")){
String gameName = WMUtil.getValueOfAttribute(fieldsId, "game-name");
message = "I do not know how to play " + gameName +
". This is a multiplayer game (true/false)?";
} else if(type.equals("game-new-verb")){
message = "What is an associated verb for this action, or finished";
} else if(type.equals("game-new-goal")){
message = "Ok tell me the name of the goal in the game.";
} else if(type.equals("game-new-failure")){
message = "Ok tell me the name of a failure state in the game. (or none)";
} else if(type.equals("game-new-parameter1")){
message = "Ok describe an object for this action.\n";
} else if(type.equals("game-new-parameter")){
message = "Ok list an object, or finished.";
} else if(type.equals("game-new-condition")){
message = "Ok list a condition for this parameter, or finished.";
+ } else if(type.equals("game-new-heuristic")){
+ message = "Are there any heuristics you can teach me? (or finished)";
+ } else if(type.equals("game-final-state")){
+ message = "Please demonstrate the final goal state.";
} else if(type.equals("game-learned")){
message = "Ok I have now learned the basics of the game.";
} else if(type.equals("game-over")){
message = "Game Over. Shall we play another?";
}
return message;
}
private static String translateTeachingRequest(Identifier id){
LingObject obj = LingObject.createFromSoarSpeak(id, "description");
String prep = WMUtil.getValueOfAttribute(id, "preposition");
if (prep != null)
return "I don't know the preposition " + prep + ". Please teach me with examples";
else {
return "I don't see " + obj.toString() + ". Please teach me to recognize one";
}
}
private static String translateDifferentAttributeQuestion(Identifier id){
Set<String> exceptions = WMUtil.getAllValuesOfAttribute(id, "exception");
String exceptionStr = getExceptionString(exceptions);
LingObject differentObject = LingObject.createFromSoarSpeak(id, "different-object");
Set<LingObject> similarObjects = LingObject.createAllFromSoarSpeak(id, "similar-object");
String message = String.format("How does %s differ from ", differentObject.toString());
for(LingObject obj : similarObjects){
message += obj.toString() + "; ";
}
return exceptionStr + message;
}
private static String translateCommonAttributeQuestion(Identifier id){
Set<String> exceptions = WMUtil.getAllValuesOfAttribute(id, "exception");
String exceptionStr = getExceptionString(exceptions);
Set<LingObject> similarObjects = LingObject.createAllFromSoarSpeak(id, "object");
String message = "What do ";
for(LingObject obj : similarObjects){
message += obj.toString() + "; ";
}
return exceptionStr + message + " have in common?";
}
private static String translateAttributePresenceQuestion(Identifier id){
Set<String> exceptions = WMUtil.getAllValuesOfAttribute(id, "exception");
String exceptionStr = getExceptionString(exceptions);
LingObject object = LingObject.createFromSoarSpeak(id, "object");
String message = String.format("What attribute does %s have?", object.toString());
return exceptionStr + message;
}
private static String translateCategoryQuestion(Identifier id){
String word = WMUtil.getValueOfAttribute(id, "word");
return String.format("What kind of attribute is %s?", word);
}
private static String translateCategoryPropertyQuestion(Identifier id){
String word = WMUtil.getValueOfAttribute(id, "word");
return String.format("What type of property is %s?", word);
}
private static String translateAmbiguousCategory(Identifier id){
Set<String> cats = WMUtil.getAllValuesOfAttribute(id, "result");
String word = WMUtil.getValueOfAttribute(id, "word");
String s = "By " + word + " do you mean ";
int i = 0;
for(String cat : cats){
if((++i) == cats.size()){
s += "or " + cat + "?";
} else {
s += cat + ", ";
}
}
return s;
}
private static String translateSceneObjectsQuestion(Identifier id){
Identifier objects = WMUtil.getIdentifierOfAttribute(id, "objects");
Set<LingObject> object = LingObject.createAllFromSoarSpeak(objects, "object");
String message = "The objects in the scene are";
Iterator<LingObject> it = object.iterator();
if (object.isEmpty())
return "There are no objects in the scene.";
while(it.hasNext())
{
String obj = it.next().toString();
if (!it.hasNext() && object.size() > 1)
message+= " and";
if (obj.startsWith(" a") || obj.startsWith(" e") || obj.startsWith(" i") ||
obj.startsWith(" o") || obj.startsWith(" u"))
{
message += " an";
}
else
{
message += " a";
}
message += obj;
if (it.hasNext() && object.size() > 2)
message+= ",";
}
return message;
}
private static String translateObjectsQuestion(Identifier id){
Identifier objects = WMUtil.getIdentifierOfAttribute(id, "objects");
Set<LingObject> object = LingObject.createAllFromSoarSpeak(objects, "object");
String message = "";
Iterator<LingObject> it = object.iterator();
if (object.isEmpty())
return "Nothing.";
while(it.hasNext())
{
String obj = it.next().toString();
if (!it.hasNext() && object.size() > 1)
message+= " and";
if (obj.startsWith(" a") || obj.startsWith(" e") || obj.startsWith(" i") ||
obj.startsWith(" o") || obj.startsWith(" u"))
{
message += " an";
}
else
{
message += " a";
}
message += obj;
if (it.hasNext() && object.size() > 2)
message+= ",";
}
return message;
}
private static String translateSceneQuestion(Identifier id){
String prep = WMUtil.getValueOfAttribute(id, "prep");
String prep2 = prep.replaceAll("-", " ");
String object1 = LingObject.createFromSoarSpeak(id, "object1").toString();
String object2 = LingObject.createFromSoarSpeak(id, "object2").toString();
return "The" + object1 + " is " + prep2 + " the" + object2;
}
private static String translateValueQuestion(Identifier id){
Identifier attRelationId = WMUtil.getIdentifierOfAttribute(id, "attribute-relation");
String objString = LingObject.createFromSoarSpeak(attRelationId, "object1").toString();
String attribute = WMUtil.getValueOfAttribute(attRelationId, "word");
return String.format("What %s is %s?", attribute, objString);
}
private static String getExceptionString(Set<String> exceptions){
String exceptionStr = "";
if (exceptions.size() > 0)
{
exceptionStr = "Other than ";
for(String exception : exceptions){
exceptionStr += exception + ", ";
}
exceptionStr = exceptionStr.substring(0, exceptionStr.length() - 2);
exceptionStr += "; ";
}
return exceptionStr;
}
private static String translateDescription(Identifier id){
if(id == null){
return null;
}
//kind of a hack :(
Identifier objectId = WMUtil.getIdentifierOfAttribute(id, "object");
if (objectId == null)
return "nothing";
// CK: choose a/an correctly
String ret = LingObject.createFromSoarSpeak(id, "object").toString();
if(ret.matches("^ [aeiouAEIOU].*")) {
ret = "An"+ret;
} else {
ret = "A"+ret;
}
return ret;
}
private static String translateWhichQuestion(Identifier id){
Identifier objectId = WMUtil.getIdentifierOfAttribute(id, "description");
if (objectId == null)
return "Which one?";
return "Which " + LingObject.createFromSoarSpeak(id, "description") + "?";
}
private static String translateRequestIndexConfirmation(Identifier id){
LingObject obj = LingObject.createFromSoarSpeak(id, "object");
return "Is this " + obj.toString() + "?";
}
}
| true | true | public static String translateAgentMessage(Identifier id){
String message = null;
String type = WMUtil.getValueOfAttribute(id, "type");
System.out.println(type);
Identifier fieldsId = WMUtil.getIdentifierOfAttribute(id, "fields");
if(type == null){
return null;
} else if(type.equals("different-attribute-question")){
message = translateDifferentAttributeQuestion(fieldsId);
} else if(type.equals("value-question")){
message = translateValueQuestion(fieldsId);
} else if(type.equals("common-attribute-question")){
message = translateCommonAttributeQuestion(fieldsId);
} else if(type.equals("attribute-presence-question")){
message = translateAttributePresenceQuestion(fieldsId);
} else if(type.equals("ask-property-name")){
message = translateCategoryQuestion(fieldsId);
} else if(type.equals("category-of-property")){
message = translateCategoryPropertyQuestion(fieldsId);
} else if(type.equals("how-to-measure")){
message = String.format("How do I measure %s?", WMUtil.getValueOfAttribute(fieldsId, "property"));
} else if(type.equals("ambiguous-category")){
message = translateAmbiguousCategory(fieldsId);
} else if(type.equals("describe-object")){
message = translateDescription(fieldsId);
} else if(type.equals("dont-know")){
message = "I don't know";
} else if(type.equals("no-prep")){
message = "I don't know that preposition.";
} else if(type.equals("single-word-response")){
message = WMUtil.getValueOfAttribute(fieldsId, "word");
} else if(type.equals("no-object")){
message = "I do not see the object you are talking about";
} else if(type.equals("count-response")){
int count = Integer.parseInt(WMUtil.getValueOfAttribute(fieldsId, "count"));
message = "There " + (count == 1 ? "is" : "are") + " " + count;
} else if(type.equals("unknown-message")){
message = "I was not able to understand your last message";
} else if(type.equals("teaching-request")){
message = translateTeachingRequest(fieldsId);
} else if(type.equals("which-question")){
message = translateWhichQuestion(fieldsId);
} else if(type.equals("get-next-task")){
message = "Waiting for next command...";
} else if(type.equals("get-next-subaction")){
message = "What action should I take next?";
} else if(type.equals("confirmation")){
message = "Okay.";
} else if (type.equals("get-goal")){
message = "What is the goal of the action?";
} else if (type.equals("restart-task-instruction")){
message = "The provided instruction sequence does not lead to the provided goal. Please give the instructions again.";
} else if(type.equals("request-index-confirmation")){
message = translateRequestIndexConfirmation(fieldsId);
} else if(type.equals("describe-scene")){
message = translateSceneQuestion(fieldsId);
} else if(type.equals("describe-scene-objects")){
message = translateSceneObjectsQuestion(fieldsId);
} else if(type.equals("list-objects")){
message = translateObjectsQuestion(fieldsId);
} else if(type.equals("location-unknown")){
message = "Relative location of object unknown";
} else if(type.equals("play-game")){
message = "Shall we play a game?";
} else if(type.equals("game-start")){
message = "Ok I know that game. Tell me \"your turn\" when it's my turn.";
} else if(type.equals("game-new-params")){
message = "Tell me the name of an action, failure state, or goal of the game, or finished.";
} else if(type.equals("game-new-action2")){
message = "Ok tell me the name of a legal action in this game, or finished.";
} else if(type.equals("game-new-action")){
String gameName = WMUtil.getValueOfAttribute(fieldsId, "game-name");
message = "I do not know how to play " + gameName +
". This is a multiplayer game (true/false)?";
} else if(type.equals("game-new-verb")){
message = "What is an associated verb for this action, or finished";
} else if(type.equals("game-new-goal")){
message = "Ok tell me the name of the goal in the game.";
} else if(type.equals("game-new-failure")){
message = "Ok tell me the name of a failure state in the game. (or none)";
} else if(type.equals("game-new-parameter1")){
message = "Ok describe an object for this action.\n";
} else if(type.equals("game-new-parameter")){
message = "Ok list an object, or finished.";
} else if(type.equals("game-new-condition")){
message = "Ok list a condition for this parameter, or finished.";
} else if(type.equals("game-learned")){
message = "Ok I have now learned the basics of the game.";
} else if(type.equals("game-over")){
message = "Game Over. Shall we play another?";
}
return message;
}
| public static String translateAgentMessage(Identifier id){
String message = null;
String type = WMUtil.getValueOfAttribute(id, "type");
System.out.println(type);
Identifier fieldsId = WMUtil.getIdentifierOfAttribute(id, "fields");
if(type == null){
return null;
} else if(type.equals("different-attribute-question")){
message = translateDifferentAttributeQuestion(fieldsId);
} else if(type.equals("value-question")){
message = translateValueQuestion(fieldsId);
} else if(type.equals("common-attribute-question")){
message = translateCommonAttributeQuestion(fieldsId);
} else if(type.equals("attribute-presence-question")){
message = translateAttributePresenceQuestion(fieldsId);
} else if(type.equals("ask-property-name")){
message = translateCategoryQuestion(fieldsId);
} else if(type.equals("category-of-property")){
message = translateCategoryPropertyQuestion(fieldsId);
} else if(type.equals("how-to-measure")){
message = String.format("How do I measure %s?", WMUtil.getValueOfAttribute(fieldsId, "property"));
} else if(type.equals("ambiguous-category")){
message = translateAmbiguousCategory(fieldsId);
} else if(type.equals("describe-object")){
message = translateDescription(fieldsId);
} else if(type.equals("dont-know")){
message = "I don't know";
} else if(type.equals("no-prep")){
message = "I don't know that preposition.";
} else if(type.equals("single-word-response")){
message = WMUtil.getValueOfAttribute(fieldsId, "word");
} else if(type.equals("no-object")){
message = "I do not see the object you are talking about";
} else if(type.equals("count-response")){
int count = Integer.parseInt(WMUtil.getValueOfAttribute(fieldsId, "count"));
message = "There " + (count == 1 ? "is" : "are") + " " + count;
} else if(type.equals("unknown-message")){
message = "I was not able to understand your last message";
} else if(type.equals("teaching-request")){
message = translateTeachingRequest(fieldsId);
} else if(type.equals("which-question")){
message = translateWhichQuestion(fieldsId);
} else if(type.equals("get-next-task")){
message = "Waiting for next command...";
} else if(type.equals("get-next-subaction")){
message = "What action should I take next?";
} else if(type.equals("confirmation")){
message = "Okay.";
} else if (type.equals("get-goal")){
message = "What is the goal of the action?";
} else if (type.equals("restart-task-instruction")){
message = "The provided instruction sequence does not lead to the provided goal. Please give the instructions again.";
} else if(type.equals("request-index-confirmation")){
message = translateRequestIndexConfirmation(fieldsId);
} else if(type.equals("describe-scene")){
message = translateSceneQuestion(fieldsId);
} else if(type.equals("describe-scene-objects")){
message = translateSceneObjectsQuestion(fieldsId);
} else if(type.equals("list-objects")){
message = translateObjectsQuestion(fieldsId);
} else if(type.equals("location-unknown")){
message = "Relative location of object unknown";
} else if(type.equals("play-game")){
message = "Shall we play a game?";
} else if(type.equals("game-start")){
message = "Ok I know that game. Tell me \"your turn\" when it's my turn.";
} else if(type.equals("game-new-params")){
message = "Tell me the name of an action, failure state, or goal of the game, or finished.";
} else if(type.equals("game-new-action2")){
message = "Ok tell me the name of a legal action in this game, or finished.";
} else if(type.equals("game-new-action")){
String gameName = WMUtil.getValueOfAttribute(fieldsId, "game-name");
message = "I do not know how to play " + gameName +
". This is a multiplayer game (true/false)?";
} else if(type.equals("game-new-verb")){
message = "What is an associated verb for this action, or finished";
} else if(type.equals("game-new-goal")){
message = "Ok tell me the name of the goal in the game.";
} else if(type.equals("game-new-failure")){
message = "Ok tell me the name of a failure state in the game. (or none)";
} else if(type.equals("game-new-parameter1")){
message = "Ok describe an object for this action.\n";
} else if(type.equals("game-new-parameter")){
message = "Ok list an object, or finished.";
} else if(type.equals("game-new-condition")){
message = "Ok list a condition for this parameter, or finished.";
} else if(type.equals("game-new-heuristic")){
message = "Are there any heuristics you can teach me? (or finished)";
} else if(type.equals("game-final-state")){
message = "Please demonstrate the final goal state.";
} else if(type.equals("game-learned")){
message = "Ok I have now learned the basics of the game.";
} else if(type.equals("game-over")){
message = "Game Over. Shall we play another?";
}
return message;
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_motd.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_motd.java
index 8f30a92..b0a7724 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_motd.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_motd.java
@@ -1,74 +1,75 @@
package com.github.zathrus_writer.commandsex.handlers;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import com.github.zathrus_writer.commandsex.CommandsEX;
import com.github.zathrus_writer.commandsex.Vault;
import com.github.zathrus_writer.commandsex.helpers.Nicknames;
import com.github.zathrus_writer.commandsex.helpers.Utils;
public class Handler_motd implements Listener {
/***
* Activate event listener.
*/
public Handler_motd() {
CommandsEX.plugin.getServer().getPluginManager().registerEvents(this, CommandsEX.plugin);
}
public static void displayMOTD(CommandSender p) {
// check if we can use Vault to determine player's group
- if (Vault.permsEnabled() && (p instanceof Player)) {
+ // check we aren't using SuperPerms, SuperPerms no like groups!
+ if (Vault.permsEnabled() && !Vault.perms.getName().equals("SuperPerms") && (p instanceof Player)) {
// check if we have extra MOTD for this group set up
FileConfiguration conf = CommandsEX.getConf();
Boolean privateMOTDsent = false;
for (String s : Vault.perms.getPlayerGroups((Player) p)) {
if (!conf.getString("motd_" + s, "").equals("")) {
privateMOTDsent = true;
String[] msg = CommandsEX.getConf().getString("motd_" + s).replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
// show generic MOTD in case we did not find a custom one for this player's group
if (!privateMOTDsent) {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
} else {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
/***
* Welcomes a player on server join.
* @param e
* @return
*/
@EventHandler(priority = EventPriority.LOW)
public void passJoin(PlayerJoinEvent e) {
Player p = e.getPlayer();
if (p.hasPlayedBefore()) {
displayMOTD(p);
} else {
String[] msg = CommandsEX.getConf().getString("motdNewPlayer").replace("{playername}", p.getName()).split("\\{newline\\}");
for (String s : msg) {
p.sendMessage(Utils.replaceChatColors(s));
}
}
}
}
| true | true | public static void displayMOTD(CommandSender p) {
// check if we can use Vault to determine player's group
if (Vault.permsEnabled() && (p instanceof Player)) {
// check if we have extra MOTD for this group set up
FileConfiguration conf = CommandsEX.getConf();
Boolean privateMOTDsent = false;
for (String s : Vault.perms.getPlayerGroups((Player) p)) {
if (!conf.getString("motd_" + s, "").equals("")) {
privateMOTDsent = true;
String[] msg = CommandsEX.getConf().getString("motd_" + s).replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
// show generic MOTD in case we did not find a custom one for this player's group
if (!privateMOTDsent) {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
} else {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
| public static void displayMOTD(CommandSender p) {
// check if we can use Vault to determine player's group
// check we aren't using SuperPerms, SuperPerms no like groups!
if (Vault.permsEnabled() && !Vault.perms.getName().equals("SuperPerms") && (p instanceof Player)) {
// check if we have extra MOTD for this group set up
FileConfiguration conf = CommandsEX.getConf();
Boolean privateMOTDsent = false;
for (String s : Vault.perms.getPlayerGroups((Player) p)) {
if (!conf.getString("motd_" + s, "").equals("")) {
privateMOTDsent = true;
String[] msg = CommandsEX.getConf().getString("motd_" + s).replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
// show generic MOTD in case we did not find a custom one for this player's group
if (!privateMOTDsent) {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
} else {
String[] msg = CommandsEX.getConf().getString("motd").replace("{playername}", Nicknames.getNick(p.getName())).split("\\{newline\\}");
for (String s1 : msg) {
p.sendMessage(Utils.replaceChatColors(s1));
}
}
}
|
diff --git a/src/com/gulshansingh/urlrecognizer/MainActivity.java b/src/com/gulshansingh/urlrecognizer/MainActivity.java
index d7694ef..89c9a7b 100644
--- a/src/com/gulshansingh/urlrecognizer/MainActivity.java
+++ b/src/com/gulshansingh/urlrecognizer/MainActivity.java
@@ -1,186 +1,191 @@
package com.gulshansingh.urlrecognizer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
public class MainActivity extends Activity {
private static final String APP_NAME = "UrlRecognizer";
private static final int INTENT_ID_CAPTURE_IMAGE = 0;
private File mCaptureFile;
private TextView mResultStringTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResultStringTextView = (TextView) findViewById(R.id.result_string);
try {
installTrainingData();
} catch (IOException e) {
e.printStackTrace();
}
}
private void installTrainingData() throws IOException {
File file = new File(getFilesDir() + "/tessdata/eng.traineddata");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
InputStream in = getAssets().open("eng.traineddata");
copyFile(in, out);
out.close();
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
private File captureImage() throws IOException {
// TODO: Move this to internal directory after image capture
File file = new File(Environment.getExternalStorageDirectory(),
"capture.jpg");
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, INTENT_ID_CAPTURE_IMAGE);
Toast.makeText(this, "Launching Camera", Toast.LENGTH_SHORT).show();
System.out.println("file: " + file);
return file;
}
private void onPhotoTaken() {
if (mCaptureFile == null) {
throw new NullPointerException("Decoded bitmap is null");
}
/*
* TODO: This fails for images with low compression ratios. We need to
* choose the sample size dynamically.
*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
System.out.println("onPhotoTaken: " + mCaptureFile);
Bitmap b = BitmapFactory.decodeFile(mCaptureFile.getAbsolutePath(),
options);
if (b == null) {
throw new NullPointerException("Decoded bitmap is null");
}
try {
prepareBitmap(b);
} catch (IOException e) {
e.printStackTrace();
}
mResultStringTextView.setText("Result: " + parseText(b));
}
/*
* The bitmap must be properly rotated and the format must be ARGB_8888 in
* order to work with the Tesseract API
*/
private void prepareBitmap(Bitmap b) throws IOException {
+ /*
+ * TODO: There is a bug in Android that affects this code for some devices:
+ * http://stackoverflow.com/questions/8450539/images-taken-with-action-image-capture-always-returns-1-for-exifinterface-tag-or
+ * We need to implement the workaround.
+ */
ExifInterface exif = new ExifInterface(mCaptureFile.getAbsolutePath());
int exifOrientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
Log.d(APP_NAME, "Rotating " + rotate + " degrees");
int w = b.getWidth();
int h = b.getHeight();
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
b = Bitmap.createBitmap(b, 0, 0, w, h, mtx, false);
}
b = b.copy(Bitmap.Config.ARGB_8888, true);
}
private String parseText(Bitmap b) {
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(getFilesDir().getAbsolutePath(), "eng");
baseApi.setImage(b);
String text = baseApi.getUTF8Text();
baseApi.end();
return text;
}
public void captureImageClicked(View v) {
try {
mCaptureFile = captureImage();
System.out.println("mCaptureFile: ");
System.out.println(mCaptureFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/*
* TODO: Get bitmap directly from intent data if possible. This doesn't work on
* Nexus and Galaxy devices, but may work on other devices.
*/
if (requestCode == INTENT_ID_CAPTURE_IMAGE) {
switch (resultCode) {
case Activity.RESULT_OK:
onPhotoTaken();
break;
}
}
}
}
| true | true | private void prepareBitmap(Bitmap b) throws IOException {
ExifInterface exif = new ExifInterface(mCaptureFile.getAbsolutePath());
int exifOrientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
Log.d(APP_NAME, "Rotating " + rotate + " degrees");
int w = b.getWidth();
int h = b.getHeight();
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
b = Bitmap.createBitmap(b, 0, 0, w, h, mtx, false);
}
b = b.copy(Bitmap.Config.ARGB_8888, true);
}
| private void prepareBitmap(Bitmap b) throws IOException {
/*
* TODO: There is a bug in Android that affects this code for some devices:
* http://stackoverflow.com/questions/8450539/images-taken-with-action-image-capture-always-returns-1-for-exifinterface-tag-or
* We need to implement the workaround.
*/
ExifInterface exif = new ExifInterface(mCaptureFile.getAbsolutePath());
int exifOrientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
Log.d(APP_NAME, "Rotating " + rotate + " degrees");
int w = b.getWidth();
int h = b.getHeight();
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
b = Bitmap.createBitmap(b, 0, 0, w, h, mtx, false);
}
b = b.copy(Bitmap.Config.ARGB_8888, true);
}
|
diff --git a/FeedReader/src/com/brent/feedreader/MainActivity.java b/FeedReader/src/com/brent/feedreader/MainActivity.java
index 2c77c44..e3d9b80 100644
--- a/FeedReader/src/com/brent/feedreader/MainActivity.java
+++ b/FeedReader/src/com/brent/feedreader/MainActivity.java
@@ -1,347 +1,347 @@
package com.brent.feedreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.brent.feedreader.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {@link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {@link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
public static final String TAG = "FeedReader";
private Spinner titleSpinner;
WebView articleBodyView;
private ArrayList<String> articleTitles;
private ArrayList<String> articleLinks;
public ArrayList<String> articleTimeStamps;
private ArrayList<String> articleBodies;
private String appTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
titleSpinner = (Spinner)findViewById(R.id.title_spinner);
titleSpinner.setOnItemSelectedListener(this);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
articleBodyView = (WebView) findViewById(R.id.article_body_webview);
articleBodyView.getSettings().setSupportZoom(true); //this line and next allow zooming in and out of view
articleBodyView.getSettings().setBuiltInZoomControls(true);
articleBodyView.getSettings().setJavaScriptEnabled(true); //needed for progress indication
articleBodyView.setWebChromeClient(new WebChromeClient() {
//Show progress when loading page, since it takes a little while
public void onProgressChanged(WebView view, int progress) {
// articleBodyView.loadData("Loading page...", "text/html", "UTF-8");
MainActivity.this.setTitle("Loading page...");
MainActivity.this.setProgress(progress * 100);
if(progress == 100) {
MainActivity.this.setTitle(appTitle);
// articleBodyView.loadData(articleBodies.get(0), "text/html", "UTF-8");
}
}
});
// Get the articles. Network "stuff" needs to be done outside of the UI thread:
(new FetchArticlesTask()).execute("http://feeds2.feedburner.com/TheTechnologyEdge");
// Code from here to "end" generated automatically when project created,
// to hide and show title and status bars (i.e., run app full screen)
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, articleBodyView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
articleBodyView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.title_spinner).setOnTouchListener(
mDelayHideTouchListener);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
// End automatically generated code to run app full screen
@Override
public void onResume() {
super.onResume();
}
private class FetchArticlesTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
BufferedReader reader=null;
String rawXML = null;
// Make the connection to the URL and get the xml as one big string
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line=reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
rawXML = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Parse the xml and create 3 lists holding article titles, contents (bodies), and external links
articleTitles = new ArrayList<String>();
articleBodies = new ArrayList<String>();
articleLinks = new ArrayList<String>();
articleTimeStamps = new ArrayList<String>();
articleTitles.add("Reader Instructions");
articleBodies.add("Touch the screen to display the article-selection list at the bottom.");
articleLinks.add("");
articleTimeStamps.add("");
DocumentBuilder builder;
Document doc = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(rawXML)));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; i < titles.getLength(); i++) {
Element title = (Element)titles.item(i);
if (i == 0) {
appTitle = title.getFirstChild().getNodeValue();
}
else articleTitles.add(title.getFirstChild().getNodeValue());
}
NodeList bodies = doc.getElementsByTagName("content");
for (int i = 0; i < bodies.getLength(); i++) {
Element body = (Element)bodies.item(i);
articleBodies.add(body.getFirstChild().getNodeValue());
}
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); i++) {
Element link = (Element)links.item(i);
if (link == null) Log.i(TAG, i + " is null");
if (link.getAttribute("rel").equals("alternate") && link.getAttribute("title").length() > 0) {
String articleLink = ("<a href=" + "`" + link.getAttribute("href") + "`" + "target=" + "`"+ "_blank" + "`" + ">" + link.getAttribute("title") + "</a>").replace('`', '"');
if (i == 0 || i == 1 || i == 2) Log.i(TAG, i + " " + articleLink);
articleLinks.add(articleLink);
}
}
NodeList timeStamps = doc.getElementsByTagName("updated");
Log.i(TAG, "timestamps length: " + timeStamps.getLength());
- for (int i = 0; i < timeStamps.getLength(); i++) {
+ for (int i = 1; i < timeStamps.getLength(); i++) {
Element timeStamp = (Element)timeStamps.item(i);
articleTimeStamps.add(timeStamp.getFirstChild().getNodeValue());
}
return null;
}
@Override
protected void onPostExecute(String string) {
// Populate the spinner with the article titles
ArrayAdapter<String> aa = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, articleTitles);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
titleSpinner.setAdapter(aa);
MainActivity.this.setTitle(appTitle);
}
}
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
// Load the article bodies and external links into the WebView for display
String article = "<br>" + "<br>" + articleLinks.get(position) + "<br>" + articleTimeStamps.get(position)+ "<p>" + articleBodies.get(position);
articleBodyView.loadData(article, "text/html", "UTF-8");
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| true | true | protected String doInBackground(String... urls) {
BufferedReader reader=null;
String rawXML = null;
// Make the connection to the URL and get the xml as one big string
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line=reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
rawXML = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Parse the xml and create 3 lists holding article titles, contents (bodies), and external links
articleTitles = new ArrayList<String>();
articleBodies = new ArrayList<String>();
articleLinks = new ArrayList<String>();
articleTimeStamps = new ArrayList<String>();
articleTitles.add("Reader Instructions");
articleBodies.add("Touch the screen to display the article-selection list at the bottom.");
articleLinks.add("");
articleTimeStamps.add("");
DocumentBuilder builder;
Document doc = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(rawXML)));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; i < titles.getLength(); i++) {
Element title = (Element)titles.item(i);
if (i == 0) {
appTitle = title.getFirstChild().getNodeValue();
}
else articleTitles.add(title.getFirstChild().getNodeValue());
}
NodeList bodies = doc.getElementsByTagName("content");
for (int i = 0; i < bodies.getLength(); i++) {
Element body = (Element)bodies.item(i);
articleBodies.add(body.getFirstChild().getNodeValue());
}
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); i++) {
Element link = (Element)links.item(i);
if (link == null) Log.i(TAG, i + " is null");
if (link.getAttribute("rel").equals("alternate") && link.getAttribute("title").length() > 0) {
String articleLink = ("<a href=" + "`" + link.getAttribute("href") + "`" + "target=" + "`"+ "_blank" + "`" + ">" + link.getAttribute("title") + "</a>").replace('`', '"');
if (i == 0 || i == 1 || i == 2) Log.i(TAG, i + " " + articleLink);
articleLinks.add(articleLink);
}
}
NodeList timeStamps = doc.getElementsByTagName("updated");
Log.i(TAG, "timestamps length: " + timeStamps.getLength());
for (int i = 0; i < timeStamps.getLength(); i++) {
Element timeStamp = (Element)timeStamps.item(i);
articleTimeStamps.add(timeStamp.getFirstChild().getNodeValue());
}
return null;
}
| protected String doInBackground(String... urls) {
BufferedReader reader=null;
String rawXML = null;
// Make the connection to the URL and get the xml as one big string
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line=reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
rawXML = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Parse the xml and create 3 lists holding article titles, contents (bodies), and external links
articleTitles = new ArrayList<String>();
articleBodies = new ArrayList<String>();
articleLinks = new ArrayList<String>();
articleTimeStamps = new ArrayList<String>();
articleTitles.add("Reader Instructions");
articleBodies.add("Touch the screen to display the article-selection list at the bottom.");
articleLinks.add("");
articleTimeStamps.add("");
DocumentBuilder builder;
Document doc = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(rawXML)));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; i < titles.getLength(); i++) {
Element title = (Element)titles.item(i);
if (i == 0) {
appTitle = title.getFirstChild().getNodeValue();
}
else articleTitles.add(title.getFirstChild().getNodeValue());
}
NodeList bodies = doc.getElementsByTagName("content");
for (int i = 0; i < bodies.getLength(); i++) {
Element body = (Element)bodies.item(i);
articleBodies.add(body.getFirstChild().getNodeValue());
}
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); i++) {
Element link = (Element)links.item(i);
if (link == null) Log.i(TAG, i + " is null");
if (link.getAttribute("rel").equals("alternate") && link.getAttribute("title").length() > 0) {
String articleLink = ("<a href=" + "`" + link.getAttribute("href") + "`" + "target=" + "`"+ "_blank" + "`" + ">" + link.getAttribute("title") + "</a>").replace('`', '"');
if (i == 0 || i == 1 || i == 2) Log.i(TAG, i + " " + articleLink);
articleLinks.add(articleLink);
}
}
NodeList timeStamps = doc.getElementsByTagName("updated");
Log.i(TAG, "timestamps length: " + timeStamps.getLength());
for (int i = 1; i < timeStamps.getLength(); i++) {
Element timeStamp = (Element)timeStamps.item(i);
articleTimeStamps.add(timeStamp.getFirstChild().getNodeValue());
}
return null;
}
|
diff --git a/src/org/apache/xalan/xsltc/compiler/XslAttribute.java b/src/org/apache/xalan/xsltc/compiler/XslAttribute.java
index 779fb38e..161adf6d 100644
--- a/src/org/apache/xalan/xsltc/compiler/XslAttribute.java
+++ b/src/org/apache/xalan/xsltc/compiler/XslAttribute.java
@@ -1,261 +1,259 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
* @author Erwin Bolwidt <[email protected]>
* @author Gunnlaugur Briem <[email protected]>
*/
package org.apache.xalan.xsltc.compiler;
import java.util.Vector;
import org.apache.xalan.xsltc.compiler.util.Type;
import de.fub.bytecode.generic.*;
import org.apache.xalan.xsltc.compiler.util.*;
final class XslAttribute extends Instruction {
// Error messages:
private final static String ILLEGAL_ATTRIBUTE_NAME =
"Illegal attribute name: 'xmlns'";
// Attribute contents
private AttributeValue _name; // name treated as AVT (7.1.3)
private AttributeValueTemplate _namespace = null;
private String _prefix;
private boolean _ignore = false;
/**
* Returns the name of the attribute
*/
public AttributeValue getName() {
return _name;
}
/**
* Displays the contents of the attribute
*/
public void display(int indent) {
indent(indent);
Util.println("Attribute " + _name);
displayContents(indent + IndentIncrement);
}
/**
* Parses the attribute's contents. Special care taken for namespaces.
*/
public void parseContents(Parser parser) {
final SymbolTable stable = parser.getSymbolTable();
String namespace = getAttribute("namespace");
String name = getAttribute("name");
QName qname = parser.getQName(name);
final String prefix = qname.getPrefix();
boolean generated = false;
if ((prefix != null) && (prefix.equals("xmlns"))) {
reportError(this, parser, ErrorMsg.ILL_ATTR_ERR, name);
return;
}
// Ignore attribute if preceeded by some other type of element
final SyntaxTreeNode parent = getParent();
final Vector siblings = parent.getContents();
for (int i = 0; i < parent.elementCount(); i++) {
SyntaxTreeNode item = (SyntaxTreeNode)siblings.elementAt(i);
if (item == this) break;
// These three objects result in one or more attribute output
if (item instanceof XslAttribute) continue;
if (item instanceof UseAttributeSets) continue;
if (item instanceof LiteralAttribute) continue;
// These objects _can_ result in one or more attribute
// The output handler will generate an error if not (at runtime)
if (item instanceof If) continue;
if (item instanceof Choose) continue;
if (item instanceof CopyOf) continue; // bug fix 3320, g. briem
- _ignore = true;
reportWarning(this, parser, ErrorMsg.ATTROUTS_ERR, name);
- return;
}
// Get namespace from namespace attribute?
if ((namespace != null) && (namespace != Constants.EMPTYSTRING)) {
// Prefix could be in symbol table
_prefix = lookupPrefix(namespace);
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Get namespace from prefix in name attribute?
else if ((prefix != null) && (prefix != Constants.EMPTYSTRING)) {
_prefix = prefix;
namespace = lookupNamespace(prefix);
if (namespace != null)
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Common handling for namespaces:
if (_namespace != null) {
// Generate prefix if we have none
if (_prefix == null) {
if (prefix != null) {
_prefix = prefix;
}
else {
_prefix = stable.generateNamespacePrefix();
generated = true;
}
}
if (_prefix == Constants.EMPTYSTRING) {
name = qname.getLocalPart();
}
else {
name = _prefix+":"+qname.getLocalPart();
// PROBLEM:
// The namespace URI must be passed to the parent element,
// but we don't yet know what the actual URI is (as we only
// know it as an attribute value template). New design needed.
if ((parent instanceof LiteralElement) && (!generated)) {
((LiteralElement)parent).registerNamespace(_prefix,
namespace,
stable,false);
}
}
}
if (name.equals("xmlns")) {
final ErrorMsg msg =
new ErrorMsg(ILLEGAL_ATTRIBUTE_NAME, getLineNumber());
parser.reportError(Constants.ERROR, msg);
return;
}
if (parent instanceof LiteralElement) {
((LiteralElement)parent).addAttribute(this);
}
_name = AttributeValue.create(this, name, parser);
parseChildren(parser);
}
/**
*
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
if (_ignore) return(Type.Void);
_name.typeCheck(stable);
if (_namespace != null)
_namespace.typeCheck(stable);
typeCheckContents(stable);
return Type.Void;
}
/**
*
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
if (_ignore) return;
_ignore = true;
// Compile code that emits any needed namespace declaration
if (_namespace != null) {
// public void attribute(final String name, final String value)
il.append(methodGen.loadHandler());
il.append(new PUSH(cpg,_prefix));
_namespace.translate(classGen,methodGen);
il.append(methodGen.namespace());
}
// Save the current handler base on the stack
il.append(methodGen.loadHandler());
il.append(DUP); // first arg to "attributes" call
// Push attribute name
_name.translate(classGen, methodGen);// 2nd arg
// Push attribute value - shortcut for literal strings
if ((elementCount() == 1) && (elementAt(0) instanceof Text)) {
il.append(new PUSH(cpg, ((Text)elementAt(0)).getText()));
}
else {
il.append(classGen.loadTranslet());
il.append(new GETFIELD(cpg.addFieldref(TRANSLET_CLASS,
"stringValueHandler",
STRING_VALUE_HANDLER_SIG)));
il.append(DUP);
il.append(methodGen.storeHandler());
// translate contents with substituted handler
translateContents(classGen, methodGen);
// get String out of the handler
il.append(new INVOKEVIRTUAL(cpg.addMethodref(STRING_VALUE_HANDLER,
"getValue",
"()" + STRING_SIG)));
}
// call "attribute"
il.append(methodGen.attribute());
// Restore old handler base from stack
il.append(methodGen.storeHandler());
}
}
| false | true | public void parseContents(Parser parser) {
final SymbolTable stable = parser.getSymbolTable();
String namespace = getAttribute("namespace");
String name = getAttribute("name");
QName qname = parser.getQName(name);
final String prefix = qname.getPrefix();
boolean generated = false;
if ((prefix != null) && (prefix.equals("xmlns"))) {
reportError(this, parser, ErrorMsg.ILL_ATTR_ERR, name);
return;
}
// Ignore attribute if preceeded by some other type of element
final SyntaxTreeNode parent = getParent();
final Vector siblings = parent.getContents();
for (int i = 0; i < parent.elementCount(); i++) {
SyntaxTreeNode item = (SyntaxTreeNode)siblings.elementAt(i);
if (item == this) break;
// These three objects result in one or more attribute output
if (item instanceof XslAttribute) continue;
if (item instanceof UseAttributeSets) continue;
if (item instanceof LiteralAttribute) continue;
// These objects _can_ result in one or more attribute
// The output handler will generate an error if not (at runtime)
if (item instanceof If) continue;
if (item instanceof Choose) continue;
if (item instanceof CopyOf) continue; // bug fix 3320, g. briem
_ignore = true;
reportWarning(this, parser, ErrorMsg.ATTROUTS_ERR, name);
return;
}
// Get namespace from namespace attribute?
if ((namespace != null) && (namespace != Constants.EMPTYSTRING)) {
// Prefix could be in symbol table
_prefix = lookupPrefix(namespace);
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Get namespace from prefix in name attribute?
else if ((prefix != null) && (prefix != Constants.EMPTYSTRING)) {
_prefix = prefix;
namespace = lookupNamespace(prefix);
if (namespace != null)
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Common handling for namespaces:
if (_namespace != null) {
// Generate prefix if we have none
if (_prefix == null) {
if (prefix != null) {
_prefix = prefix;
}
else {
_prefix = stable.generateNamespacePrefix();
generated = true;
}
}
if (_prefix == Constants.EMPTYSTRING) {
name = qname.getLocalPart();
}
else {
name = _prefix+":"+qname.getLocalPart();
// PROBLEM:
// The namespace URI must be passed to the parent element,
// but we don't yet know what the actual URI is (as we only
// know it as an attribute value template). New design needed.
if ((parent instanceof LiteralElement) && (!generated)) {
((LiteralElement)parent).registerNamespace(_prefix,
namespace,
stable,false);
}
}
}
if (name.equals("xmlns")) {
final ErrorMsg msg =
new ErrorMsg(ILLEGAL_ATTRIBUTE_NAME, getLineNumber());
parser.reportError(Constants.ERROR, msg);
return;
}
if (parent instanceof LiteralElement) {
((LiteralElement)parent).addAttribute(this);
}
_name = AttributeValue.create(this, name, parser);
parseChildren(parser);
}
| public void parseContents(Parser parser) {
final SymbolTable stable = parser.getSymbolTable();
String namespace = getAttribute("namespace");
String name = getAttribute("name");
QName qname = parser.getQName(name);
final String prefix = qname.getPrefix();
boolean generated = false;
if ((prefix != null) && (prefix.equals("xmlns"))) {
reportError(this, parser, ErrorMsg.ILL_ATTR_ERR, name);
return;
}
// Ignore attribute if preceeded by some other type of element
final SyntaxTreeNode parent = getParent();
final Vector siblings = parent.getContents();
for (int i = 0; i < parent.elementCount(); i++) {
SyntaxTreeNode item = (SyntaxTreeNode)siblings.elementAt(i);
if (item == this) break;
// These three objects result in one or more attribute output
if (item instanceof XslAttribute) continue;
if (item instanceof UseAttributeSets) continue;
if (item instanceof LiteralAttribute) continue;
// These objects _can_ result in one or more attribute
// The output handler will generate an error if not (at runtime)
if (item instanceof If) continue;
if (item instanceof Choose) continue;
if (item instanceof CopyOf) continue; // bug fix 3320, g. briem
reportWarning(this, parser, ErrorMsg.ATTROUTS_ERR, name);
}
// Get namespace from namespace attribute?
if ((namespace != null) && (namespace != Constants.EMPTYSTRING)) {
// Prefix could be in symbol table
_prefix = lookupPrefix(namespace);
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Get namespace from prefix in name attribute?
else if ((prefix != null) && (prefix != Constants.EMPTYSTRING)) {
_prefix = prefix;
namespace = lookupNamespace(prefix);
if (namespace != null)
_namespace = new AttributeValueTemplate(namespace, parser);
}
// Common handling for namespaces:
if (_namespace != null) {
// Generate prefix if we have none
if (_prefix == null) {
if (prefix != null) {
_prefix = prefix;
}
else {
_prefix = stable.generateNamespacePrefix();
generated = true;
}
}
if (_prefix == Constants.EMPTYSTRING) {
name = qname.getLocalPart();
}
else {
name = _prefix+":"+qname.getLocalPart();
// PROBLEM:
// The namespace URI must be passed to the parent element,
// but we don't yet know what the actual URI is (as we only
// know it as an attribute value template). New design needed.
if ((parent instanceof LiteralElement) && (!generated)) {
((LiteralElement)parent).registerNamespace(_prefix,
namespace,
stable,false);
}
}
}
if (name.equals("xmlns")) {
final ErrorMsg msg =
new ErrorMsg(ILLEGAL_ATTRIBUTE_NAME, getLineNumber());
parser.reportError(Constants.ERROR, msg);
return;
}
if (parent instanceof LiteralElement) {
((LiteralElement)parent).addAttribute(this);
}
_name = AttributeValue.create(this, name, parser);
parseChildren(parser);
}
|
diff --git a/bridgemonitor/src/bridgemonitor/BridgeMonitor.java b/bridgemonitor/src/bridgemonitor/BridgeMonitor.java
index 7f6050d..0213dca 100644
--- a/bridgemonitor/src/bridgemonitor/BridgeMonitor.java
+++ b/bridgemonitor/src/bridgemonitor/BridgeMonitor.java
@@ -1,568 +1,569 @@
/*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge 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/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package bridgemonitor;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.sun.mpk20.voicelib.impl.service.voice.BridgeConnection;
import com.sun.mpk20.voicelib.impl.service.voice.BridgeOfflineListener;
import java.awt.BorderLayout;
import java.awt.Point;
/**
*
* @author jp
*/
public class BridgeMonitor implements Runnable, BridgeOfflineListener {
/** a logger */
private static final Logger logger =
Logger.getLogger(BridgeMonitor.class.getName());
private BridgeStatusPanel bsp;
private BridgeConnection bc;
private static BridgeMonitor callTableOwner;
private InsideCallBar insideCallBar;
public BridgeMonitor(BridgeStatusPanel bsp) {
this.bsp = bsp;
}
public void initialize() {
insideCallBar = new InsideCallBar();
JPanel callBar = bsp.getCallBar();
callBar.add(insideCallBar, BorderLayout.CENTER);
callBar.validate();
insideCallBar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
insideCallBarMouseClicked(evt);
}
});
setInitialState();
}
public void bridgeTextFieldKeyTyped(KeyEvent evt) {
setMonitorButton();
setBridgeInfoButton();
setEnableButton();
}
private void connect() throws IOException {
if (bc != null && bc.isConnected()) {
return;
}
String bridgeText = bsp.getBridgeTextField().getText();
bridgeText = bridgeText.substring(0, bridgeText.length());
String[] tokens = bridgeText.split(":");
if (tokens.length != 3) {
logger.info("Syntax is <host>:<sipPort>:<controlPort>");
throw new IOException("Syntax is <host>:<sipPort>:<controlPort>");
}
String server;
try {
server = InetAddress.getByName(tokens[0]).getHostAddress();
} catch (UnknownHostException e) {
throw new IOException("Couldn't get bridge connection: "
+ e.getMessage());
}
int sipPort;
try {
sipPort = Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
logger.info("Syntax is <host>:<sipPort>:<controlPort>");
throw new IOException("Syntax is <host>:<sipPort>:<controlPort>");
}
int controlPort;
try {
controlPort = Integer.parseInt(tokens[2]);
} catch (NumberFormatException e) {
logger.info("Syntax is <host>:<sipPort>:<controlPort>");
throw new IOException("Syntax is <host>:<sipPort>:<controlPort>");
}
logger.info(" trying to connect to " + server + ":"
+ sipPort + ":" + controlPort);
bc = new BridgeConnection(server, sipPort, controlPort, true);
bc.addBridgeOfflineListener(this);
}
public void bridgeTextFieldKeyReleased(KeyEvent evt) {
String s = bsp.getBridgeTextField().getText();
if (s.length() == 0) {
setInitialState();
}
}
public void monitorButtonMouseClicked(MouseEvent evt) {
JButton monitorButton = bsp.getMonitorButton();
String s = monitorButton.getText();
try {
connect();
} catch (IOException e) {
logger.info("Unable to connect to bridge: " + e.getMessage());
return;
}
if (s.equalsIgnoreCase("Monitor")) {
setMonitoring();
showBridgeCalls();
done = false;
new Thread(this).start();
return;
}
done();
setInitialState();
}
private void setInitialState() {
setMonitorButton();
setEnableButton();
setBridgeInfoButton();
bsp.getMonitorButton().setText("Monitor");
bsp.getStatusLabel().setText("");
bsp.getBridgeTextField().setEditable(true);
}
private void setMonitoring() {
bsp.getMonitorButton().setText("Stop Monitoring");
bsp.getStatusLabel().setText("Online");
bsp.getBridgeTextField().setEditable(false);
}
private void setOffline() {
bsp.getMonitorButton().setEnabled(false);
setEnableButton();
setBridgeInfoButton();
bsp.getMonitorButton().setText("Monitor");
bsp.getStatusLabel().setText("Offline");
bsp.getBridgeTextField().setEditable(true);
bsp.getCallLabel().setVisible(true);
bsp.getCallLabel().setText("");
}
private void setMonitorButton() {
if (bsp.getBridgeTextField().getText().length() == 0) {
bsp.getMonitorButton().setEnabled(false);
} else {
bsp.getMonitorButton().setEnabled(true);
}
}
private void setEnableButton() {
if (bsp.getBridgeTextField().getText().length() == 0) {
bsp.getEnableButton().setEnabled(false);
} else {
bsp.getEnableButton().setEnabled(true);
}
}
private void setBridgeInfoButton() {
if (bsp.getBridgeTextField().getText().length() == 0) {
bsp.getBridgeInfoButton().setEnabled(false);
} else {
bsp.getBridgeInfoButton().setEnabled(true);
}
}
public void bridgeInfoButtonMouseClicked(MouseEvent evt) {
try {
connect();
} catch (IOException e) {
logger.info("Unable to connect to bridge: " + e.getMessage());
setOffline();
return;
}
try {
String info = bc.getBridgeInfo();
JFrame jFrame = new JFrame("Bridge Info for " + bc);
String[] tokens = info.split("\n");
JTable jTable = new JTable(0, 2);
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
model.setRowCount(tokens.length);
String[] columnIdentifiers = new String[2];
columnIdentifiers[0] = "Parameter";
columnIdentifiers[1] = "Value";
model.setColumnIdentifiers(columnIdentifiers);
logger.info("tokens length " + tokens.length);
for (int i = 0; i < tokens.length; i++) {
String s = tokens[i];
String[] nameValue = s.split("=");
jTable.setValueAt(nameValue[0].trim(), i, 0);
jTable.setValueAt(nameValue[1].trim(), i, 1);
}
JScrollPane jScrollPane = new JScrollPane(jTable);
jFrame.add(jScrollPane);
jFrame.setVisible(true);
jFrame.pack();
jFrame.toFront();
jFrame.setResizable(true);
} catch (IOException e) {
logger.info(e.getMessage());
}
}
public void enableButtonMouseClicked(MouseEvent evt) {
JButton enableButton = bsp.getEnableButton();
String s = enableButton.getText();
try {
connect();
} catch (IOException e) {
logger.info("Unable to connect to bridge: " + e.getMessage());
return;
}
if (s.equalsIgnoreCase("Enable")) {
try {
bc.suspend(false);
enableButton.setText("Disable");
bsp.getMonitorButton().setEnabled(true);
} catch (IOException e) {
logger.info("Unable to resume " + bsp.getBridgeTextField().getText()
+ " " + e.getMessage());
setOffline();
}
return;
}
monitorButtonMouseClicked(null);
done();
try {
bc.suspend(true);
bc.disconnect();
setOffline();
enableButton.setText("Enable");
} catch (IOException e) {
logger.info("Unable to suspend " + bsp.getBridgeTextField().getText()
+ " " + e.getMessage());
setOffline();
}
}
public void insideCallBarMouseClicked(java.awt.event.MouseEvent evt) {
if (bc.isConnected() == false) {
logger.info("Not connected: " + bc);
setOffline();
return;
}
bridgeCalls = bc;
showBridgeCalls();
}
private void showBridgeCalls() {
String status;
try {
status = bc.getCallInfo();
} catch (IOException e) {
logger.info(e.getMessage());
return;
}
String[] tokens = status.split("\n");
int callCount = 0;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].startsWith(" ") == false) {
continue;
}
callCount++;
}
JTable callTable = bsp.getCallTable();
synchronized (callTable) {
DefaultTableModel model = (DefaultTableModel) callTable.getModel();
if (callTableOwner != this) {
String[] columnIdentifiers = new String[3];
columnIdentifiers[0] = "CallID";
columnIdentifiers[1] = "Bridge " + bc;
columnIdentifiers[2] = "Audio Quality";
model.setColumnIdentifiers(columnIdentifiers);
}
callTableOwner = this;
model.setRowCount(callCount);
callCount = 0;
int myCt = 0;
for (int i = 0; i < tokens.length; i++) {
String[] items = tokens[i].split("@");
String cID = items[0];
if (tokens[i].startsWith(" ") == false) {
continue;
}
String[] callDetails = items[1].split(" ");
int cdLen = callDetails.length;
String aQualityTmp = callDetails[cdLen -1];
String[] aQTarr = aQualityTmp.split(":");
String aQuality = aQTarr[1];
String fName = callDetails[0];
String[] checkFname = items[1].split(" ");
if(checkFname.length > 2) {
// if the audio filename has a space in it, build the name string using the array elts
// in between 0 and cdLen - 1
// reset fName
fName = "";
for(int n = 0;n < cdLen - 1; n++) {
// if the audio filename has a space in it, build the name string using the array elts
// in between 0 and cdLen - 2
fName = fName + callDetails[n] + " ";
}
}
String[] infoArr = {cID, fName, aQuality};
for(int j = 0; j < infoArr.length; j++) {
model.setValueAt(infoArr[j], myCt, j);
}
myCt++;
}
}
}
public void callTableMouseClicked(java.awt.event.MouseEvent evt) {
JTable callTable = bsp.getCallTable();
int[] rows = callTable.getSelectedRows();
for (int i = 0; i < rows.length; i++) {
String callId = (String)
callTable.getValueAt(rows[i], 0);
callId = callId.trim();
if (callId.startsWith("sip:")) {
callId = callId.substring(4);
}
new CallInfoUpdater(i * 200, bc, (String) callId);
}
}
private static int lastTotalCalls = 0;
private BridgeConnection bridgeCalls;
class InsideCallBar extends JPanel {
private int callCount;
public void setCallCount(int callCount) {
this.callCount = callCount;
repaint();
}
public void paintComponent(Graphics g) {
//int height = callCount * 20;
int height = (getHeight() * callCount) / 10;
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.GREEN);
g.fillRect(0, getHeight() - height, getWidth(), height);
//g.setColor(Color.RED);
//g.drawRect(0, 0, getWidth(), getHeight());
}
}
private boolean done;
public void done() {
synchronized (this) {
if (done) {
return;
}
done = true;
try {
wait();
} catch (InterruptedException e) {
}
}
}
public void run() {
int lastNumberOfCalls = 0;
while (!done) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
if (callTableOwner == this) {
showBridgeCalls();
}
try {
String status = bc.getBridgeStatus();
status = status.replaceAll("\t", "");
String[] tokens = status.split("\n");
tokens = tokens[1].split(":");
int n;
try {
n = Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
logger.info("Unable to parse status: " + status);
continue;
}
String s = " Calls";
if (n == 1) {
s = " Call";
}
bsp.getCallLabel().setText(n + s);
if (n == lastNumberOfCalls) {
continue;
}
insideCallBar.setCallCount(n);
if (n > lastTotalCalls) {
lastTotalCalls = n;
}
bsp.getEnableButton().setText("Disable");
} catch (IOException e) {
logger.info("Unable to get status for " + bc);
setOffline();
break;
}
}
lastTotalCalls = 0;
if (callTableOwner == this) {
synchronized (callTableOwner) {
bridgeCalls = null;
JTable callTable = bsp.getCallTable();
callTable.removeAll();
callTableOwner = null;
//String[] columnIdentifiers = new String[1];
//columnIdentifiers[0] = "Calls";
//DefaultTableModel model = (DefaultTableModel) callTable.getModel();
//model.setColumnIdentifiers(columnIdentifiers);
}
}
insideCallBar.setCallCount(0);
bsp.getCallLabel().setText("");
synchronized (this) {
+ done = true;
notifyAll();
}
}
public void bridgeOffline(BridgeConnection bc) {
logger.info("Bridge offline: " + bc);
bc.disconnect();
setOffline();
}
}
| true | true | public void run() {
int lastNumberOfCalls = 0;
while (!done) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
if (callTableOwner == this) {
showBridgeCalls();
}
try {
String status = bc.getBridgeStatus();
status = status.replaceAll("\t", "");
String[] tokens = status.split("\n");
tokens = tokens[1].split(":");
int n;
try {
n = Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
logger.info("Unable to parse status: " + status);
continue;
}
String s = " Calls";
if (n == 1) {
s = " Call";
}
bsp.getCallLabel().setText(n + s);
if (n == lastNumberOfCalls) {
continue;
}
insideCallBar.setCallCount(n);
if (n > lastTotalCalls) {
lastTotalCalls = n;
}
bsp.getEnableButton().setText("Disable");
} catch (IOException e) {
logger.info("Unable to get status for " + bc);
setOffline();
break;
}
}
lastTotalCalls = 0;
if (callTableOwner == this) {
synchronized (callTableOwner) {
bridgeCalls = null;
JTable callTable = bsp.getCallTable();
callTable.removeAll();
callTableOwner = null;
//String[] columnIdentifiers = new String[1];
//columnIdentifiers[0] = "Calls";
//DefaultTableModel model = (DefaultTableModel) callTable.getModel();
//model.setColumnIdentifiers(columnIdentifiers);
}
}
insideCallBar.setCallCount(0);
bsp.getCallLabel().setText("");
synchronized (this) {
notifyAll();
}
}
| public void run() {
int lastNumberOfCalls = 0;
while (!done) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
if (callTableOwner == this) {
showBridgeCalls();
}
try {
String status = bc.getBridgeStatus();
status = status.replaceAll("\t", "");
String[] tokens = status.split("\n");
tokens = tokens[1].split(":");
int n;
try {
n = Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
logger.info("Unable to parse status: " + status);
continue;
}
String s = " Calls";
if (n == 1) {
s = " Call";
}
bsp.getCallLabel().setText(n + s);
if (n == lastNumberOfCalls) {
continue;
}
insideCallBar.setCallCount(n);
if (n > lastTotalCalls) {
lastTotalCalls = n;
}
bsp.getEnableButton().setText("Disable");
} catch (IOException e) {
logger.info("Unable to get status for " + bc);
setOffline();
break;
}
}
lastTotalCalls = 0;
if (callTableOwner == this) {
synchronized (callTableOwner) {
bridgeCalls = null;
JTable callTable = bsp.getCallTable();
callTable.removeAll();
callTableOwner = null;
//String[] columnIdentifiers = new String[1];
//columnIdentifiers[0] = "Calls";
//DefaultTableModel model = (DefaultTableModel) callTable.getModel();
//model.setColumnIdentifiers(columnIdentifiers);
}
}
insideCallBar.setCallCount(0);
bsp.getCallLabel().setText("");
synchronized (this) {
done = true;
notifyAll();
}
}
|
diff --git a/PA3B/src/ray/tracer/WhittedRayTracer.java b/PA3B/src/ray/tracer/WhittedRayTracer.java
index 4c18a44..cd1e543 100755
--- a/PA3B/src/ray/tracer/WhittedRayTracer.java
+++ b/PA3B/src/ray/tracer/WhittedRayTracer.java
@@ -1,265 +1,265 @@
package ray.tracer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ray.Image;
import ray.IntersectionRecord;
import ray.Ray;
import ray.RayRecord;
import ray.Scene;
import ray.Workspace;
import ray.accel.AccelStruct;
import ray.accel.Bvh;
import ray.camera.Camera;
import ray.light.Light;
import ray.material.Material;
import ray.math.Color;
import ray.math.Vector3;
import ray.surface.Surface;
public class WhittedRayTracer extends RayTracer {
/**
* The main method takes all the parameters and assumes they are input files
* for the ray tracer. It tries to render each one and write it out to a PNG
* file named <input_file>.png.
*
* @param args
*/
public static final void main(String[] args) {
WhittedRayTracer rayTracer = new WhittedRayTracer();
rayTracer.run("data/scenes/whitted_ray_tracer", args);
}
/**
* The renderImage method renders the entire scene.
*
* @param scene The scene to be rendered
*/
public void renderImage(Scene scene) {
// Get the output image
Image image = scene.getImage();
Camera cam = scene.getCamera();
// Set the camera aspect ratio to match output image
int width = image.getWidth();
int height = image.getHeight();
// Timing counters
long startTime = System.currentTimeMillis();
// Do some basic setup
Workspace work = new Workspace();
Ray ray = work.eyeRay;
Color pixelColor = work.pixelColor;
Color rayColor = work.rayColor;
int total = height * width;
int counter = 0;
int lastShownPercent = 0;
int samples = scene.getSamples();
double sInv = 1.0/samples;
double sInvD2 = sInv / 2;
double sInvSqr = sInv * sInv;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pixelColor.set(0, 0, 0);
// TODO(B): Support Anti-Aliasing
for(int i = 0; i < samples; i++) {
for(int j = 0; j < samples; j++) {
// TODO(B): Compute the "ray" and call shadeRay on it.
pixelColor.add(rayColor);
}
}
pixelColor.scale(sInvSqr);
//Gamma correct and clamp pixel values
pixelColor.gammaCorrect(2.2);
pixelColor.clamp(0, 1);
image.setPixelColor(pixelColor, x, y);
counter ++;
if((int)(100.0 * counter / total) != lastShownPercent) {
lastShownPercent = (int)(100.0*counter / total);
System.out.println(lastShownPercent + "%");
}
}
}
// Output time
long totalTime = (System.currentTimeMillis() - startTime);
System.out.println("Done. Total rendering time: "
+ (totalTime / 1000.0) + " seconds");
}
/**
* This method returns the color along a single ray in outColor.
*
* @param outColor output space
* @param scene the scene
* @param ray the ray to shade
*/
public void shadeRay(Color outColor, Scene scene, Ray ray, Workspace workspace, Color absorption, int depth) {
// Reset the output color
outColor.set(0, 0, 0);
// TODO(B): Return immediately if depth is greater than 12.
if (depth > 12) {
return ;
}
// Rename all the workspace entries to avoid field accesses
// and alot of typing "workspace."
IntersectionRecord intersectionRecord = workspace.intersectionRecord;
// TODO(B): Fill in the part of BasicRayTracer.shadeRay
// from getting the first intersection onward.
if (!scene.getFirstIntersection(intersectionRecord, ray)) {
return;
}
// TODO(A): Compute the color of the intersection point.
// 1) Get the material from the intersection record.
// 2) Check whether the material can interact directly with light.
// If not, do nothing.
// 3) Compute the direction of outgoing light, by subtracting the
// intersection point from the origin of the ray.
// 4) Loop through each light in the scene.
// 5) For each light, compute the incoming direction by subtracting
// the intersection point from the light's position.
// 6) Compute the BRDF value by calling the evaluate method of the material.
// 7) If the BRDF is not zero, check whether the intersection point is
// shadowed.
// 8) If the intersection point is not shadowed, scale the light intensity
// by the BRDF value and add it to outColor.
// 1)
Material material = intersectionRecord.surface.getMaterial();
// 2)
if (!material.canInteractWithLight()) {
return;
}
// 3)
Vector3 intersectionPoint = new Vector3(intersectionRecord.location);
Vector3 outgoing = new Vector3(ray.origin);
outgoing.sub(intersectionPoint);
//outgoing.normalize();
// 4)
for (Iterator<Light> iter = scene.getLights().iterator(); iter.hasNext();) {
Light light = iter.next();
// 5)
Vector3 incoming = new Vector3(light.position);
incoming.sub(intersectionPoint);
//incoming.normalize();
// 6)
Color BDRF = new Color();
material.evaluate(BDRF, intersectionRecord, incoming, outgoing);
// 7)
if (!BDRF.isZero()) {
Ray shadowRay = new Ray();
// 8)
if (!isShadowed(scene, light, intersectionRecord, shadowRay)) {
Color intensity = new Color(light.intensity);
intensity.scale(BDRF);
outColor.add(intensity);
}
}
}
// TODO(B): Recursively trace rays due to perfectly specular components.
// 1) Check whether the material has perfectly specular components.
// 2) If so, call material.getIncomingSpecularRays to get the set of rays.
// 3) For each ray, see if the scaling factor is greater than zero.
// If not, ignore the ray.
// 4) If the factor is greater than zero, check whether the ray is going
// inside or outside the surface by dotting it with the normal.
// The ray goes inside if the dot product is less than zero.
// 5) Based on whether the ray goes inside or outside, compute the absorption
// coefficient of the region the next ray will travel through.
// 6) Call shadeRay recursively, increasing the depth by 1 and using
// the absorption coefficient you just computed.
// 7) Scale the resulting ray color with the scaling factor of the specular ray,
// and add it to the output color.
// 1)
if (material.hasPerfectlySpecularComponent()) {
// 2)
RayRecord[] records = material.getIncomingSpecularRays(intersectionRecord, ray.direction);
// 3)
for (int i = 0; i < records.length; i++) {
Ray specRay = records[i].ray;
if (!records[i].factor.isZero() && records[i].factor.b > 0.0 &&
records[i].factor.g > 0.0 && records[i].factor.r > 0.0) {
// 4)
double dot = specRay.direction.dot(intersectionRecord.normal);
// 5)
Color absorp = new Color();
- if (dot < 0) {
+ if (dot > 0) {
//ray is traveling inside, so the ray will travel outside next
absorp.set(intersectionRecord.surface.getOutsideAbsorption());
}
- else if (dot > 0) {
+ else {
absorp.set(intersectionRecord.surface.getInsideAbsorption());
}
// 6)
Color outColorRec = new Color();
shadeRay(outColorRec, scene, ray, workspace, absorp, depth + 1);
// 7)
outColorRec.scale(records[i].factor);
outColor.add(outColorRec);
}
}
}
// TODO(B): Compute the distance that the ray travels and attenuate
// the output color by the absorption according to Beer's law.
double tBegin = ray.start;
double tEnd = intersectionRecord.t;
Vector3 startPos = new Vector3(ray.origin);
startPos.scaleAdd(tBegin, ray.direction);
Vector3 endPos = new Vector3(ray.origin);
endPos.scaleAdd(tEnd, ray.direction);
//subtract the end position from the starting position to
//get the vector from start to finish
endPos.sub(startPos);
double length = endPos.length();
Color absorp = new Color(absorption);
absorp.scale(-length);
//outColor = outColor exp(- l * absorp)
outColor.scale(Math.exp(absorp.r), Math.exp(absorp.g), Math.exp(absorp.b));
}
@Override
protected AccelStruct createAccelStruct(Scene scene) {
ArrayList<Surface> allSurfaces = new ArrayList<Surface>();
List<Surface> surfaces = scene.getSurfaces();
for (Iterator<Surface> iter = surfaces.iterator(); iter.hasNext();) {
iter.next().appendRenderableSurfaces(allSurfaces);
}
Surface []surfaceArray = new Surface[allSurfaces.size()];
int count = 0;
for(Iterator<Surface> iter = allSurfaces.iterator(); iter.hasNext();)
surfaceArray[count++] = iter.next();
AccelStruct accelStruct = new Bvh(surfaceArray, 0, surfaceArray.length);
accelStruct.build();
return accelStruct;
}
}
| false | true | public void shadeRay(Color outColor, Scene scene, Ray ray, Workspace workspace, Color absorption, int depth) {
// Reset the output color
outColor.set(0, 0, 0);
// TODO(B): Return immediately if depth is greater than 12.
if (depth > 12) {
return ;
}
// Rename all the workspace entries to avoid field accesses
// and alot of typing "workspace."
IntersectionRecord intersectionRecord = workspace.intersectionRecord;
// TODO(B): Fill in the part of BasicRayTracer.shadeRay
// from getting the first intersection onward.
if (!scene.getFirstIntersection(intersectionRecord, ray)) {
return;
}
// TODO(A): Compute the color of the intersection point.
// 1) Get the material from the intersection record.
// 2) Check whether the material can interact directly with light.
// If not, do nothing.
// 3) Compute the direction of outgoing light, by subtracting the
// intersection point from the origin of the ray.
// 4) Loop through each light in the scene.
// 5) For each light, compute the incoming direction by subtracting
// the intersection point from the light's position.
// 6) Compute the BRDF value by calling the evaluate method of the material.
// 7) If the BRDF is not zero, check whether the intersection point is
// shadowed.
// 8) If the intersection point is not shadowed, scale the light intensity
// by the BRDF value and add it to outColor.
// 1)
Material material = intersectionRecord.surface.getMaterial();
// 2)
if (!material.canInteractWithLight()) {
return;
}
// 3)
Vector3 intersectionPoint = new Vector3(intersectionRecord.location);
Vector3 outgoing = new Vector3(ray.origin);
outgoing.sub(intersectionPoint);
//outgoing.normalize();
// 4)
for (Iterator<Light> iter = scene.getLights().iterator(); iter.hasNext();) {
Light light = iter.next();
// 5)
Vector3 incoming = new Vector3(light.position);
incoming.sub(intersectionPoint);
//incoming.normalize();
// 6)
Color BDRF = new Color();
material.evaluate(BDRF, intersectionRecord, incoming, outgoing);
// 7)
if (!BDRF.isZero()) {
Ray shadowRay = new Ray();
// 8)
if (!isShadowed(scene, light, intersectionRecord, shadowRay)) {
Color intensity = new Color(light.intensity);
intensity.scale(BDRF);
outColor.add(intensity);
}
}
}
// TODO(B): Recursively trace rays due to perfectly specular components.
// 1) Check whether the material has perfectly specular components.
// 2) If so, call material.getIncomingSpecularRays to get the set of rays.
// 3) For each ray, see if the scaling factor is greater than zero.
// If not, ignore the ray.
// 4) If the factor is greater than zero, check whether the ray is going
// inside or outside the surface by dotting it with the normal.
// The ray goes inside if the dot product is less than zero.
// 5) Based on whether the ray goes inside or outside, compute the absorption
// coefficient of the region the next ray will travel through.
// 6) Call shadeRay recursively, increasing the depth by 1 and using
// the absorption coefficient you just computed.
// 7) Scale the resulting ray color with the scaling factor of the specular ray,
// and add it to the output color.
// 1)
if (material.hasPerfectlySpecularComponent()) {
// 2)
RayRecord[] records = material.getIncomingSpecularRays(intersectionRecord, ray.direction);
// 3)
for (int i = 0; i < records.length; i++) {
Ray specRay = records[i].ray;
if (!records[i].factor.isZero() && records[i].factor.b > 0.0 &&
records[i].factor.g > 0.0 && records[i].factor.r > 0.0) {
// 4)
double dot = specRay.direction.dot(intersectionRecord.normal);
// 5)
Color absorp = new Color();
if (dot < 0) {
//ray is traveling inside, so the ray will travel outside next
absorp.set(intersectionRecord.surface.getOutsideAbsorption());
}
else if (dot > 0) {
absorp.set(intersectionRecord.surface.getInsideAbsorption());
}
// 6)
Color outColorRec = new Color();
shadeRay(outColorRec, scene, ray, workspace, absorp, depth + 1);
// 7)
outColorRec.scale(records[i].factor);
outColor.add(outColorRec);
}
}
}
// TODO(B): Compute the distance that the ray travels and attenuate
// the output color by the absorption according to Beer's law.
double tBegin = ray.start;
double tEnd = intersectionRecord.t;
Vector3 startPos = new Vector3(ray.origin);
startPos.scaleAdd(tBegin, ray.direction);
Vector3 endPos = new Vector3(ray.origin);
endPos.scaleAdd(tEnd, ray.direction);
//subtract the end position from the starting position to
//get the vector from start to finish
endPos.sub(startPos);
double length = endPos.length();
Color absorp = new Color(absorption);
absorp.scale(-length);
//outColor = outColor exp(- l * absorp)
outColor.scale(Math.exp(absorp.r), Math.exp(absorp.g), Math.exp(absorp.b));
}
| public void shadeRay(Color outColor, Scene scene, Ray ray, Workspace workspace, Color absorption, int depth) {
// Reset the output color
outColor.set(0, 0, 0);
// TODO(B): Return immediately if depth is greater than 12.
if (depth > 12) {
return ;
}
// Rename all the workspace entries to avoid field accesses
// and alot of typing "workspace."
IntersectionRecord intersectionRecord = workspace.intersectionRecord;
// TODO(B): Fill in the part of BasicRayTracer.shadeRay
// from getting the first intersection onward.
if (!scene.getFirstIntersection(intersectionRecord, ray)) {
return;
}
// TODO(A): Compute the color of the intersection point.
// 1) Get the material from the intersection record.
// 2) Check whether the material can interact directly with light.
// If not, do nothing.
// 3) Compute the direction of outgoing light, by subtracting the
// intersection point from the origin of the ray.
// 4) Loop through each light in the scene.
// 5) For each light, compute the incoming direction by subtracting
// the intersection point from the light's position.
// 6) Compute the BRDF value by calling the evaluate method of the material.
// 7) If the BRDF is not zero, check whether the intersection point is
// shadowed.
// 8) If the intersection point is not shadowed, scale the light intensity
// by the BRDF value and add it to outColor.
// 1)
Material material = intersectionRecord.surface.getMaterial();
// 2)
if (!material.canInteractWithLight()) {
return;
}
// 3)
Vector3 intersectionPoint = new Vector3(intersectionRecord.location);
Vector3 outgoing = new Vector3(ray.origin);
outgoing.sub(intersectionPoint);
//outgoing.normalize();
// 4)
for (Iterator<Light> iter = scene.getLights().iterator(); iter.hasNext();) {
Light light = iter.next();
// 5)
Vector3 incoming = new Vector3(light.position);
incoming.sub(intersectionPoint);
//incoming.normalize();
// 6)
Color BDRF = new Color();
material.evaluate(BDRF, intersectionRecord, incoming, outgoing);
// 7)
if (!BDRF.isZero()) {
Ray shadowRay = new Ray();
// 8)
if (!isShadowed(scene, light, intersectionRecord, shadowRay)) {
Color intensity = new Color(light.intensity);
intensity.scale(BDRF);
outColor.add(intensity);
}
}
}
// TODO(B): Recursively trace rays due to perfectly specular components.
// 1) Check whether the material has perfectly specular components.
// 2) If so, call material.getIncomingSpecularRays to get the set of rays.
// 3) For each ray, see if the scaling factor is greater than zero.
// If not, ignore the ray.
// 4) If the factor is greater than zero, check whether the ray is going
// inside or outside the surface by dotting it with the normal.
// The ray goes inside if the dot product is less than zero.
// 5) Based on whether the ray goes inside or outside, compute the absorption
// coefficient of the region the next ray will travel through.
// 6) Call shadeRay recursively, increasing the depth by 1 and using
// the absorption coefficient you just computed.
// 7) Scale the resulting ray color with the scaling factor of the specular ray,
// and add it to the output color.
// 1)
if (material.hasPerfectlySpecularComponent()) {
// 2)
RayRecord[] records = material.getIncomingSpecularRays(intersectionRecord, ray.direction);
// 3)
for (int i = 0; i < records.length; i++) {
Ray specRay = records[i].ray;
if (!records[i].factor.isZero() && records[i].factor.b > 0.0 &&
records[i].factor.g > 0.0 && records[i].factor.r > 0.0) {
// 4)
double dot = specRay.direction.dot(intersectionRecord.normal);
// 5)
Color absorp = new Color();
if (dot > 0) {
//ray is traveling inside, so the ray will travel outside next
absorp.set(intersectionRecord.surface.getOutsideAbsorption());
}
else {
absorp.set(intersectionRecord.surface.getInsideAbsorption());
}
// 6)
Color outColorRec = new Color();
shadeRay(outColorRec, scene, ray, workspace, absorp, depth + 1);
// 7)
outColorRec.scale(records[i].factor);
outColor.add(outColorRec);
}
}
}
// TODO(B): Compute the distance that the ray travels and attenuate
// the output color by the absorption according to Beer's law.
double tBegin = ray.start;
double tEnd = intersectionRecord.t;
Vector3 startPos = new Vector3(ray.origin);
startPos.scaleAdd(tBegin, ray.direction);
Vector3 endPos = new Vector3(ray.origin);
endPos.scaleAdd(tEnd, ray.direction);
//subtract the end position from the starting position to
//get the vector from start to finish
endPos.sub(startPos);
double length = endPos.length();
Color absorp = new Color(absorption);
absorp.scale(-length);
//outColor = outColor exp(- l * absorp)
outColor.scale(Math.exp(absorp.r), Math.exp(absorp.g), Math.exp(absorp.b));
}
|
diff --git a/src/org/broad/igv/renderer/SequenceRenderer.java b/src/org/broad/igv/renderer/SequenceRenderer.java
index cc59366c..8640fd21 100644
--- a/src/org/broad/igv/renderer/SequenceRenderer.java
+++ b/src/org/broad/igv/renderer/SequenceRenderer.java
@@ -1,474 +1,474 @@
/*
* Copyright (c) 2007-2011 by The Broad Institute, Inc. and the Massachusetts Institute of
* Technology. 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.renderer;
import org.broad.igv.feature.*;
import org.broad.igv.track.RenderContext;
import org.broad.igv.track.Track;
import org.broad.igv.ui.FontManager;
import org.broad.igv.ui.UIConstants;
import org.broad.igv.util.SOLIDUtils;
import java.awt.*;
import java.util.*;
/**
* @author jrobinso
*/
public class SequenceRenderer {
//Maximum scale at which the track is displayed
public static final double MAX_SCALE_FOR_RENDER = 1000;
static Map<Character, Color> nucleotideColors = new HashMap();
static {
//nucleotideColors.put('A', new Color(160, 160, 255));
//nucleotideColors.put('C', new Color(255, 140, 75));
//nucleotideColors.put('T', new Color(160, 255, 255));
//nucleotideColors.put('G', new Color(255, 112, 112));
//nucleotideColors.put('N', Color.gray);
nucleotideColors.put('A', Color.GREEN);
nucleotideColors.put('a', Color.GREEN);
nucleotideColors.put('C', Color.BLUE);
nucleotideColors.put('c', Color.BLUE);
nucleotideColors.put('T', Color.RED);
nucleotideColors.put('t', Color.RED);
nucleotideColors.put('G', new Color(209, 113, 5));
nucleotideColors.put('g', new Color(209, 113, 5));
nucleotideColors.put('N', Color.gray);
nucleotideColors.put('n', Color.gray);
}
protected TranslatedSequenceDrawer translatedSequenceDrawer;
//are we rendering positive or negative strand?
protected Strand strand = Strand.POSITIVE;
public SequenceRenderer() {
translatedSequenceDrawer = new TranslatedSequenceDrawer();
}
/**
* @param context
* @param trackRectangle
* @param showColorSpace
* @param showTranslation Should we show the translated amino acids?
*/
public void draw(RenderContext context, Rectangle trackRectangle,
boolean showColorSpace, boolean showTranslation) {
if (context.getScale() >= MAX_SCALE_FOR_RENDER) {
// Zoomed out too far to see sequences. This can happen when in gene list view and one of the frames
// is zoomed in but others are not
context.getGraphic2DForColor(UIConstants.VERY_LIGHT_GRAY).fill(trackRectangle);
} else {
double locScale = context.getScale();
double origin = context.getOrigin();
String chr = context.getChr();
String genome = context.getGenomeId();
//The location of the first base that is loaded, which may include padding around what's visible
int start = Math.max(0, (int) origin - 1);
//The location of the last base that is loaded
int end = (int) (origin + trackRectangle.width * locScale) + 1;
if (end <= start) return;
int firstVisibleNucleotideStart = start;
int lastVisibleNucleotideEnd = end;
int firstCodonOffset = 0;
int lastCodonOffset = 0;
//If we're translating, we need to start with the first bp of the first codon, in frame 3, and
//end with the last bp of the last codon, in frame 1
if (showTranslation) {
if (start > 1) {
firstCodonOffset = 2;
start -= firstCodonOffset;
}
lastCodonOffset = 2;
end += lastCodonOffset;
}
byte[] seq = SequenceManager.readSequence(genome, chr, start, end);
//The combined height of sequence and (optionally) colorspace bands
int untranslatedSequenceHeight = (int) trackRectangle.getHeight();
if (showTranslation) {
untranslatedSequenceHeight = showColorSpace ? (int) trackRectangle.getHeight() / 5 * 2 :
(int) (trackRectangle.getHeight() / 4);
// Draw translated sequence
Rectangle translatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y + untranslatedSequenceHeight,
(int) trackRectangle.getWidth(), (int) trackRectangle.getHeight() - untranslatedSequenceHeight);
if (context.getScale() < 5) {
translatedSequenceDrawer.draw(context, start, translatedSequenceRect, seq, strand);
}
}
//Rectangle containing the sequence and (optionally) colorspace bands
Rectangle untranslatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y,
(int) trackRectangle.getWidth(), untranslatedSequenceHeight);
byte[] seqCS = null;
if (showColorSpace) {
seqCS = SOLIDUtils.convertToColorSpace(seq);
}
if (seq != null && seq.length > 0) {
int hCS = (showColorSpace ? untranslatedSequenceRect.height / 2 : 0);
int yBase = hCS + untranslatedSequenceRect.y + 2;
int yCS = untranslatedSequenceRect.y + 2;
int dY = (showColorSpace ? hCS : untranslatedSequenceRect.height) - 4;
int dX = (int) (1.0 / locScale);
// Create a graphics to use
Graphics2D g = (Graphics2D) context.getGraphics().create();
//dhmay adding check for adequate track height
int fontSize = Math.min(untranslatedSequenceRect.height, Math.min(dX, 12));
if (fontSize >= 8) {
Font f = FontManager.getScalableFont(Font.BOLD, fontSize);
g.setFont(f);
}
// Loop through base pair coordinates
int lastPx0 = -1;
- int scale = Math.max(0, (int) context.getScale() - 1);
+ int scale = Math.max(1, (int) context.getScale());
for (int loc = firstVisibleNucleotideStart; loc < lastVisibleNucleotideEnd; loc += scale) {
for (; loc < lastVisibleNucleotideEnd; loc++) {
int idx = loc - start;
int pX0 = (int) ((loc - origin) / locScale);
if (pX0 > lastPx0) {
lastPx0 = pX0;
char c = (char) seq[idx];
if (Strand.NEGATIVE.equals(strand))
c = complementChar(c);
Color color = nucleotideColors.get(c);
if (fontSize >= 8) {
if (color == null) {
color = Color.black;
}
g.setColor(color);
drawCenteredText(g, new char[]{c}, pX0, yBase + 2, dX, dY - 2);
if (showColorSpace) {
// draw color space #. Color space is shifted to be between bases as it represents
// two bases.
g.setColor(Color.black);
String cCS = String.valueOf(seqCS[idx]);
drawCenteredText(g, cCS.toCharArray(), pX0 - dX / 2, yCS + 2, dX, dY - 2);
}
} else {
int bw = Math.max(1, dX - 1);
if (color != null) {
g.setColor(color);
g.fillRect(pX0, yBase, bw, dY);
}
}
}
break;
}
}
}
}
}
/**
* complement a nucleotide. If not ATGC, return the intput char
*
* @param inputChar
* @return
*/
protected char complementChar(char inputChar) {
switch (inputChar) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
case 'C':
return 'G';
default:
return inputChar;
}
}
private void drawCenteredText(Graphics2D g, char[] chars, int x, int y, int w, int h) {
// Get measures needed to center the message
FontMetrics fm = g.getFontMetrics();
// How many pixels wide is the string
int msg_width = fm.charsWidth(chars, 0, 1);
// How far above the baseline can the font go?
int ascent = fm.getMaxAscent();
// How far below the baseline?
int descent = fm.getMaxDescent();
// Use the string width to find the starting point
int msgX = x + w / 2 - msg_width / 2;
// Use the vertical height of this font to find
// the vertical starting coordinate
int msgY = y + h / 2 - descent / 2 + ascent / 2;
g.drawChars(chars, 0, 1, msgX, msgY);
}
public Strand getStrand() {
return strand;
}
public void setStrand(Strand strand) {
this.strand = strand;
}
/**
* @author Damon May
* This class draws three amino acid bands representing the 3-frame translation of one strand
* of the associated SequenceTrack
*/
public static class TranslatedSequenceDrawer {
public static final int HEIGHT_PER_BAND = 14;
public static final int TOTAL_HEIGHT = 3 * HEIGHT_PER_BAND;
//alternating colors for aminoacids
public static final Color AA_COLOR_1 = new Color(128, 128, 128);
public static final Color AA_COLOR_2 = new Color(170, 170, 170);
public static final Color AA_FONT_COLOR = Color.WHITE;
//minimum font size for drawing AA characters
public static final int MIN_FONT_SIZE = 6;
//minimum vertical buffer around AA characters in band
public static final int MIN_FONT_VBUFFER = 1;
//ideal vertical buffer around AA characters in band
public static final int IDEAL_FONT_VBUFFER = 2;
protected static final Color STOP_CODON_COLOR = Color.RED;
protected static final Color METHIONINE_COLOR = Color.GREEN;
protected static final Color NUCLEOTIDE_SEPARATOR_COLOR = new Color(150, 150, 150, 120);
/**
* @param context
* @param start Must be the first base involved in any codon that's even partially visible
* @param trackRectangle
* @param seq
*/
public void draw(RenderContext context, int start, Rectangle trackRectangle, byte[] seq, Strand strand) {
//each band gets 1/3 of the height, rounded
int idealHeightPerBand = trackRectangle.height / 3;
//In this situation, band height is more equal if we tweak things a bit
if (trackRectangle.height % 3 == 2)
idealHeightPerBand++;
int minHeightPerBand = Math.min(idealHeightPerBand, trackRectangle.height - (2 * idealHeightPerBand));
double locScale = context.getScale();
double origin = context.getOrigin();
//Figure out the dimensions of a single box containing an aminoacid, at this zoom
int oneAcidBoxWidth = getPixelFromChromosomeLocation(context.getChr(), 3, origin, locScale) -
getPixelFromChromosomeLocation(context.getChr(), 0, origin, locScale) + 1;
int oneAcidBoxMinDimension = Math.min(oneAcidBoxWidth, minHeightPerBand);
//Calculate the font size. If that's less than MIN_FONT_SIZE, we won't draw amino acids
int fontSize = 0;
boolean shouldDrawLetters = false;
if (oneAcidBoxMinDimension >= 2 * MIN_FONT_VBUFFER + MIN_FONT_SIZE) {
int idealFontSize = oneAcidBoxMinDimension - 2 * IDEAL_FONT_VBUFFER;
fontSize = Math.max(idealFontSize, MIN_FONT_SIZE);
shouldDrawLetters = true;
}
boolean shouldDrawNucleotideLines = shouldDrawLetters && oneAcidBoxWidth >= 2.5 * fontSize;
Rectangle bandRectangle = new Rectangle(trackRectangle.x, 0, trackRectangle.width, 0);
int heightAlreadyUsed = 0;
//rf 0
bandRectangle.y = trackRectangle.y;
bandRectangle.height = idealHeightPerBand;
heightAlreadyUsed += bandRectangle.height;
//This set collects the X positions for nucleotide lines, if we choose to draw them.
//Technically we could calculate these, but I haven't managed to do that without some wiggle
Set<Integer> nucleotideLineXPositions = new HashSet<Integer>();
//only draw nucleotide lines the last time this is called
drawOneTranslation(context, start, bandRectangle, 0, shouldDrawLetters, fontSize,
nucleotideLineXPositions, seq, strand);
//rf 1
bandRectangle.y = trackRectangle.y + heightAlreadyUsed;
bandRectangle.height = idealHeightPerBand;
heightAlreadyUsed += bandRectangle.height;
drawOneTranslation(context, start, bandRectangle, 1, shouldDrawLetters, fontSize,
nucleotideLineXPositions, seq, strand);
//rf 2
bandRectangle.y = trackRectangle.y + heightAlreadyUsed;
bandRectangle.height = trackRectangle.height - heightAlreadyUsed;
drawOneTranslation(context, start, bandRectangle, 2, shouldDrawLetters, fontSize,
nucleotideLineXPositions, seq, strand);
if (shouldDrawNucleotideLines) {
Graphics2D graphicsForNucleotideLines = context.getGraphic2DForColor(NUCLEOTIDE_SEPARATOR_COLOR);
//use a dashed stroke
graphicsForNucleotideLines.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
0, new float[]{1, 2}, 0));
int topYCoord = trackRectangle.y - 1;
for (int xVal : nucleotideLineXPositions) {
if (xVal >= trackRectangle.x && xVal <= trackRectangle.x + trackRectangle.width)
graphicsForNucleotideLines.drawLine(xVal,
topYCoord,
xVal, topYCoord + trackRectangle.height);
}
}
}
/**
* Draw the band representing a translation of the sequence in one reading frame
*
* @param context
* @param start the index of the first base in seq. Should be the first nucleotide that's in a codon
* that's even partially visible, in any frame
* @param bandRectangle
* @param readingFrame
* @param shouldDrawLetters
* @param fontSize
* @param nucleotideLineXPositions a Set that will accrue all of the x positions that we define here
* @param seq nucleotide sequence starting at start
* for the beginning and end of aminoacid boxes
*/
protected void drawOneTranslation(RenderContext context, int start,
Rectangle bandRectangle, int readingFrame,
boolean shouldDrawLetters, int fontSize,
Set<Integer> nucleotideLineXPositions, byte[] seq,
Strand strand) {
double locScale = context.getScale();
double origin = context.getOrigin();
Graphics2D fontGraphics = (Graphics2D) context.getGraphic2DForColor(AA_FONT_COLOR).create();
//The start location of the first codon that overlaps this region
int readingFrameOfFullSeq = start % 3;
int indexOfFirstCodonStart = readingFrame - readingFrameOfFullSeq;
if (indexOfFirstCodonStart < 0)
indexOfFirstCodonStart += 3;
if (seq != null && seq.length > 0) {
Graphics2D g = (Graphics2D) context.getGraphics().create();
String nucSequence = new String(seq, indexOfFirstCodonStart,
seq.length - indexOfFirstCodonStart);
java.util.List<AminoAcid> acids = AminoAcidManager.getAminoAcids(nucSequence, strand);
// Set the start position of this amino acid.
AminoAcidSequence aaSequence = new AminoAcidSequence(strand, start + indexOfFirstCodonStart, acids);
if ((aaSequence != null) && aaSequence.hasNonNullSequence()) {
//This rectangle holds a single AA glyph. x and width will be updated in the for loop
Rectangle aaRect = new Rectangle(0, bandRectangle.y, 1, bandRectangle.height);
//start position for this amino acid. Will increment in for loop below
int aaSeqStartPosition = aaSequence.getStartPosition();
//calculated oddness or evenness of first amino acid
int firstFullAcidIndex = (int) Math.floor((aaSeqStartPosition - readingFrame) / 3);
boolean odd = (firstFullAcidIndex % 2) == 1;
if (shouldDrawLetters) {
Font f = FontManager.getScalableFont(Font.BOLD, fontSize);
g.setFont(f);
}
for (AminoAcid acid : aaSequence.getSequence()) {
if (acid != null) {
//calculate x pixel boundaries of this AA rectangle
int px = getPixelFromChromosomeLocation(context.getChr(), aaSeqStartPosition, origin, locScale);
int px2 = getPixelFromChromosomeLocation(context.getChr(), aaSeqStartPosition + 3,
origin, locScale);
//if x boundaries of this AA overlap the band rectangle
if ((px <= bandRectangle.getMaxX()) && (px2 >= bandRectangle.getX())) {
aaRect.x = px;
aaRect.width = px2 - px;
nucleotideLineXPositions.add(aaRect.x);
nucleotideLineXPositions.add(aaRect.x + aaRect.width);
Graphics2D bgGraphics =
context.getGraphic2DForColor(getColorForAminoAcid(acid.getSymbol(), odd));
bgGraphics.fill(aaRect);
if (shouldDrawLetters) {
String acidString = new String(new char[]{acid.getSymbol()});
GraphicUtils.drawCenteredText(acidString, aaRect, fontGraphics);
}
}
//need to switch oddness whether we displayed the AA or not,
//because oddness is calculated from first AA
odd = !odd;
aaSeqStartPosition += 3;
}
}
}
}
}
protected Color getColorForAminoAcid(char acidSymbol, boolean odd) {
switch (acidSymbol) {
case 'M':
return METHIONINE_COLOR;
case 'X':
return STOP_CODON_COLOR;
default:
return odd ? AA_COLOR_1 : AA_COLOR_2;
}
}
protected int getPixelFromChromosomeLocation(String chr, int chromosomeLocation, double origin,
double locationScale) {
return (int) Math.round((chromosomeLocation - origin) / locationScale);
}
public Color getDefaultColor() {
return Color.BLACK;
}
}
}
| true | true | public void draw(RenderContext context, Rectangle trackRectangle,
boolean showColorSpace, boolean showTranslation) {
if (context.getScale() >= MAX_SCALE_FOR_RENDER) {
// Zoomed out too far to see sequences. This can happen when in gene list view and one of the frames
// is zoomed in but others are not
context.getGraphic2DForColor(UIConstants.VERY_LIGHT_GRAY).fill(trackRectangle);
} else {
double locScale = context.getScale();
double origin = context.getOrigin();
String chr = context.getChr();
String genome = context.getGenomeId();
//The location of the first base that is loaded, which may include padding around what's visible
int start = Math.max(0, (int) origin - 1);
//The location of the last base that is loaded
int end = (int) (origin + trackRectangle.width * locScale) + 1;
if (end <= start) return;
int firstVisibleNucleotideStart = start;
int lastVisibleNucleotideEnd = end;
int firstCodonOffset = 0;
int lastCodonOffset = 0;
//If we're translating, we need to start with the first bp of the first codon, in frame 3, and
//end with the last bp of the last codon, in frame 1
if (showTranslation) {
if (start > 1) {
firstCodonOffset = 2;
start -= firstCodonOffset;
}
lastCodonOffset = 2;
end += lastCodonOffset;
}
byte[] seq = SequenceManager.readSequence(genome, chr, start, end);
//The combined height of sequence and (optionally) colorspace bands
int untranslatedSequenceHeight = (int) trackRectangle.getHeight();
if (showTranslation) {
untranslatedSequenceHeight = showColorSpace ? (int) trackRectangle.getHeight() / 5 * 2 :
(int) (trackRectangle.getHeight() / 4);
// Draw translated sequence
Rectangle translatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y + untranslatedSequenceHeight,
(int) trackRectangle.getWidth(), (int) trackRectangle.getHeight() - untranslatedSequenceHeight);
if (context.getScale() < 5) {
translatedSequenceDrawer.draw(context, start, translatedSequenceRect, seq, strand);
}
}
//Rectangle containing the sequence and (optionally) colorspace bands
Rectangle untranslatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y,
(int) trackRectangle.getWidth(), untranslatedSequenceHeight);
byte[] seqCS = null;
if (showColorSpace) {
seqCS = SOLIDUtils.convertToColorSpace(seq);
}
if (seq != null && seq.length > 0) {
int hCS = (showColorSpace ? untranslatedSequenceRect.height / 2 : 0);
int yBase = hCS + untranslatedSequenceRect.y + 2;
int yCS = untranslatedSequenceRect.y + 2;
int dY = (showColorSpace ? hCS : untranslatedSequenceRect.height) - 4;
int dX = (int) (1.0 / locScale);
// Create a graphics to use
Graphics2D g = (Graphics2D) context.getGraphics().create();
//dhmay adding check for adequate track height
int fontSize = Math.min(untranslatedSequenceRect.height, Math.min(dX, 12));
if (fontSize >= 8) {
Font f = FontManager.getScalableFont(Font.BOLD, fontSize);
g.setFont(f);
}
// Loop through base pair coordinates
int lastPx0 = -1;
int scale = Math.max(0, (int) context.getScale() - 1);
for (int loc = firstVisibleNucleotideStart; loc < lastVisibleNucleotideEnd; loc += scale) {
for (; loc < lastVisibleNucleotideEnd; loc++) {
int idx = loc - start;
int pX0 = (int) ((loc - origin) / locScale);
if (pX0 > lastPx0) {
lastPx0 = pX0;
char c = (char) seq[idx];
if (Strand.NEGATIVE.equals(strand))
c = complementChar(c);
Color color = nucleotideColors.get(c);
if (fontSize >= 8) {
if (color == null) {
color = Color.black;
}
g.setColor(color);
drawCenteredText(g, new char[]{c}, pX0, yBase + 2, dX, dY - 2);
if (showColorSpace) {
// draw color space #. Color space is shifted to be between bases as it represents
// two bases.
g.setColor(Color.black);
String cCS = String.valueOf(seqCS[idx]);
drawCenteredText(g, cCS.toCharArray(), pX0 - dX / 2, yCS + 2, dX, dY - 2);
}
} else {
int bw = Math.max(1, dX - 1);
if (color != null) {
g.setColor(color);
g.fillRect(pX0, yBase, bw, dY);
}
}
}
break;
}
}
}
}
}
| public void draw(RenderContext context, Rectangle trackRectangle,
boolean showColorSpace, boolean showTranslation) {
if (context.getScale() >= MAX_SCALE_FOR_RENDER) {
// Zoomed out too far to see sequences. This can happen when in gene list view and one of the frames
// is zoomed in but others are not
context.getGraphic2DForColor(UIConstants.VERY_LIGHT_GRAY).fill(trackRectangle);
} else {
double locScale = context.getScale();
double origin = context.getOrigin();
String chr = context.getChr();
String genome = context.getGenomeId();
//The location of the first base that is loaded, which may include padding around what's visible
int start = Math.max(0, (int) origin - 1);
//The location of the last base that is loaded
int end = (int) (origin + trackRectangle.width * locScale) + 1;
if (end <= start) return;
int firstVisibleNucleotideStart = start;
int lastVisibleNucleotideEnd = end;
int firstCodonOffset = 0;
int lastCodonOffset = 0;
//If we're translating, we need to start with the first bp of the first codon, in frame 3, and
//end with the last bp of the last codon, in frame 1
if (showTranslation) {
if (start > 1) {
firstCodonOffset = 2;
start -= firstCodonOffset;
}
lastCodonOffset = 2;
end += lastCodonOffset;
}
byte[] seq = SequenceManager.readSequence(genome, chr, start, end);
//The combined height of sequence and (optionally) colorspace bands
int untranslatedSequenceHeight = (int) trackRectangle.getHeight();
if (showTranslation) {
untranslatedSequenceHeight = showColorSpace ? (int) trackRectangle.getHeight() / 5 * 2 :
(int) (trackRectangle.getHeight() / 4);
// Draw translated sequence
Rectangle translatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y + untranslatedSequenceHeight,
(int) trackRectangle.getWidth(), (int) trackRectangle.getHeight() - untranslatedSequenceHeight);
if (context.getScale() < 5) {
translatedSequenceDrawer.draw(context, start, translatedSequenceRect, seq, strand);
}
}
//Rectangle containing the sequence and (optionally) colorspace bands
Rectangle untranslatedSequenceRect = new Rectangle(trackRectangle.x, trackRectangle.y,
(int) trackRectangle.getWidth(), untranslatedSequenceHeight);
byte[] seqCS = null;
if (showColorSpace) {
seqCS = SOLIDUtils.convertToColorSpace(seq);
}
if (seq != null && seq.length > 0) {
int hCS = (showColorSpace ? untranslatedSequenceRect.height / 2 : 0);
int yBase = hCS + untranslatedSequenceRect.y + 2;
int yCS = untranslatedSequenceRect.y + 2;
int dY = (showColorSpace ? hCS : untranslatedSequenceRect.height) - 4;
int dX = (int) (1.0 / locScale);
// Create a graphics to use
Graphics2D g = (Graphics2D) context.getGraphics().create();
//dhmay adding check for adequate track height
int fontSize = Math.min(untranslatedSequenceRect.height, Math.min(dX, 12));
if (fontSize >= 8) {
Font f = FontManager.getScalableFont(Font.BOLD, fontSize);
g.setFont(f);
}
// Loop through base pair coordinates
int lastPx0 = -1;
int scale = Math.max(1, (int) context.getScale());
for (int loc = firstVisibleNucleotideStart; loc < lastVisibleNucleotideEnd; loc += scale) {
for (; loc < lastVisibleNucleotideEnd; loc++) {
int idx = loc - start;
int pX0 = (int) ((loc - origin) / locScale);
if (pX0 > lastPx0) {
lastPx0 = pX0;
char c = (char) seq[idx];
if (Strand.NEGATIVE.equals(strand))
c = complementChar(c);
Color color = nucleotideColors.get(c);
if (fontSize >= 8) {
if (color == null) {
color = Color.black;
}
g.setColor(color);
drawCenteredText(g, new char[]{c}, pX0, yBase + 2, dX, dY - 2);
if (showColorSpace) {
// draw color space #. Color space is shifted to be between bases as it represents
// two bases.
g.setColor(Color.black);
String cCS = String.valueOf(seqCS[idx]);
drawCenteredText(g, cCS.toCharArray(), pX0 - dX / 2, yCS + 2, dX, dY - 2);
}
} else {
int bw = Math.max(1, dX - 1);
if (color != null) {
g.setColor(color);
g.fillRect(pX0, yBase, bw, dY);
}
}
}
break;
}
}
}
}
}
|
diff --git a/src/main/java/me/ase34/citylanterns/CityLanterns.java b/src/main/java/me/ase34/citylanterns/CityLanterns.java
index aa79e6b..a427996 100644
--- a/src/main/java/me/ase34/citylanterns/CityLanterns.java
+++ b/src/main/java/me/ase34/citylanterns/CityLanterns.java
@@ -1,75 +1,76 @@
package me.ase34.citylanterns;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import me.ase34.citylanterns.executor.SelectLanternExecutor;
import me.ase34.citylanterns.listener.LanternRedstoneListener;
import me.ase34.citylanterns.listener.LanternSelectListener;
import me.ase34.citylanterns.runnable.LanternUpdateThread;
import me.ase34.citylanterns.storage.LanternFileStorage;
import me.ase34.citylanterns.storage.LanternStorage;
import org.bukkit.Location;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.Metrics;
public class CityLanterns extends JavaPlugin {
private List<String> selectingPlayers;
private List<Location> lanterns;
private LanternStorage storage;
@Override
public void onDisable() {
try {
storage.save(lanterns);
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An Exception occured!", e);
return;
}
getLogger().info(getDescription().getFullName() + " by " + getDescription().getAuthors().get(0) + " disabled!");
}
@Override
public void onEnable() {
try {
getDataFolder().mkdir();
+ saveDefaultConfig();
File storageFile = new File(getDataFolder(), "storage.txt");
storageFile.createNewFile();
storage = new LanternFileStorage(storageFile);
lanterns = storage.load();
selectingPlayers = new ArrayList<String>();
getCommand("selectlanterns").setExecutor(new SelectLanternExecutor(this));
getServer().getPluginManager().registerEvents(new LanternSelectListener(this), this);
getServer().getPluginManager().registerEvents(new LanternRedstoneListener(this), this);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new LanternUpdateThread(this), 0, 1);
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
getServer().getLogger().log(Level.WARNING, "Submitting plugin metrics failed: ", e);
}
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An Exception occured! Aborting plugin start.", e);
this.getServer().getPluginManager().disablePlugin(this);
return;
}
getLogger().info(getDescription().getFullName() + " by " + getDescription().getAuthors().get(0) + " enabled!");
}
public List<String> getSelectingPlayers() {
return selectingPlayers;
}
public List<Location> getLanterns() {
return lanterns;
}
}
| true | true | public void onEnable() {
try {
getDataFolder().mkdir();
File storageFile = new File(getDataFolder(), "storage.txt");
storageFile.createNewFile();
storage = new LanternFileStorage(storageFile);
lanterns = storage.load();
selectingPlayers = new ArrayList<String>();
getCommand("selectlanterns").setExecutor(new SelectLanternExecutor(this));
getServer().getPluginManager().registerEvents(new LanternSelectListener(this), this);
getServer().getPluginManager().registerEvents(new LanternRedstoneListener(this), this);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new LanternUpdateThread(this), 0, 1);
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
getServer().getLogger().log(Level.WARNING, "Submitting plugin metrics failed: ", e);
}
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An Exception occured! Aborting plugin start.", e);
this.getServer().getPluginManager().disablePlugin(this);
return;
}
getLogger().info(getDescription().getFullName() + " by " + getDescription().getAuthors().get(0) + " enabled!");
}
| public void onEnable() {
try {
getDataFolder().mkdir();
saveDefaultConfig();
File storageFile = new File(getDataFolder(), "storage.txt");
storageFile.createNewFile();
storage = new LanternFileStorage(storageFile);
lanterns = storage.load();
selectingPlayers = new ArrayList<String>();
getCommand("selectlanterns").setExecutor(new SelectLanternExecutor(this));
getServer().getPluginManager().registerEvents(new LanternSelectListener(this), this);
getServer().getPluginManager().registerEvents(new LanternRedstoneListener(this), this);
getServer().getScheduler().scheduleSyncRepeatingTask(this, new LanternUpdateThread(this), 0, 1);
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
getServer().getLogger().log(Level.WARNING, "Submitting plugin metrics failed: ", e);
}
} catch (Exception e) {
getLogger().log(Level.SEVERE, "An Exception occured! Aborting plugin start.", e);
this.getServer().getPluginManager().disablePlugin(this);
return;
}
getLogger().info(getDescription().getFullName() + " by " + getDescription().getAuthors().get(0) + " enabled!");
}
|
diff --git a/src/main/java/net/ae97/totalpermissions/lang/Cipher.java b/src/main/java/net/ae97/totalpermissions/lang/Cipher.java
index 87843b2..860c769 100644
--- a/src/main/java/net/ae97/totalpermissions/lang/Cipher.java
+++ b/src/main/java/net/ae97/totalpermissions/lang/Cipher.java
@@ -1,74 +1,75 @@
/*
* Copyright (C) 2013 AE97
*
* 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 net.ae97.totalpermissions.lang;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Level;
import net.ae97.totalpermissions.TotalPermissions;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
/**
* @version 0.2
* @author 1Rogue
* @since 0.2
*/
public class Cipher {
private YamlConfiguration langFile;
private final String langFileLoc = "https://raw.github.com/AE97/TotalPermissions/master/lang/";
public Cipher(String language) {
language += ".yml";
try {
- this.setLangFile(YamlConfiguration.loadConfiguration(TotalPermissions.getPlugin().getResource(language)));
+ InputStream temp = TotalPermissions.getPlugin().getResource(language);
+ this.setLangFile(YamlConfiguration.loadConfiguration(temp));
} catch (NullPointerException e) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Language resource file is NULL! Trying web files instead...");
try {
URL upstr = new URL(langFileLoc + language);
InputStream langs = upstr.openStream();
this.setLangFile(YamlConfiguration.loadConfiguration(langs));
langs.close();
} catch (Exception ex) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Error grabbing language file from web!");
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Defaulting to english (en_US)");
this.setLangFile(YamlConfiguration.loadConfiguration(TotalPermissions.getPlugin().getResource("en_US.yml")));
}
}
}
private void setLangFile(YamlConfiguration file) {
langFile = file;
}
public FileConfiguration getLangFile() {
return langFile;
}
public String getString(String path) {
return getString(path, "", "");
}
public String getString(String path, String varOne) {
return getString(path, varOne, "");
}
public String getString(String path, String varOne, String varTwo) {
return langFile.getString(path).replace("{0}", varOne).replace("{1}", varTwo);
}
}
| true | true | public Cipher(String language) {
language += ".yml";
try {
this.setLangFile(YamlConfiguration.loadConfiguration(TotalPermissions.getPlugin().getResource(language)));
} catch (NullPointerException e) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Language resource file is NULL! Trying web files instead...");
try {
URL upstr = new URL(langFileLoc + language);
InputStream langs = upstr.openStream();
this.setLangFile(YamlConfiguration.loadConfiguration(langs));
langs.close();
} catch (Exception ex) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Error grabbing language file from web!");
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Defaulting to english (en_US)");
this.setLangFile(YamlConfiguration.loadConfiguration(TotalPermissions.getPlugin().getResource("en_US.yml")));
}
}
}
| public Cipher(String language) {
language += ".yml";
try {
InputStream temp = TotalPermissions.getPlugin().getResource(language);
this.setLangFile(YamlConfiguration.loadConfiguration(temp));
} catch (NullPointerException e) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Language resource file is NULL! Trying web files instead...");
try {
URL upstr = new URL(langFileLoc + language);
InputStream langs = upstr.openStream();
this.setLangFile(YamlConfiguration.loadConfiguration(langs));
langs.close();
} catch (Exception ex) {
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Error grabbing language file from web!");
TotalPermissions.getPlugin().getLogger().log(Level.SEVERE, "Defaulting to english (en_US)");
this.setLangFile(YamlConfiguration.loadConfiguration(TotalPermissions.getPlugin().getResource("en_US.yml")));
}
}
}
|
diff --git a/src/java/org/codehaus/groovy/grails/documentation/MetadataGeneratingMetaClassCreationHandle.java b/src/java/org/codehaus/groovy/grails/documentation/MetadataGeneratingMetaClassCreationHandle.java
index 707aa7b81..92989f076 100644
--- a/src/java/org/codehaus/groovy/grails/documentation/MetadataGeneratingMetaClassCreationHandle.java
+++ b/src/java/org/codehaus/groovy/grails/documentation/MetadataGeneratingMetaClassCreationHandle.java
@@ -1,88 +1,89 @@
/* Copyright 2004-2005 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.codehaus.groovy.grails.documentation;
import groovy.lang.*;
import org.codehaus.groovy.reflection.ClassInfo;
/**
* Used to enable the Metadata generating EMC creation handle
*
* @author Graeme Rocher
* @since 1.2
*/
public class MetadataGeneratingMetaClassCreationHandle extends ExpandoMetaClassCreationHandle {
private static final MetadataGeneratingMetaClassCreationHandle instance = new MetadataGeneratingMetaClassCreationHandle();
/* (non-Javadoc)
* @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle#create(java.lang.Class, groovy.lang.MetaClassRegistry)
*/
protected MetaClass createNormalMetaClass(Class theClass, MetaClassRegistry registry) {
if(!isExcludedClass(theClass)) {
return new MetadataGeneratingExpandoMetaClass(theClass);
}
else {
return super.createNormalMetaClass(theClass, registry);
}
}
public static boolean isExcludedClass(Class theClass) {
return theClass == MetadataGeneratingExpandoMetaClass.class
|| theClass == ExpandoMetaClass.class
|| theClass == DocumentationContext.class
|| theClass == DocumentedMethod.class
|| theClass == DocumentedProperty.class
|| theClass == DocumentedElement.class
|| theClass == DocumentationContextThreadLocal.class
+ || theClass == Boolean.class
|| Closure.class.isAssignableFrom(theClass);
}
/**
* Registers a modified ExpandoMetaClass with the creation handle
*
* @param emc The EMC
*/
public void registerModifiedMetaClass(ExpandoMetaClass emc) {
final Class klazz = emc.getJavaClass();
GroovySystem.getMetaClassRegistry().setMetaClass(klazz,emc);
}
public boolean hasModifiedMetaClass(ExpandoMetaClass emc) {
return emc.getClassInfo().getModifiedExpando() != null;
}
/**
* <p>Enables the ExpandoMetaClassCreationHandle with the registry
*
* <code>ExpandoMetaClassCreationHandle.enable();</code>
*
*/
public static void enable() {
final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
if (metaClassRegistry.getMetaClassCreationHandler() != instance) {
ClassInfo.clearModifiedExpandos();
metaClassRegistry.setMetaClassCreationHandle(instance);
}
}
public static void disable() {
final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry();
if (metaClassRegistry.getMetaClassCreationHandler() == instance) {
ClassInfo.clearModifiedExpandos();
metaClassRegistry.setMetaClassCreationHandle(new MetaClassRegistry.MetaClassCreationHandle());
}
}
}
| true | true | public static boolean isExcludedClass(Class theClass) {
return theClass == MetadataGeneratingExpandoMetaClass.class
|| theClass == ExpandoMetaClass.class
|| theClass == DocumentationContext.class
|| theClass == DocumentedMethod.class
|| theClass == DocumentedProperty.class
|| theClass == DocumentedElement.class
|| theClass == DocumentationContextThreadLocal.class
|| Closure.class.isAssignableFrom(theClass);
}
| public static boolean isExcludedClass(Class theClass) {
return theClass == MetadataGeneratingExpandoMetaClass.class
|| theClass == ExpandoMetaClass.class
|| theClass == DocumentationContext.class
|| theClass == DocumentedMethod.class
|| theClass == DocumentedProperty.class
|| theClass == DocumentedElement.class
|| theClass == DocumentationContextThreadLocal.class
|| theClass == Boolean.class
|| Closure.class.isAssignableFrom(theClass);
}
|
diff --git a/src/net/nightwhistler/pageturner/view/bookview/TextLoader.java b/src/net/nightwhistler/pageturner/view/bookview/TextLoader.java
index 6508853..4bc1466 100644
--- a/src/net/nightwhistler/pageturner/view/bookview/TextLoader.java
+++ b/src/net/nightwhistler/pageturner/view/bookview/TextLoader.java
@@ -1,285 +1,285 @@
/*
* Copyright (C) 2013 Alex Kuiper
*
* This file is part of PageTurner
*
* PageTurner 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.
*
* PageTurner 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 PageTurner. If not, see <http://www.gnu.org/licenses/>.*
*/
package net.nightwhistler.pageturner.view.bookview;
import android.text.Spannable;
import com.google.inject.Inject;
import net.nightwhistler.htmlspanner.FontFamily;
import net.nightwhistler.htmlspanner.HtmlSpanner;
import net.nightwhistler.htmlspanner.TagNodeHandler;
import net.nightwhistler.pageturner.Configuration;
import net.nightwhistler.pageturner.view.FastBitmapDrawable;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.MediaType;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;
import nl.siegmann.epublib.service.MediatypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* Singleton storage for opened book and rendered text.
*
* Optimization in case of rotation of the screen.
*/
public class TextLoader implements LinkTagHandler.LinkCallBack {
/**
* We start clearing the cache if memory usage exceeds 75%.
*/
private static final double CACHE_CLEAR_THRESHOLD = 0.75;
private String currentFile;
private Book currentBook;
private Map<String, Spannable> renderedText = new HashMap<String, Spannable>();
private Map<String, FastBitmapDrawable> imageCache = new HashMap<String, FastBitmapDrawable>();
private Map<String, Map<String, Integer>> anchors = new HashMap<String, Map<String, Integer>>();
private List<AnchorHandler> anchorHandlers = new ArrayList<AnchorHandler>();
private static final Logger LOG = LoggerFactory.getLogger("TextLoader");
private HtmlSpanner htmlSpanner;
private LinkTagHandler.LinkCallBack linkCallBack;
@Inject
public void setHtmlSpanner(HtmlSpanner spanner) {
this.htmlSpanner = spanner;
spanner.registerHandler("a", registerAnchorHandler(new LinkTagHandler(this)));
spanner.registerHandler("h1",
registerAnchorHandler(spanner.getHandlerFor("h1")));
spanner.registerHandler("h2",
registerAnchorHandler(spanner.getHandlerFor("h2")));
spanner.registerHandler("h3",
registerAnchorHandler(spanner.getHandlerFor("h3")));
spanner.registerHandler("h4",
registerAnchorHandler(spanner.getHandlerFor("h4")));
spanner.registerHandler("h5",
registerAnchorHandler(spanner.getHandlerFor("h5")));
spanner.registerHandler("h6",
registerAnchorHandler(spanner.getHandlerFor("h6")));
spanner.registerHandler("p",
registerAnchorHandler(spanner.getHandlerFor("p")));
}
private AnchorHandler registerAnchorHandler( TagNodeHandler wrapThis ) {
AnchorHandler handler = new AnchorHandler(wrapThis);
anchorHandlers.add(handler);
return handler;
}
@Override
public void linkClicked(String href) {
if ( linkCallBack != null ) {
linkCallBack.linkClicked(href);
}
}
public void setLinkCallBack( LinkTagHandler.LinkCallBack callBack ) {
this.linkCallBack = callBack;
}
public void registerTagNodeHandler( String tag, TagNodeHandler handler ) {
this.htmlSpanner.registerHandler(tag, handler);
}
public Book initBook(String fileName) throws IOException {
if (fileName == null) {
throw new IOException("No file-name specified.");
}
if ( fileName.equals(currentFile) ) {
LOG.debug("Returning cached Book for fileName " + currentFile );
return currentBook;
}
closeCurrentBook();
this.anchors = new HashMap<String, Map<String, Integer>>();
// read epub file
EpubReader epubReader = new EpubReader();
Book newBook = epubReader.readEpubLazy(fileName, "UTF-8");
this.currentBook = newBook;
this.currentFile = fileName;
return newBook;
}
public Integer getAnchor( String href, String anchor ) {
if ( this.anchors.containsKey(href) ) {
Map<String, Integer> nestedMap = this.anchors.get( href );
return nestedMap.get(anchor);
}
return null;
}
public void setFontFamily(FontFamily family) {
this.htmlSpanner.setDefaultFont(family);
}
public void setSerifFontFamily(FontFamily family) {
this.htmlSpanner.setSerifFont(family);
}
public void setSansSerifFontFamily(FontFamily family) {
this.htmlSpanner.setSansSerifFont(family);
}
public void setStripWhiteSpace(boolean stripWhiteSpace) {
this.htmlSpanner.setStripExtraWhiteSpace(stripWhiteSpace);
}
public FastBitmapDrawable getCachedImage( String href ) {
return imageCache.get( href );
}
public boolean hasCachedImage( String href ) {
return imageCache.containsKey(href);
}
public void storeImageInChache( String href, FastBitmapDrawable drawable ) {
this.imageCache.put(href, drawable);
}
private void registerNewAnchor(String href, String anchor, int position ) {
if ( ! anchors.containsKey(href)) {
anchors.put(href, new HashMap<String, Integer>());
}
anchors.get(href).put(anchor, position);
}
public boolean hasCachedText( Resource resource ) {
return renderedText.containsKey(resource.getHref());
}
public Spannable getText( final Resource resource ) throws IOException {
if ( hasCachedText(resource) ) {
LOG.debug("Returning cached text for href " + resource.getHref() );
return renderedText.get(resource.getHref());
}
AnchorHandler.AnchorCallback callback = new AnchorHandler.AnchorCallback() {
@Override
public void registerAnchor(String anchor, int position) {
registerNewAnchor(resource.getHref(), anchor, position);
}
};
for ( AnchorHandler handler: this.anchorHandlers ) {
handler.setCallback(callback);
}
double memoryUsage = Configuration.getMemoryUsage();
double bitmapUsage = Configuration.getBitmapMemoryUsage();
LOG.debug("Current memory usage is " + (int) (memoryUsage * 100) + "%" );
LOG.debug("Current bitmap memory usage is " + (int) (bitmapUsage * 100) + "%" );
//If memory usage gets over the threshold, try to free up memory
if ( memoryUsage > CACHE_CLEAR_THRESHOLD || bitmapUsage > CACHE_CLEAR_THRESHOLD) {
clearCachedText();
closeLazyLoadedResources();
}
boolean shouldClose = false;
Resource res = resource;
//If it's already in memory, use that. If not, create a copy
//that we can safely close after using it
if ( ! resource.isInitialized() ) {
- res = new Resource( this.currentFile, res.getSize(), res.getHref() );
+ res = new Resource( this.currentFile, res.getSize(), res.getOriginalHref() );
shouldClose = true;
}
Spannable result = null;
try {
result = htmlSpanner.fromHtml(res.getReader());
} finally {
if ( shouldClose ) {
//We have the rendered version, so it's safe to close the resource
resource.close();
}
}
renderedText.put(res.getHref(), result);
return result;
}
private void closeLazyLoadedResources() {
if ( currentBook != null ) {
for ( Resource res: currentBook.getResources().getAll() ) {
res.close();
}
}
}
private void clearCachedText() {
clearImageCache();
anchors.clear();
renderedText.clear();
}
public void closeCurrentBook() {
if ( currentBook != null ) {
for ( Resource res: currentBook.getResources().getAll() ) {
res.setData(null); //Release the byte[] data.
}
}
currentBook = null;
currentFile = null;
renderedText.clear();
clearImageCache();
anchors.clear();
}
public void clearImageCache() {
for (Map.Entry<String, FastBitmapDrawable> draw : imageCache.entrySet()) {
draw.getValue().destroy();
}
imageCache.clear();
}
}
| true | true | public Spannable getText( final Resource resource ) throws IOException {
if ( hasCachedText(resource) ) {
LOG.debug("Returning cached text for href " + resource.getHref() );
return renderedText.get(resource.getHref());
}
AnchorHandler.AnchorCallback callback = new AnchorHandler.AnchorCallback() {
@Override
public void registerAnchor(String anchor, int position) {
registerNewAnchor(resource.getHref(), anchor, position);
}
};
for ( AnchorHandler handler: this.anchorHandlers ) {
handler.setCallback(callback);
}
double memoryUsage = Configuration.getMemoryUsage();
double bitmapUsage = Configuration.getBitmapMemoryUsage();
LOG.debug("Current memory usage is " + (int) (memoryUsage * 100) + "%" );
LOG.debug("Current bitmap memory usage is " + (int) (bitmapUsage * 100) + "%" );
//If memory usage gets over the threshold, try to free up memory
if ( memoryUsage > CACHE_CLEAR_THRESHOLD || bitmapUsage > CACHE_CLEAR_THRESHOLD) {
clearCachedText();
closeLazyLoadedResources();
}
boolean shouldClose = false;
Resource res = resource;
//If it's already in memory, use that. If not, create a copy
//that we can safely close after using it
if ( ! resource.isInitialized() ) {
res = new Resource( this.currentFile, res.getSize(), res.getHref() );
shouldClose = true;
}
Spannable result = null;
try {
result = htmlSpanner.fromHtml(res.getReader());
} finally {
if ( shouldClose ) {
//We have the rendered version, so it's safe to close the resource
resource.close();
}
}
renderedText.put(res.getHref(), result);
return result;
}
| public Spannable getText( final Resource resource ) throws IOException {
if ( hasCachedText(resource) ) {
LOG.debug("Returning cached text for href " + resource.getHref() );
return renderedText.get(resource.getHref());
}
AnchorHandler.AnchorCallback callback = new AnchorHandler.AnchorCallback() {
@Override
public void registerAnchor(String anchor, int position) {
registerNewAnchor(resource.getHref(), anchor, position);
}
};
for ( AnchorHandler handler: this.anchorHandlers ) {
handler.setCallback(callback);
}
double memoryUsage = Configuration.getMemoryUsage();
double bitmapUsage = Configuration.getBitmapMemoryUsage();
LOG.debug("Current memory usage is " + (int) (memoryUsage * 100) + "%" );
LOG.debug("Current bitmap memory usage is " + (int) (bitmapUsage * 100) + "%" );
//If memory usage gets over the threshold, try to free up memory
if ( memoryUsage > CACHE_CLEAR_THRESHOLD || bitmapUsage > CACHE_CLEAR_THRESHOLD) {
clearCachedText();
closeLazyLoadedResources();
}
boolean shouldClose = false;
Resource res = resource;
//If it's already in memory, use that. If not, create a copy
//that we can safely close after using it
if ( ! resource.isInitialized() ) {
res = new Resource( this.currentFile, res.getSize(), res.getOriginalHref() );
shouldClose = true;
}
Spannable result = null;
try {
result = htmlSpanner.fromHtml(res.getReader());
} finally {
if ( shouldClose ) {
//We have the rendered version, so it's safe to close the resource
resource.close();
}
}
renderedText.put(res.getHref(), result);
return result;
}
|
diff --git a/indexbuilder/src/test/java/uk/ac/ebi/gxa/index/builder/TestDefaultIndexBuilder.java b/indexbuilder/src/test/java/uk/ac/ebi/gxa/index/builder/TestDefaultIndexBuilder.java
index a6dc8de66..bb91d1d5e 100644
--- a/indexbuilder/src/test/java/uk/ac/ebi/gxa/index/builder/TestDefaultIndexBuilder.java
+++ b/indexbuilder/src/test/java/uk/ac/ebi/gxa/index/builder/TestDefaultIndexBuilder.java
@@ -1,220 +1,220 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.index.builder;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.core.CoreContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.xml.sax.SAXException;
import uk.ac.ebi.gxa.dao.AtlasDAOTestCase;
import uk.ac.ebi.gxa.index.SolrContainerFactory;
import uk.ac.ebi.gxa.index.builder.listener.IndexBuilderEvent;
import uk.ac.ebi.gxa.index.builder.listener.IndexBuilderListener;
import uk.ac.ebi.gxa.index.builder.service.ExperimentAtlasIndexBuilderService;
import uk.ac.ebi.gxa.index.builder.service.IndexBuilderService;
import uk.ac.ebi.gxa.utils.FileUtil;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.logging.LogManager;
/**
* A test case fo assessing whether the DefaultIndexBuilder class initializes correctly and can run a build of the index
* over some dummy data from the test database. Note that only very simple checks are run to ensure that some data has
* gone into the index. Precise implementations tests should be done on the individual index building services, not
* this class. This test is just to ensure clean startup and shutdown of the main index builder.
*
* @author Junit Generation Plugin for Maven, written by Tony Burdett
* @date 07-10-2009
*/
public class TestDefaultIndexBuilder extends AtlasDAOTestCase {
private File indexLocation;
private DefaultIndexBuilder indexBuilder;
private CoreContainer coreContainer;
private SolrServer exptServer;
private boolean buildFinished = false;
private final Logger log = LoggerFactory.getLogger(getClass());
public void setUp() throws Exception {
super.setUp();
try {
LogManager.getLogManager()
.readConfiguration(this.getClass().getClassLoader().getResourceAsStream("logging.properties"));
}
catch (Exception e) {
e.printStackTrace();
}
SLF4JBridgeHandler.install();
indexLocation =
new File("target" + File.separator + "test" + File.separator + "index");
System.out.println("Extracting index to " + indexLocation.getAbsolutePath());
createSOLRServers();
ExperimentAtlasIndexBuilderService eaibs = new ExperimentAtlasIndexBuilderService();
eaibs.setAtlasDAO(getAtlasDAO());
eaibs.setSolrServer(exptServer);
indexBuilder = new DefaultIndexBuilder();
indexBuilder.setIncludeIndexes(Collections.singletonList("experiments"));
indexBuilder.setServices(Collections.<IndexBuilderService>singletonList(eaibs));
}
public void tearDown() throws Exception {
super.tearDown();
// shutdown the indexBuilder and coreContainer if its not already been done
indexBuilder.shutdown();
if (coreContainer != null) {
coreContainer.shutdown();
}
// delete the index
if (indexLocation.exists() && !FileUtil.deleteDirectory(indexLocation)) {
log.warn("Failed to delete " + indexLocation.getAbsolutePath());
}
indexLocation = null;
indexBuilder = null;
}
public void createSOLRServers() {
try {
SolrContainerFactory solrContainerFactory = new SolrContainerFactory();
solrContainerFactory.setAtlasIndex(indexLocation);
solrContainerFactory.setTemplatePath("solr");
coreContainer = solrContainerFactory.createContainer();
// create an embedded solr server for experiments and genes from this container
exptServer = new EmbeddedSolrServer(coreContainer, "expt");
}
catch (IOException e) {
e.printStackTrace();
fail();
}
catch (SAXException e) {
e.printStackTrace();
fail();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
fail();
}
}
public void testStartup() {
try {
indexBuilder.startup();
// now try a repeat startup
indexBuilder.startup();
}
catch (IndexBuilderException e) {
e.printStackTrace();
fail();
}
}
public void testShutdown() {
try {
// try shutdown without startup
indexBuilder.shutdown();
// now startup
indexBuilder.startup();
// just check shutdown occurs cleanly, without throwing an exception
indexBuilder.shutdown();
}
catch (IndexBuilderException e) {
e.printStackTrace();
fail();
}
}
public void testBuildIndex() {
try {
indexBuilder.startup();
// run buildIndex
indexBuilder.doCommand(new IndexAllCommand(), new IndexBuilderListener() {
public void buildSuccess(IndexBuilderEvent event) {
try {
// now query the index for the stuff that is in the test DB
SolrQuery q = new SolrQuery("*:*");
q.setRows(10);
q.setFields("");
q.addSortField("id", SolrQuery.ORDER.asc);
QueryResponse queryResponse = exptServer.query(q);
SolrDocumentList documentList = queryResponse.getResults();
if (documentList == null || documentList.size() < 1) {
fail("No experiments available");
}
// just check we have 2 experiments - as this is the number in our dataset
int expected = getDataSet().getTable("A2_EXPERIMENT").getRowCount();
int actual = documentList.size();
assertEquals("Wrong number of docs: expected " + expected +
", actual " + actual, expected, actual);
} catch (Exception e) {
fail();
} finally {
buildFinished = true;
}
}
public void buildError(IndexBuilderEvent event) {
- fail();
buildFinished = true;
+ fail();
}
public void buildProgress(String progressStatus) {}
});
while(buildFinished != true) {
synchronized(this) { wait(100); };
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| false | true | public void testBuildIndex() {
try {
indexBuilder.startup();
// run buildIndex
indexBuilder.doCommand(new IndexAllCommand(), new IndexBuilderListener() {
public void buildSuccess(IndexBuilderEvent event) {
try {
// now query the index for the stuff that is in the test DB
SolrQuery q = new SolrQuery("*:*");
q.setRows(10);
q.setFields("");
q.addSortField("id", SolrQuery.ORDER.asc);
QueryResponse queryResponse = exptServer.query(q);
SolrDocumentList documentList = queryResponse.getResults();
if (documentList == null || documentList.size() < 1) {
fail("No experiments available");
}
// just check we have 2 experiments - as this is the number in our dataset
int expected = getDataSet().getTable("A2_EXPERIMENT").getRowCount();
int actual = documentList.size();
assertEquals("Wrong number of docs: expected " + expected +
", actual " + actual, expected, actual);
} catch (Exception e) {
fail();
} finally {
buildFinished = true;
}
}
public void buildError(IndexBuilderEvent event) {
fail();
buildFinished = true;
}
public void buildProgress(String progressStatus) {}
});
while(buildFinished != true) {
synchronized(this) { wait(100); };
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
| public void testBuildIndex() {
try {
indexBuilder.startup();
// run buildIndex
indexBuilder.doCommand(new IndexAllCommand(), new IndexBuilderListener() {
public void buildSuccess(IndexBuilderEvent event) {
try {
// now query the index for the stuff that is in the test DB
SolrQuery q = new SolrQuery("*:*");
q.setRows(10);
q.setFields("");
q.addSortField("id", SolrQuery.ORDER.asc);
QueryResponse queryResponse = exptServer.query(q);
SolrDocumentList documentList = queryResponse.getResults();
if (documentList == null || documentList.size() < 1) {
fail("No experiments available");
}
// just check we have 2 experiments - as this is the number in our dataset
int expected = getDataSet().getTable("A2_EXPERIMENT").getRowCount();
int actual = documentList.size();
assertEquals("Wrong number of docs: expected " + expected +
", actual " + actual, expected, actual);
} catch (Exception e) {
fail();
} finally {
buildFinished = true;
}
}
public void buildError(IndexBuilderEvent event) {
buildFinished = true;
fail();
}
public void buildProgress(String progressStatus) {}
});
while(buildFinished != true) {
synchronized(this) { wait(100); };
}
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
diff --git a/src/main/java/net/orange_server/orangeserver/utils/plugin/DynmapHandler.java b/src/main/java/net/orange_server/orangeserver/utils/plugin/DynmapHandler.java
index 8f95a2e..3ce811f 100644
--- a/src/main/java/net/orange_server/orangeserver/utils/plugin/DynmapHandler.java
+++ b/src/main/java/net/orange_server/orangeserver/utils/plugin/DynmapHandler.java
@@ -1,155 +1,157 @@
/**
* OrangeServer - Package: net.orange_server.orangeserver.utils.plugin
* Created: 2013/01/05 2:59:10
*/
package net.orange_server.orangeserver.utils.plugin;
import net.orange_server.orangeserver.OrangeServer;
import net.syamn.utils.LogUtil;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.dynmap.DynmapAPI;
import org.dynmap.Log;
import org.dynmap.markers.MarkerAPI;
/**
* DynmapHandler (DynmapHandler.java)
* @author syam(syamn)
*/
public class DynmapHandler {
private static boolean listenerActivated = false;
private static DynmapHandler instance;
public static DynmapHandler getInstance(){
return instance;
}
public static void dispose(){
instance = null;
}
public static void createInstance(){
instance = new DynmapHandler();
}
private final OrangeServer plugin;
private Plugin dynmap;
private DynmapAPI api;
private MarkerAPI markerapi;
private boolean activated = false;
/**
* コンストラクタ
*/
private DynmapHandler(){
this.plugin = OrangeServer.getInstance();
init();
}
/**
* 初期化
*/
public void init(){
// regist listener
if (!listenerActivated){
listenerActivated = true;
plugin.getServer().getPluginManager().registerEvents(new DynmapPluginListener(), plugin);
}
activate();
}
/**
* 有効化
*/
public void activate(){
if (activated) return;
// get dynmap
PluginManager pm = plugin.getServer().getPluginManager();
dynmap = pm.getPlugin("dynmap");
if (dynmap == null){
LogUtil.warning("Cannot find dynmap!");
+ return;
}
if (!dynmap.isEnabled()){
LogUtil.warning("Dynmap is not enabled!");
+ return;
}
// get api
api = (DynmapAPI) dynmap;
// get marker API
markerapi = api.getMarkerAPI();
if (markerapi == null){
Log.warning("Cannot loading Dynmap marker API!");
return;
}
// TODO do stuff..
// Activated!
activated = true;
LogUtil.info("Hooked to dynmap!");
}
/**
* 無効化
*/
public void deactivate(){
if (markerapi != null){
// TODO Clear all added markers
}
dynmap = null;
api = null;
markerapi = null;
activated = false;
}
/**
* dynmap上でのプレイヤー表示/非表示を切り変える
* @param player
* @param visible
*/
public void setPlayerVisiblity(final Player player, final boolean visible){
if (activated && api != null){
api.setPlayerVisiblity(player, visible);
}
}
/**
* 有効かどうかを返す
* @return
*/
public boolean isActivated(){
return activated;
}
/**
* Dynmapの有効を検出するリスナー
* DynmapPluginListener (DynmapHandler.java)
* @author syam(syamn)
*/
private class DynmapPluginListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPluginEnable(final PluginEnableEvent event) {
final Plugin plugin = event.getPlugin();
if (plugin.getDescription().getName().equals("dynmap")) {
activate();
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPluginDisable(final PluginDisableEvent event) {
final Plugin plugin = event.getPlugin();
if (plugin.getDescription().getName().equals("dynmap")) {
deactivate();
}
}
}
}
| false | true | public void activate(){
if (activated) return;
// get dynmap
PluginManager pm = plugin.getServer().getPluginManager();
dynmap = pm.getPlugin("dynmap");
if (dynmap == null){
LogUtil.warning("Cannot find dynmap!");
}
if (!dynmap.isEnabled()){
LogUtil.warning("Dynmap is not enabled!");
}
// get api
api = (DynmapAPI) dynmap;
// get marker API
markerapi = api.getMarkerAPI();
if (markerapi == null){
Log.warning("Cannot loading Dynmap marker API!");
return;
}
// TODO do stuff..
// Activated!
activated = true;
LogUtil.info("Hooked to dynmap!");
}
| public void activate(){
if (activated) return;
// get dynmap
PluginManager pm = plugin.getServer().getPluginManager();
dynmap = pm.getPlugin("dynmap");
if (dynmap == null){
LogUtil.warning("Cannot find dynmap!");
return;
}
if (!dynmap.isEnabled()){
LogUtil.warning("Dynmap is not enabled!");
return;
}
// get api
api = (DynmapAPI) dynmap;
// get marker API
markerapi = api.getMarkerAPI();
if (markerapi == null){
Log.warning("Cannot loading Dynmap marker API!");
return;
}
// TODO do stuff..
// Activated!
activated = true;
LogUtil.info("Hooked to dynmap!");
}
|
diff --git a/src/com/gitblit/GitBlit.java b/src/com/gitblit/GitBlit.java
index 782da63e..54ca6d20 100644
--- a/src/com/gitblit/GitBlit.java
+++ b/src/com/gitblit/GitBlit.java
@@ -1,3191 +1,3191 @@
/*
* 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;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.Principal;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
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.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.resource.ContextRelativeResource;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.RepositoryCache.FileKey;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.storage.file.WindowCache;
import org.eclipse.jgit.storage.file.WindowCacheConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gitblit.Constants.AccessPermission;
import com.gitblit.Constants.AccessRestrictionType;
import com.gitblit.Constants.AuthenticationType;
import com.gitblit.Constants.AuthorizationControl;
import com.gitblit.Constants.FederationRequest;
import com.gitblit.Constants.FederationStrategy;
import com.gitblit.Constants.FederationToken;
import com.gitblit.Constants.PermissionType;
import com.gitblit.Constants.RegistrantType;
import com.gitblit.models.FederationModel;
import com.gitblit.models.FederationProposal;
import com.gitblit.models.FederationSet;
import com.gitblit.models.ForkModel;
import com.gitblit.models.Metric;
import com.gitblit.models.ProjectModel;
import com.gitblit.models.RegistrantAccessPermission;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.SearchResult;
import com.gitblit.models.ServerSettings;
import com.gitblit.models.ServerStatus;
import com.gitblit.models.SettingModel;
import com.gitblit.models.TeamModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.Base64;
import com.gitblit.utils.ByteFormat;
import com.gitblit.utils.ContainerUtils;
import com.gitblit.utils.DeepCopier;
import com.gitblit.utils.FederationUtils;
import com.gitblit.utils.HttpUtils;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.JsonUtils;
import com.gitblit.utils.MetricUtils;
import com.gitblit.utils.ObjectCache;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
import com.gitblit.utils.X509Utils.X509Metadata;
import com.gitblit.wicket.GitBlitWebSession;
import com.gitblit.wicket.WicketUtils;
/**
* GitBlit is the servlet context listener singleton that acts as the core for
* the web ui and the servlets. This class is either directly instantiated by
* the GitBlitServer class (Gitblit GO) or is reflectively instantiated from the
* definition in the web.xml file (Gitblit WAR).
*
* This class is the central logic processor for Gitblit. All settings, user
* object, and repository object operations pass through this class.
*
* Repository Resolution. There are two pathways for finding repositories. One
* pathway, for web ui display and repository authentication & authorization, is
* within this class. The other pathway is through the standard GitServlet.
*
* @author James Moger
*
*/
public class GitBlit implements ServletContextListener {
private static GitBlit gitblit;
private final Logger logger = LoggerFactory.getLogger(GitBlit.class);
private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
private final List<FederationModel> federationRegistrations = Collections
.synchronizedList(new ArrayList<FederationModel>());
private final Map<String, FederationModel> federationPullResults = new ConcurrentHashMap<String, FederationModel>();
private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
private final Map<String, RepositoryModel> repositoryListCache = new ConcurrentHashMap<String, RepositoryModel>();
private final Map<String, ProjectModel> projectCache = new ConcurrentHashMap<String, ProjectModel>();
private final AtomicReference<String> repositoryListSettingsChecksum = new AtomicReference<String>("");
private ServletContext servletContext;
private File repositoriesFolder;
private IUserService userService;
private IStoredSettings settings;
private ServerSettings settingsModel;
private ServerStatus serverStatus;
private MailExecutor mailExecutor;
private LuceneExecutor luceneExecutor;
private GCExecutor gcExecutor;
private TimeZone timezone;
private FileBasedConfig projectConfigs;
public GitBlit() {
if (gitblit == null) {
// set the static singleton reference
gitblit = this;
}
}
public GitBlit(final IUserService userService) {
this.userService = userService;
gitblit = this;
}
/**
* Returns the Gitblit singleton.
*
* @return gitblit singleton
*/
public static GitBlit self() {
if (gitblit == null) {
new GitBlit();
}
return gitblit;
}
/**
* Determine if this is the GO variant of Gitblit.
*
* @return true if this is the GO variant of Gitblit.
*/
public static boolean isGO() {
return self().settings instanceof FileSettings;
}
/**
* Returns the preferred timezone for the Gitblit instance.
*
* @return a timezone
*/
public static TimeZone getTimezone() {
if (self().timezone == null) {
String tzid = getString("web.timezone", null);
if (StringUtils.isEmpty(tzid)) {
self().timezone = TimeZone.getDefault();
return self().timezone;
}
self().timezone = TimeZone.getTimeZone(tzid);
}
return self().timezone;
}
/**
* Returns the user-defined blob encodings.
*
* @return an array of encodings, may be empty
*/
public static String [] getEncodings() {
return getStrings(Keys.web.blobEncodings).toArray(new String[0]);
}
/**
* Returns the boolean value for the specified key. If the key does not
* exist or the value for the key can not be interpreted as a boolean, the
* defaultValue is returned.
*
* @see IStoredSettings.getBoolean(String, boolean)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static boolean getBoolean(String key, boolean defaultValue) {
return self().settings.getBoolean(key, defaultValue);
}
/**
* Returns the integer value for the specified key. If the key does not
* exist or the value for the key can not be interpreted as an integer, the
* defaultValue is returned.
*
* @see IStoredSettings.getInteger(String key, int defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static int getInteger(String key, int defaultValue) {
return self().settings.getInteger(key, defaultValue);
}
/**
* Returns the value in bytes for the specified key. If the key does not
* exist or the value for the key can not be interpreted as an integer, the
* defaultValue is returned.
*
* @see IStoredSettings.getFilesize(String key, int defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static int getFilesize(String key, int defaultValue) {
return self().settings.getFilesize(key, defaultValue);
}
/**
* Returns the value in bytes for the specified key. If the key does not
* exist or the value for the key can not be interpreted as a long, the
* defaultValue is returned.
*
* @see IStoredSettings.getFilesize(String key, long defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static long getFilesize(String key, long defaultValue) {
return self().settings.getFilesize(key, defaultValue);
}
/**
* Returns the char value for the specified key. If the key does not exist
* or the value for the key can not be interpreted as a character, the
* defaultValue is returned.
*
* @see IStoredSettings.getChar(String key, char defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static char getChar(String key, char defaultValue) {
return self().settings.getChar(key, defaultValue);
}
/**
* Returns the string value for the specified key. If the key does not exist
* or the value for the key can not be interpreted as a string, the
* defaultValue is returned.
*
* @see IStoredSettings.getString(String key, String defaultValue)
* @param key
* @param defaultValue
* @return key value or defaultValue
*/
public static String getString(String key, String defaultValue) {
return self().settings.getString(key, defaultValue);
}
/**
* Returns a list of space-separated strings from the specified key.
*
* @see IStoredSettings.getStrings(String key)
* @param name
* @return list of strings
*/
public static List<String> getStrings(String key) {
return self().settings.getStrings(key);
}
/**
* Returns a map of space-separated key-value pairs from the specified key.
*
* @see IStoredSettings.getStrings(String key)
* @param name
* @return map of string, string
*/
public static Map<String, String> getMap(String key) {
return self().settings.getMap(key);
}
/**
* Returns the list of keys whose name starts with the specified prefix. If
* the prefix is null or empty, all key names are returned.
*
* @see IStoredSettings.getAllKeys(String key)
* @param startingWith
* @return list of keys
*/
public static List<String> getAllKeys(String startingWith) {
return self().settings.getAllKeys(startingWith);
}
/**
* Is Gitblit running in debug mode?
*
* @return true if Gitblit is running in debug mode
*/
public static boolean isDebugMode() {
return self().settings.getBoolean(Keys.web.debugMode, false);
}
/**
* Returns the file object for the specified configuration key.
*
* @return the file
*/
public static File getFileOrFolder(String key, String defaultFileOrFolder) {
String fileOrFolder = GitBlit.getString(key, defaultFileOrFolder);
return getFileOrFolder(fileOrFolder);
}
/**
* Returns the file object which may have it's base-path determined by
* environment variables for running on a cloud hosting service. All Gitblit
* file or folder retrievals are (at least initially) funneled through this
* method so it is the correct point to globally override/alter filesystem
* access based on environment or some other indicator.
*
* @return the file
*/
public static File getFileOrFolder(String fileOrFolder) {
String openShift = System.getenv("OPENSHIFT_DATA_DIR");
if (!StringUtils.isEmpty(openShift)) {
// running on RedHat OpenShift
return new File(openShift, fileOrFolder);
}
return new File(fileOrFolder);
}
/**
* Returns the path of the repositories folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the repositories folder path
*/
public static File getRepositoriesFolder() {
return getFileOrFolder(Keys.git.repositoriesFolder, "git");
}
/**
* Returns the path of the proposals folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the proposals folder path
*/
public static File getProposalsFolder() {
return getFileOrFolder(Keys.federation.proposalsFolder, "proposals");
}
/**
* Returns the path of the Groovy folder. This method checks to see if
* Gitblit is running on a cloud service and may return an adjusted path.
*
* @return the Groovy scripts folder path
*/
public static File getGroovyScriptsFolder() {
return getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
}
/**
* Updates the list of server settings.
*
* @param settings
* @return true if the update succeeded
*/
public boolean updateSettings(Map<String, String> updatedSettings) {
return settings.saveSettings(updatedSettings);
}
public ServerStatus getStatus() {
// update heap memory status
serverStatus.heapAllocated = Runtime.getRuntime().totalMemory();
serverStatus.heapFree = Runtime.getRuntime().freeMemory();
return serverStatus;
}
/**
* Returns the list of non-Gitblit clone urls. This allows Gitblit to
* advertise alternative urls for Git client repository access.
*
* @param repositoryName
* @return list of non-gitblit clone urls
*/
public List<String> getOtherCloneUrls(String repositoryName) {
List<String> cloneUrls = new ArrayList<String>();
for (String url : settings.getStrings(Keys.web.otherUrls)) {
cloneUrls.add(MessageFormat.format(url, repositoryName));
}
return cloneUrls;
}
/**
* Set the user service. The user service authenticates all users and is
* responsible for managing user permissions.
*
* @param userService
*/
public void setUserService(IUserService userService) {
logger.info("Setting up user service " + userService.toString());
this.userService = userService;
this.userService.setup(settings);
}
/**
*
* @return true if the user service supports credential changes
*/
public boolean supportsCredentialChanges() {
return userService.supportsCredentialChanges();
}
/**
*
* @return true if the user service supports display name changes
*/
public boolean supportsDisplayNameChanges() {
return userService.supportsDisplayNameChanges();
}
/**
*
* @return true if the user service supports email address changes
*/
public boolean supportsEmailAddressChanges() {
return userService.supportsEmailAddressChanges();
}
/**
*
* @return true if the user service supports team membership changes
*/
public boolean supportsTeamMembershipChanges() {
return userService.supportsTeamMembershipChanges();
}
/**
* Authenticate a user based on a username and password.
*
* @see IUserService.authenticate(String, char[])
* @param username
* @param password
* @return a user object or null
*/
public UserModel authenticate(String username, char[] password) {
if (StringUtils.isEmpty(username)) {
// can not authenticate empty username
return null;
}
String pw = new String(password);
if (StringUtils.isEmpty(pw)) {
// can not authenticate empty password
return null;
}
// check to see if this is the federation user
if (canFederate()) {
if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
List<String> tokens = getFederationTokens();
if (tokens.contains(pw)) {
// the federation user is an administrator
UserModel federationUser = new UserModel(Constants.FEDERATION_USER);
federationUser.canAdmin = true;
return federationUser;
}
}
}
// delegate authentication to the user service
if (userService == null) {
return null;
}
return userService.authenticate(username, password);
}
/**
* Authenticate a user based on their cookie.
*
* @param cookies
* @return a user object or null
*/
protected UserModel authenticate(Cookie[] cookies) {
if (userService == null) {
return null;
}
if (userService.supportsCookies()) {
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(Constants.NAME)) {
String value = cookie.getValue();
return userService.authenticate(value.toCharArray());
}
}
}
}
return null;
}
/**
* Authenticate a user based on HTTP request parameters.
*
* Authentication by X509Certificate is tried first and then by cookie.
*
* @param httpRequest
* @return a user object or null
*/
public UserModel authenticate(HttpServletRequest httpRequest) {
return authenticate(httpRequest, false);
}
/**
* Authenticate a user based on HTTP request parameters.
*
* Authentication by X509Certificate, servlet container principal, cookie,
* and BASIC header.
*
* @param httpRequest
* @param requiresCertificate
* @return a user object or null
*/
public UserModel authenticate(HttpServletRequest httpRequest, boolean requiresCertificate) {
// try to authenticate by certificate
boolean checkValidity = settings.getBoolean(Keys.git.enforceCertificateValidity, true);
String [] oids = getStrings(Keys.git.certificateUsernameOIDs).toArray(new String[0]);
UserModel model = HttpUtils.getUserModelFromCertificate(httpRequest, checkValidity, oids);
if (model != null) {
// grab real user model and preserve certificate serial number
UserModel user = getUserModel(model.username);
X509Metadata metadata = HttpUtils.getCertificateMetadata(httpRequest);
if (user != null) {
flagWicketSession(AuthenticationType.CERTIFICATE);
logger.info(MessageFormat.format("{0} authenticated by client certificate {1} from {2}",
user.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
return user;
} else {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted client certificate ({1}) authentication from {2}",
model.username, metadata.serialNumber, httpRequest.getRemoteAddr()));
}
}
if (requiresCertificate) {
// caller requires client certificate authentication (e.g. git servlet)
return null;
}
// try to authenticate by servlet container principal
Principal principal = httpRequest.getUserPrincipal();
if (principal != null) {
UserModel user = getUserModel(principal.getName());
if (user != null) {
flagWicketSession(AuthenticationType.CONTAINER);
logger.info(MessageFormat.format("{0} authenticated by servlet container principal from {1}",
user.username, httpRequest.getRemoteAddr()));
return user;
} else {
logger.warn(MessageFormat.format("Failed to find UserModel for {0}, attempted servlet container authentication from {1}",
principal.getName(), httpRequest.getRemoteAddr()));
}
}
// try to authenticate by cookie
if (allowCookieAuthentication()) {
UserModel user = authenticate(httpRequest.getCookies());
if (user != null) {
flagWicketSession(AuthenticationType.COOKIE);
logger.info(MessageFormat.format("{0} authenticated by cookie from {1}",
user.username, httpRequest.getRemoteAddr()));
return user;
}
}
// try to authenticate by BASIC
final String authorization = httpRequest.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Basic")) {
// Authorization: Basic base64credentials
String base64Credentials = authorization.substring("Basic".length()).trim();
String credentials = new String(Base64.decode(base64Credentials),
Charset.forName("UTF-8"));
// credentials = username:password
final String[] values = credentials.split(":",2);
if (values.length == 2) {
String username = values[0];
char[] password = values[1].toCharArray();
UserModel user = authenticate(username, password);
if (user != null) {
flagWicketSession(AuthenticationType.CREDENTIALS);
logger.info(MessageFormat.format("{0} authenticated by BASIC request header from {1}",
user.username, httpRequest.getRemoteAddr()));
return user;
} else {
logger.warn(MessageFormat.format("Failed login attempt for {0}, invalid credentials ({1}) from {2}",
username, credentials, httpRequest.getRemoteAddr()));
}
}
}
return null;
}
protected void flagWicketSession(AuthenticationType authenticationType) {
RequestCycle requestCycle = RequestCycle.get();
if (requestCycle != null) {
// flag the Wicket session, if this is a Wicket request
GitBlitWebSession session = GitBlitWebSession.get();
session.authenticationType = authenticationType;
}
}
/**
* Open a file resource using the Servlet container.
* @param file to open
* @return InputStream of the opened file
* @throws ResourceStreamNotFoundException
*/
public InputStream getResourceAsStream(String file) throws ResourceStreamNotFoundException {
ContextRelativeResource res = WicketUtils.getResource(file);
return res.getResourceStream().getInputStream();
}
/**
* Sets a cookie for the specified user.
*
* @param response
* @param user
*/
public void setCookie(WebResponse response, UserModel user) {
if (userService == null) {
return;
}
if (userService.supportsCookies()) {
Cookie userCookie;
if (user == null) {
// clear cookie for logout
userCookie = new Cookie(Constants.NAME, "");
} else {
// set cookie for login
String cookie = userService.getCookie(user);
if (StringUtils.isEmpty(cookie)) {
// create empty cookie
userCookie = new Cookie(Constants.NAME, "");
} else {
// create real cookie
userCookie = new Cookie(Constants.NAME, cookie);
userCookie.setMaxAge(Integer.MAX_VALUE);
}
}
userCookie.setPath("/");
response.addCookie(userCookie);
}
}
/**
* Logout a user.
*
* @param user
*/
public void logout(UserModel user) {
if (userService == null) {
return;
}
userService.logout(user);
}
/**
* Returns the list of all users available to the login service.
*
* @see IUserService.getAllUsernames()
* @return list of all usernames
*/
public List<String> getAllUsernames() {
List<String> names = new ArrayList<String>(userService.getAllUsernames());
return names;
}
/**
* Returns the list of all users available to the login service.
*
* @see IUserService.getAllUsernames()
* @return list of all usernames
*/
public List<UserModel> getAllUsers() {
List<UserModel> users = userService.getAllUsers();
return users;
}
/**
* Delete the user object with the specified username
*
* @see IUserService.deleteUser(String)
* @param username
* @return true if successful
*/
public boolean deleteUser(String username) {
if (StringUtils.isEmpty(username)) {
return false;
}
return userService.deleteUser(username);
}
/**
* Retrieve the user object for the specified username.
*
* @see IUserService.getUserModel(String)
* @param username
* @return a user object or null
*/
public UserModel getUserModel(String username) {
if (StringUtils.isEmpty(username)) {
return null;
}
UserModel user = userService.getUserModel(username);
return user;
}
/**
* Returns the effective list of permissions for this user, taking into account
* team memberships, ownerships.
*
* @param user
* @return the effective list of permissions for the user
*/
public List<RegistrantAccessPermission> getUserAccessPermissions(UserModel user) {
Set<RegistrantAccessPermission> set = new LinkedHashSet<RegistrantAccessPermission>();
set.addAll(user.getRepositoryPermissions());
// Flag missing repositories
for (RegistrantAccessPermission permission : set) {
if (permission.mutable && PermissionType.EXPLICIT.equals(permission.permissionType)) {
RepositoryModel rm = GitBlit.self().getRepositoryModel(permission.registrant);
if (rm == null) {
permission.permissionType = PermissionType.MISSING;
permission.mutable = false;
continue;
}
}
}
// TODO reconsider ownership as a user property
// manually specify personal repository ownerships
for (RepositoryModel rm : repositoryListCache.values()) {
if (rm.isUsersPersonalRepository(user.username) || rm.isOwner(user.username)) {
RegistrantAccessPermission rp = new RegistrantAccessPermission(rm.name, AccessPermission.REWIND,
PermissionType.OWNER, RegistrantType.REPOSITORY, null, false);
// user may be owner of a repository to which they've inherited
// a team permission, replace any existing perm with owner perm
set.remove(rp);
set.add(rp);
}
}
List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>(set);
Collections.sort(list);
return list;
}
/**
* Returns the list of users and their access permissions for the specified
* repository including permission source information such as the team or
* regular expression which sets the permission.
*
* @param repository
* @return a list of RegistrantAccessPermissions
*/
public List<RegistrantAccessPermission> getUserAccessPermissions(RepositoryModel repository) {
List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>();
if (AccessRestrictionType.NONE.equals(repository.accessRestriction)) {
// no permissions needed, REWIND for everyone!
return list;
}
if (AuthorizationControl.AUTHENTICATED.equals(repository.authorizationControl)) {
// no permissions needed, REWIND for authenticated!
return list;
}
// NAMED users and teams
for (UserModel user : userService.getAllUsers()) {
RegistrantAccessPermission ap = user.getRepositoryPermission(repository);
if (ap.permission.exceeds(AccessPermission.NONE)) {
list.add(ap);
}
}
return list;
}
/**
* Sets the access permissions to the specified repository for the specified users.
*
* @param repository
* @param permissions
* @return true if the user models have been updated
*/
public boolean setUserAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
List<UserModel> users = new ArrayList<UserModel>();
for (RegistrantAccessPermission up : permissions) {
if (up.mutable) {
// only set editable defined permissions
UserModel user = userService.getUserModel(up.registrant);
user.setRepositoryPermission(repository.name, up.permission);
users.add(user);
}
}
return userService.updateUserModels(users);
}
/**
* Returns the list of all users who have an explicit access permission
* for the specified repository.
*
* @see IUserService.getUsernamesForRepositoryRole(String)
* @param repository
* @return list of all usernames that have an access permission for the repository
*/
public List<String> getRepositoryUsers(RepositoryModel repository) {
return userService.getUsernamesForRepositoryRole(repository.name);
}
/**
* Sets the list of all uses who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.setUsernamesForRepositoryRole(String, List<String>)
* @param repository
* @param usernames
* @return true if successful
*/
@Deprecated
public boolean setRepositoryUsers(RepositoryModel repository, List<String> repositoryUsers) {
// rejects all changes since 1.2.0 because this would elevate
// all discrete access permissions to RW+
return false;
}
/**
* Adds/updates a complete user object keyed by username. This method allows
* for renaming a user.
*
* @see IUserService.updateUserModel(String, UserModel)
* @param username
* @param user
* @param isCreate
* @throws GitBlitException
*/
public void updateUserModel(String username, UserModel user, boolean isCreate)
throws GitBlitException {
if (!username.equalsIgnoreCase(user.username)) {
if (userService.getUserModel(user.username) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", username,
user.username));
}
// rename repositories and owner fields for all repositories
for (RepositoryModel model : getRepositoryModels(user)) {
if (model.isUsersPersonalRepository(username)) {
// personal repository
model.owner = user.username;
String oldRepositoryName = model.name;
model.name = "~" + user.username + model.name.substring(model.projectPath.length());
model.projectPath = "~" + user.username;
updateRepositoryModel(oldRepositoryName, model, false);
} else if (model.isOwner(username)) {
// common/shared repo
model.owner = user.username;
updateRepositoryModel(model.name, model, false);
}
}
}
if (!userService.updateUserModel(username, user)) {
throw new GitBlitException(isCreate ? "Failed to add user!" : "Failed to update user!");
}
}
/**
* Returns the list of available teams that a user or repository may be
* assigned to.
*
* @return the list of teams
*/
public List<String> getAllTeamnames() {
List<String> teams = new ArrayList<String>(userService.getAllTeamNames());
return teams;
}
/**
* Returns the list of available teams that a user or repository may be
* assigned to.
*
* @return the list of teams
*/
public List<TeamModel> getAllTeams() {
List<TeamModel> teams = userService.getAllTeams();
return teams;
}
/**
* Returns the TeamModel object for the specified name.
*
* @param teamname
* @return a TeamModel object or null
*/
public TeamModel getTeamModel(String teamname) {
return userService.getTeamModel(teamname);
}
/**
* Returns the list of teams and their access permissions for the specified
* repository including the source of the permission such as the admin flag
* or a regular expression.
*
* @param repository
* @return a list of RegistrantAccessPermissions
*/
public List<RegistrantAccessPermission> getTeamAccessPermissions(RepositoryModel repository) {
List<RegistrantAccessPermission> list = new ArrayList<RegistrantAccessPermission>();
for (TeamModel team : userService.getAllTeams()) {
RegistrantAccessPermission ap = team.getRepositoryPermission(repository);
if (ap.permission.exceeds(AccessPermission.NONE)) {
list.add(ap);
}
}
Collections.sort(list);
return list;
}
/**
* Sets the access permissions to the specified repository for the specified teams.
*
* @param repository
* @param permissions
* @return true if the team models have been updated
*/
public boolean setTeamAccessPermissions(RepositoryModel repository, Collection<RegistrantAccessPermission> permissions) {
List<TeamModel> teams = new ArrayList<TeamModel>();
for (RegistrantAccessPermission tp : permissions) {
if (tp.mutable) {
// only set explicitly defined access permissions
TeamModel team = userService.getTeamModel(tp.registrant);
team.setRepositoryPermission(repository.name, tp.permission);
teams.add(team);
}
}
return userService.updateTeamModels(teams);
}
/**
* Returns the list of all teams who have an explicit access permission for
* the specified repository.
*
* @see IUserService.getTeamnamesForRepositoryRole(String)
* @param repository
* @return list of all teamnames with explicit access permissions to the repository
*/
public List<String> getRepositoryTeams(RepositoryModel repository) {
return userService.getTeamnamesForRepositoryRole(repository.name);
}
/**
* Sets the list of all uses who are allowed to bypass the access
* restriction placed on the specified repository.
*
* @see IUserService.setTeamnamesForRepositoryRole(String, List<String>)
* @param repository
* @param teamnames
* @return true if successful
*/
@Deprecated
public boolean setRepositoryTeams(RepositoryModel repository, List<String> repositoryTeams) {
// rejects all changes since 1.2.0 because this would elevate
// all discrete access permissions to RW+
return false;
}
/**
* Updates the TeamModel object for the specified name.
*
* @param teamname
* @param team
* @param isCreate
*/
public void updateTeamModel(String teamname, TeamModel team, boolean isCreate)
throws GitBlitException {
if (!teamname.equalsIgnoreCase(team.name)) {
if (userService.getTeamModel(team.name) != null) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
team.name));
}
}
if (!userService.updateTeamModel(teamname, team)) {
throw new GitBlitException(isCreate ? "Failed to add team!" : "Failed to update team!");
}
}
/**
* Delete the team object with the specified teamname
*
* @see IUserService.deleteTeam(String)
* @param teamname
* @return true if successful
*/
public boolean deleteTeam(String teamname) {
return userService.deleteTeam(teamname);
}
/**
* Adds the repository to the list of cached repositories if Gitblit is
* configured to cache the repository list.
*
* @param model
*/
private void addToCachedRepositoryList(RepositoryModel model) {
if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
repositoryListCache.put(model.name.toLowerCase(), model);
// update the fork origin repository with this repository clone
if (!StringUtils.isEmpty(model.originRepository)) {
if (repositoryListCache.containsKey(model.originRepository)) {
RepositoryModel origin = repositoryListCache.get(model.originRepository);
origin.addFork(model.name);
}
}
}
}
/**
* Removes the repository from the list of cached repositories.
*
* @param name
* @return the model being removed
*/
private RepositoryModel removeFromCachedRepositoryList(String name) {
if (StringUtils.isEmpty(name)) {
return null;
}
return repositoryListCache.remove(name.toLowerCase());
}
/**
* Clears all the cached metadata for the specified repository.
*
* @param repositoryName
*/
private void clearRepositoryMetadataCache(String repositoryName) {
repositorySizeCache.remove(repositoryName);
repositoryMetricsCache.remove(repositoryName);
}
/**
* Resets the repository list cache.
*
*/
public void resetRepositoryListCache() {
logger.info("Repository cache manually reset");
repositoryListCache.clear();
}
/**
* Calculate the checksum of settings that affect the repository list cache.
* @return a checksum
*/
private String getRepositoryListSettingsChecksum() {
StringBuilder ns = new StringBuilder();
ns.append(settings.getString(Keys.git.cacheRepositoryList, "")).append('\n');
ns.append(settings.getString(Keys.git.onlyAccessBareRepositories, "")).append('\n');
ns.append(settings.getString(Keys.git.searchRepositoriesSubfolders, "")).append('\n');
ns.append(settings.getString(Keys.git.searchRecursionDepth, "")).append('\n');
ns.append(settings.getString(Keys.git.searchExclusions, "")).append('\n');
String checksum = StringUtils.getSHA1(ns.toString());
return checksum;
}
/**
* Compare the last repository list setting checksum to the current checksum.
* If different then clear the cache so that it may be rebuilt.
*
* @return true if the cached repository list is valid since the last check
*/
private boolean isValidRepositoryList() {
String newChecksum = getRepositoryListSettingsChecksum();
boolean valid = newChecksum.equals(repositoryListSettingsChecksum.get());
repositoryListSettingsChecksum.set(newChecksum);
if (!valid && settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
logger.info("Repository list settings have changed. Clearing repository list cache.");
repositoryListCache.clear();
}
return valid;
}
/**
* Returns the list of all repositories available to Gitblit. This method
* does not consider user access permissions.
*
* @return list of all repositories
*/
public List<String> getRepositoryList() {
if (repositoryListCache.size() == 0 || !isValidRepositoryList()) {
// we are not caching OR we have not yet cached OR the cached list is invalid
long startTime = System.currentTimeMillis();
List<String> repositories = JGitUtils.getRepositoryList(repositoriesFolder,
settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true),
settings.getInteger(Keys.git.searchRecursionDepth, -1),
settings.getStrings(Keys.git.searchExclusions));
if (!settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
// we are not caching
StringUtils.sortRepositorynames(repositories);
return repositories;
} else {
// we are caching this list
String msg = "{0} repositories identified in {1} msecs";
// optionally (re)calculate repository sizes
if (getBoolean(Keys.web.showRepositorySizes, true)) {
msg = "{0} repositories identified with calculated folder sizes in {1} msecs";
for (String repository : repositories) {
RepositoryModel model = getRepositoryModel(repository);
if (!model.skipSizeCalculation) {
calculateSize(model);
}
}
} else {
// update cache
for (String repository : repositories) {
getRepositoryModel(repository);
}
}
// rebuild fork networks
for (RepositoryModel model : repositoryListCache.values()) {
if (!StringUtils.isEmpty(model.originRepository)) {
if (repositoryListCache.containsKey(model.originRepository)) {
RepositoryModel origin = repositoryListCache.get(model.originRepository);
origin.addFork(model.name);
}
}
}
long duration = System.currentTimeMillis() - startTime;
logger.info(MessageFormat.format(msg, repositoryListCache.size(), duration));
}
}
// return sorted copy of cached list
List<String> list = new ArrayList<String>(repositoryListCache.keySet());
StringUtils.sortRepositorynames(list);
return list;
}
/**
* Returns the JGit repository for the specified name.
*
* @param repositoryName
* @return repository or null
*/
public Repository getRepository(String repositoryName) {
return getRepository(repositoryName, true);
}
/**
* Returns the JGit repository for the specified name.
*
* @param repositoryName
* @param logError
* @return repository or null
*/
public Repository getRepository(String repositoryName, boolean logError) {
if (isCollectingGarbage(repositoryName)) {
logger.warn(MessageFormat.format("Rejecting request for {0}, busy collecting garbage!", repositoryName));
return null;
}
File dir = FileKey.resolve(new File(repositoriesFolder, repositoryName), FS.DETECTED);
if (dir == null)
return null;
Repository r = null;
try {
FileKey key = FileKey.exact(dir, FS.DETECTED);
r = RepositoryCache.open(key, true);
} catch (IOException e) {
if (logError) {
logger.error("GitBlit.getRepository(String) failed to find "
+ new File(repositoriesFolder, repositoryName).getAbsolutePath());
}
}
return r;
}
/**
* Returns the list of repository models that are accessible to the user.
*
* @param user
* @return list of repository models accessible to user
*/
public List<RepositoryModel> getRepositoryModels(UserModel user) {
long methodStart = System.currentTimeMillis();
List<String> list = getRepositoryList();
List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
for (String repo : list) {
RepositoryModel model = getRepositoryModel(user, repo);
if (model != null) {
repositories.add(model);
}
}
if (getBoolean(Keys.web.showRepositorySizes, true)) {
int repoCount = 0;
long startTime = System.currentTimeMillis();
ByteFormat byteFormat = new ByteFormat();
for (RepositoryModel model : repositories) {
if (!model.skipSizeCalculation) {
repoCount++;
model.size = byteFormat.format(calculateSize(model));
}
}
long duration = System.currentTimeMillis() - startTime;
if (duration > 250) {
// only log calcualtion time if > 250 msecs
logger.info(MessageFormat.format("{0} repository sizes calculated in {1} msecs",
repoCount, duration));
}
}
long duration = System.currentTimeMillis() - methodStart;
logger.info(MessageFormat.format("{0} repository models loaded for {1} in {2} msecs",
repositories.size(), user == null ? "anonymous" : user.username, duration));
return repositories;
}
/**
* Returns a repository model if the repository exists and the user may
* access the repository.
*
* @param user
* @param repositoryName
* @return repository model or null
*/
public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
RepositoryModel model = getRepositoryModel(repositoryName);
if (model == null) {
return null;
}
if (user == null) {
user = UserModel.ANONYMOUS;
}
if (user.canView(model)) {
return model;
}
return null;
}
/**
* Returns the repository model for the specified repository. This method
* does not consider user access permissions.
*
* @param repositoryName
* @return repository model or null
*/
public RepositoryModel getRepositoryModel(String repositoryName) {
if (!repositoryListCache.containsKey(repositoryName)) {
RepositoryModel model = loadRepositoryModel(repositoryName);
if (model == null) {
return null;
}
addToCachedRepositoryList(model);
return model;
}
// cached model
RepositoryModel model = repositoryListCache.get(repositoryName.toLowerCase());
if (gcExecutor.isCollectingGarbage(model.name)) {
// Gitblit is busy collecting garbage, use our cached model
RepositoryModel rm = DeepCopier.copy(model);
rm.isCollectingGarbage = true;
return rm;
}
// check for updates
Repository r = getRepository(model.name);
if (r == null) {
// repository is missing
removeFromCachedRepositoryList(repositoryName);
logger.error(MessageFormat.format("Repository \"{0}\" is missing! Removing from cache.", repositoryName));
return null;
}
FileBasedConfig config = (FileBasedConfig) getRepositoryConfig(r);
if (config.isOutdated()) {
// reload model
logger.info(MessageFormat.format("Config for \"{0}\" has changed. Reloading model and updating cache.", repositoryName));
model = loadRepositoryModel(repositoryName);
removeFromCachedRepositoryList(repositoryName);
addToCachedRepositoryList(model);
} else {
// update a few repository parameters
if (!model.hasCommits) {
// update hasCommits, assume a repository only gains commits :)
model.hasCommits = JGitUtils.hasCommits(r);
}
model.lastChange = JGitUtils.getLastChange(r);
}
r.close();
// return a copy of the cached model
return DeepCopier.copy(model);
}
/**
* Returns the map of project config. This map is cached and reloaded if
* the underlying projects.conf file changes.
*
* @return project config map
*/
private Map<String, ProjectModel> getProjectConfigs() {
if (projectCache.isEmpty() || projectConfigs.isOutdated()) {
try {
projectConfigs.load();
} catch (Exception e) {
}
// project configs
String rootName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main");
ProjectModel rootProject = new ProjectModel(rootName, true);
Map<String, ProjectModel> configs = new HashMap<String, ProjectModel>();
// cache the root project under its alias and an empty path
configs.put("", rootProject);
configs.put(rootProject.name.toLowerCase(), rootProject);
for (String name : projectConfigs.getSubsections("project")) {
ProjectModel project;
if (name.equalsIgnoreCase(rootName)) {
project = rootProject;
} else {
project = new ProjectModel(name);
}
project.title = projectConfigs.getString("project", name, "title");
project.description = projectConfigs.getString("project", name, "description");
configs.put(name.toLowerCase(), project);
}
projectCache.clear();
projectCache.putAll(configs);
}
return projectCache;
}
/**
* Returns a list of project models for the user.
*
* @param user
* @param includeUsers
* @return list of projects that are accessible to the user
*/
public List<ProjectModel> getProjectModels(UserModel user, boolean includeUsers) {
Map<String, ProjectModel> configs = getProjectConfigs();
// per-user project lists, this accounts for security and visibility
Map<String, ProjectModel> map = new TreeMap<String, ProjectModel>();
// root project
map.put("", configs.get(""));
for (RepositoryModel model : getRepositoryModels(user)) {
String rootPath = StringUtils.getRootPath(model.name).toLowerCase();
if (!map.containsKey(rootPath)) {
ProjectModel project;
if (configs.containsKey(rootPath)) {
// clone the project model because it's repository list will
// be tailored for the requesting user
project = DeepCopier.copy(configs.get(rootPath));
} else {
project = new ProjectModel(rootPath);
}
map.put(rootPath, project);
}
map.get(rootPath).addRepository(model);
}
// sort projects, root project first
List<ProjectModel> projects;
if (includeUsers) {
// all projects
projects = new ArrayList<ProjectModel>(map.values());
Collections.sort(projects);
projects.remove(map.get(""));
projects.add(0, map.get(""));
} else {
// all non-user projects
projects = new ArrayList<ProjectModel>();
ProjectModel root = map.remove("");
for (ProjectModel model : map.values()) {
if (!model.isUserProject()) {
projects.add(model);
}
}
Collections.sort(projects);
projects.add(0, root);
}
return projects;
}
/**
* Returns the project model for the specified user.
*
* @param name
* @param user
* @return a project model, or null if it does not exist
*/
public ProjectModel getProjectModel(String name, UserModel user) {
for (ProjectModel project : getProjectModels(user, true)) {
if (project.name.equalsIgnoreCase(name)) {
return project;
}
}
return null;
}
/**
* Returns a project model for the Gitblit/system user.
*
* @param name a project name
* @return a project model or null if the project does not exist
*/
public ProjectModel getProjectModel(String name) {
Map<String, ProjectModel> configs = getProjectConfigs();
ProjectModel project = configs.get(name.toLowerCase());
if (project == null) {
project = new ProjectModel(name);
if (name.length() > 0 && name.charAt(0) == '~') {
UserModel user = getUserModel(name.substring(1));
if (user != null) {
project.title = user.getDisplayName();
project.description = "personal repositories";
}
}
} else {
// clone the object
project = DeepCopier.copy(project);
}
if (StringUtils.isEmpty(name)) {
// get root repositories
for (String repository : getRepositoryList()) {
if (repository.indexOf('/') == -1) {
project.addRepository(repository);
}
}
} else {
// get repositories in subfolder
String folder = name.toLowerCase() + "/";
for (String repository : getRepositoryList()) {
if (repository.toLowerCase().startsWith(folder)) {
project.addRepository(repository);
}
}
}
if (project.repositories.size() == 0) {
// no repositories == no project
return null;
}
return project;
}
/**
* Workaround JGit. I need to access the raw config object directly in order
* to see if the config is dirty so that I can reload a repository model.
* If I use the stock JGit method to get the config it already reloads the
* config. If the config changes are made within Gitblit this is fine as
* the returned config will still be flagged as dirty. BUT... if the config
* is manipulated outside Gitblit then it fails to recognize this as dirty.
*
* @param r
* @return a config
*/
private StoredConfig getRepositoryConfig(Repository r) {
try {
Field f = r.getClass().getDeclaredField("repoConfig");
f.setAccessible(true);
StoredConfig config = (StoredConfig) f.get(r);
return config;
} catch (Exception e) {
logger.error("Failed to retrieve \"repoConfig\" via reflection", e);
}
return r.getConfig();
}
/**
* Create a repository model from the configuration and repository data.
*
* @param repositoryName
* @return a repositoryModel or null if the repository does not exist
*/
private RepositoryModel loadRepositoryModel(String repositoryName) {
Repository r = getRepository(repositoryName);
if (r == null) {
return null;
}
RepositoryModel model = new RepositoryModel();
model.isBare = r.isBare();
File basePath = getFileOrFolder(Keys.git.repositoriesFolder, "git");
if (model.isBare) {
model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
} else {
model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
}
model.hasCommits = JGitUtils.hasCommits(r);
model.lastChange = JGitUtils.getLastChange(r);
model.projectPath = StringUtils.getFirstPathElement(repositoryName);
StoredConfig config = r.getConfig();
boolean hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
if (config != null) {
model.description = getConfig(config, "description", "");
model.owner = getConfig(config, "owner", "");
model.useTickets = getConfig(config, "useTickets", false);
model.useDocs = getConfig(config, "useDocs", false);
model.allowForks = getConfig(config, "allowForks", true);
model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
"accessRestriction", settings.getString(Keys.git.defaultAccessRestriction, null)));
model.authorizationControl = AuthorizationControl.fromName(getConfig(config,
"authorizationControl", settings.getString(Keys.git.defaultAuthorizationControl, null)));
model.verifyCommitter = getConfig(config, "verifyCommitter", false);
model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
model.isFrozen = getConfig(config, "isFrozen", false);
model.showReadme = getConfig(config, "showReadme", false);
model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
model.federationStrategy = FederationStrategy.fromName(getConfig(config,
"federationStrategy", null));
model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
Constants.CONFIG_GITBLIT, null, "federationSets")));
model.isFederated = getConfig(config, "isFederated", false);
model.gcThreshold = getConfig(config, "gcThreshold", settings.getString(Keys.git.defaultGarbageCollectionThreshold, "500KB"));
model.gcPeriod = getConfig(config, "gcPeriod", settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7));
try {
model.lastGC = new SimpleDateFormat(Constants.ISO8601).parse(getConfig(config, "lastGC", "1970-01-01'T'00:00:00Z"));
} catch (Exception e) {
model.lastGC = new Date(0);
}
model.maxActivityCommits = getConfig(config, "maxActivityCommits", settings.getInteger(Keys.web.maxActivityCommits, 0));
model.origin = config.getString("remote", "origin", "url");
if (model.origin != null) {
model.origin = model.origin.replace('\\', '/');
}
model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
Constants.CONFIG_GITBLIT, null, "mailingList")));
model.indexedBranches = new ArrayList<String>(Arrays.asList(config.getStringList(
Constants.CONFIG_GITBLIT, null, "indexBranch")));
// Custom defined properties
model.customFields = new LinkedHashMap<String, String>();
for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
model.customFields.put(aProperty, config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
}
}
model.HEAD = JGitUtils.getHEADRef(r);
model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
r.close();
if (model.origin != null && model.origin.startsWith("file://")) {
// repository was cloned locally... perhaps as a fork
try {
File folder = new File(new URI(model.origin));
String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
if (!StringUtils.isEmpty(originRepo)) {
// ensure origin still exists
File repoFolder = new File(getRepositoriesFolder(), originRepo);
if (repoFolder.exists()) {
model.originRepository = originRepo.toLowerCase();
}
}
} catch (URISyntaxException e) {
logger.error("Failed to determine fork for " + model, e);
}
}
return model;
}
/**
* Determines if this server has the requested repository.
*
* @param name
* @return true if the repository exists
*/
public boolean hasRepository(String repositoryName) {
if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
// if we are caching use the cache to determine availability
// otherwise we end up adding a phantom repository to the cache
return repositoryListCache.containsKey(repositoryName.toLowerCase());
}
Repository r = getRepository(repositoryName, false);
if (r == null) {
return false;
}
r.close();
return true;
}
/**
* Determines if the specified user has a fork of the specified origin
* repository.
*
* @param username
* @param origin
* @return true the if the user has a fork
*/
public boolean hasFork(String username, String origin) {
return getFork(username, origin) != null;
}
/**
* Gets the name of a user's fork of the specified origin
* repository.
*
* @param username
* @param origin
* @return the name of the user's fork, null otherwise
*/
public String getFork(String username, String origin) {
String userProject = "~" + username.toLowerCase();
if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
String userPath = userProject + "/";
// collect all origin nodes in fork network
Set<String> roots = new HashSet<String>();
roots.add(origin);
RepositoryModel originModel = repositoryListCache.get(origin);
while (originModel != null) {
if (!ArrayUtils.isEmpty(originModel.forks)) {
for (String fork : originModel.forks) {
if (!fork.startsWith(userPath)) {
roots.add(fork);
}
}
}
if (originModel.originRepository != null) {
roots.add(originModel.originRepository);
originModel = repositoryListCache.get(originModel.originRepository);
} else {
// break
originModel = null;
}
}
for (String repository : repositoryListCache.keySet()) {
if (repository.startsWith(userPath)) {
RepositoryModel model = repositoryListCache.get(repository);
if (!StringUtils.isEmpty(model.originRepository)) {
if (roots.contains(model.originRepository)) {
// user has a fork in this graph
return model.name;
}
}
}
}
} else {
// not caching
ProjectModel project = getProjectModel(userProject);
for (String repository : project.repositories) {
if (repository.startsWith(userProject)) {
RepositoryModel model = repositoryListCache.get(repository);
if (model.originRepository.equalsIgnoreCase(origin)) {
// user has a fork
return model.name;
}
}
}
}
// user does not have a fork
return null;
}
/**
* Returns the fork network for a repository by traversing up the fork graph
* to discover the root and then down through all children of the root node.
*
* @param repository
* @return a ForkModel
*/
public ForkModel getForkNetwork(String repository) {
if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
// find the root
RepositoryModel model = repositoryListCache.get(repository.toLowerCase());
while (model.originRepository != null) {
model = repositoryListCache.get(model.originRepository);
}
ForkModel root = getForkModel(model.name);
return root;
}
return null;
}
private ForkModel getForkModel(String repository) {
RepositoryModel model = repositoryListCache.get(repository.toLowerCase());
ForkModel fork = new ForkModel(model);
if (!ArrayUtils.isEmpty(model.forks)) {
for (String aFork : model.forks) {
ForkModel fm = getForkModel(aFork);
fork.forks.add(fm);
}
}
return fork;
}
/**
* Returns the size in bytes of the repository. Gitblit caches the
* repository sizes to reduce the performance penalty of recursive
* calculation. The cache is updated if the repository has been changed
* since the last calculation.
*
* @param model
* @return size in bytes
*/
public long calculateSize(RepositoryModel model) {
if (repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
return repositorySizeCache.getObject(model.name);
}
File gitDir = FileKey.resolve(new File(repositoriesFolder, model.name), FS.DETECTED);
long size = com.gitblit.utils.FileUtils.folderSize(gitDir);
repositorySizeCache.updateObject(model.name, model.lastChange, size);
return size;
}
/**
* Ensure that a cached repository is completely closed and its resources
* are properly released.
*
* @param repositoryName
*/
private void closeRepository(String repositoryName) {
Repository repository = getRepository(repositoryName);
if (repository == null) {
return;
}
RepositoryCache.close(repository);
// assume 2 uses in case reflection fails
int uses = 2;
try {
// The FileResolver caches repositories which is very useful
// for performance until you want to delete a repository.
// I have to use reflection to call close() the correct
// number of times to ensure that the object and ref databases
// are properly closed before I can delete the repository from
// the filesystem.
Field useCnt = Repository.class.getDeclaredField("useCnt");
useCnt.setAccessible(true);
uses = ((AtomicInteger) useCnt.get(repository)).get();
} catch (Exception e) {
logger.warn(MessageFormat
.format("Failed to reflectively determine use count for repository {0}",
repositoryName), e);
}
if (uses > 0) {
logger.info(MessageFormat
.format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
repositoryName, uses, uses));
for (int i = 0; i < uses; i++) {
repository.close();
}
}
// close any open index writer/searcher in the Lucene executor
luceneExecutor.close(repositoryName);
}
/**
* Returns the metrics for the default branch of the specified repository.
* This method builds a metrics cache. The cache is updated if the
* repository is updated. A new copy of the metrics list is returned on each
* call so that modifications to the list are non-destructive.
*
* @param model
* @param repository
* @return a new array list of metrics
*/
public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
}
List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null, getTimezone());
repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
return new ArrayList<Metric>(metrics);
}
/**
* Returns the gitblit string value for the specified key. If key is not
* set, returns defaultValue.
*
* @param config
* @param field
* @param defaultValue
* @return field value or defaultValue
*/
private String getConfig(StoredConfig config, String field, String defaultValue) {
String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
return value;
}
/**
* Returns the gitblit boolean value for the specified key. If key is not
* set, returns defaultValue.
*
* @param config
* @param field
* @param defaultValue
* @return field value or defaultValue
*/
private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
return config.getBoolean(Constants.CONFIG_GITBLIT, field, defaultValue);
}
/**
* Returns the gitblit string value for the specified key. If key is not
* set, returns defaultValue.
*
* @param config
* @param field
* @param defaultValue
* @return field value or defaultValue
*/
private int getConfig(StoredConfig config, String field, int defaultValue) {
String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (Exception e) {
}
return defaultValue;
}
/**
* Creates/updates the repository model keyed by reopsitoryName. Saves all
* repository settings in .git/config. This method allows for renaming
* repositories and will update user access permissions accordingly.
*
* All repositories created by this method are bare and automatically have
* .git appended to their names, which is the standard convention for bare
* repositories.
*
* @param repositoryName
* @param repository
* @param isCreate
* @throws GitBlitException
*/
public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
if (gcExecutor.isCollectingGarbage(repositoryName)) {
throw new GitBlitException(MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}",
repositoryName));
}
Repository r = null;
String projectPath = StringUtils.getFirstPathElement(repository.name);
if (!StringUtils.isEmpty(projectPath)) {
if (projectPath.equalsIgnoreCase(getString(Keys.web.repositoryRootGroupName, "main"))) {
// strip leading group name
repository.name = repository.name.substring(projectPath.length() + 1);
}
}
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
- if (new File(repositoriesFolder, repository.name).exists()) {
+ if (hasRepository(repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
File parentFile = destFolder.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new GitBlitException(MessageFormat.format(
"Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
}
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// rename fork origins in their configs
if (!ArrayUtils.isEmpty(repository.forks)) {
for (String fork : repository.forks) {
Repository rf = getRepository(fork);
try {
StoredConfig config = rf.getConfig();
String origin = config.getString("remote", "origin", "url");
origin = origin.replace(repositoryName, repository.name);
config.setString("remote", "origin", "url", origin);
config.save();
} catch (Exception e) {
logger.error("Failed to update repository fork config for " + fork, e);
}
rf.close();
}
}
// remove this repository from any origin model's fork list
if (!StringUtils.isEmpty(repository.originRepository)) {
RepositoryModel origin = repositoryListCache.get(repository.originRepository);
if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
origin.forks.remove(repositoryName);
}
}
// clear the cache
clearRepositoryMetadataCache(repositoryName);
repository.resetDisplayName();
}
// load repository
logger.info("edit repository " + repository.name);
r = getRepository(repository.name);
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
// only update symbolic head if it changes
String currentRef = JGitUtils.getHEADRef(r);
if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}",
repository.name, currentRef, repository.HEAD));
if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
// clear the cache
clearRepositoryMetadataCache(repository.name);
}
}
// close the repository object
r.close();
}
// update repository cache
removeFromCachedRepositoryList(repositoryName);
// model will actually be replaced on next load because config is stale
addToCachedRepositoryList(repository);
}
/**
* Updates the Gitblit configuration for the specified repository.
*
* @param r
* the Git repository
* @param repository
* the Gitblit repository model
*/
public void updateConfiguration(Repository r, RepositoryModel repository) {
StoredConfig config = r.getConfig();
config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
config.setString(Constants.CONFIG_GITBLIT, null, "owner", repository.owner);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "useTickets", repository.useTickets);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "useDocs", repository.useDocs);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks);
config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl", repository.authorizationControl.name());
config.setBoolean(Constants.CONFIG_GITBLIT, null, "verifyCommitter", repository.verifyCommitter);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "showReadme", repository.showReadme);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
repository.federationStrategy.name());
config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
config.setString(Constants.CONFIG_GITBLIT, null, "gcThreshold", repository.gcThreshold);
if (repository.gcPeriod == settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7)) {
// use default from config
config.unset(Constants.CONFIG_GITBLIT, null, "gcPeriod");
} else {
config.setInt(Constants.CONFIG_GITBLIT, null, "gcPeriod", repository.gcPeriod);
}
if (repository.lastGC != null) {
config.setString(Constants.CONFIG_GITBLIT, null, "lastGC", new SimpleDateFormat(Constants.ISO8601).format(repository.lastGC));
}
if (repository.maxActivityCommits == settings.getInteger(Keys.web.maxActivityCommits, 0)) {
// use default from config
config.unset(Constants.CONFIG_GITBLIT, null, "maxActivityCommits");
} else {
config.setInt(Constants.CONFIG_GITBLIT, null, "maxActivityCommits", repository.maxActivityCommits);
}
updateList(config, "federationSets", repository.federationSets);
updateList(config, "preReceiveScript", repository.preReceiveScripts);
updateList(config, "postReceiveScript", repository.postReceiveScripts);
updateList(config, "mailingList", repository.mailingLists);
updateList(config, "indexBranch", repository.indexedBranches);
// User Defined Properties
if (repository.customFields != null) {
if (repository.customFields.size() == 0) {
// clear section
config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
} else {
for (Entry<String, String> property : repository.customFields.entrySet()) {
// set field
String key = property.getKey();
String value = property.getValue();
config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
}
}
}
try {
config.save();
} catch (IOException e) {
logger.error("Failed to save repository config!", e);
}
}
private void updateList(StoredConfig config, String field, List<String> list) {
// a null list is skipped, not cleared
// this is for RPC administration where an older manager might be used
if (list == null) {
return;
}
if (ArrayUtils.isEmpty(list)) {
config.unset(Constants.CONFIG_GITBLIT, null, field);
} else {
config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
}
}
/**
* Deletes the repository from the file system and removes the repository
* permission from all repository users.
*
* @param model
* @return true if successful
*/
public boolean deleteRepositoryModel(RepositoryModel model) {
return deleteRepository(model.name);
}
/**
* Deletes the repository from the file system and removes the repository
* permission from all repository users.
*
* @param repositoryName
* @return true if successful
*/
public boolean deleteRepository(String repositoryName) {
try {
closeRepository(repositoryName);
// clear the repository cache
clearRepositoryMetadataCache(repositoryName);
RepositoryModel model = removeFromCachedRepositoryList(repositoryName);
if (model != null && !ArrayUtils.isEmpty(model.forks)) {
resetRepositoryListCache();
}
File folder = new File(repositoriesFolder, repositoryName);
if (folder.exists() && folder.isDirectory()) {
FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
if (userService.deleteRepositoryRole(repositoryName)) {
logger.info(MessageFormat.format("Repository \"{0}\" deleted", repositoryName));
return true;
}
}
} catch (Throwable t) {
logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
}
return false;
}
/**
* Returns an html version of the commit message with any global or
* repository-specific regular expression substitution applied.
*
* @param repositoryName
* @param text
* @return html version of the commit message
*/
public String processCommitMessage(String repositoryName, String text) {
String html = StringUtils.breakLinesForHtml(text);
Map<String, String> map = new HashMap<String, String>();
// global regex keys
if (settings.getBoolean(Keys.regex.global, false)) {
for (String key : settings.getAllKeys(Keys.regex.global)) {
if (!key.equals(Keys.regex.global)) {
String subKey = key.substring(key.lastIndexOf('.') + 1);
map.put(subKey, settings.getString(key, ""));
}
}
}
// repository-specific regex keys
List<String> keys = settings.getAllKeys(Keys.regex._ROOT + "."
+ repositoryName.toLowerCase());
for (String key : keys) {
String subKey = key.substring(key.lastIndexOf('.') + 1);
map.put(subKey, settings.getString(key, ""));
}
for (Entry<String, String> entry : map.entrySet()) {
String definition = entry.getValue().trim();
String[] chunks = definition.split("!!!");
if (chunks.length == 2) {
html = html.replaceAll(chunks[0], chunks[1]);
} else {
logger.warn(entry.getKey()
+ " improperly formatted. Use !!! to separate match from replacement: "
+ definition);
}
}
return html;
}
/**
* Returns Gitblit's scheduled executor service for scheduling tasks.
*
* @return scheduledExecutor
*/
public ScheduledExecutorService executor() {
return scheduledExecutor;
}
public static boolean canFederate() {
String passphrase = getString(Keys.federation.passphrase, "");
return !StringUtils.isEmpty(passphrase);
}
/**
* Configures this Gitblit instance to pull any registered federated gitblit
* instances.
*/
private void configureFederation() {
boolean validPassphrase = true;
String passphrase = settings.getString(Keys.federation.passphrase, "");
if (StringUtils.isEmpty(passphrase)) {
logger.warn("Federation passphrase is blank! This server can not be PULLED from.");
validPassphrase = false;
}
if (validPassphrase) {
// standard tokens
for (FederationToken tokenType : FederationToken.values()) {
logger.info(MessageFormat.format("Federation {0} token = {1}", tokenType.name(),
getFederationToken(tokenType)));
}
// federation set tokens
for (String set : settings.getStrings(Keys.federation.sets)) {
logger.info(MessageFormat.format("Federation Set {0} token = {1}", set,
getFederationToken(set)));
}
}
// Schedule the federation executor
List<FederationModel> registrations = getFederationRegistrations();
if (registrations.size() > 0) {
FederationPullExecutor executor = new FederationPullExecutor(registrations, true);
scheduledExecutor.schedule(executor, 1, TimeUnit.MINUTES);
}
}
/**
* Returns the list of federated gitblit instances that this instance will
* try to pull.
*
* @return list of registered gitblit instances
*/
public List<FederationModel> getFederationRegistrations() {
if (federationRegistrations.isEmpty()) {
federationRegistrations.addAll(FederationUtils.getFederationRegistrations(settings));
}
return federationRegistrations;
}
/**
* Retrieve the specified federation registration.
*
* @param name
* the name of the registration
* @return a federation registration
*/
public FederationModel getFederationRegistration(String url, String name) {
// check registrations
for (FederationModel r : getFederationRegistrations()) {
if (r.name.equals(name) && r.url.equals(url)) {
return r;
}
}
// check the results
for (FederationModel r : getFederationResultRegistrations()) {
if (r.name.equals(name) && r.url.equals(url)) {
return r;
}
}
return null;
}
/**
* Returns the list of federation sets.
*
* @return list of federation sets
*/
public List<FederationSet> getFederationSets(String gitblitUrl) {
List<FederationSet> list = new ArrayList<FederationSet>();
// generate standard tokens
for (FederationToken type : FederationToken.values()) {
FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));
fset.repositories = getRepositories(gitblitUrl, fset.token);
list.add(fset);
}
// generate tokens for federation sets
for (String set : settings.getStrings(Keys.federation.sets)) {
FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,
getFederationToken(set));
fset.repositories = getRepositories(gitblitUrl, fset.token);
list.add(fset);
}
return list;
}
/**
* Returns the list of possible federation tokens for this Gitblit instance.
*
* @return list of federation tokens
*/
public List<String> getFederationTokens() {
List<String> tokens = new ArrayList<String>();
// generate standard tokens
for (FederationToken type : FederationToken.values()) {
tokens.add(getFederationToken(type));
}
// generate tokens for federation sets
for (String set : settings.getStrings(Keys.federation.sets)) {
tokens.add(getFederationToken(set));
}
return tokens;
}
/**
* Returns the specified federation token for this Gitblit instance.
*
* @param type
* @return a federation token
*/
public String getFederationToken(FederationToken type) {
return getFederationToken(type.name());
}
/**
* Returns the specified federation token for this Gitblit instance.
*
* @param value
* @return a federation token
*/
public String getFederationToken(String value) {
String passphrase = settings.getString(Keys.federation.passphrase, "");
return StringUtils.getSHA1(passphrase + "-" + value);
}
/**
* Compares the provided token with this Gitblit instance's tokens and
* determines if the requested permission may be granted to the token.
*
* @param req
* @param token
* @return true if the request can be executed
*/
public boolean validateFederationRequest(FederationRequest req, String token) {
String all = getFederationToken(FederationToken.ALL);
String unr = getFederationToken(FederationToken.USERS_AND_REPOSITORIES);
String jur = getFederationToken(FederationToken.REPOSITORIES);
switch (req) {
case PULL_REPOSITORIES:
return token.equals(all) || token.equals(unr) || token.equals(jur);
case PULL_USERS:
case PULL_TEAMS:
return token.equals(all) || token.equals(unr);
case PULL_SETTINGS:
case PULL_SCRIPTS:
return token.equals(all);
default:
break;
}
return false;
}
/**
* Acknowledge and cache the status of a remote Gitblit instance.
*
* @param identification
* the identification of the pulling Gitblit instance
* @param registration
* the registration from the pulling Gitblit instance
* @return true if acknowledged
*/
public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
// reset the url to the identification of the pulling Gitblit instance
registration.url = identification;
String id = identification;
if (!StringUtils.isEmpty(registration.folder)) {
id += "-" + registration.folder;
}
federationPullResults.put(id, registration);
return true;
}
/**
* Returns the list of registration results.
*
* @return the list of registration results
*/
public List<FederationModel> getFederationResultRegistrations() {
return new ArrayList<FederationModel>(federationPullResults.values());
}
/**
* Submit a federation proposal. The proposal is cached locally and the
* Gitblit administrator(s) are notified via email.
*
* @param proposal
* the proposal
* @param gitblitUrl
* the url of your gitblit instance to send an email to
* administrators
* @return true if the proposal was submitted
*/
public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
// convert proposal to json
String json = JsonUtils.toJsonString(proposal);
try {
// make the proposals folder
File proposalsFolder = getProposalsFolder();
proposalsFolder.mkdirs();
// cache json to a file
File file = new File(proposalsFolder, proposal.token + Constants.PROPOSAL_EXT);
com.gitblit.utils.FileUtils.writeContent(file, json);
} catch (Exception e) {
logger.error(MessageFormat.format("Failed to cache proposal from {0}", proposal.url), e);
}
// send an email, if possible
try {
Message message = mailExecutor.createMessageForAdministrators();
if (message != null) {
message.setSubject("Federation proposal from " + proposal.url);
message.setText("Please review the proposal @ " + gitblitUrl + "/proposal/"
+ proposal.token);
mailExecutor.queue(message);
}
} catch (Throwable t) {
logger.error("Failed to notify administrators of proposal", t);
}
return true;
}
/**
* Returns the list of pending federation proposals
*
* @return list of federation proposals
*/
public List<FederationProposal> getPendingFederationProposals() {
List<FederationProposal> list = new ArrayList<FederationProposal>();
File folder = getProposalsFolder();
if (folder.exists()) {
File[] files = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile()
&& file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
}
});
for (File file : files) {
String json = com.gitblit.utils.FileUtils.readContent(file, null);
FederationProposal proposal = JsonUtils.fromJsonString(json,
FederationProposal.class);
list.add(proposal);
}
}
return list;
}
/**
* Get repositories for the specified token.
*
* @param gitblitUrl
* the base url of this gitblit instance
* @param token
* the federation token
* @return a map of <cloneurl, RepositoryModel>
*/
public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
Map<String, String> federationSets = new HashMap<String, String>();
for (String set : getStrings(Keys.federation.sets)) {
federationSets.put(getFederationToken(set), set);
}
// Determine the Gitblit clone url
StringBuilder sb = new StringBuilder();
sb.append(gitblitUrl);
sb.append(Constants.GIT_PATH);
sb.append("{0}");
String cloneUrl = sb.toString();
// Retrieve all available repositories
UserModel user = new UserModel(Constants.FEDERATION_USER);
user.canAdmin = true;
List<RepositoryModel> list = getRepositoryModels(user);
// create the [cloneurl, repositoryModel] map
Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
for (RepositoryModel model : list) {
// by default, setup the url for THIS repository
String url = MessageFormat.format(cloneUrl, model.name);
switch (model.federationStrategy) {
case EXCLUDE:
// skip this repository
continue;
case FEDERATE_ORIGIN:
// federate the origin, if it is defined
if (!StringUtils.isEmpty(model.origin)) {
url = model.origin;
}
break;
default:
break;
}
if (federationSets.containsKey(token)) {
// include repositories only for federation set
String set = federationSets.get(token);
if (model.federationSets.contains(set)) {
repositories.put(url, model);
}
} else {
// standard federation token for ALL
repositories.put(url, model);
}
}
return repositories;
}
/**
* Creates a proposal from the token.
*
* @param gitblitUrl
* the url of this Gitblit instance
* @param token
* @return a potential proposal
*/
public FederationProposal createFederationProposal(String gitblitUrl, String token) {
FederationToken tokenType = FederationToken.REPOSITORIES;
for (FederationToken type : FederationToken.values()) {
if (token.equals(getFederationToken(type))) {
tokenType = type;
break;
}
}
Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token,
repositories);
return proposal;
}
/**
* Returns the proposal identified by the supplied token.
*
* @param token
* @return the specified proposal or null
*/
public FederationProposal getPendingFederationProposal(String token) {
List<FederationProposal> list = getPendingFederationProposals();
for (FederationProposal proposal : list) {
if (proposal.token.equals(token)) {
return proposal;
}
}
return null;
}
/**
* Deletes a pending federation proposal.
*
* @param a
* proposal
* @return true if the proposal was deleted
*/
public boolean deletePendingFederationProposal(FederationProposal proposal) {
File folder = getProposalsFolder();
File file = new File(folder, proposal.token + Constants.PROPOSAL_EXT);
return file.delete();
}
/**
* Returns the list of all Groovy push hook scripts. Script files must have
* .groovy extension
*
* @return list of available hook scripts
*/
public List<String> getAllScripts() {
File groovyFolder = getGroovyScriptsFolder();
File[] files = groovyFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".groovy");
}
});
List<String> scripts = new ArrayList<String>();
if (files != null) {
for (File file : files) {
String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
scripts.add(script);
}
}
return scripts;
}
/**
* Returns the list of pre-receive scripts the repository inherited from the
* global settings and team affiliations.
*
* @param repository
* if null only the globally specified scripts are returned
* @return a list of scripts
*/
public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
Set<String> scripts = new LinkedHashSet<String>();
// Globals
for (String script : getStrings(Keys.groovy.preReceiveScripts)) {
if (script.endsWith(".groovy")) {
scripts.add(script.substring(0, script.lastIndexOf('.')));
} else {
scripts.add(script);
}
}
// Team Scripts
if (repository != null) {
for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
TeamModel team = userService.getTeamModel(teamname);
scripts.addAll(team.preReceiveScripts);
}
}
return new ArrayList<String>(scripts);
}
/**
* Returns the list of all available Groovy pre-receive push hook scripts
* that are not already inherited by the repository. Script files must have
* .groovy extension
*
* @param repository
* optional parameter
* @return list of available hook scripts
*/
public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
Set<String> inherited = new TreeSet<String>(getPreReceiveScriptsInherited(repository));
// create list of available scripts by excluding inherited scripts
List<String> scripts = new ArrayList<String>();
for (String script : getAllScripts()) {
if (!inherited.contains(script)) {
scripts.add(script);
}
}
return scripts;
}
/**
* Returns the list of post-receive scripts the repository inherited from
* the global settings and team affiliations.
*
* @param repository
* if null only the globally specified scripts are returned
* @return a list of scripts
*/
public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
Set<String> scripts = new LinkedHashSet<String>();
// Global Scripts
for (String script : getStrings(Keys.groovy.postReceiveScripts)) {
if (script.endsWith(".groovy")) {
scripts.add(script.substring(0, script.lastIndexOf('.')));
} else {
scripts.add(script);
}
}
// Team Scripts
if (repository != null) {
for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
TeamModel team = userService.getTeamModel(teamname);
scripts.addAll(team.postReceiveScripts);
}
}
return new ArrayList<String>(scripts);
}
/**
* Returns the list of unused Groovy post-receive push hook scripts that are
* not already inherited by the repository. Script files must have .groovy
* extension
*
* @param repository
* optional parameter
* @return list of available hook scripts
*/
public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
Set<String> inherited = new TreeSet<String>(getPostReceiveScriptsInherited(repository));
// create list of available scripts by excluding inherited scripts
List<String> scripts = new ArrayList<String>();
for (String script : getAllScripts()) {
if (!inherited.contains(script)) {
scripts.add(script);
}
}
return scripts;
}
/**
* Search the specified repositories using the Lucene query.
*
* @param query
* @param page
* @param pageSize
* @param repositories
* @return
*/
public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {
List<SearchResult> srs = luceneExecutor.search(query, page, pageSize, repositories);
return srs;
}
/**
* Notify the administrators by email.
*
* @param subject
* @param message
*/
public void sendMailToAdministrators(String subject, String message) {
try {
Message mail = mailExecutor.createMessageForAdministrators();
if (mail != null) {
mail.setSubject(subject);
mail.setText(message);
mailExecutor.queue(mail);
}
} catch (MessagingException e) {
logger.error("Messaging error", e);
}
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendMail(String subject, String message, Collection<String> toAddresses) {
this.sendMail(subject, message, toAddresses.toArray(new String[0]));
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendMail(String subject, String message, String... toAddresses) {
try {
Message mail = mailExecutor.createMessage(toAddresses);
if (mail != null) {
mail.setSubject(subject);
mail.setText(message);
mailExecutor.queue(mail);
}
} catch (MessagingException e) {
logger.error("Messaging error", e);
}
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendHtmlMail(String subject, String message, Collection<String> toAddresses) {
this.sendHtmlMail(subject, message, toAddresses.toArray(new String[0]));
}
/**
* Notify users by email of something.
*
* @param subject
* @param message
* @param toAddresses
*/
public void sendHtmlMail(String subject, String message, String... toAddresses) {
try {
Message mail = mailExecutor.createMessage(toAddresses);
if (mail != null) {
mail.setSubject(subject);
mail.setContent(message, "text/html");
mailExecutor.queue(mail);
}
} catch (MessagingException e) {
logger.error("Messaging error", e);
}
}
/**
* Returns the descriptions/comments of the Gitblit config settings.
*
* @return SettingsModel
*/
public ServerSettings getSettingsModel() {
// ensure that the current values are updated in the setting models
for (String key : settings.getAllKeys(null)) {
SettingModel setting = settingsModel.get(key);
if (setting == null) {
// unreferenced setting, create a setting model
setting = new SettingModel();
setting.name = key;
settingsModel.add(setting);
}
setting.currentValue = settings.getString(key, "");
}
settingsModel.pushScripts = getAllScripts();
return settingsModel;
}
/**
* Parse the properties file and aggregate all the comments by the setting
* key. A setting model tracks the current value, the default value, the
* description of the setting and and directives about the setting.
* @param referencePropertiesInputStream
*
* @return Map<String, SettingModel>
*/
private ServerSettings loadSettingModels(InputStream referencePropertiesInputStream) {
ServerSettings settingsModel = new ServerSettings();
settingsModel.supportsCredentialChanges = userService.supportsCredentialChanges();
settingsModel.supportsDisplayNameChanges = userService.supportsDisplayNameChanges();
settingsModel.supportsEmailAddressChanges = userService.supportsEmailAddressChanges();
settingsModel.supportsTeamMembershipChanges = userService.supportsTeamMembershipChanges();
try {
// Read bundled Gitblit properties to extract setting descriptions.
// This copy is pristine and only used for populating the setting
// models map.
InputStream is = referencePropertiesInputStream;
BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
StringBuilder description = new StringBuilder();
SettingModel setting = new SettingModel();
String line = null;
while ((line = propertiesReader.readLine()) != null) {
if (line.length() == 0) {
description.setLength(0);
setting = new SettingModel();
} else {
if (line.charAt(0) == '#') {
if (line.length() > 1) {
String text = line.substring(1).trim();
if (SettingModel.CASE_SENSITIVE.equals(text)) {
setting.caseSensitive = true;
} else if (SettingModel.RESTART_REQUIRED.equals(text)) {
setting.restartRequired = true;
} else if (SettingModel.SPACE_DELIMITED.equals(text)) {
setting.spaceDelimited = true;
} else if (text.startsWith(SettingModel.SINCE)) {
try {
setting.since = text.split(" ")[1];
} catch (Exception e) {
setting.since = text;
}
} else {
description.append(text);
description.append('\n');
}
}
} else {
String[] kvp = line.split("=", 2);
String key = kvp[0].trim();
setting.name = key;
setting.defaultValue = kvp[1].trim();
setting.currentValue = setting.defaultValue;
setting.description = description.toString().trim();
settingsModel.add(setting);
description.setLength(0);
setting = new SettingModel();
}
}
}
propertiesReader.close();
} catch (NullPointerException e) {
logger.error("Failed to find resource copy of gitblit.properties");
} catch (IOException e) {
logger.error("Failed to load resource copy of gitblit.properties");
}
return settingsModel;
}
/**
* Configure the Gitblit singleton with the specified settings source. This
* source may be file settings (Gitblit GO) or may be web.xml settings
* (Gitblit WAR).
*
* @param settings
*/
public void configureContext(IStoredSettings settings, boolean startFederation) {
logger.info("Reading configuration from " + settings.toString());
this.settings = settings;
repositoriesFolder = getRepositoriesFolder();
logger.info("Git repositories folder " + repositoriesFolder.getAbsolutePath());
// prepare service executors
mailExecutor = new MailExecutor(settings);
luceneExecutor = new LuceneExecutor(settings, repositoriesFolder);
gcExecutor = new GCExecutor(settings);
// calculate repository list settings checksum for future config changes
repositoryListSettingsChecksum.set(getRepositoryListSettingsChecksum());
// build initial repository list
if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
logger.info("Identifying available repositories...");
getRepositoryList();
}
logTimezone("JVM", TimeZone.getDefault());
logTimezone(Constants.NAME, getTimezone());
serverStatus = new ServerStatus(isGO());
if (this.userService == null) {
String realm = settings.getString(Keys.realm.userService, "users.properties");
IUserService loginService = null;
try {
// check to see if this "file" is a login service class
Class<?> realmClass = Class.forName(realm);
loginService = (IUserService) realmClass.newInstance();
} catch (Throwable t) {
loginService = new GitblitUserService();
}
setUserService(loginService);
}
// load and cache the project metadata
projectConfigs = new FileBasedConfig(getFileOrFolder(Keys.web.projectsFile, "projects.conf"), FS.detect());
getProjectConfigs();
// schedule mail engine
if (mailExecutor.isReady()) {
logger.info("Mail executor is scheduled to process the message queue every 2 minutes.");
scheduledExecutor.scheduleAtFixedRate(mailExecutor, 1, 2, TimeUnit.MINUTES);
} else {
logger.warn("Mail server is not properly configured. Mail services disabled.");
}
// schedule lucene engine
logger.info("Lucene executor is scheduled to process indexed branches every 2 minutes.");
scheduledExecutor.scheduleAtFixedRate(luceneExecutor, 1, 2, TimeUnit.MINUTES);
// schedule gc engine
if (gcExecutor.isReady()) {
logger.info("GC executor is scheduled to scan repositories every 24 hours.");
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, settings.getInteger(Keys.git.garbageCollectionHour, 0));
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date cd = c.getTime();
Date now = new Date();
int delay = 0;
if (cd.before(now)) {
c.add(Calendar.DATE, 1);
cd = c.getTime();
}
delay = (int) ((cd.getTime() - now.getTime())/TimeUtils.MIN);
String when = delay + " mins";
if (delay > 60) {
when = MessageFormat.format("{0,number,0.0} hours", ((float)delay)/60f);
}
logger.info(MessageFormat.format("Next scheculed GC scan is in {0}", when));
scheduledExecutor.scheduleAtFixedRate(gcExecutor, delay, 60*24, TimeUnit.MINUTES);
}
if (startFederation) {
configureFederation();
}
// Configure JGit
WindowCacheConfig cfg = new WindowCacheConfig();
cfg.setPackedGitWindowSize(settings.getFilesize(Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
cfg.setPackedGitLimit(settings.getFilesize(Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
cfg.setDeltaBaseCacheLimit(settings.getFilesize(Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
cfg.setPackedGitOpenFiles(settings.getFilesize(Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
cfg.setStreamFileThreshold(settings.getFilesize(Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
cfg.setPackedGitMMAP(settings.getBoolean(Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
try {
WindowCache.reconfigure(cfg);
logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
logger.debug(MessageFormat.format("{0} = {1}", Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
} catch (IllegalArgumentException e) {
logger.error("Failed to configure JGit parameters!", e);
}
ContainerUtils.CVE_2007_0450.test();
}
private void logTimezone(String type, TimeZone zone) {
SimpleDateFormat df = new SimpleDateFormat("z Z");
df.setTimeZone(zone);
String offset = df.format(new Date());
logger.info(type + " timezone is " + zone.getID() + " (" + offset + ")");
}
/**
* Configure Gitblit from the web.xml, if no configuration has already been
* specified.
*
* @see ServletContextListener.contextInitialize(ServletContextEvent)
*/
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
contextInitialized(contextEvent, contextEvent.getServletContext().getResourceAsStream("/WEB-INF/reference.properties"));
}
public void contextInitialized(ServletContextEvent contextEvent, InputStream referencePropertiesInputStream) {
servletContext = contextEvent.getServletContext();
if (settings == null) {
// Gitblit WAR is running in a servlet container
ServletContext context = contextEvent.getServletContext();
WebXmlSettings webxmlSettings = new WebXmlSettings(context);
// gitblit.properties file located within the webapp
String webProps = context.getRealPath("/WEB-INF/gitblit.properties");
if (!StringUtils.isEmpty(webProps)) {
File overrideFile = new File(webProps);
webxmlSettings.applyOverrides(overrideFile);
}
// gitblit.properties file located outside the deployed war
// folder lie, for example, on RedHat OpenShift.
File overrideFile = getFileOrFolder("gitblit.properties");
if (!overrideFile.getPath().equals("gitblit.properties")) {
webxmlSettings.applyOverrides(overrideFile);
}
configureContext(webxmlSettings, true);
// Copy the included scripts to the configured groovy folder
File localScripts = getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
if (!localScripts.exists()) {
File includedScripts = new File(context.getRealPath("/WEB-INF/groovy"));
if (!includedScripts.equals(localScripts)) {
try {
com.gitblit.utils.FileUtils.copy(localScripts, includedScripts.listFiles());
} catch (IOException e) {
logger.error(MessageFormat.format(
"Failed to copy included Groovy scripts from {0} to {1}",
includedScripts, localScripts));
}
}
}
}
settingsModel = loadSettingModels(referencePropertiesInputStream);
serverStatus.servletContainer = servletContext.getServerInfo();
}
/**
* Gitblit is being shutdown either because the servlet container is
* shutting down or because the servlet container is re-deploying Gitblit.
*/
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
logger.info("Gitblit context destroyed by servlet container.");
scheduledExecutor.shutdownNow();
luceneExecutor.close();
gcExecutor.close();
}
/**
*
* @return true if we are running the gc executor
*/
public boolean isCollectingGarbage() {
return gcExecutor.isRunning();
}
/**
* Returns true if Gitblit is actively collecting garbage in this repository.
*
* @param repositoryName
* @return true if actively collecting garbage
*/
public boolean isCollectingGarbage(String repositoryName) {
return gcExecutor.isCollectingGarbage(repositoryName);
}
/**
* Creates a personal fork of the specified repository. The clone is view
* restricted by default and the owner of the source repository is given
* access to the clone.
*
* @param repository
* @param user
* @return the repository model of the fork, if successful
* @throws GitBlitException
*/
public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException {
String cloneName = MessageFormat.format("~{0}/{1}.git", user.username, StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
String fromUrl = MessageFormat.format("file://{0}/{1}", repositoriesFolder.getAbsolutePath(), repository.name);
// clone the repository
try {
JGitUtils.cloneRepository(repositoriesFolder, cloneName, fromUrl, true, null);
} catch (Exception e) {
throw new GitBlitException(e);
}
// create a Gitblit repository model for the clone
RepositoryModel cloneModel = repository.cloneAs(cloneName);
// owner has REWIND/RW+ permissions
cloneModel.owner = user.username;
updateRepositoryModel(cloneName, cloneModel, false);
// add the owner of the source repository to the clone's access list
if (!StringUtils.isEmpty(repository.owner)) {
UserModel originOwner = getUserModel(repository.owner);
if (originOwner != null) {
originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE);
updateUserModel(originOwner.username, originOwner, false);
}
}
// grant origin's user list clone permission to fork
List<String> users = getRepositoryUsers(repository);
List<UserModel> cloneUsers = new ArrayList<UserModel>();
for (String name : users) {
if (!name.equalsIgnoreCase(user.username)) {
UserModel cloneUser = getUserModel(name);
if (cloneUser.canClone(repository)) {
// origin user can clone origin, grant clone access to fork
cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneUsers.add(cloneUser);
}
}
userService.updateUserModels(cloneUsers);
// grant origin's team list clone permission to fork
List<String> teams = getRepositoryTeams(repository);
List<TeamModel> cloneTeams = new ArrayList<TeamModel>();
for (String name : teams) {
TeamModel cloneTeam = getTeamModel(name);
if (cloneTeam.canClone(repository)) {
// origin team can clone origin, grant clone access to fork
cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE);
}
cloneTeams.add(cloneTeam);
}
userService.updateTeamModels(cloneTeams);
// add this clone to the cached model
addToCachedRepositoryList(cloneModel);
return cloneModel;
}
/**
* Allow to understand if GitBlit supports and is configured to allow
* cookie-based authentication.
*
* @return status of Cookie authentication enablement.
*/
public boolean allowCookieAuthentication() {
return GitBlit.getBoolean(Keys.web.allowCookieAuthentication, true) && userService.supportsCookies();
}
}
| true | true | public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
if (gcExecutor.isCollectingGarbage(repositoryName)) {
throw new GitBlitException(MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}",
repositoryName));
}
Repository r = null;
String projectPath = StringUtils.getFirstPathElement(repository.name);
if (!StringUtils.isEmpty(projectPath)) {
if (projectPath.equalsIgnoreCase(getString(Keys.web.repositoryRootGroupName, "main"))) {
// strip leading group name
repository.name = repository.name.substring(projectPath.length() + 1);
}
}
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
File parentFile = destFolder.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new GitBlitException(MessageFormat.format(
"Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
}
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// rename fork origins in their configs
if (!ArrayUtils.isEmpty(repository.forks)) {
for (String fork : repository.forks) {
Repository rf = getRepository(fork);
try {
StoredConfig config = rf.getConfig();
String origin = config.getString("remote", "origin", "url");
origin = origin.replace(repositoryName, repository.name);
config.setString("remote", "origin", "url", origin);
config.save();
} catch (Exception e) {
logger.error("Failed to update repository fork config for " + fork, e);
}
rf.close();
}
}
// remove this repository from any origin model's fork list
if (!StringUtils.isEmpty(repository.originRepository)) {
RepositoryModel origin = repositoryListCache.get(repository.originRepository);
if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
origin.forks.remove(repositoryName);
}
}
// clear the cache
clearRepositoryMetadataCache(repositoryName);
repository.resetDisplayName();
}
// load repository
logger.info("edit repository " + repository.name);
r = getRepository(repository.name);
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
// only update symbolic head if it changes
String currentRef = JGitUtils.getHEADRef(r);
if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}",
repository.name, currentRef, repository.HEAD));
if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
// clear the cache
clearRepositoryMetadataCache(repository.name);
}
}
// close the repository object
r.close();
}
// update repository cache
removeFromCachedRepositoryList(repositoryName);
// model will actually be replaced on next load because config is stale
addToCachedRepositoryList(repository);
}
| public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
boolean isCreate) throws GitBlitException {
if (gcExecutor.isCollectingGarbage(repositoryName)) {
throw new GitBlitException(MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}",
repositoryName));
}
Repository r = null;
String projectPath = StringUtils.getFirstPathElement(repository.name);
if (!StringUtils.isEmpty(projectPath)) {
if (projectPath.equalsIgnoreCase(getString(Keys.web.repositoryRootGroupName, "main"))) {
// strip leading group name
repository.name = repository.name.substring(projectPath.length() + 1);
}
}
if (isCreate) {
// ensure created repository name ends with .git
if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (hasRepository(repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Can not create repository ''{0}'' because it already exists.",
repository.name));
}
// create repository
logger.info("create repository " + repository.name);
r = JGitUtils.createRepository(repositoriesFolder, repository.name);
} else {
// rename repository
if (!repositoryName.equalsIgnoreCase(repository.name)) {
if (!repository.name.toLowerCase().endsWith(
org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
}
if (new File(repositoriesFolder, repository.name).exists()) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename ''{0}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
closeRepository(repositoryName);
File folder = new File(repositoriesFolder, repositoryName);
File destFolder = new File(repositoriesFolder, repository.name);
if (destFolder.exists()) {
throw new GitBlitException(
MessageFormat
.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
repositoryName, repository.name));
}
File parentFile = destFolder.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
throw new GitBlitException(MessageFormat.format(
"Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
}
if (!folder.renameTo(destFolder)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
repository.name));
}
// rename the roles
if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
throw new GitBlitException(MessageFormat.format(
"Failed to rename repository permissions ''{0}'' to ''{1}''.",
repositoryName, repository.name));
}
// rename fork origins in their configs
if (!ArrayUtils.isEmpty(repository.forks)) {
for (String fork : repository.forks) {
Repository rf = getRepository(fork);
try {
StoredConfig config = rf.getConfig();
String origin = config.getString("remote", "origin", "url");
origin = origin.replace(repositoryName, repository.name);
config.setString("remote", "origin", "url", origin);
config.save();
} catch (Exception e) {
logger.error("Failed to update repository fork config for " + fork, e);
}
rf.close();
}
}
// remove this repository from any origin model's fork list
if (!StringUtils.isEmpty(repository.originRepository)) {
RepositoryModel origin = repositoryListCache.get(repository.originRepository);
if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
origin.forks.remove(repositoryName);
}
}
// clear the cache
clearRepositoryMetadataCache(repositoryName);
repository.resetDisplayName();
}
// load repository
logger.info("edit repository " + repository.name);
r = getRepository(repository.name);
}
// update settings
if (r != null) {
updateConfiguration(r, repository);
// only update symbolic head if it changes
String currentRef = JGitUtils.getHEADRef(r);
if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}",
repository.name, currentRef, repository.HEAD));
if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
// clear the cache
clearRepositoryMetadataCache(repository.name);
}
}
// close the repository object
r.close();
}
// update repository cache
removeFromCachedRepositoryList(repositoryName);
// model will actually be replaced on next load because config is stale
addToCachedRepositoryList(repository);
}
|
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
index 936eba653..8212f9c5b 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/ModelAdapter.java
@@ -1,427 +1,427 @@
/*
*************************************************************************
* Copyright (c) 2006 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.report.data.adapter.impl;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSourceDesign;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ColumnDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ComputedColumn;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.ParameterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ColumnAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ComputedColumnAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ConditionAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ExpressionAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.FilterAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.GroupAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.InputParamBindingAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.JointDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.OdaDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.OdaDataSourceAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ParameterAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ScriptDataSetAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.ScriptDataSourceAdapter;
import org.eclipse.birt.report.data.adapter.internal.adapter.SortAdapter;
import org.eclipse.birt.report.model.api.AggregationArgumentHandle;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSetParameterHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.Expression;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSourceHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.model.api.ScriptDataSourceHandle;
import org.eclipse.birt.report.model.api.SortKeyHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;
import org.mozilla.javascript.Scriptable;
/**
* An adaptor to create Data Engine request objects based on Model element definitions
*/
public class ModelAdapter implements IModelAdapter
{
private static Logger logger = Logger.getLogger( ModelAdapter.class.getName( ) );
DataSessionContext context;
public ModelAdapter( DataSessionContext context)
{
this.context = context;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptDataSource(org.eclipse.birt.report.model.api.DataSourceHandle)
*/
public BaseDataSourceDesign adaptDataSource( DataSourceHandle handle ) throws BirtException
{
if ( handle instanceof OdaDataSourceHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
return new OdaDataSourceAdapter( (OdaDataSourceHandle) handle,
propBindingScope,
context.getDataEngineContext( ) );
}
if ( handle instanceof ScriptDataSourceHandle )
{
return new ScriptDataSourceAdapter( (ScriptDataSourceHandle) handle );
}
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
return null;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptDataSet(org.eclipse.birt.report.model.api.DataSetHandle)
*/
public BaseDataSetDesign adaptDataSet( DataSetHandle handle ) throws BirtException
{
BaseDataSetDesign design = null;
if ( handle instanceof OdaDataSetHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
design = new OdaDataSetAdapter( (OdaDataSetHandle) handle,
propBindingScope,
this,
context.getDataEngineContext( ) );
}
if ( handle instanceof ScriptDataSetHandle )
design = new ScriptDataSetAdapter( (ScriptDataSetHandle) handle, this );
if ( handle instanceof JointDataSetHandle )
design = new JointDataSetAdapter( (JointDataSetHandle) handle, this );
if( design != null )
{
if( handle.getACLExpression( )!= null )
design.setDataSetACL( this.adaptExpression( (Expression) handle.getACLExpression( ).getValue( ) ) );
if( handle.getRowACLExpression( )!= null )
design.setRowACL( this.adaptExpression( (Expression) handle.getRowACLExpression( ).getValue( ) ) );
Iterator columnHintIterator = handle.columnHintsIterator( );
while( columnHintIterator.hasNext( ))
{
ColumnHintHandle ch = (ColumnHintHandle) columnHintIterator.next( );
design.setDataSetColumnACL( ch.getColumnName( ), this.adaptExpression( (Expression) ch.getACLExpression( ).getValue( ) ));
}
}
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
- return null;
+ return design;
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptConditionalExpression(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public ConditionalExpression adaptConditionalExpression(
String mainExpr, String operator, String operand1, String operand2 )
{
return new ConditionAdapter( mainExpr, operator, operand1, operand2);
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptExpression(java.lang.String, java.lang.String)
*/
public ScriptExpression adaptExpression( Expression expr, String dataType )
{
if( expr == null || expr.getStringExpression( ) == null )
return null;
return new ExpressionAdapter( expr, dataType );
}
/* *//**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptExpression(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*//*
public ScriptExpression adaptExpression( ComputedColumnHandle ccHandle )
{
return new ExpressionAdapter( ccHandle );
}
*/
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptFilter(org.eclipse.birt.report.model.api.FilterConditionHandle)
*/
public FilterDefinition adaptFilter( FilterConditionHandle modelFilter )
{
try
{
return new FilterAdapter( this, modelFilter );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptGroup(org.eclipse.birt.report.model.api.GroupHandle)
*/
public GroupDefinition adaptGroup( GroupHandle groupHandle )
{
try
{
return new GroupAdapter( this, groupHandle );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptSort(org.eclipse.birt.report.model.api.SortKeyHandle)
*/
public SortDefinition adaptSort( SortKeyHandle sortHandle )
{
try
{
return new SortAdapter( this, sortHandle );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptSort(java.lang.String, java.lang.String)
*/
public SortDefinition adaptSort( Expression expr, String direction )
{
try
{
return new SortAdapter( this, expr, direction );
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptParameter(org.eclipse.birt.report.model.api.DataSetParameterHandle)
*/
public ParameterDefinition adaptParameter( DataSetParameterHandle paramHandle )
{
return new ParameterAdapter( paramHandle );
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptInputParamBinding(org.eclipse.birt.report.model.api.ParamBindingHandle)
*/
public InputParameterBinding adaptInputParamBinding( ParamBindingHandle modelHandle )
{
try
{
return new InputParamBindingAdapter( this, modelHandle);
}
catch ( AdapterException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#ColumnAdaptor(org.eclipse.birt.report.model.api.ResultSetColumnHandle)
*/
public ColumnDefinition ColumnAdaptor( ResultSetColumnHandle modelColumn )
{
return new ColumnAdapter( modelColumn);
}
/**
* @throws AdapterException
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptComputedColumn(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*/
public ComputedColumn adaptComputedColumn( ComputedColumnHandle modelHandle ) throws AdapterException
{
return new ComputedColumnAdapter( this, modelHandle);
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.report.data.adapter.api.IModelAdapter#adaptBinding(org.eclipse.birt.report.model.api.ComputedColumnHandle)
*/
public IBinding adaptBinding( ComputedColumnHandle handle )
{
try
{
if ( handle == null )
return null;
Binding result = new Binding( handle.getName( ) );
if ( handle.getExpression( ) != null )
{
ScriptExpression expr = this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.EXPRESSION_MEMBER )
.getValue( ),
handle.getDataType( ) );
expr.setGroupName( handle.getAggregateOn( ) );
result.setExpression( expr );
}
result.setDisplayName( handle.getExternalizedValue( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.DISPLAY_NAME_ID_MEMBER,
org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.DISPLAY_NAME_MEMBER,
this.context.getDataEngineContext( ).getLocale( ) ) );
result.setDataType( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelDataType( handle.getDataType( ) ) );
result.setAggrFunction( org.eclipse.birt.report.data.adapter.api.DataAdapterUtil.adaptModelAggregationType( handle.getAggregateFunction( ) ) );
result.setFilter( handle.getFilterExpression( ) == null
? null
: this.adaptExpression( (Expression) handle.getExpressionProperty( org.eclipse.birt.report.model.api.elements.structures.ComputedColumn.FILTER_MEMBER )
.getValue( ),
DesignChoiceConstants.COLUMN_DATA_TYPE_BOOLEAN ) );
populateArgument( result, handle );
populateAggregateOns( result, handle );
return result;
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
return null;
}
}
/**
*
* @param handle
* @param result
* @throws AdapterException
*/
private void populateAggregateOns( IBinding result,
ComputedColumnHandle handle ) throws AdapterException
{
List aggrOns = handle.getAggregateOnList( );
if ( aggrOns == null )
return;
for ( int i = 0; i < aggrOns.size( ); i++ )
{
try
{
result.addAggregateOn( aggrOns.get( i ).toString( ) );
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
}
/**
*
* @param binding
* @param modelCmptdColumn
* @throws AdapterException
*/
private void populateArgument( IBinding binding,
ComputedColumnHandle modelCmptdColumn ) throws AdapterException
{
Iterator it = modelCmptdColumn.argumentsIterator( );
while ( it != null && it.hasNext( ) )
{
AggregationArgumentHandle arg = (AggregationArgumentHandle) it.next( );
try
{
Expression expr = (Expression)arg.getExpressionProperty( AggregationArgument.VALUE_MEMBER ).getValue( );
binding.addArgument( this.adaptExpression( expr ));
}
catch ( DataException e )
{
throw new AdapterException( e.getLocalizedMessage( ), e );
}
}
}
public ConditionalExpression adaptConditionalExpression(
Expression mainExpr, String operator,
Expression operand1, Expression operand2 )
{
return new ConditionAdapter( this.adaptExpression( mainExpr ), operator, this.adaptExpression( operand1 ), this.adaptExpression( operand2 ));
}
public ScriptExpression adaptExpression( Expression expr )
{
return adaptExpression( expr, IModelAdapter.ExpressionLocation.TABLE );
}
public ScriptExpression adaptExpression( String jsExpr, String dataType )
{
if( jsExpr == null )
return null;
return new ExpressionAdapter( jsExpr, dataType );
}
public ScriptExpression adaptJSExpression( String jsExpr, String dataType )
{
if( jsExpr == null )
return null;
return new ExpressionAdapter( jsExpr, dataType );
}
public ScriptExpression adaptExpression( Expression expr,
ExpressionLocation el )
{
if( expr == null || expr.getStringExpression( ) == null)
return null;
return new ExpressionAdapter( expr, el );
}
}
| true | true | public BaseDataSetDesign adaptDataSet( DataSetHandle handle ) throws BirtException
{
BaseDataSetDesign design = null;
if ( handle instanceof OdaDataSetHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
design = new OdaDataSetAdapter( (OdaDataSetHandle) handle,
propBindingScope,
this,
context.getDataEngineContext( ) );
}
if ( handle instanceof ScriptDataSetHandle )
design = new ScriptDataSetAdapter( (ScriptDataSetHandle) handle, this );
if ( handle instanceof JointDataSetHandle )
design = new JointDataSetAdapter( (JointDataSetHandle) handle, this );
if( design != null )
{
if( handle.getACLExpression( )!= null )
design.setDataSetACL( this.adaptExpression( (Expression) handle.getACLExpression( ).getValue( ) ) );
if( handle.getRowACLExpression( )!= null )
design.setRowACL( this.adaptExpression( (Expression) handle.getRowACLExpression( ).getValue( ) ) );
Iterator columnHintIterator = handle.columnHintsIterator( );
while( columnHintIterator.hasNext( ))
{
ColumnHintHandle ch = (ColumnHintHandle) columnHintIterator.next( );
design.setDataSetColumnACL( ch.getColumnName( ), this.adaptExpression( (Expression) ch.getACLExpression( ).getValue( ) ));
}
}
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
return null;
}
| public BaseDataSetDesign adaptDataSet( DataSetHandle handle ) throws BirtException
{
BaseDataSetDesign design = null;
if ( handle instanceof OdaDataSetHandle )
{
// If an external top level scope is available (i.e., our
// consumer
// is the report engine), use it to resolve property bindings.
// Otherwise
// property bindings are not resolved
Scriptable propBindingScope = context.hasExternalScope( )
? context.getTopScope( ) : null;
design = new OdaDataSetAdapter( (OdaDataSetHandle) handle,
propBindingScope,
this,
context.getDataEngineContext( ) );
}
if ( handle instanceof ScriptDataSetHandle )
design = new ScriptDataSetAdapter( (ScriptDataSetHandle) handle, this );
if ( handle instanceof JointDataSetHandle )
design = new JointDataSetAdapter( (JointDataSetHandle) handle, this );
if( design != null )
{
if( handle.getACLExpression( )!= null )
design.setDataSetACL( this.adaptExpression( (Expression) handle.getACLExpression( ).getValue( ) ) );
if( handle.getRowACLExpression( )!= null )
design.setRowACL( this.adaptExpression( (Expression) handle.getRowACLExpression( ).getValue( ) ) );
Iterator columnHintIterator = handle.columnHintsIterator( );
while( columnHintIterator.hasNext( ))
{
ColumnHintHandle ch = (ColumnHintHandle) columnHintIterator.next( );
design.setDataSetColumnACL( ch.getColumnName( ), this.adaptExpression( (Expression) ch.getACLExpression( ).getValue( ) ));
}
}
logger.warning( "handle type: " + (handle == null ? "" : handle.getClass( ).getName( )) ); //$NON-NLS-1$
return design;
}
|
diff --git a/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java b/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
index b5b9981..fde3d9f 100644
--- a/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
+++ b/src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
@@ -1,1144 +1,1144 @@
package org.agmip.translators.dssat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static org.agmip.translators.dssat.DssatCommonInput.copyItem;
import static org.agmip.util.MapUtil.*;
/**
* DSSAT Experiment Data I/O API Class
*
* @author Meng Zhang
* @version 1.0
*/
public class DssatXFileOutput extends DssatCommonOutput {
public static final DssatCRIDHelper crHelper = new DssatCRIDHelper();
/**
* DSSAT Experiment Data Output method
*
* @param arg0 file output path
* @param result data holder object
*/
@Override
public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
HashMap soilData = getObjectOr(result, "soil", new HashMap());
HashMap wthData = getObjectOr(result, "weather", new HashMap());
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList<HashMap> meArr; // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList<HashMap> smArr; // array for simulation control record
String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getExName(result),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
meArr = getDataList(expData, "dssat_environment_modification", "data");
smArr = getDataList(expData, "dssat_simulation_control", "data");
boolean isSmExist = !smArr.isEmpty();
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set field info
HashMap flData = new HashMap();
copyItem(flData, expData, "id_field");
if (wthData.isEmpty()) {
// copyItem(flData, expData, "wst_id");
flData.put("wst_id", getWthFileName(expData));
} else {
flData.put("wst_id", getWthFileName(wthData));
}
copyItem(flData, expData, "flsl");
copyItem(flData, expData, "flob");
copyItem(flData, expData, "fl_drntype");
copyItem(flData, expData, "fldrd");
copyItem(flData, expData, "fldrs");
copyItem(flData, expData, "flst");
copyItem(flData, soilData, "sltx");
copyItem(flData, soilData, "sldp");
copyItem(flData, expData, "soil_id");
copyItem(flData, expData, "fl_name");
copyItem(flData, expData, "fl_lat");
copyItem(flData, expData, "fl_long");
copyItem(flData, expData, "flele");
copyItem(flData, expData, "farea");
copyItem(flData, expData, "fllwr");
copyItem(flData, expData, "flsla");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(expData, "initial_conditions", new HashMap()), icArr);
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getDataList(expData, "soil", "soilLayer");
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int i = 0; i < soilLarys.size(); i++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(i), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(i), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
HashMap cuData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
// ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
// Set environment modification info
// meSubArr = getObjectOr(sqData, "em_data", meSubArr);
String meNumStr = "";
meNum = 0;
for (int j = 0, cnt = 0; j < meArr.size(); j++) {
if (!meNumStr.equals(meArr.get(j).get("em"))) {
meNumStr = (String) meArr.get(j).get("em");
cnt++;
if (em.equals(meNumStr)) {
meNum = cnt;
break;
}
}
}
// Set simulation control info
smNum = 0;
if (isSmExist) {
for (int j = 0; j < smArr.size(); j++) {
if (sm.equals(smArr.get(j).get("sm"))) {
smNum = j + 1;
break;
}
}
}
if (smNum == 0) {
smData.put("fertilizer", mfSubArr);
smData.put("irrigation", miSubArr);
smData.put("planting", mpData);
smNum = setSecDataArr(smData, smArr);
}
// if (!getValueOr(sqData, "sm_general", "").equals("")) {
// smData.put("sm_general", getValueOr(sqData, "sm_general", defValBlank));
// smData.put("sm_options", getValueOr(sqData, "sm_options", defValBlank));
// smData.put("sm_methods", getValueOr(sqData, "sm_methods", defValBlank));
// smData.put("sm_management", getValueOr(sqData, "sm_management", defValBlank));
// smData.put("sm_outputs", getValueOr(sqData, "sm_outputs", defValBlank));
// smData.put("sm_planting", getValueOr(sqData, "sm_planting", defValBlank));
// smData.put("sm_irrigation", getValueOr(sqData, "sm_irrigation", defValBlank));
// smData.put("sm_nitrogen", getValueOr(sqData, "sm_nitrogen", defValBlank));
// smData.put("sm_residues", getValueOr(sqData, "sm_residues", defValBlank));
// smData.put("sm_harvests", getValueOr(sqData, "sm_harvests", defValBlank));
// } else {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
- copyItem(cuData, evtData, "cul_id");
+ copyItem(cuData, evtData, "cul_id", "dssat_cul_id", false);
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
// meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
// smNum = setSecDataArr(smData, smArr);
// if (smArr.isEmpty()) {
// smNum = 1;
// }
sbData.append(String.format("%1$2s %2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
getValueOr(sqData, "trno", "1").toString(),
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
getValueOr(sqData, "tr_name", getValueOr(expData, "tr_name", defValC)).toString(),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "crid", defValBlank).toString(), // P.S. if missing, default value use blank string
getObjectOr(secData, "cul_id", defValC).toString(), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
if (getObjectOr(secData, "soil_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
getObjectOr(secData, "soil_id", defValC).toString(),
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
String emNumStr = "";
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
// secDataArr = (ArrayList) meArr.get(idx);
secData = meArr.get(idx);
if (!emNumStr.equals(secData.get("em"))) {
cnt++;
emNumStr = (String) secData.get("em");
}
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// for (int i = 0; i < secDataArr.size(); i++) {
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
// }
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
} else {
sbData.append(createSMMAStr(idx + 1, expData, secData));
}
}
} else {
sbData.append(createSMMAStr(1, expData, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Create string of Simulation Control and Automatic Management Section
*
* @param smid simulation index number
* @param expData date holder for experiment data
* @param trData date holder for one treatment data
* @return date string with format of "yyddd"
*/
private String createSMMAStr(int smid, HashMap expData, HashMap trData) {
StringBuilder sb = new StringBuilder();
String nitro = "Y";
String water = "Y";
String sdate;
String sm = String.format("%2d", smid);
ArrayList<HashMap> dataArr;
HashMap subData;
// // Check if the meta data of fertilizer is not "N" ("Y" or null)
// if (!getValueOr(expData, "fertilizer", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// // P.S. rule changed since all the necessary data has a default value for it
// dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList());
// if (dataArr.isEmpty()) {
// nitro = "N";
// }
//// for (int i = 0; i < dataArr.size(); i++) {
//// subData = dataArr.get(i);
//// if (getValueOr(subData, "date", "").equals("")
//// || getValueOr(subData, "fecd", "").equals("")
//// || getValueOr(subData, "feacd", "").equals("")
//// || getValueOr(subData, "feamn", "").equals("")) {
//// nitro = "N";
//// break;
//// }
//// }
// }
// // Check if the meta data of irrigation is not "N" ("Y" or null)
// if (!getValueOr(expData, "irrigation", "").equals("N")) {
//
// // Check if necessary data is missing in all the event records
// dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList());
// for (int i = 0; i < dataArr.size(); i++) {
// subData = dataArr.get(i);
// if (getValueOr(subData, "date", "").equals("")
// || getValueOr(subData, "irval", "").equals("")) {
// water = "N";
// break;
// }
// }
// }
sdate = getObjectOr(expData, "sdat", "").toString();
if (sdate.equals("")) {
subData = (HashMap) getObjectOr(trData, "planting", new HashMap());
sdate = getValueOr(subData, "date", defValD);
}
sdate = formatDateStr(sdate);
sb.append("*SIMULATION CONTROLS\r\n");
sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n");
sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n");
sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y M\r\n");
sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P"
sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
sb.append(sm).append(" MA R R R R M\r\n");
sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n");
sb.append("@ AUTOMATIC MANAGEMENT\r\n");
sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n");
sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n");
sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n");
sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n");
sb.append(sm).append(" RE 100 1 20\r\n");
sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
sb.append(sm).append(" HA 0 83057 100 0\r\n");
return sb.toString();
}
/**
* Get index value of the record and set new id value in the array
*
* @param m sub data
* @param arr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(HashMap m, ArrayList arr) {
if (!m.isEmpty()) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j).equals(m)) {
return j + 1;
}
}
arr.add(m);
return arr.size();
} else {
return 0;
}
}
/**
* Get index value of the record and set new id value in the array
*
* @param inArr sub array of data
* @param outArr array of sub data
* @return current index value of the sub data
*/
private int setSecDataArr(ArrayList inArr, ArrayList outArr) {
if (!inArr.isEmpty()) {
for (int j = 0; j < outArr.size(); j++) {
if (outArr.get(j).equals(inArr)) {
return j + 1;
}
}
outArr.add(inArr);
return outArr.size();
} else {
return 0;
}
}
/**
* To check if there is plot info data existed in the experiment
*
* @param expData experiment data holder
* @return the boolean value for if plot info exists
*/
private boolean isPlotInfoExist(Map expData) {
String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "plot_layout", "pltha", "plth#", "plthl", "plthm"};
for (int i = 0; i < plotIds.length; i++) {
if (!getValueOr(expData, plotIds[i], "").equals("")) {
return true;
}
}
return false;
}
/**
* To check if there is soil analysis info data existed in the experiment
*
* @param expData initial condition layer data array
* @return the boolean value for if soil analysis info exists
*/
private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) {
for (int i = 0; i < icSubArr.size(); i++) {
if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) {
return true;
}
}
return false;
}
/**
* Get sub data array from experiment data object
*
* @param expData experiment data holder
* @param blockName top level block name
* @param dataListName sub array name
* @return sub data array
*/
private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) {
HashMap dataBlock = getObjectOr(expData, blockName, new HashMap());
return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>());
}
/**
* Try to translate 3-bit crid to 2-bit version stored in the map
*
* @param cuData the cultivar data record
* @param id the field id for contain crop id info
*/
private void translateTo2BitCrid(HashMap cuData, String id) {
String crid = getObjectOr(cuData, id, "");
if (!crid.equals("")) {
DssatCRIDHelper crids = new DssatCRIDHelper();
cuData.put(id, crids.get2BitCrid(crid));
}
}
/**
* Try to translate 3-bit crid to 2-bit version stored in the map
*
* @param cuData the cultivar data record
*/
private void translateTo2BitCrid(HashMap cuData) {
translateTo2BitCrid(cuData, "crid");
}
}
| true | true | public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
HashMap soilData = getObjectOr(result, "soil", new HashMap());
HashMap wthData = getObjectOr(result, "weather", new HashMap());
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList<HashMap> meArr; // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList<HashMap> smArr; // array for simulation control record
String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getExName(result),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
meArr = getDataList(expData, "dssat_environment_modification", "data");
smArr = getDataList(expData, "dssat_simulation_control", "data");
boolean isSmExist = !smArr.isEmpty();
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set field info
HashMap flData = new HashMap();
copyItem(flData, expData, "id_field");
if (wthData.isEmpty()) {
// copyItem(flData, expData, "wst_id");
flData.put("wst_id", getWthFileName(expData));
} else {
flData.put("wst_id", getWthFileName(wthData));
}
copyItem(flData, expData, "flsl");
copyItem(flData, expData, "flob");
copyItem(flData, expData, "fl_drntype");
copyItem(flData, expData, "fldrd");
copyItem(flData, expData, "fldrs");
copyItem(flData, expData, "flst");
copyItem(flData, soilData, "sltx");
copyItem(flData, soilData, "sldp");
copyItem(flData, expData, "soil_id");
copyItem(flData, expData, "fl_name");
copyItem(flData, expData, "fl_lat");
copyItem(flData, expData, "fl_long");
copyItem(flData, expData, "flele");
copyItem(flData, expData, "farea");
copyItem(flData, expData, "fllwr");
copyItem(flData, expData, "flsla");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(expData, "initial_conditions", new HashMap()), icArr);
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getDataList(expData, "soil", "soilLayer");
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int i = 0; i < soilLarys.size(); i++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(i), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(i), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
HashMap cuData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
// ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
// Set environment modification info
// meSubArr = getObjectOr(sqData, "em_data", meSubArr);
String meNumStr = "";
meNum = 0;
for (int j = 0, cnt = 0; j < meArr.size(); j++) {
if (!meNumStr.equals(meArr.get(j).get("em"))) {
meNumStr = (String) meArr.get(j).get("em");
cnt++;
if (em.equals(meNumStr)) {
meNum = cnt;
break;
}
}
}
// Set simulation control info
smNum = 0;
if (isSmExist) {
for (int j = 0; j < smArr.size(); j++) {
if (sm.equals(smArr.get(j).get("sm"))) {
smNum = j + 1;
break;
}
}
}
if (smNum == 0) {
smData.put("fertilizer", mfSubArr);
smData.put("irrigation", miSubArr);
smData.put("planting", mpData);
smNum = setSecDataArr(smData, smArr);
}
// if (!getValueOr(sqData, "sm_general", "").equals("")) {
// smData.put("sm_general", getValueOr(sqData, "sm_general", defValBlank));
// smData.put("sm_options", getValueOr(sqData, "sm_options", defValBlank));
// smData.put("sm_methods", getValueOr(sqData, "sm_methods", defValBlank));
// smData.put("sm_management", getValueOr(sqData, "sm_management", defValBlank));
// smData.put("sm_outputs", getValueOr(sqData, "sm_outputs", defValBlank));
// smData.put("sm_planting", getValueOr(sqData, "sm_planting", defValBlank));
// smData.put("sm_irrigation", getValueOr(sqData, "sm_irrigation", defValBlank));
// smData.put("sm_nitrogen", getValueOr(sqData, "sm_nitrogen", defValBlank));
// smData.put("sm_residues", getValueOr(sqData, "sm_residues", defValBlank));
// smData.put("sm_harvests", getValueOr(sqData, "sm_harvests", defValBlank));
// } else {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id");
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
// meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
// smNum = setSecDataArr(smData, smArr);
// if (smArr.isEmpty()) {
// smNum = 1;
// }
sbData.append(String.format("%1$2s %2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
getValueOr(sqData, "trno", "1").toString(),
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
getValueOr(sqData, "tr_name", getValueOr(expData, "tr_name", defValC)).toString(),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "crid", defValBlank).toString(), // P.S. if missing, default value use blank string
getObjectOr(secData, "cul_id", defValC).toString(), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
if (getObjectOr(secData, "soil_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
getObjectOr(secData, "soil_id", defValC).toString(),
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
String emNumStr = "";
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
// secDataArr = (ArrayList) meArr.get(idx);
secData = meArr.get(idx);
if (!emNumStr.equals(secData.get("em"))) {
cnt++;
emNumStr = (String) secData.get("em");
}
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// for (int i = 0; i < secDataArr.size(); i++) {
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
// }
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
} else {
sbData.append(createSMMAStr(idx + 1, expData, secData));
}
}
} else {
sbData.append(createSMMAStr(1, expData, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void writeFile(String arg0, Map result) {
// Initial variables
HashMap expData = (HashMap) result;
HashMap soilData = getObjectOr(result, "soil", new HashMap());
HashMap wthData = getObjectOr(result, "weather", new HashMap());
BufferedWriter bwX; // output object
StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output
StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output
StringBuilder sbData = new StringBuilder(); // construct the data info in the output
StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data
HashMap secData;
ArrayList subDataArr; // Arraylist for event data holder
HashMap subData;
ArrayList secDataArr; // Arraylist for section data holder
HashMap sqData;
ArrayList<HashMap> evtArr; // Arraylist for section data holder
HashMap evtData;
// int trmnNum; // total numbers of treatment in the data holder
int cuNum; // total numbers of cultivars in the data holder
int flNum; // total numbers of fields in the data holder
int saNum; // total numbers of soil analysis in the data holder
int icNum; // total numbers of initial conditions in the data holder
int mpNum; // total numbers of plaintings in the data holder
int miNum; // total numbers of irrigations in the data holder
int mfNum; // total numbers of fertilizers in the data holder
int mrNum; // total numbers of residues in the data holder
int mcNum; // total numbers of chemical in the data holder
int mtNum; // total numbers of tillage in the data holder
int meNum; // total numbers of enveronment modification in the data holder
int mhNum; // total numbers of harvest in the data holder
int smNum; // total numbers of simulation controll record
ArrayList<HashMap> sqArr; // array for treatment record
ArrayList cuArr = new ArrayList(); // array for cultivars record
ArrayList flArr = new ArrayList(); // array for fields record
ArrayList saArr = new ArrayList(); // array for soil analysis record
ArrayList icArr = new ArrayList(); // array for initial conditions record
ArrayList mpArr = new ArrayList(); // array for plaintings record
ArrayList miArr = new ArrayList(); // array for irrigations record
ArrayList mfArr = new ArrayList(); // array for fertilizers record
ArrayList mrArr = new ArrayList(); // array for residues record
ArrayList mcArr = new ArrayList(); // array for chemical record
ArrayList mtArr = new ArrayList(); // array for tillage record
ArrayList<HashMap> meArr; // array for enveronment modification record
ArrayList mhArr = new ArrayList(); // array for harvest record
ArrayList<HashMap> smArr; // array for simulation control record
String exName;
try {
// Set default value for missing data
if (expData == null || expData.isEmpty()) {
return;
}
// decompressData((HashMap) result);
setDefVal();
// Initial BufferedWriter
String fileName = getFileName(result, "X");
arg0 = revisePath(arg0);
outputFile = new File(arg0 + fileName);
bwX = new BufferedWriter(new FileWriter(outputFile));
// Output XFile
// EXP.DETAILS Section
sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n",
getExName(result),
getObjectOr(expData, "local_name", defValBlank).toString()));
// GENERAL Section
sbGenData.append("*GENERAL\r\n");
// People
if (!getObjectOr(expData, "people", "").equals("")) {
sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString()));
}
// Address
if (getObjectOr(expData, "institution", "").equals("")) {
if (!getObjectOr(expData, "fl_loc_1", "").equals("")
&& getObjectOr(expData, "fl_loc_2", "").equals("")
&& getObjectOr(expData, "fl_loc_3", "").equals("")) {
sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n",
getObjectOr(expData, "fl_loc_1", defValBlank).toString(),
getObjectOr(expData, "fl_loc_2", defValBlank).toString(),
getObjectOr(expData, "fl_loc_3", defValBlank).toString()));
}
} else {
sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString()));
}
// Site
if (!getObjectOr(expData, "site", "").equals("")) {
sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString()));
}
// Plot Info
if (isPlotInfoExist(expData)) {
sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n");
sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n",
formatNumStr(6, expData, "plta", defValR),
formatNumStr(5, expData, "pltr#", defValI),
formatNumStr(5, expData, "pltln", defValR),
formatNumStr(5, expData, "pldr", defValI),
formatNumStr(5, expData, "pltsp", defValI),
getObjectOr(expData, "plot_layout", defValC).toString(),
formatNumStr(5, expData, "pltha", defValR),
formatNumStr(5, expData, "plth#", defValI),
formatNumStr(5, expData, "plthl", defValR),
getObjectOr(expData, "plthm", defValC).toString()));
}
// Notes
if (!getObjectOr(expData, "tr_notes", "").equals("")) {
sbNotesData.append("@NOTES\r\n");
String notes = getObjectOr(expData, "tr_notes", defValC).toString();
notes = notes.replaceAll("\\\\r\\\\n", "\r\n");
// If notes contain newline code, then write directly
if (notes.indexOf("\r\n") >= 0) {
// sbData.append(String.format(" %1$s\r\n", notes));
sbNotesData.append(notes);
} // Otherwise, add newline for every 75-bits charactors
else {
while (notes.length() > 75) {
sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n");
notes = notes.substring(75);
}
sbNotesData.append(" ").append(notes).append("\r\n");
}
}
sbData.append("\r\n");
// TREATMENT Section
sqArr = getDataList(expData, "dssat_sequence", "data");
evtArr = getDataList(expData, "management", "events");
meArr = getDataList(expData, "dssat_environment_modification", "data");
smArr = getDataList(expData, "dssat_simulation_control", "data");
boolean isSmExist = !smArr.isEmpty();
String seqId;
String em;
String sm;
sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n");
sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n");
// if there is no sequence info, create dummy data
if (sqArr.isEmpty()) {
sqArr.add(new HashMap());
}
// Set field info
HashMap flData = new HashMap();
copyItem(flData, expData, "id_field");
if (wthData.isEmpty()) {
// copyItem(flData, expData, "wst_id");
flData.put("wst_id", getWthFileName(expData));
} else {
flData.put("wst_id", getWthFileName(wthData));
}
copyItem(flData, expData, "flsl");
copyItem(flData, expData, "flob");
copyItem(flData, expData, "fl_drntype");
copyItem(flData, expData, "fldrd");
copyItem(flData, expData, "fldrs");
copyItem(flData, expData, "flst");
copyItem(flData, soilData, "sltx");
copyItem(flData, soilData, "sldp");
copyItem(flData, expData, "soil_id");
copyItem(flData, expData, "fl_name");
copyItem(flData, expData, "fl_lat");
copyItem(flData, expData, "fl_long");
copyItem(flData, expData, "flele");
copyItem(flData, expData, "farea");
copyItem(flData, expData, "fllwr");
copyItem(flData, expData, "flsla");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "flhst");
copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "fhdur");
// remove the "_trno" in the soil_id when soil analysis is available
String soilId = getValueOr(flData, "soil_id", "");
if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) {
flData.put("soil_id", soilId.replaceAll("_\\d+$", ""));
}
flNum = setSecDataArr(flData, flArr);
// Set initial condition info
icNum = setSecDataArr(getObjectOr(expData, "initial_conditions", new HashMap()), icArr);
// Set soil analysis info
// ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer");
ArrayList<HashMap> soilLarys = getDataList(expData, "soil", "soilLayer");
// // If it is stored in the initial condition block
// if (isSoilAnalysisExist(icSubArr)) {
// HashMap saData = new HashMap();
// ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
// HashMap saSubData;
// for (int i = 0; i < icSubArr.size(); i++) {
// saSubData = new HashMap();
// copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false);
// copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false);
// saSubArr.add(saSubData);
// }
// copyItem(saData, soilData, "sadat");
// saData.put("soilLayer", saSubArr);
// saNum = setSecDataArr(saData, saArr);
// } else
// If it is stored in the soil block
if (isSoilAnalysisExist(soilLarys)) {
HashMap saData = new HashMap();
ArrayList<HashMap> saSubArr = new ArrayList<HashMap>();
HashMap saSubData;
for (int i = 0; i < soilLarys.size(); i++) {
saSubData = new HashMap();
copyItem(saSubData, soilLarys.get(i), "sabl", "sllb", false);
copyItem(saSubData, soilLarys.get(i), "sasc", "slsc", false);
saSubArr.add(saSubData);
}
copyItem(saData, soilData, "sadat");
saData.put("soilLayer", saSubArr);
saNum = setSecDataArr(saData, saArr);
} else {
saNum = 0;
}
// Set sequence related block info
for (int i = 0; i < sqArr.size(); i++) {
sqData = sqArr.get(i);
seqId = getValueOr(sqData, "seqid", defValBlank);
em = getValueOr(sqData, "em", defValBlank);
sm = getValueOr(sqData, "sm", defValBlank);
HashMap cuData = new HashMap();
HashMap mpData = new HashMap();
ArrayList<HashMap> miSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>();
// ArrayList<HashMap> meSubArr = new ArrayList<HashMap>();
ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>();
HashMap smData = new HashMap();
// Set environment modification info
// meSubArr = getObjectOr(sqData, "em_data", meSubArr);
String meNumStr = "";
meNum = 0;
for (int j = 0, cnt = 0; j < meArr.size(); j++) {
if (!meNumStr.equals(meArr.get(j).get("em"))) {
meNumStr = (String) meArr.get(j).get("em");
cnt++;
if (em.equals(meNumStr)) {
meNum = cnt;
break;
}
}
}
// Set simulation control info
smNum = 0;
if (isSmExist) {
for (int j = 0; j < smArr.size(); j++) {
if (sm.equals(smArr.get(j).get("sm"))) {
smNum = j + 1;
break;
}
}
}
if (smNum == 0) {
smData.put("fertilizer", mfSubArr);
smData.put("irrigation", miSubArr);
smData.put("planting", mpData);
smNum = setSecDataArr(smData, smArr);
}
// if (!getValueOr(sqData, "sm_general", "").equals("")) {
// smData.put("sm_general", getValueOr(sqData, "sm_general", defValBlank));
// smData.put("sm_options", getValueOr(sqData, "sm_options", defValBlank));
// smData.put("sm_methods", getValueOr(sqData, "sm_methods", defValBlank));
// smData.put("sm_management", getValueOr(sqData, "sm_management", defValBlank));
// smData.put("sm_outputs", getValueOr(sqData, "sm_outputs", defValBlank));
// smData.put("sm_planting", getValueOr(sqData, "sm_planting", defValBlank));
// smData.put("sm_irrigation", getValueOr(sqData, "sm_irrigation", defValBlank));
// smData.put("sm_nitrogen", getValueOr(sqData, "sm_nitrogen", defValBlank));
// smData.put("sm_residues", getValueOr(sqData, "sm_residues", defValBlank));
// smData.put("sm_harvests", getValueOr(sqData, "sm_harvests", defValBlank));
// } else {
// smData.put("fertilizer", mfSubArr);
// smData.put("irrigation", miSubArr);
// smData.put("planting", mpData);
// }
// Loop all event data
for (int j = 0; j < evtArr.size(); j++) {
evtData = new HashMap();
evtData.putAll(evtArr.get(j));
// Check if it has same sequence number
if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) {
evtData.remove("seqid");
// Planting event
if (getValueOr(evtData, "event", defValBlank).equals("planting")) {
// Set cultivals info
copyItem(cuData, evtData, "cul_name");
copyItem(cuData, evtData, "crid");
copyItem(cuData, evtData, "cul_id", "dssat_cul_id", false);
copyItem(cuData, evtData, "rm");
copyItem(cuData, evtData, "cul_notes");
translateTo2BitCrid(cuData);
// Set planting info
mpData.putAll(evtData);
mpData.remove("cul_name");
} // irrigation event
else if (getValueOr(evtData, "event", "").equals("irrigation")) {
miSubArr.add(evtData);
} // fertilizer event
else if (getValueOr(evtData, "event", "").equals("fertilizer")) {
mfSubArr.add(evtData);
} // organic_matter event
else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again.
mrSubArr.add(evtData);
} // chemical event
else if (getValueOr(evtData, "event", "").equals("chemical")) {
mcSubArr.add(evtData);
} // tillage event
else if (getValueOr(evtData, "event", "").equals("tillage")) {
mtSubArr.add(evtData);
// } // environment_modification event
// else if (getValueOr(evtData, "event", "").equals("environment_modification")) {
// meSubArr.add(evtData);
} // harvest event
else if (getValueOr(evtData, "event", "").equals("harvest")) {
mhSubArr.add(evtData);
} else {
}
} else {
}
}
// If alternative fields are avaiable for fertilizer data
if (mfSubArr.isEmpty()) {
if (!getObjectOr(result, "fen_tot", "").equals("")
|| !getObjectOr(result, "fep_tot", "").equals("")
|| !getObjectOr(result, "fek_tot", "").equals("")) {
mfSubArr.add(new HashMap());
}
}
cuNum = setSecDataArr(cuData, cuArr);
mpNum = setSecDataArr(mpData, mpArr);
miNum = setSecDataArr(miSubArr, miArr);
mfNum = setSecDataArr(mfSubArr, mfArr);
mrNum = setSecDataArr(mrSubArr, mrArr);
mcNum = setSecDataArr(mcSubArr, mcArr);
mtNum = setSecDataArr(mtSubArr, mtArr);
// meNum = setSecDataArr(meSubArr, meArr);
mhNum = setSecDataArr(mhSubArr, mhArr);
// smNum = setSecDataArr(smData, smArr);
// if (smArr.isEmpty()) {
// smNum = 1;
// }
sbData.append(String.format("%1$2s %2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n",
getValueOr(sqData, "trno", "1").toString(),
getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf
getValueOr(sqData, "op", "1").toString(),
getValueOr(sqData, "co", "0").toString(),
getValueOr(sqData, "tr_name", getValueOr(expData, "tr_name", defValC)).toString(),
cuNum, //getObjectOr(data, "ge", defValI).toString(),
flNum, //getObjectOr(data, "fl", defValI).toString(),
saNum, //getObjectOr(data, "sa", defValI).toString(),
icNum, //getObjectOr(data, "ic", defValI).toString(),
mpNum, //getObjectOr(data, "pl", defValI).toString(),
miNum, //getObjectOr(data, "ir", defValI).toString(),
mfNum, //getObjectOr(data, "fe", defValI).toString(),
mrNum, //getObjectOr(data, "om", defValI).toString(),
mcNum, //getObjectOr(data, "ch", defValI).toString(),
mtNum, //getObjectOr(data, "ti", defValI).toString(),
meNum, //getObjectOr(data, "em", defValI).toString(),
mhNum, //getObjectOr(data, "ha", defValI).toString(),
smNum)); // 1
}
sbData.append("\r\n");
// CULTIVARS Section
if (!cuArr.isEmpty()) {
sbData.append("*CULTIVARS\r\n");
sbData.append("@C CR INGENO CNAME\r\n");
for (int idx = 0; idx < cuArr.size(); idx++) {
secData = (HashMap) cuArr.get(idx);
// String cul_id = defValC;
String crid = getObjectOr(secData, "crid", "");
// Checl if necessary data is missing
if (crid.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n");
// } else {
// // Set cultivar id a default value deponds on the crop id
// if (crid.equals("MZ")) {
// cul_id = "990002";
// } else {
// cul_id = "999999";
// }
// }
// if (getObjectOr(secData, "cul_id", "").equals("")) {
// sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n");
}
sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "crid", defValBlank).toString(), // P.S. if missing, default value use blank string
getObjectOr(secData, "cul_id", defValC).toString(), // P.S. Set default value which is deponds on crid(Cancelled)
getObjectOr(secData, "cul_name", defValC).toString()));
if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) {
if (sbNotesData.toString().equals("")) {
sbNotesData.append("@NOTES\r\n");
}
sbNotesData.append(" Cultivar Additional Info\r\n");
sbNotesData.append(" C RM CNAME CUL_NOTES\r\n");
sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n",
idx + 1, //getObjectOr(secData, "ge", defValI).toString(),
getObjectOr(secData, "rm", defValC).toString(),
getObjectOr(secData, "cul_notes", defValC).toString()));
}
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no cultivar data in the experiment.\r\n");
}
// FIELDS Section
if (!flArr.isEmpty()) {
sbData.append("*FIELDS\r\n");
sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n");
eventPart2 = new StringBuilder();
eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n");
} else {
sbError.append("! Warning: There is no field data in the experiment.\r\n");
}
for (int idx = 0; idx < flArr.size(); idx++) {
secData = (HashMap) flArr.get(idx);
// Check if the necessary is missing
if (getObjectOr(secData, "wst_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n");
}
if (getObjectOr(secData, "soil_id", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n");
}
sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
getObjectOr(secData, "id_field", defValC).toString(),
getObjectOr(secData, "wst_id", defValC).toString(),
getObjectOr(secData, "flsl", defValC).toString(),
formatNumStr(5, secData, "flob", defValR),
getObjectOr(secData, "fl_drntype", defValC).toString(),
formatNumStr(5, secData, "fldrd", defValR),
formatNumStr(5, secData, "fldrs", defValR),
getObjectOr(secData, "flst", defValC).toString(),
getObjectOr(secData, "sltx", defValC).toString(),
formatNumStr(5, secData, "sldp", defValR),
getObjectOr(secData, "soil_id", defValC).toString(),
getObjectOr(secData, "fl_name", defValC).toString()));
eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(secData, "fl", defValI).toString(),
formatNumStr(15, secData, "fl_lat", defValR),
formatNumStr(15, secData, "fl_long", defValR),
formatNumStr(9, secData, "flele", defValR),
formatNumStr(17, secData, "farea", defValR),
"-99", // P.S. SLEN keeps -99
formatNumStr(5, secData, "fllwr", defValR),
formatNumStr(5, secData, "flsla", defValR),
getObjectOr(secData, "flhst", defValC).toString(),
formatNumStr(5, secData, "fhdur", defValR)));
}
if (!flArr.isEmpty()) {
sbData.append(eventPart2.toString()).append("\r\n");
}
// SOIL ANALYSIS Section
if (!saArr.isEmpty()) {
sbData.append("*SOIL ANALYSIS\r\n");
for (int idx = 0; idx < saArr.size(); idx++) {
secData = (HashMap) saArr.get(idx);
sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n",
idx + 1, //getObjectOr(secData, "sa", defValI).toString(),
formatDateStr(getObjectOr(secData, "sadat", defValD).toString()),
getObjectOr(secData, "samhb", defValC).toString(),
getObjectOr(secData, "sampx", defValC).toString(),
getObjectOr(secData, "samke", defValC).toString(),
getObjectOr(secData, "sa_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n",
idx + 1, //getObjectOr(subData, "sa", defValI).toString(),
formatNumStr(5, subData, "sabl", defValR),
formatNumStr(5, subData, "sabdm", defValR),
formatNumStr(5, subData, "saoc", defValR),
formatNumStr(5, subData, "sani", defValR),
formatNumStr(5, subData, "saphw", defValR),
formatNumStr(5, subData, "saphb", defValR),
formatNumStr(5, subData, "sapx", defValR),
formatNumStr(5, subData, "sake", defValR),
formatNumStr(5, subData, "sasc", defValR)));
}
}
sbData.append("\r\n");
}
// INITIAL CONDITIONS Section
if (!icArr.isEmpty()) {
sbData.append("*INITIAL CONDITIONS\r\n");
for (int idx = 0; idx < icArr.size(); idx++) {
secData = (HashMap) icArr.get(idx);
translateTo2BitCrid(secData, "icpcr");
sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n",
idx + 1, //getObjectOr(secData, "ic", defValI).toString(),
getObjectOr(secData, "icpcr", defValC).toString(),
formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()),
formatNumStr(5, secData, "icrt", defValR),
formatNumStr(5, secData, "icnd", defValR),
formatNumStr(5, secData, "icrz#", defValR),
formatNumStr(5, secData, "icrze", defValR),
formatNumStr(5, secData, "icwt", defValR),
formatNumStr(5, secData, "icrag", defValR),
formatNumStr(5, secData, "icrn", defValR),
formatNumStr(5, secData, "icrp", defValR),
formatNumStr(5, secData, "icrip", defValR),
formatNumStr(5, secData, "icrdp", defValR),
getObjectOr(secData, "ic_name", defValC).toString()));
subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList());
if (!subDataArr.isEmpty()) {
sbData.append("@C ICBL SH2O SNH4 SNO3\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n",
idx + 1, //getObjectOr(subData, "ic", defValI).toString(),
formatNumStr(5, subData, "icbl", defValR),
formatNumStr(5, subData, "ich2o", defValR),
formatNumStr(5, subData, "icnh4", defValR),
formatNumStr(5, subData, "icno3", defValR)));
}
}
sbData.append("\r\n");
}
// PLANTING DETAILS Section
if (!mpArr.isEmpty()) {
sbData.append("*PLANTING DETAILS\r\n");
sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n");
for (int idx = 0; idx < mpArr.size(); idx++) {
secData = (HashMap) mpArr.get(idx);
// Check if necessary data is missing
String pdate = getObjectOr(secData, "date", "");
if (pdate.equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n");
} else if (formatDateStr(pdate).equals(defValD)) {
sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n");
}
if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n");
}
if (getObjectOr(secData, "plrs", "").equals("")) {
sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n");
}
// if (getObjectOr(secData, "plma", "").equals("")) {
// sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n");
// }
// if (getObjectOr(secData, "plds", "").equals("")) {
// sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n");
// }
// if (getObjectOr(secData, "pldp", "").equals("")) {
// sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n",
idx + 1, //getObjectOr(data, "pl", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()),
formatDateStr(getObjectOr(secData, "pldae", defValD).toString()),
formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)),
formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)),
getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled)
getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled)
formatNumStr(5, secData, "plrs", defValR),
formatNumStr(5, secData, "plrd", defValR),
formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled)
formatNumStr(5, secData, "plmwt", defValR),
formatNumStr(5, secData, "page", defValR),
formatNumStr(5, secData, "penv", defValR),
formatNumStr(5, secData, "plph", defValR),
formatNumStr(5, secData, "plspl", defValR),
getObjectOr(secData, "pl_name", defValC).toString()));
}
sbData.append("\r\n");
} else {
sbError.append("! Warning: There is no plainting data in the experiment.\r\n");
}
// IRRIGATION AND WATER MANAGEMENT Section
if (!miArr.isEmpty()) {
sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n");
for (int idx = 0; idx < miArr.size(); idx++) {
// secData = (ArrayList) miArr.get(idx);
subDataArr = (ArrayList) miArr.get(idx);
if (!subDataArr.isEmpty()) {
subData = (HashMap) subDataArr.get(0);
} else {
subData = new HashMap();
}
sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n");
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n",
idx + 1, //getObjectOr(data, "ir", defValI).toString(),
formatNumStr(5, subData, "ireff", defValR),
formatNumStr(5, subData, "irmdp", defValR),
formatNumStr(5, subData, "irthr", defValR),
formatNumStr(5, subData, "irept", defValR),
getObjectOr(subData, "irstg", defValC).toString(),
getObjectOr(subData, "iame", defValC).toString(),
formatNumStr(5, subData, "iamt", defValR),
getObjectOr(subData, "ir_name", defValC).toString()));
if (!subDataArr.isEmpty()) {
sbData.append("@I IDATE IROP IRVAL\r\n");
}
for (int j = 0; j < subDataArr.size(); j++) {
subData = (HashMap) subDataArr.get(j);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n",
idx + 1, //getObjectOr(subData, "ir", defValI).toString(),
formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date
getObjectOr(subData, "irop", defValC).toString(),
formatNumStr(5, subData, "irval", defValR)));
}
}
sbData.append("\r\n");
}
// FERTILIZERS (INORGANIC) Section
if (!mfArr.isEmpty()) {
sbData.append("*FERTILIZERS (INORGANIC)\r\n");
sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n");
// String fen_tot = getObjectOr(result, "fen_tot", defValR);
// String fep_tot = getObjectOr(result, "fep_tot", defValR);
// String fek_tot = getObjectOr(result, "fek_tot", defValR);
// String pdate = getPdate(result);
// if (pdate.equals("")) {
// pdate = defValD;
// }
for (int idx = 0; idx < mfArr.size(); idx++) {
secDataArr = (ArrayList) mfArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
// if (getObjectOr(secData, "fdate", "").equals("")) {
// sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n");
// }
// if (getObjectOr(secData, "fecd", "").equals("")) {
// sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n");
// }
// if (getObjectOr(secData, "feacd", "").equals("")) {
// sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n");
// }
// if (getObjectOr(secData, "fedep", "").equals("")) {
// sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n");
// }
// if (getObjectOr(secData, "feamn", "").equals("")) {
// sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamp", "").equals("")) {
// sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n");
// }
// if (getObjectOr(secData, "feamk", "").equals("")) {
// sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n");
// }
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n",
idx + 1, //getObjectOr(data, "fe", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date
getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled)
getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled)
formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled)
formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled)
formatNumStr(5, secData, "feamc", defValR),
formatNumStr(5, secData, "feamo", defValR),
getObjectOr(secData, "feocd", defValC).toString(),
getObjectOr(secData, "fe_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// RESIDUES AND ORGANIC FERTILIZER Section
if (!mrArr.isEmpty()) {
sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n");
sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n");
for (int idx = 0; idx < mrArr.size(); idx++) {
secDataArr = (ArrayList) mrArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n",
idx + 1, //getObjectOr(secData, "om", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date
getObjectOr(secData, "omcd", defValC).toString(),
formatNumStr(5, secData, "omamt", defValR),
formatNumStr(5, secData, "omn%", defValR),
formatNumStr(5, secData, "omp%", defValR),
formatNumStr(5, secData, "omk%", defValR),
formatNumStr(5, secData, "ominp", defValR),
formatNumStr(5, secData, "omdep", defValR),
formatNumStr(5, secData, "omacd", defValR),
getObjectOr(secData, "om_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// CHEMICAL APPLICATIONS Section
if (!mcArr.isEmpty()) {
sbData.append("*CHEMICAL APPLICATIONS\r\n");
sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n");
for (int idx = 0; idx < mcArr.size(); idx++) {
secDataArr = (ArrayList) mcArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ch", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date
getObjectOr(secData, "chcd", defValC).toString(),
formatNumStr(5, secData, "chamt", defValR),
getObjectOr(secData, "chacd", defValC).toString(),
getObjectOr(secData, "chdep", defValC).toString(),
getObjectOr(secData, "ch_targets", defValC).toString(),
getObjectOr(secData, "ch_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// TILLAGE Section
if (!mtArr.isEmpty()) {
sbData.append("*TILLAGE AND ROTATIONS\r\n");
sbData.append("@T TDATE TIMPL TDEP TNAME\r\n");
for (int idx = 0; idx < mtArr.size(); idx++) {
secDataArr = (ArrayList) mtArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n",
idx + 1, //getObjectOr(secData, "ti", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date
getObjectOr(secData, "tiimp", defValC).toString(),
formatNumStr(5, secData, "tidep", defValR),
getObjectOr(secData, "ti_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// ENVIRONMENT MODIFICATIONS Section
if (!meArr.isEmpty()) {
sbData.append("*ENVIRONMENT MODIFICATIONS\r\n");
sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n");
String emNumStr = "";
for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) {
// secDataArr = (ArrayList) meArr.get(idx);
secData = meArr.get(idx);
if (!emNumStr.equals(secData.get("em"))) {
cnt++;
emNumStr = (String) secData.get("em");
}
sbData.append(String.format("%1$2s%2$s\r\n",
cnt,
secData.get("em_data")));
// for (int i = 0; i < secDataArr.size(); i++) {
// sbData.append(String.format("%1$2s%2$s\r\n",
// idx + 1,
// (String) secDataArr.get(i)));
// sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n",
// idx + 1, //getObjectOr(secData, "em", defValI).toString(),
// formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date
// getObjectOr(secData, "ecdyl", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdyl", defValR),
// getObjectOr(secData, "ecrad", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrad", defValR),
// getObjectOr(secData, "ecmax", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmax", defValR),
// getObjectOr(secData, "ecmin", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emmin", defValR),
// getObjectOr(secData, "ecrai", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emrai", defValR),
// getObjectOr(secData, "ecco2", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emco2", defValR),
// getObjectOr(secData, "ecdew", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emdew", defValR),
// getObjectOr(secData, "ecwnd", defValBlank).toString(),
// formatNumStr(4, getObjectOr(secData, "emwnd", defValR),
// getObjectOr(secData, "em_name", defValC).toString()));
// }
}
sbData.append("\r\n");
}
// HARVEST DETAILS Section
if (!mhArr.isEmpty()) {
sbData.append("*HARVEST DETAILS\r\n");
sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n");
for (int idx = 0; idx < mhArr.size(); idx++) {
secDataArr = (ArrayList) mhArr.get(idx);
for (int i = 0; i < secDataArr.size(); i++) {
secData = (HashMap) secDataArr.get(i);
sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n",
idx + 1, //getObjectOr(secData, "ha", defValI).toString(),
formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date
getObjectOr(secData, "hastg", defValC).toString(),
getObjectOr(secData, "hacom", defValC).toString(),
getObjectOr(secData, "hasiz", defValC).toString(),
formatNumStr(5, secData, "hapc", defValR),
formatNumStr(5, secData, "habpc", defValR),
getObjectOr(secData, "ha_name", defValC).toString()));
}
}
sbData.append("\r\n");
}
// SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section
if (!smArr.isEmpty()) {
// Set Title list
ArrayList smTitles = new ArrayList();
smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n");
smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n");
smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n");
smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n");
smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n");
smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n");
smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n");
smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n");
smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n");
smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n");
String[] keys = new String[10];
keys[0] = "sm_general";
keys[1] = "sm_options";
keys[2] = "sm_methods";
keys[3] = "sm_management";
keys[4] = "sm_outputs";
keys[5] = "sm_planting";
keys[6] = "sm_irrigation";
keys[7] = "sm_nitrogen";
keys[8] = "sm_residues";
keys[9] = "sm_harvests";
// Loop all the simulation control records
for (int idx = 0; idx < smArr.size(); idx++) {
secData = (HashMap) smArr.get(idx);
if (secData.containsKey("sm_general")) {
sbData.append("*SIMULATION CONTROLS\r\n");
secData.remove("sm");
// Object[] keys = secData.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
sbData.append(smTitles.get(i));
sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n");
if (i == 4) {
sbData.append("\r\n");
}
}
} else {
sbData.append(createSMMAStr(idx + 1, expData, secData));
}
}
} else {
sbData.append(createSMMAStr(1, expData, new HashMap()));
}
// Output finish
bwX.write(sbError.toString());
bwX.write(sbGenData.toString());
bwX.write(sbNotesData.toString());
bwX.write(sbData.toString());
bwX.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index 8501016..9db0323 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,381 +1,381 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.server.Server;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.map.fastfindgrid.Traceable;
import java.awt.geom.Ellipse2D;
import java.util.List;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private Traceable caster3;
private SimplePosition target;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im WEg steht und man wartet bis es den WEg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 3000000000l;
/**
* Wird für die Abstandssuche benötigt. Falls jemals eine Einheit größer ist, MUSS dieser Wert auch erhöht werden.
*/
private static final double maxRadius = 4;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, Traceable caster3, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.caster3 = caster3;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
- if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
+ if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius()) && m != this.caster) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius()) && m != this.caster) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde (Movemap)
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
// Herausfinden, ob der Sektor gewechselt wurde (FastFindGrid)
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* @param pos die Zielposition, wird auf direktem Weg angesteuert.
*/
public synchronized void setTargetVector(SimplePosition pos) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed) {
changeSpeed(speed);
setTargetVector(pos);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Überprüft auf RTC mit Zielposition
* @param pos die zu testende Position
* @return true, wenn frei
*/
private boolean checkPosition(FloatingPointPosition pos) {
List<Moveable> movers = moveMap.moversAroundPoint(pos, caster2.getRadius() + maxRadius);
movers.remove(caster2);
for (Moveable m : movers) {
if (m.getPrecisePosition().getDistance(pos) < (m.getRadius() + caster2.getRadius())) {
return false;
}
}
return true;
}
}
| true | true | public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius()) && m != this.caster) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde (Movemap)
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
// Herausfinden, ob der Sektor gewechselt wurde (FastFindGrid)
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
| public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius()) && m != this.caster) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Traceable t : this.caster3.getCell().getTraceablesAroundMe()) {
Unit m = t.getUnit();
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius()) && m != this.caster) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde (Movemap)
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
// Herausfinden, ob der Sektor gewechselt wurde (FastFindGrid)
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
|
diff --git a/src/com/oresomecraft/BattleMaps/maps/DesertCastle.java b/src/com/oresomecraft/BattleMaps/maps/DesertCastle.java
index 092959a..a5379b1 100644
--- a/src/com/oresomecraft/BattleMaps/maps/DesertCastle.java
+++ b/src/com/oresomecraft/BattleMaps/maps/DesertCastle.java
@@ -1,243 +1,243 @@
package com.oresomecraft.BattleMaps.maps;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector;
import com.oresomecraft.BattleMaps.*;
import com.oresomecraft.OresomeBattles.api.*;
public class DesertCastle extends BattleMap implements IBattleMap, Listener {
public DesertCastle() {
super.initiate(this, name, fullName, creators, modes);
setTDMTime(15);
setAllowBuild(false);
}
String name = "desertcastle";
String fullName = "Desert Castle";
String creators = "Hourani95";
Gamemode[] modes = {Gamemode.TDM, Gamemode.FFA, Gamemode.INFECTION};
public void readyTDMSpawns() {
Location redSpawn = new Location(w, -37, 66, 30);
Location blueSpawn = new Location(w, 38, 78, 29);
redSpawns.add(redSpawn);
blueSpawns.add(blueSpawn);
redSpawns.add(new Location(w, -37, 78, 30));
blueSpawns.add(new Location(w, 38, 66, 29));
setRedSpawns(name, redSpawns);
setBlueSpawns(name, blueSpawns);
}
public void readyFFASpawns() {
Location redSpawn = new Location(w, -37, 66, 30);
Location blueSpawn = new Location(w, 38, 78, 29);
FFASpawns.add(redSpawn);
FFASpawns.add(blueSpawn);
FFASpawns.add(new Location(w, -37, 78, 30));
FFASpawns.add(new Location(w, 38, 66, 29));
}
public void applyInventory(final BattlePlayer p) {
Inventory i = p.getInventory();
ItemStack HEALTH_POTION = new ItemStack(Material.POTION, 1, (short) 16373);
ItemStack STEAK = new ItemStack(Material.COOKED_BEEF, 1);
ItemStack BOW = new ItemStack(Material.BOW, 1);
ItemStack ARROWS = new ItemStack(Material.ARROW, 64);
ItemStack IRON_HELMET = new ItemStack(Material.IRON_HELMET, 1);
ItemStack IRON_CHESTPLATE = new ItemStack(Material.IRON_CHESTPLATE, 1);
ItemStack IRON_PANTS = new ItemStack(Material.IRON_LEGGINGS, 1);
ItemStack IRON_BOOTS = new ItemStack(Material.IRON_BOOTS, 1);
ItemStack IRON_SWORD = new ItemStack(Material.IRON_SWORD, 1);
ItemStack EXP = new ItemStack(Material.EXP_BOTTLE, 5);
ItemStack FISHING_ROD = new ItemStack(Material.FISHING_ROD, 1);
ItemMeta fishing_rod = FISHING_ROD.getItemMeta();
fishing_rod.setDisplayName(ChatColor.BLUE + "Grappling hook");
FISHING_ROD.setItemMeta(fishing_rod);
p.getInventory().setBoots(IRON_BOOTS);
p.getInventory().setLeggings(IRON_PANTS);
p.getInventory().setChestplate(IRON_CHESTPLATE);
p.getInventory().setHelmet(IRON_HELMET);
i.setItem(0, IRON_SWORD);
i.setItem(1, BOW);
if (p.getTeam() == Team.TDM_RED || p.getTeam() == Team.TDM_BLUE || p.getTeam() == Team.FFA) {
i.setItem(2, FISHING_ROD);
}
i.setItem(3, EXP);
i.setItem(4, STEAK);
i.setItem(5, HEALTH_POTION);
i.setItem(6, ARROWS);
p.getInventory().getBoots().addEnchantment(Enchantment.PROTECTION_FALL, 4);
}
public int x1 = -1451;
public int y1 = 63;
public int z1 = -2145;
public int x2 = -1383;
public int y2 = 159;
public int z2 = -2066;
@EventHandler(priority = EventPriority.NORMAL)
public void fishing(PlayerFishEvent event) {
PlayerFishEvent.State state = event.getState();
Player p = event.getPlayer();
ItemStack is = p.getItemInHand();
Material mat = is.getType();
Location loc = p.getLocation();
if (loc.getWorld().getName().equals(name)) {
if (mat == Material.FISHING_ROD) {
if (state == PlayerFishEvent.State.IN_GROUND) {
p.launchProjectile(Snowball.class);
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void grapple(ProjectileHitEvent event) {
Entity proj = event.getEntity();
Location hit = proj.getLocation();
- if (contains(hit, x1, x2, y1, y2, z1, z2)) {
+ if (hit.getWorld().getName().equals(name)) {
if (proj instanceof Snowball) {
Snowball fish = (Snowball) proj;
Entity shooter = fish.getShooter();
if (shooter instanceof Player) {
Player p = (Player) shooter;
Location loc = p.getLocation();
ItemStack is = p.getItemInHand();
Material mat = is.getType();
if (mat == Material.FISHING_ROD) {
p.setFallDistance(0);
p.playSound(loc, Sound.ARROW_HIT, 1, 1);
int hitx = hit.getBlockX();
int hity = hit.getBlockY();
int hitz = hit.getBlockZ();
int locx = loc.getBlockX();
int locy = loc.getBlockY();
int locz = loc.getBlockZ();
double co[] = new double[3];
if (hitx > locx) {
co[0] = 1.2;
} else if (hitx < locx) {
co[0] = -1.2;
} else if (hitx == locx) {
co[0] = 0;
}
if (hity > locy) {
co[1] = 1.4;
} else if (hity < locy) {
co[1] = -0.8;
} else if (hity == locy) {
co[1] = 0;
}
if (hitz > locz) {
co[2] = 1.2;
} else if (hitz < locz) {
co[2] = -1.2;
} else if (hitz == locz) {
co[2] = 0;
}
p.setVelocity(new Vector(co[0], co[1], co[2]));
}
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void glassShot(ProjectileHitEvent event) {
Entity proj = event.getEntity();
Location hit = proj.getLocation();
Block b = hit.getBlock();
Material mat = b.getType();
if (contains(hit, x1, x2, y1, y2, z1, z2)) {
if (proj instanceof Arrow) {
if (mat == Material.THIN_GLASS) {
b.breakNaturally();
}
}
}
}
@EventHandler
public void arrowBoom(ProjectileHitEvent event) {
Entity arrow = event.getEntity();
World world = Bukkit.getWorld(name);
if (getArena().equals(name)) {
if (arrow instanceof Arrow) {
world.playEffect(arrow.getLocation(), Effect.STEP_SOUND, 10);
}
}
}
public int particles;
@EventHandler
public void arrowParticles(org.bukkit.event.world.WorldLoadEvent event) {
if (event.getWorld().getName().equals(name)) {
particles = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
World world = Bukkit.getWorld(name);
if (getArena().equals(name)) {
for (org.bukkit.entity.Entity arrow : world.getEntities()) {
if (arrow != null) {
if (arrow instanceof org.bukkit.entity.Arrow) {
world.playEffect(arrow.getLocation(), org.bukkit.Effect.SMOKE, 10);
}
}
}
}
}
}, 5L, 5L);
}
}
@EventHandler
public void cancelParticles(WorldUnloadEvent event) {
Bukkit.getScheduler().cancelTask(particles);
}
}
| true | true | public void grapple(ProjectileHitEvent event) {
Entity proj = event.getEntity();
Location hit = proj.getLocation();
if (contains(hit, x1, x2, y1, y2, z1, z2)) {
if (proj instanceof Snowball) {
Snowball fish = (Snowball) proj;
Entity shooter = fish.getShooter();
if (shooter instanceof Player) {
Player p = (Player) shooter;
Location loc = p.getLocation();
ItemStack is = p.getItemInHand();
Material mat = is.getType();
if (mat == Material.FISHING_ROD) {
p.setFallDistance(0);
p.playSound(loc, Sound.ARROW_HIT, 1, 1);
int hitx = hit.getBlockX();
int hity = hit.getBlockY();
int hitz = hit.getBlockZ();
int locx = loc.getBlockX();
int locy = loc.getBlockY();
int locz = loc.getBlockZ();
double co[] = new double[3];
if (hitx > locx) {
co[0] = 1.2;
} else if (hitx < locx) {
co[0] = -1.2;
} else if (hitx == locx) {
co[0] = 0;
}
if (hity > locy) {
co[1] = 1.4;
} else if (hity < locy) {
co[1] = -0.8;
} else if (hity == locy) {
co[1] = 0;
}
if (hitz > locz) {
co[2] = 1.2;
} else if (hitz < locz) {
co[2] = -1.2;
} else if (hitz == locz) {
co[2] = 0;
}
p.setVelocity(new Vector(co[0], co[1], co[2]));
}
}
}
}
}
| public void grapple(ProjectileHitEvent event) {
Entity proj = event.getEntity();
Location hit = proj.getLocation();
if (hit.getWorld().getName().equals(name)) {
if (proj instanceof Snowball) {
Snowball fish = (Snowball) proj;
Entity shooter = fish.getShooter();
if (shooter instanceof Player) {
Player p = (Player) shooter;
Location loc = p.getLocation();
ItemStack is = p.getItemInHand();
Material mat = is.getType();
if (mat == Material.FISHING_ROD) {
p.setFallDistance(0);
p.playSound(loc, Sound.ARROW_HIT, 1, 1);
int hitx = hit.getBlockX();
int hity = hit.getBlockY();
int hitz = hit.getBlockZ();
int locx = loc.getBlockX();
int locy = loc.getBlockY();
int locz = loc.getBlockZ();
double co[] = new double[3];
if (hitx > locx) {
co[0] = 1.2;
} else if (hitx < locx) {
co[0] = -1.2;
} else if (hitx == locx) {
co[0] = 0;
}
if (hity > locy) {
co[1] = 1.4;
} else if (hity < locy) {
co[1] = -0.8;
} else if (hity == locy) {
co[1] = 0;
}
if (hitz > locz) {
co[2] = 1.2;
} else if (hitz < locz) {
co[2] = -1.2;
} else if (hitz == locz) {
co[2] = 0;
}
p.setVelocity(new Vector(co[0], co[1], co[2]));
}
}
}
}
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index b907482..f19220f 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,216 +1,216 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private SimplePosition target;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private Vector lastVec;
private MovementMap moveMap;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
lastVec = new Vector(vec.getX(), vec.getY());
}
long ticktime = System.currentTimeMillis();
vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
- if (!caster2.getMidLevelManager().reachedTarget(caster2)) {
+ if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* @param pos die Zielposition, wird auf direktem Weg angesteuert.
*/
public synchronized void setTargetVector(SimplePosition pos) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null");
}
target = pos;
lastTick = System.currentTimeMillis();
lastVec = Vector.ZERO;
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed) {
changeSpeed(speed);
setTargetVector(pos);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
}
| true | true | public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
lastVec = new Vector(vec.getX(), vec.getY());
}
long ticktime = System.currentTimeMillis();
vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
| public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
if (!vec.equals(lastVec)) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
lastVec = new Vector(vec.getX(), vec.getY());
}
long ticktime = System.currentTimeMillis();
vec.multiplyMe((ticktime - lastTick) / 1000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec)) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.currentTimeMillis();
}
}
}
|
diff --git a/news-impl/impl/src/java/org/sakaiproject/news/impl/BasicNewsChannel.java b/news-impl/impl/src/java/org/sakaiproject/news/impl/BasicNewsChannel.java
index fa6443d..8710965 100644
--- a/news-impl/impl/src/java/org/sakaiproject/news/impl/BasicNewsChannel.java
+++ b/news-impl/impl/src/java/org/sakaiproject/news/impl/BasicNewsChannel.java
@@ -1,517 +1,518 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.news.impl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.news.api.NewsChannel;
import org.sakaiproject.news.api.NewsConnectionException;
import org.sakaiproject.news.api.NewsFormatException;
import org.sakaiproject.news.api.NewsItem;
import org.sakaiproject.news.api.NewsItemEnclosure;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndImage;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
/***********************************************************************************
* NewsChannel implementation
**********************************************************************************/
public class BasicNewsChannel implements NewsChannel
{
protected String m_source = null;
protected String m_link = null;
protected String m_title = null;
protected String m_description = null;
protected String m_language = null;
protected String m_copyright = null;
protected String m_pubdate = null;
protected String m_lastbuilddate = null;
protected String m_imageLink = null;
protected String m_imageTitle = null;
protected String m_imageUrl = null;
protected String m_imageHeight = "31";
protected String m_imageWidth = "88";
protected String m_imageDescription = null;
protected List<NewsItem> m_items = null;
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(BasicNewsService.class);
/**
* Construct.
*
* @param source
* The URL from which the feed can be obtained
* @exception NewsConnectionException,
* for errors making the connection.
* @exception NewsFormatException,
* for errors in the URL or errors parsing the feed.
*/
public BasicNewsChannel(String source) throws NewsConnectionException, NewsFormatException
{
if (m_items == null)
{
m_items = new Vector<NewsItem>();
}
// get the file, parse it and cache it
// throw NewsConnectionException if unable to get file
// throw NewsFormatException if file is in wrong format
initChannel(source);
}
// get the file, parse it and cache it
// throw NewsConnectionException if unable to get file
// throw NewsFormatException if file is in wrong format
// updated to use ROME syndication api
private void initChannel(String source) throws NewsConnectionException, NewsFormatException
{
SyndFeed feed = null;
ResourceLoader rl = new ResourceLoader("news-impl");
try
{
URL feedUrl = new URL(source);
FeedFetcher feedFetcher = new HttpURLFeedFetcher();
feed = feedFetcher.retrieveFeed(feedUrl);
}
catch (MalformedURLException e)
{
if (M_log.isDebugEnabled()) M_log.debug("initChannel(" + source + ") bad url: " + e.getMessage());
throw new NewsFormatException("\"" + source + "\" " + rl.getString("is_not_a_valid_url"));
}
catch (IOException e)
{
if (M_log.isDebugEnabled())
M_log.debug("initChannel(" + source + ") constructor: couldn't connect: " + e.getMessage());
throw new NewsConnectionException( rl.getString("unable_to_obtain_news_feed") + " " + source);
}
catch (Exception e)
{
M_log.info("initChannel(" + source + ") constructor: couldn't parse: " + e.getMessage());
throw new NewsConnectionException(rl.getString("unable_to_interpret") +" " + source);
}
m_title = FormattedText.processEscapedHtml(feed.getTitle());
m_source = source;
m_description = FormattedText.processEscapedHtml(feed.getDescription());
m_description = Validator.stripAllNewlines(m_description);
m_lastbuilddate = "";
m_pubdate = "";
Date pubdate = feed.getPublishedDate();
if (pubdate != null)
{
m_pubdate = FormattedText.processEscapedHtml(DateFormat.getDateInstance().format(pubdate));
m_lastbuilddate = m_pubdate;
}
m_pubdate = Validator.stripAllNewlines(m_pubdate);
m_lastbuilddate = Validator.stripAllNewlines(m_lastbuilddate);
m_copyright = FormattedText.processEscapedHtml(feed.getCopyright());
m_copyright = Validator.stripAllNewlines(m_copyright);
m_language = FormattedText.processEscapedHtml(feed.getLanguage());
m_language = Validator.stripAllNewlines(m_language);
m_link = FormattedText.processEscapedHtml(feed.getLink());
m_link = Validator.stripAllNewlines(m_link);
SyndImage image = feed.getImage();
if (image != null)
{
m_imageLink = FormattedText.processEscapedHtml(image.getLink());
m_imageLink = Validator.stripAllNewlines(m_imageLink);
m_imageTitle = FormattedText.processEscapedHtml(image.getTitle());
m_imageTitle = Validator.stripAllNewlines(m_imageTitle);
m_imageUrl = FormattedText.processEscapedHtml(image.getUrl());
m_imageUrl = Validator.stripAllNewlines(m_imageUrl);
m_imageHeight = "";
m_imageWidth = "";
m_imageDescription = FormattedText.processEscapedHtml(image.getDescription());
m_imageDescription = Validator.stripAllNewlines(m_imageDescription);
}
// others??
m_items = new Vector<NewsItem>();
List items = feed.getEntries();
for (int i = 0; i < items.size(); ++i)
{
SyndEntry entry = (SyndEntry) items.get(i);
String iTitle = FormattedText.processEscapedHtml(entry.getTitle());
iTitle = Validator.stripAllNewlines(iTitle);
String iDescription = null;
try
{
if (entry.getDescription() != null)
{
iDescription = FormattedText.processEscapedHtml(
entry.getDescription().getValue());
iDescription = Validator.stripAllNewlines(iDescription);
}
}
catch (Exception e)
{
M_log.warn(e);
}
String iLink = FormattedText.processEscapedHtml(entry.getLink());
iLink = Validator.stripAllNewlines(iLink);
String iPubDate = "";
Date entrydate = entry.getPublishedDate();
if (entrydate != null)
{
iPubDate = FormattedText.processEscapedHtml(
DateFormat.getDateInstance().format(entrydate));
}
List<NewsItemEnclosure> enclosures = new Vector<NewsItemEnclosure>();
List syndEnclosures = entry.getEnclosures();
for (int j = 0; j < syndEnclosures.size(); j++)
{
SyndEnclosure syndEnclosure = (SyndEnclosure) syndEnclosures.get(j);
- enclosures.add(new BasicNewsItemEnclosure(syndEnclosure.getUrl(),
+ enclosures.add(new BasicNewsItemEnclosure(
+ FormattedText.processEscapedHtml(syndEnclosure.getUrl()),
syndEnclosure.getType(), syndEnclosure.getLength()));
}
iPubDate = Validator.stripAllNewlines(iPubDate);
m_items.add(new BasicNewsItem(iTitle, iDescription, iLink, iPubDate, enclosures));
}
} // initChannel
/**
* A .
*
* @return the NewsItem that has the specified id.
*/
public List getNewsitems()
{
List<NewsItem> rv = new Vector<NewsItem>();
rv.addAll(m_items);
return rv;
} // getNewsitems
/**
* A .
*
* @param filter
* A filtering object to accept messages, or null if no filtering is desired.
* @return a list of NewsItems objects (may be empty).
*/
public List getNewsitems(Filter filter)
{
List items = new Vector<NewsItem>(m_items);
if (filter != null)
{
List<NewsItem> accepted = new Vector<NewsItem>();
Iterator it = items.iterator();
while (it.hasNext())
{
NewsItem item = (NewsItem) it.next();
if (filter.accept(item))
{
accepted.add(item);
}
}
items = accepted;
}
return items;
}
public String getSource()
{
return m_source;
}
public String getLink()
{
return m_link;
}
public String getTitle()
{
return m_title;
}
public String getDescription()
{
return m_description;
}
public String getLanguage()
{
return m_language;
}
public String getCopyright()
{
return m_copyright;
}
public String getPubdate()
{
return m_pubdate;
}
public String getLastbuilddate()
{
return m_lastbuilddate;
}
public String getImageUrl()
{
return m_imageUrl;
}
public String getImageTitle()
{
return m_imageTitle;
}
public String getImageLink()
{
return m_imageLink;
}
public String getImageWidth()
{
return m_imageWidth;
}
public String getImageHeight()
{
return m_imageHeight;
}
public String getImageDescription()
{
return m_imageDescription;
}
public void setNewsitems(List items)
{
m_items = new Vector(items);
}
public void addNewsitem(NewsItem item)
{
m_items.add(item);
}
public void setSource(String source) throws NewsConnectionException, NewsFormatException
{
m_source = source;
initChannel(source);
}
public void setLink(String link)
{
m_link = link;
}
public void setTitle(String title)
{
m_title = title;
}
public void setDescription(String description)
{
m_description = description;
}
public void setLanguage(String language)
{
m_language = language;
}
public void setCopyright(String copyright)
{
m_copyright = copyright;
}
public void setPubdate(String pubdate)
{
m_pubdate = pubdate;
}
public void setLastbuilddate(String builddate)
{
m_lastbuilddate = builddate;
}
public void setImageUrl(String imageUrl)
{
m_imageUrl = imageUrl;
}
public void setImageTitle(String imageTitle)
{
m_imageTitle = imageTitle;
}
public void setImageLink(String imageLink)
{
m_imageLink = imageLink;
}
public void setImageWidth(String imageWidth)
{
m_imageWidth = imageWidth;
}
public void setImageHeight(String imageHeight)
{
m_imageHeight = imageHeight;
}
public void setImageDescription(String imageDescription)
{
m_imageDescription = imageDescription;
}
/**
* Checks whether an update is available for the rss news feed.
*
* @return true if update is available, false otherwise
*/
public boolean isUpdateAvailable()
{
// %%%%%%%%
return true;
}
/**
* Checks the relative ordering of the String url's of two Channels. Same
* response pattern as compareTo method for Strings--negative if "this"
* object is greater than parameter, zero if the objects are equal, and
* positive if "this" object is less than the parameter. The parameter
* can be a String reference or a NewsChannel object (otherwise method
* throws ClassCastException).
*
* @return A negative integer if "this" object is greater than parameter,
* zero if the objects are equal, and a positive integer if "this" object
* is less than the parameter
*/
public int compareTo(Object obj) throws ClassCastException
{
int rv = 0;
if (m_source == null)
{
if (obj != null)
{
rv = -1;
}
}
else if (obj == null)
{
rv = 1;
}
else if (obj instanceof String)
{
rv = m_source.compareTo((String) obj);
}
else
{
NewsChannel other = (NewsChannel) obj;
rv = m_source.compareTo(other.getLink());
}
return rv;
}
/**
* Checks whether the parameter obj refers to the same channel as "this" channel.
* The parameter can be a String URL or a NewsChannel object (otherwise method
* throws ClassCastException).
*
* @return true if the channels are the same, false otherwise
*/
public boolean equals(Object obj) throws ClassCastException
{
return (compareTo(obj) == 0);
}
/**
* Calculates a hash code for the channel object's URL.
*
* @return The hash-code for the String URL to the channel.
*/
public int hashCode()
{
String hval = "";
if (m_source != null)
{
hval = m_source;
}
return hval.hashCode();
}
} // BasicNewsChannel
| true | true | private void initChannel(String source) throws NewsConnectionException, NewsFormatException
{
SyndFeed feed = null;
ResourceLoader rl = new ResourceLoader("news-impl");
try
{
URL feedUrl = new URL(source);
FeedFetcher feedFetcher = new HttpURLFeedFetcher();
feed = feedFetcher.retrieveFeed(feedUrl);
}
catch (MalformedURLException e)
{
if (M_log.isDebugEnabled()) M_log.debug("initChannel(" + source + ") bad url: " + e.getMessage());
throw new NewsFormatException("\"" + source + "\" " + rl.getString("is_not_a_valid_url"));
}
catch (IOException e)
{
if (M_log.isDebugEnabled())
M_log.debug("initChannel(" + source + ") constructor: couldn't connect: " + e.getMessage());
throw new NewsConnectionException( rl.getString("unable_to_obtain_news_feed") + " " + source);
}
catch (Exception e)
{
M_log.info("initChannel(" + source + ") constructor: couldn't parse: " + e.getMessage());
throw new NewsConnectionException(rl.getString("unable_to_interpret") +" " + source);
}
m_title = FormattedText.processEscapedHtml(feed.getTitle());
m_source = source;
m_description = FormattedText.processEscapedHtml(feed.getDescription());
m_description = Validator.stripAllNewlines(m_description);
m_lastbuilddate = "";
m_pubdate = "";
Date pubdate = feed.getPublishedDate();
if (pubdate != null)
{
m_pubdate = FormattedText.processEscapedHtml(DateFormat.getDateInstance().format(pubdate));
m_lastbuilddate = m_pubdate;
}
m_pubdate = Validator.stripAllNewlines(m_pubdate);
m_lastbuilddate = Validator.stripAllNewlines(m_lastbuilddate);
m_copyright = FormattedText.processEscapedHtml(feed.getCopyright());
m_copyright = Validator.stripAllNewlines(m_copyright);
m_language = FormattedText.processEscapedHtml(feed.getLanguage());
m_language = Validator.stripAllNewlines(m_language);
m_link = FormattedText.processEscapedHtml(feed.getLink());
m_link = Validator.stripAllNewlines(m_link);
SyndImage image = feed.getImage();
if (image != null)
{
m_imageLink = FormattedText.processEscapedHtml(image.getLink());
m_imageLink = Validator.stripAllNewlines(m_imageLink);
m_imageTitle = FormattedText.processEscapedHtml(image.getTitle());
m_imageTitle = Validator.stripAllNewlines(m_imageTitle);
m_imageUrl = FormattedText.processEscapedHtml(image.getUrl());
m_imageUrl = Validator.stripAllNewlines(m_imageUrl);
m_imageHeight = "";
m_imageWidth = "";
m_imageDescription = FormattedText.processEscapedHtml(image.getDescription());
m_imageDescription = Validator.stripAllNewlines(m_imageDescription);
}
// others??
m_items = new Vector<NewsItem>();
List items = feed.getEntries();
for (int i = 0; i < items.size(); ++i)
{
SyndEntry entry = (SyndEntry) items.get(i);
String iTitle = FormattedText.processEscapedHtml(entry.getTitle());
iTitle = Validator.stripAllNewlines(iTitle);
String iDescription = null;
try
{
if (entry.getDescription() != null)
{
iDescription = FormattedText.processEscapedHtml(
entry.getDescription().getValue());
iDescription = Validator.stripAllNewlines(iDescription);
}
}
catch (Exception e)
{
M_log.warn(e);
}
String iLink = FormattedText.processEscapedHtml(entry.getLink());
iLink = Validator.stripAllNewlines(iLink);
String iPubDate = "";
Date entrydate = entry.getPublishedDate();
if (entrydate != null)
{
iPubDate = FormattedText.processEscapedHtml(
DateFormat.getDateInstance().format(entrydate));
}
List<NewsItemEnclosure> enclosures = new Vector<NewsItemEnclosure>();
List syndEnclosures = entry.getEnclosures();
for (int j = 0; j < syndEnclosures.size(); j++)
{
SyndEnclosure syndEnclosure = (SyndEnclosure) syndEnclosures.get(j);
enclosures.add(new BasicNewsItemEnclosure(syndEnclosure.getUrl(),
syndEnclosure.getType(), syndEnclosure.getLength()));
}
iPubDate = Validator.stripAllNewlines(iPubDate);
m_items.add(new BasicNewsItem(iTitle, iDescription, iLink, iPubDate, enclosures));
}
} // initChannel
| private void initChannel(String source) throws NewsConnectionException, NewsFormatException
{
SyndFeed feed = null;
ResourceLoader rl = new ResourceLoader("news-impl");
try
{
URL feedUrl = new URL(source);
FeedFetcher feedFetcher = new HttpURLFeedFetcher();
feed = feedFetcher.retrieveFeed(feedUrl);
}
catch (MalformedURLException e)
{
if (M_log.isDebugEnabled()) M_log.debug("initChannel(" + source + ") bad url: " + e.getMessage());
throw new NewsFormatException("\"" + source + "\" " + rl.getString("is_not_a_valid_url"));
}
catch (IOException e)
{
if (M_log.isDebugEnabled())
M_log.debug("initChannel(" + source + ") constructor: couldn't connect: " + e.getMessage());
throw new NewsConnectionException( rl.getString("unable_to_obtain_news_feed") + " " + source);
}
catch (Exception e)
{
M_log.info("initChannel(" + source + ") constructor: couldn't parse: " + e.getMessage());
throw new NewsConnectionException(rl.getString("unable_to_interpret") +" " + source);
}
m_title = FormattedText.processEscapedHtml(feed.getTitle());
m_source = source;
m_description = FormattedText.processEscapedHtml(feed.getDescription());
m_description = Validator.stripAllNewlines(m_description);
m_lastbuilddate = "";
m_pubdate = "";
Date pubdate = feed.getPublishedDate();
if (pubdate != null)
{
m_pubdate = FormattedText.processEscapedHtml(DateFormat.getDateInstance().format(pubdate));
m_lastbuilddate = m_pubdate;
}
m_pubdate = Validator.stripAllNewlines(m_pubdate);
m_lastbuilddate = Validator.stripAllNewlines(m_lastbuilddate);
m_copyright = FormattedText.processEscapedHtml(feed.getCopyright());
m_copyright = Validator.stripAllNewlines(m_copyright);
m_language = FormattedText.processEscapedHtml(feed.getLanguage());
m_language = Validator.stripAllNewlines(m_language);
m_link = FormattedText.processEscapedHtml(feed.getLink());
m_link = Validator.stripAllNewlines(m_link);
SyndImage image = feed.getImage();
if (image != null)
{
m_imageLink = FormattedText.processEscapedHtml(image.getLink());
m_imageLink = Validator.stripAllNewlines(m_imageLink);
m_imageTitle = FormattedText.processEscapedHtml(image.getTitle());
m_imageTitle = Validator.stripAllNewlines(m_imageTitle);
m_imageUrl = FormattedText.processEscapedHtml(image.getUrl());
m_imageUrl = Validator.stripAllNewlines(m_imageUrl);
m_imageHeight = "";
m_imageWidth = "";
m_imageDescription = FormattedText.processEscapedHtml(image.getDescription());
m_imageDescription = Validator.stripAllNewlines(m_imageDescription);
}
// others??
m_items = new Vector<NewsItem>();
List items = feed.getEntries();
for (int i = 0; i < items.size(); ++i)
{
SyndEntry entry = (SyndEntry) items.get(i);
String iTitle = FormattedText.processEscapedHtml(entry.getTitle());
iTitle = Validator.stripAllNewlines(iTitle);
String iDescription = null;
try
{
if (entry.getDescription() != null)
{
iDescription = FormattedText.processEscapedHtml(
entry.getDescription().getValue());
iDescription = Validator.stripAllNewlines(iDescription);
}
}
catch (Exception e)
{
M_log.warn(e);
}
String iLink = FormattedText.processEscapedHtml(entry.getLink());
iLink = Validator.stripAllNewlines(iLink);
String iPubDate = "";
Date entrydate = entry.getPublishedDate();
if (entrydate != null)
{
iPubDate = FormattedText.processEscapedHtml(
DateFormat.getDateInstance().format(entrydate));
}
List<NewsItemEnclosure> enclosures = new Vector<NewsItemEnclosure>();
List syndEnclosures = entry.getEnclosures();
for (int j = 0; j < syndEnclosures.size(); j++)
{
SyndEnclosure syndEnclosure = (SyndEnclosure) syndEnclosures.get(j);
enclosures.add(new BasicNewsItemEnclosure(
FormattedText.processEscapedHtml(syndEnclosure.getUrl()),
syndEnclosure.getType(), syndEnclosure.getLength()));
}
iPubDate = Validator.stripAllNewlines(iPubDate);
m_items.add(new BasicNewsItem(iTitle, iDescription, iLink, iPubDate, enclosures));
}
} // initChannel
|
diff --git a/android/src/de/hsa/otma/android/map/Board.java b/android/src/de/hsa/otma/android/map/Board.java
index fbefa9d..0b9573d 100644
--- a/android/src/de/hsa/otma/android/map/Board.java
+++ b/android/src/de/hsa/otma/android/map/Board.java
@@ -1,166 +1,166 @@
package de.hsa.otma.android.map;
import android.util.Log;
import de.hsa.otma.android.R;
import de.hsa.otma.android.config.Config;
import de.hsa.otma.android.config.XMLConfig;
import java.util.*;
import static de.hsa.otma.android.map.Direction.*;
public class Board
{
public static final Board INSTANCE = new Board();
private Map<Coordinate, BoardElement> elements = new HashMap<Coordinate, BoardElement>();
private List<Door> doors = new ArrayList<Door>();
private Board()
{
buildBoard();
}
public Coordinate getRandomCoordinateOnBoard()
{
int x = random.nextInt(5) + 1;
int y = random.nextInt(5) + 1;
return new Coordinate(x, y);
}
private Random random = new Random(System.nanoTime());
private void assignRoomsToRandomDoors(){
Log.i(Board.class.getName(), "Assigning rooms to doors!");
Config config = new XMLConfig("http://hs-augsburg.de/~lieback/pub/otma-config-game.xml");
List<Room> rooms = config.getRooms();
if(rooms == null){
throw new NullPointerException("No rooms specified in config - list of rooms null!");
}
if(doors.size() < rooms.size()){
rooms = rooms.subList(0, doors.size()-1);
}
for(Room room : rooms){
Door door;
do{
door = doors.get(random.nextInt(doors.size()));
}
while(door.getRoom() != null);
door.setRoom(room);
door.setAbbreviation(room.getAbbreviation());
door.setTitle(room.getTitle());
}
Log.i(Board.class.getName(), "All rooms have been assigned to doors!");
}
private void createDoorForBoardElementInDirection(BoardElement element, Direction direction)
{
int x = -element.getCoordinate().getX();
int y = -element.getCoordinate().getY();
Coordinate coordinate = new Coordinate(x, y);
Door door = new Door(coordinate, element);
elements.put(coordinate, door);
element.setElementForDirection(direction, door);
doors.add(door);
}
private BoardElement createBoardElementAndPutToBoard(int x, int y, int drawable)
{
Coordinate coordinate = new Coordinate(x, y);
BoardElement boardElement = new BoardElement(coordinate, drawable);
elements.put(coordinate, boardElement);
return boardElement;
}
public BoardElement getElementFor(Coordinate coordinate)
{
return elements.get(coordinate);
}
private void buildBoard()
{
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
- createDoorForBoardElementInDirection(map2x2, EAST);
+ //createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
}
| true | true | private void buildBoard()
{
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
| private void buildBoard()
{
BoardElement map1x1 = createBoardElementAndPutToBoard(1, 1, R.drawable.map_1x1);
BoardElement map1x2 = createBoardElementAndPutToBoard(2, 1, R.drawable.map_1x2);
BoardElement map1x3 = createBoardElementAndPutToBoard(3, 1, R.drawable.map_1x3);
BoardElement map1x4 = createBoardElementAndPutToBoard(4, 1, R.drawable.map_1x4);
BoardElement map1x5 = createBoardElementAndPutToBoard(5, 1, R.drawable.map_1x5);
BoardElement map2x1 = createBoardElementAndPutToBoard(1, 2, R.drawable.map_2x1);
BoardElement map2x2 = createBoardElementAndPutToBoard(2, 2, R.drawable.map_2x2);
BoardElement map2x3 = createBoardElementAndPutToBoard(3, 2, R.drawable.map_2x3);
BoardElement map2x4 = createBoardElementAndPutToBoard(4, 2, R.drawable.map_2x4);
BoardElement map2x5 = createBoardElementAndPutToBoard(5, 2, R.drawable.map_2x5);
BoardElement map3x1 = createBoardElementAndPutToBoard(1, 3, R.drawable.map_3x1);
BoardElement map3x2 = createBoardElementAndPutToBoard(2, 3, R.drawable.map_3x2);
BoardElement map3x3 = createBoardElementAndPutToBoard(3, 3, R.drawable.map_3x3);
BoardElement map3x4 = createBoardElementAndPutToBoard(4, 3, R.drawable.map_3x4);
BoardElement map3x5 = createBoardElementAndPutToBoard(5, 3, R.drawable.map_3x5);
BoardElement map4x1 = createBoardElementAndPutToBoard(1, 4, R.drawable.map_4x1);
BoardElement map4x2 = createBoardElementAndPutToBoard(2, 4, R.drawable.map_4x2);
BoardElement map4x3 = createBoardElementAndPutToBoard(3, 4, R.drawable.map_4x3);
BoardElement map4x4 = createBoardElementAndPutToBoard(4, 4, R.drawable.map_4x4);
BoardElement map4x5 = createBoardElementAndPutToBoard(5, 4, R.drawable.map_4x5);
BoardElement map5x1 = createBoardElementAndPutToBoard(1, 5, R.drawable.map_5x1);
BoardElement map5x2 = createBoardElementAndPutToBoard(2, 5, R.drawable.map_5x2);
BoardElement map5x3 = createBoardElementAndPutToBoard(3, 5, R.drawable.map_5x3);
BoardElement map5x4 = createBoardElementAndPutToBoard(4, 5, R.drawable.map_5x4);
BoardElement map5x5 = createBoardElementAndPutToBoard(5, 5, R.drawable.map_5x5);
map1x1.setBoundaryElements(null, null, map2x1, null);
map1x2.setBoundaryElements(null, map1x3, map2x2, null);
map1x3.setBoundaryElements(null, map1x4, map2x3, map1x2);
map1x4.setBoundaryElements(null, map1x5, null, map1x3);
map1x5.setBoundaryElements(null, null, null, map1x4);
map2x1.setBoundaryElements(map1x1, map2x2, map3x1, null);
map2x2.setBoundaryElements(map1x2, null, null, map2x1);
map2x3.setBoundaryElements(map1x3, null, map3x3, null);
map2x4.setBoundaryElements(null, map2x5, null, null);
map2x5.setBoundaryElements(null, null, map3x5, map2x4);
map3x1.setBoundaryElements(map2x1, null, map4x1, null);
map3x2.setBoundaryElements(null, map3x3, map4x2, null);
map3x3.setBoundaryElements(map2x3, map3x4, null, map3x2);
map3x4.setBoundaryElements(null, map3x5, null, map3x3);
map3x5.setBoundaryElements(map2x5, null, map4x5, map3x4);
map4x1.setBoundaryElements(map3x1, map4x2, map5x1, null);
map4x2.setBoundaryElements(map3x2, map4x3, null, map4x1);
map4x3.setBoundaryElements(null, null, map5x3, map4x2);
map4x4.setBoundaryElements(null, map4x5, map5x4, null);
map4x5.setBoundaryElements(map3x5, null, map5x5, map4x4);
map5x1.setBoundaryElements(map4x1, map5x2, null, null);
map5x2.setBoundaryElements(null, map5x3, null, map5x1);
map5x3.setBoundaryElements(map4x3, map5x4, null, map5x2);
map5x4.setBoundaryElements(map4x4, null, null, map5x3);
map5x5.setBoundaryElements(map4x5, null, null, null);
createDoorForBoardElementInDirection(map1x2, NORTH);
createDoorForBoardElementInDirection(map1x5, SOUTH);
createDoorForBoardElementInDirection(map2x1, WEST);
//createDoorForBoardElementInDirection(map2x2, EAST);
createDoorForBoardElementInDirection(map2x4, WEST);
createDoorForBoardElementInDirection(map2x5, NORTH);
createDoorForBoardElementInDirection(map3x1, EAST);
createDoorForBoardElementInDirection(map3x2, NORTH);
createDoorForBoardElementInDirection(map3x4, SOUTH);
createDoorForBoardElementInDirection(map3x5, EAST);
createDoorForBoardElementInDirection(map4x1, WEST);
createDoorForBoardElementInDirection(map4x3, EAST);
createDoorForBoardElementInDirection(map4x4, NORTH);
createDoorForBoardElementInDirection(map5x2, NORTH);
createDoorForBoardElementInDirection(map5x5, WEST);
assignRoomsToRandomDoors();
}
|
diff --git a/src/core/org/pathvisio/view/VPathwayElement.java b/src/core/org/pathvisio/view/VPathwayElement.java
index 3a2d0c8f..4e8e1f67 100644
--- a/src/core/org/pathvisio/view/VPathwayElement.java
+++ b/src/core/org/pathvisio/view/VPathwayElement.java
@@ -1,333 +1,335 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.view;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import org.pathvisio.preferences.GlobalPreference;
public abstract class VPathwayElement implements Comparable<VPathwayElement>
{
protected BasicStroke defaultStroke = new BasicStroke();
protected VPathway canvas;
VPathwayElement(VPathway canvas)
{
this.canvas = canvas;
canvas.addObject(this);
}
public static Color selectColor = GlobalPreference.getValueColor(GlobalPreference.COLOR_SELECTED);
public static final float HIGHLIGHT_STROKE_WIDTH = 5.0f;
private Rectangle2D oldrect = null;
private boolean isSelected;
public final void draw(Graphics2D g2d)
{
//Create a copy to ensure that the state of this Graphics2D will be intact
//see: http://java.sun.com/docs/books/tutorial/uiswing/painting/concepts2.html
Graphics2D g = (Graphics2D)g2d.create();
//Prevent element from drawing outside its bounds
g.clip(getVBounds());
g.setStroke(defaultStroke);
//Perform the drawing
doDraw(g);
//Free resources from the copied Graphics2D
g.dispose();
}
protected abstract void doDraw(Graphics2D g2d);
/**
* mark both the area currently and previously occupied by this object for redraw
*/
protected void markDirty()
{
if (oldrect != null)
{
canvas.addDirtyRect(oldrect);
}
Rectangle2D newrect = getVBounds();
canvas.addDirtyRect(newrect);
oldrect = newrect;
}
/**
* Get the drawing this object belongs to
*/
public VPathway getDrawing()
{
return canvas;
}
/**
* Besides resetting isHighlighted, this accomplishes this:
* - marking the area dirty, so the object has a chance to redraw itself in unhighlighted state
*/
public void unhighlight()
{
if(isHighlighted)
{
isHighlighted = false;
highlightColor = null;
markDirty();
}
}
private Color highlightColor;
public Color getHighlightColor()
{
return highlightColor;
}
private boolean isHighlighted;
/**
Besides setting isHighlighted, this accomplishes this:
- marking the area dirty, so the object has a chance to redraw itself in highlighted state
@param c this will highlight in a particular color. See
highlight() without parameter if you just want to highlight with
the default color
*/
public void highlight(Color c)
{
if(!(isHighlighted && highlightColor == c))
{
isHighlighted = true;
highlightColor = c;
markDirty();
}
}
/**
highlight this element with the default highlight color
*/
public void highlight()
{
highlight (GlobalPreference.getValueColor(GlobalPreference.COLOR_HIGHLIGHTED));
}
/**
* Returns true if this object is highlighted, false otherwise
*/
public boolean isHighlighted()
{
return isHighlighted;
}
/**
* Determines whether a Graphics object intersects
* the rectangle specified
* @param r - the rectangle to check
* @return True if the object intersects the rectangle, false otherwise
*/
protected boolean vIntersects(Rectangle2D r)
{
return getVOutline().intersects(r);
}
/**
* Determines wheter a Graphics object contains
* the point specified
* @param point - the point to check
* @return True if the object contains the point, false otherwise
*/
protected boolean vContains(Point2D point)
{
return getVOutline().contains(point);
}
public boolean isSelected()
{
return isSelected;
}
/**
* Besides resetting isSelected, this accomplishes this:
* - marking the area dirty, so the object has a chance to redraw itself in unselected state
*/
public void deselect()
{
if (isSelected)
{
isSelected = false;
markDirty();
}
}
/**
* Besides setting isSelected, this accomplishes this:
* - marking the area dirty, so the object has a chance to redraw itself in selected state
*/
public void select()
{
if (!isSelected)
{
isSelected = true;
markDirty();
}
}
/**
* Transforms this object to fit to the coordinates
* passed on by the given handle
* @param h The Handle to adjust to
*/
protected void adjustToHandle(Handle h, double vx, double vy) {}
/**
* Get all the handles belonging to this object
* @return an array of GmmlHandles, an empty array if the object
* has no handles
*/
protected Handle[] getHandles() { return new Handle[] {}; }
/**
* Moves this object by specified increments
* @param dx - the value of x-increment
* @param dy - the value of y-increment
*/
protected void vMoveBy(double vdx, double vdy)
{
}
/**
* Gets the rectangular bounds of this object
* This method is equivalent to {@link #getVOutline()}.getBounds2D()
* @return
*/
public Rectangle2D getVBounds()
{
return getVOutline().getBounds2D();
}
/**
* Get the outline of this element. The outline is used to check
* whether a point is contained in this element or not and includes the stroke
* and takes into account rotation.
* Because it includes the stroke, it is not a direct model to view mapping of
* the model outline!
* @return the outline of this element
*/
abstract protected Shape getVOutline();
/**
* Scales the object to the given rectangle
* @param r
*/
protected void setVScaleRectangle(Rectangle2D r) { }
/**
* Gets the rectangle used to scale the object
*/
protected Rectangle2D getVScaleRectangle() { return new Rectangle2D.Double(); }
/**
* Orders VPathwayElements
*
* non-Graphics objects always sort above graphics objects
* selected Graphics objects sort above non-selected graphics objects
* finally, non-selected graphics objects are sorted by their z-order.
* The z-order is determined by the type of object by default,
* but can be overridden by the user.
*
* The comparison is consistent with "equals", i.e. it doesn't return 0 if
* the objects are different, even if their drawing order is the same.
*
* @param d VPathwayElement that this is compared to.
*/
public int compareTo(VPathwayElement d)
{
// same object? easy...
if (d == this)
return 0;
// for two Graphics-type objects, sort depending on z-order
if (this instanceof Graphics && d instanceof Graphics)
{
int a, b;
// if only one of two is selected (XOR):
a = ((Graphics)this).gdata.getZOrder();
b = ((Graphics)d).gdata.getZOrder();
// if sorting order is equal, use hash code
if (b == a)
{
return hashCode() - d.hashCode();
}
else
return a - b;
}
/*
* for mixed objects, sort depending on Object type
*
* Handle on top
* other non-Graphics in the middle (VPoint and others)
* Graphics at the bottom
*/
else
{
- int alevel = (this instanceof Graphics ? 1 : 0) +
- (this instanceof Handle ? 2 : 0);
+ int alevel = (this instanceof Graphics ? 1 : 0) +
+ (this instanceof SelectionBox ? 2 : 0) +
+ (this instanceof Handle ? 4 : 0);
int blevel = (d instanceof Graphics ? 1 : 0) +
- (d instanceof Handle ? 2 : 0);
+ (d instanceof SelectionBox ? 2 : 0) +
+ (d instanceof Handle ? 4 : 0);
if (alevel == blevel)
{
// objects are the same type. default ordering
return hashCode() - d.hashCode();
}
else return (alevel - blevel);
}
}
/**
* helper method to convert view coordinates to model coordinates
* */
protected double mFromV(double v) { return canvas.mFromV(v); }
/**
* helper method to convert view coordinates to model coordinates
* */
protected double vFromM(double m) { return canvas.vFromM(m); }
protected void destroyHandles() {
for(Handle h : getHandles()) {
h.destroy();
}
}
protected void destroy() {
//Remove from canvas
canvas.getDrawingObjects().remove(this);
destroyHandles();
}
}
| false | true | public int compareTo(VPathwayElement d)
{
// same object? easy...
if (d == this)
return 0;
// for two Graphics-type objects, sort depending on z-order
if (this instanceof Graphics && d instanceof Graphics)
{
int a, b;
// if only one of two is selected (XOR):
a = ((Graphics)this).gdata.getZOrder();
b = ((Graphics)d).gdata.getZOrder();
// if sorting order is equal, use hash code
if (b == a)
{
return hashCode() - d.hashCode();
}
else
return a - b;
}
/*
* for mixed objects, sort depending on Object type
*
* Handle on top
* other non-Graphics in the middle (VPoint and others)
* Graphics at the bottom
*/
else
{
int alevel = (this instanceof Graphics ? 1 : 0) +
(this instanceof Handle ? 2 : 0);
int blevel = (d instanceof Graphics ? 1 : 0) +
(d instanceof Handle ? 2 : 0);
if (alevel == blevel)
{
// objects are the same type. default ordering
return hashCode() - d.hashCode();
}
else return (alevel - blevel);
}
}
| public int compareTo(VPathwayElement d)
{
// same object? easy...
if (d == this)
return 0;
// for two Graphics-type objects, sort depending on z-order
if (this instanceof Graphics && d instanceof Graphics)
{
int a, b;
// if only one of two is selected (XOR):
a = ((Graphics)this).gdata.getZOrder();
b = ((Graphics)d).gdata.getZOrder();
// if sorting order is equal, use hash code
if (b == a)
{
return hashCode() - d.hashCode();
}
else
return a - b;
}
/*
* for mixed objects, sort depending on Object type
*
* Handle on top
* other non-Graphics in the middle (VPoint and others)
* Graphics at the bottom
*/
else
{
int alevel = (this instanceof Graphics ? 1 : 0) +
(this instanceof SelectionBox ? 2 : 0) +
(this instanceof Handle ? 4 : 0);
int blevel = (d instanceof Graphics ? 1 : 0) +
(d instanceof SelectionBox ? 2 : 0) +
(d instanceof Handle ? 4 : 0);
if (alevel == blevel)
{
// objects are the same type. default ordering
return hashCode() - d.hashCode();
}
else return (alevel - blevel);
}
}
|
diff --git a/de.jutzig.jabylon.ui/src/main/java/de/jutzig/jabylon/ui/panels/ProjectListPanel.java b/de.jutzig.jabylon.ui/src/main/java/de/jutzig/jabylon/ui/panels/ProjectListPanel.java
index 9018c352..0a79fd6c 100644
--- a/de.jutzig.jabylon.ui/src/main/java/de/jutzig/jabylon/ui/panels/ProjectListPanel.java
+++ b/de.jutzig.jabylon.ui/src/main/java/de/jutzig/jabylon/ui/panels/ProjectListPanel.java
@@ -1,66 +1,66 @@
package de.jutzig.jabylon.ui.panels;
import java.util.Random;
import org.eclipse.emf.common.util.EList;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.themes.Reindeer;
import de.jutzig.jabylon.properties.Project;
import de.jutzig.jabylon.properties.Workspace;
import de.jutzig.jabylon.ui.applications.MainDashboard;
import de.jutzig.jabylon.ui.components.StaticProgressIndicator;
public class ProjectListPanel extends GridLayout implements ClickListener {
public ProjectListPanel() {
createContents();
setMargin(true, true, true, true);
setSpacing(true);
}
private void createContents() {
Workspace workspace = MainDashboard.getCurrent().getWorkspace();
EList<Project> projects = workspace.getProjects();
setColumns(2);
setRows(projects.size());
buildHeader();
Random random = new Random();
for (Project project : projects) {
Button projectName = new Button(project.getName());
projectName.setStyleName(Reindeer.BUTTON_LINK);
// label.setWidth(300, UNITS_PIXELS);
- projectName.setWidth(200, UNITS_PIXELS);
+// projectName.setWidth(200, UNITS_PIXELS);
addComponent(projectName);
projectName.setData(project);
projectName.addListener(this);
StaticProgressIndicator progress = new StaticProgressIndicator();
progress.setPercentage(random.nextInt(100));
addComponent(progress);
}
}
private void buildHeader() {
// Label label = new Label();
// label.setCaption("")
// addComponent(c, column, row)
}
@Override
public void buttonClick(ClickEvent event) {
Project project = (Project) event.getButton().getData();
MainDashboard.getCurrent().getBreadcrumbs().walkTo(project.getName());
}
}
| true | true | private void createContents() {
Workspace workspace = MainDashboard.getCurrent().getWorkspace();
EList<Project> projects = workspace.getProjects();
setColumns(2);
setRows(projects.size());
buildHeader();
Random random = new Random();
for (Project project : projects) {
Button projectName = new Button(project.getName());
projectName.setStyleName(Reindeer.BUTTON_LINK);
// label.setWidth(300, UNITS_PIXELS);
projectName.setWidth(200, UNITS_PIXELS);
addComponent(projectName);
projectName.setData(project);
projectName.addListener(this);
StaticProgressIndicator progress = new StaticProgressIndicator();
progress.setPercentage(random.nextInt(100));
addComponent(progress);
}
}
| private void createContents() {
Workspace workspace = MainDashboard.getCurrent().getWorkspace();
EList<Project> projects = workspace.getProjects();
setColumns(2);
setRows(projects.size());
buildHeader();
Random random = new Random();
for (Project project : projects) {
Button projectName = new Button(project.getName());
projectName.setStyleName(Reindeer.BUTTON_LINK);
// label.setWidth(300, UNITS_PIXELS);
// projectName.setWidth(200, UNITS_PIXELS);
addComponent(projectName);
projectName.setData(project);
projectName.addListener(this);
StaticProgressIndicator progress = new StaticProgressIndicator();
progress.setPercentage(random.nextInt(100));
addComponent(progress);
}
}
|
diff --git a/sventon/dev/java/src/de/berlios/sventon/repository/cache/entrycache/EntryCacheUpdater.java b/sventon/dev/java/src/de/berlios/sventon/repository/cache/entrycache/EntryCacheUpdater.java
index 9c26c978..ff2f2cfb 100644
--- a/sventon/dev/java/src/de/berlios/sventon/repository/cache/entrycache/EntryCacheUpdater.java
+++ b/sventon/dev/java/src/de/berlios/sventon/repository/cache/entrycache/EntryCacheUpdater.java
@@ -1,297 +1,298 @@
/*
* ====================================================================
* Copyright (c) 2005-2006 Sventon Project. All rights reserved.
*
* This software is licensed as described in the file LICENSE, which
* you should have received as part of this distribution. The terms
* are also available at http://sventon.berlios.de.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package de.berlios.sventon.repository.cache.entrycache;
import de.berlios.sventon.config.ApplicationConfiguration;
import de.berlios.sventon.repository.AbstractRevisionObserver;
import de.berlios.sventon.repository.RepositoryEntry;
import de.berlios.sventon.repository.RevisionUpdate;
import de.berlios.sventon.repository.RepositoryFactory;
import de.berlios.sventon.repository.cache.CacheException;
import de.berlios.sventon.util.PathUtil;
import de.berlios.sventon.web.model.LogEntryActionType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.io.SVNRepository;
import java.util.*;
/**
* Class responsible for updating one or more entry cache instances.
*
* @author [email protected]
*/
public class EntryCacheUpdater extends AbstractRevisionObserver {
/**
* The static logging instance.
*/
private static final Log logger = LogFactory.getLog(EntryCacheUpdater.class);
/**
* The EntryCacheManager instance.
*/
private final EntryCacheManager entryCacheManager;
/**
* Application configuration instance.
*/
private ApplicationConfiguration configuration;
/**
* Constructor.
*
* @param entryCacheManager The EntryCacheManager instance.
* @param configuration ApplicationConfiguration instance.
*/
public EntryCacheUpdater(final EntryCacheManager entryCacheManager, final ApplicationConfiguration configuration) {
logger.info("Starting");
this.entryCacheManager = entryCacheManager;
this.configuration = configuration;
for (final String instanceName : configuration.getInstanceNames()) {
logger.debug("Initializing cache instance: " + instanceName);
try {
this.entryCacheManager.getCache(instanceName);
} catch (CacheException ce) {
logger.warn("Unable to initialize instance");
}
}
}
/**
* Updates the cache to HEAD revision.
* A Subversion <i>log</i> command will be performed and
* the cache will be updated accordingly.
* <table>
* <tr><th>Type</th><th>Description</th><th>Action</th></tr>
* <tr><td>'A'</td><td>Added</td><td>Entry is added</td></tr>
* <tr><td>'D'</td><td>Deleted</td><td>Entry is removed</td></tr>
* <tr><td>'M'</td><td>Modified</td><td>Entry's details are updated</td></tr>
* <tr><td>'R'</td><td>Replaced (means that the object is first deleted, then
* another object with the same name is added, all within a single revision)
* </td><td>Entry's details are updated</td></tr>
* </table>
*
* @param revisionUpdate The updated revisions.
*/
public void update(final RevisionUpdate revisionUpdate) {
logger.info("Observer got [" + revisionUpdate.getRevisions().size() + "] updated revision(s) for instance: "
+ revisionUpdate.getInstanceName());
if (configuration == null) {
logger.warn("Method setConfiguration() has not yet been called!");
}
try {
final EntryCache entryCache = entryCacheManager.getCache(revisionUpdate.getInstanceName());
final SVNRepository repository = RepositoryFactory.INSTANCE.getRepository(
configuration.getInstanceConfiguration(revisionUpdate.getInstanceName()));
updateInternal(entryCache, repository, revisionUpdate);
} catch (final Exception ex) {
logger.warn("Could not update cache instance [" + revisionUpdate.getInstanceName() + "]", ex);
return;
}
}
/**
* Internal update method. Made protected for testing reasons only.
*
* @param entryCache EntryCache instance
* @param revisionUpdate Update
*/
protected static void updateInternal(final EntryCache entryCache, final SVNRepository repository,
final RevisionUpdate revisionUpdate) {
final List<SVNLogEntry> revisions = revisionUpdate.getRevisions();
final int revisionCount = revisions.size();
final long firstRevision = revisions.get(0).getRevision();
final long lastRevision = revisions.get(revisionCount - 1).getRevision();
if (revisionCount > 0 && firstRevision == 1) {
logger.info("Starting initial population of cache: " + revisionUpdate.getInstanceName());
try {
addDirectories(entryCache, repository, "/", lastRevision);
entryCache.setCachedRevision(lastRevision);
} catch (SVNException svnex) {
logger.error("Unable to populate cache", svnex);
}
logger.info("Cache population done");
} else {
// Initial population has already been performed - only apply changes for now.
if (lastRevision < entryCache.getCachedRevision()) {
throw new IllegalStateException("Revision [" + lastRevision + "] is older than last cached revision ["
+ entryCache.getCachedRevision() + "]. Has the repository URL changed? Delete all cache files to "
+ "trigger a complete cache rebuild");
}
// One logEntry is one commit (or revision)
for (final SVNLogEntry logEntry : revisions) {
try {
long revision = logEntry.getRevision();
logger.debug("Applying changes in revision [" + revision + "] to cache");
final Map<String, SVNLogEntryPath> map = logEntry.getChangedPaths();
final List<String> latestPathsList = new ArrayList<String>(map.keySet());
// Sort the entries to apply changes in right order
Collections.sort(latestPathsList);
for (final String entryPath : latestPathsList) {
final SVNLogEntryPath logEntryPath = map.get(entryPath);
switch (LogEntryActionType.parse(logEntryPath.getType())) {
case ADDED:
logger.debug("Adding entry to cache: " + logEntryPath.getPath());
doEntryCacheAdd(entryCache, repository, logEntryPath, revision);
break;
case DELETED:
logger.debug("Removing deleted entry from cache: " + logEntryPath.getPath());
doEntryCacheDelete(entryCache, repository, logEntryPath, revision);
break;
case REPLACED:
logger.debug("Replacing entry in cache: " + logEntryPath.getPath());
doEntryCacheReplace(entryCache, repository, logEntryPath, revision);
break;
case MODIFIED:
logger.debug("Updating modified entry in cache: " + logEntryPath.getPath());
doEntryCacheModify(entryCache, repository, logEntryPath, revision);
break;
default :
throw new RuntimeException("Unknown log entry type: " + logEntryPath.getType() + " in rev " + logEntry.getRevision());
}
}
} catch (SVNException svnex) {
logger.error("Unable to update entryCache", svnex);
}
}
+ entryCache.setCachedRevision(lastRevision);
logger.debug("Update completed");
}
}
/**
* Modifies an entry (file or directory) in the cache.
*
* @param entryCache The cache instance.
* @param repository Repository
* @param logEntryPath The log entry path
* @param revision The log revision
* @throws org.tmatesoft.svn.core.SVNException
* if subversion error occur.
*/
private static void doEntryCacheModify(final EntryCache entryCache, final SVNRepository repository,
final SVNLogEntryPath logEntryPath, final long revision) throws SVNException {
entryCache.removeByName(logEntryPath.getPath(), false);
entryCache.add(new RepositoryEntry(repository.info(logEntryPath.getPath(), revision),
PathUtil.getPathPart(logEntryPath.getPath()), null));
}
/**
* Replaces an entry (file or directory) in the cache.
*
* @param entryCache The cache instance.
* @param repository Repository
* @param logEntryPath The log entry path
* @param revision The log revision
* @throws SVNException if subversion error occur.
*/
private static void doEntryCacheReplace(final EntryCache entryCache, final SVNRepository repository,
final SVNLogEntryPath logEntryPath, final long revision) throws SVNException {
doEntryCacheModify(entryCache, repository, logEntryPath, revision);
}
/**
* Deletes an entry (file or directory) from the cache.
*
* @param entryCache The cache instance.
* @param repository Repository
* @param logEntryPath The log entry path
* @param revision The log revision
* @throws SVNException if subversion error occur.
*/
private static void doEntryCacheDelete(final EntryCache entryCache, final SVNRepository repository,
final SVNLogEntryPath logEntryPath, final long revision) throws SVNException {
// Have to find out if deleted entry was a file or directory
final SVNDirEntry deletedEntry = repository.info(logEntryPath.getPath(), revision - 1);
if (RepositoryEntry.Kind.valueOf(deletedEntry.getKind().toString()) == RepositoryEntry.Kind.dir) {
// Directory node deleted
logger.debug(logEntryPath.getPath() + " is a directory. Doing a recursive delete");
entryCache.removeByName(logEntryPath.getPath(), true);
} else {
// Single entry delete
entryCache.removeByName(logEntryPath.getPath(), false);
}
}
/**
* Adds an entry (file or directory) to the cache.
*
* @param entryCache The cache instance.
* @param repository Repository
* @param logEntryPath The log entry path
* @param revision The log revision
* @throws SVNException if subversion error occur.
*/
private static void doEntryCacheAdd(final EntryCache entryCache, final SVNRepository repository,
final SVNLogEntryPath logEntryPath, final long revision) throws SVNException {
// Have to find out if added entry was a file or directory
final SVNDirEntry addedEntry = repository.info(logEntryPath.getPath(), revision);
// If the entry is a directory and a copyPath exists, the entry is
// a moved or copied directory (branch). In that case we have to recursively
// add the entry. If entry is a directory but does not have a copyPath
// the contents will be added one by one as single entries.
if (RepositoryEntry.Kind.valueOf(addedEntry.getKind().toString()) == RepositoryEntry.Kind.dir
&& logEntryPath.getCopyPath() != null) {
// Directory node added
logger.debug(logEntryPath.getPath() + " is a directory. Doing a recursive add");
entryCache.add(new RepositoryEntry(addedEntry, PathUtil.getPathPart(logEntryPath.getPath()), null));
// Add directory contents
addDirectories(entryCache, repository, logEntryPath.getPath() + "/", revision);
} else {
// Single entry added
entryCache.add(new RepositoryEntry(addedEntry, PathUtil.getPathPart(logEntryPath.getPath()), null));
}
}
/**
* Adds all entries in given path.
* This method will be recursively called by itself.
*
* @param entryCache The cache instance.
* @param repository Repository
* @param path The path to add.
* @throws org.tmatesoft.svn.core.SVNException
* if a Subversion error occurs.
*/
@SuppressWarnings("unchecked")
private static void addDirectories(final EntryCache entryCache, final SVNRepository repository, final String path,
final long revision) throws SVNException {
final List<SVNDirEntry> entriesList = Collections.checkedList(new ArrayList<SVNDirEntry>(), SVNDirEntry.class);
entriesList.addAll(repository.getDir(path, revision, null, (Collection) null));
for (final SVNDirEntry entry : entriesList) {
final RepositoryEntry newEntry = new RepositoryEntry(entry, path, null);
if (!entryCache.add(newEntry)) {
logger.warn("Unable to add already existing entry to cache: " + newEntry.toString());
}
if (entry.getKind() == SVNNodeKind.DIR) {
addDirectories(entryCache, repository, path + entry.getName() + "/", revision);
}
}
}
}
| true | true | protected static void updateInternal(final EntryCache entryCache, final SVNRepository repository,
final RevisionUpdate revisionUpdate) {
final List<SVNLogEntry> revisions = revisionUpdate.getRevisions();
final int revisionCount = revisions.size();
final long firstRevision = revisions.get(0).getRevision();
final long lastRevision = revisions.get(revisionCount - 1).getRevision();
if (revisionCount > 0 && firstRevision == 1) {
logger.info("Starting initial population of cache: " + revisionUpdate.getInstanceName());
try {
addDirectories(entryCache, repository, "/", lastRevision);
entryCache.setCachedRevision(lastRevision);
} catch (SVNException svnex) {
logger.error("Unable to populate cache", svnex);
}
logger.info("Cache population done");
} else {
// Initial population has already been performed - only apply changes for now.
if (lastRevision < entryCache.getCachedRevision()) {
throw new IllegalStateException("Revision [" + lastRevision + "] is older than last cached revision ["
+ entryCache.getCachedRevision() + "]. Has the repository URL changed? Delete all cache files to "
+ "trigger a complete cache rebuild");
}
// One logEntry is one commit (or revision)
for (final SVNLogEntry logEntry : revisions) {
try {
long revision = logEntry.getRevision();
logger.debug("Applying changes in revision [" + revision + "] to cache");
final Map<String, SVNLogEntryPath> map = logEntry.getChangedPaths();
final List<String> latestPathsList = new ArrayList<String>(map.keySet());
// Sort the entries to apply changes in right order
Collections.sort(latestPathsList);
for (final String entryPath : latestPathsList) {
final SVNLogEntryPath logEntryPath = map.get(entryPath);
switch (LogEntryActionType.parse(logEntryPath.getType())) {
case ADDED:
logger.debug("Adding entry to cache: " + logEntryPath.getPath());
doEntryCacheAdd(entryCache, repository, logEntryPath, revision);
break;
case DELETED:
logger.debug("Removing deleted entry from cache: " + logEntryPath.getPath());
doEntryCacheDelete(entryCache, repository, logEntryPath, revision);
break;
case REPLACED:
logger.debug("Replacing entry in cache: " + logEntryPath.getPath());
doEntryCacheReplace(entryCache, repository, logEntryPath, revision);
break;
case MODIFIED:
logger.debug("Updating modified entry in cache: " + logEntryPath.getPath());
doEntryCacheModify(entryCache, repository, logEntryPath, revision);
break;
default :
throw new RuntimeException("Unknown log entry type: " + logEntryPath.getType() + " in rev " + logEntry.getRevision());
}
}
} catch (SVNException svnex) {
logger.error("Unable to update entryCache", svnex);
}
}
logger.debug("Update completed");
}
}
| protected static void updateInternal(final EntryCache entryCache, final SVNRepository repository,
final RevisionUpdate revisionUpdate) {
final List<SVNLogEntry> revisions = revisionUpdate.getRevisions();
final int revisionCount = revisions.size();
final long firstRevision = revisions.get(0).getRevision();
final long lastRevision = revisions.get(revisionCount - 1).getRevision();
if (revisionCount > 0 && firstRevision == 1) {
logger.info("Starting initial population of cache: " + revisionUpdate.getInstanceName());
try {
addDirectories(entryCache, repository, "/", lastRevision);
entryCache.setCachedRevision(lastRevision);
} catch (SVNException svnex) {
logger.error("Unable to populate cache", svnex);
}
logger.info("Cache population done");
} else {
// Initial population has already been performed - only apply changes for now.
if (lastRevision < entryCache.getCachedRevision()) {
throw new IllegalStateException("Revision [" + lastRevision + "] is older than last cached revision ["
+ entryCache.getCachedRevision() + "]. Has the repository URL changed? Delete all cache files to "
+ "trigger a complete cache rebuild");
}
// One logEntry is one commit (or revision)
for (final SVNLogEntry logEntry : revisions) {
try {
long revision = logEntry.getRevision();
logger.debug("Applying changes in revision [" + revision + "] to cache");
final Map<String, SVNLogEntryPath> map = logEntry.getChangedPaths();
final List<String> latestPathsList = new ArrayList<String>(map.keySet());
// Sort the entries to apply changes in right order
Collections.sort(latestPathsList);
for (final String entryPath : latestPathsList) {
final SVNLogEntryPath logEntryPath = map.get(entryPath);
switch (LogEntryActionType.parse(logEntryPath.getType())) {
case ADDED:
logger.debug("Adding entry to cache: " + logEntryPath.getPath());
doEntryCacheAdd(entryCache, repository, logEntryPath, revision);
break;
case DELETED:
logger.debug("Removing deleted entry from cache: " + logEntryPath.getPath());
doEntryCacheDelete(entryCache, repository, logEntryPath, revision);
break;
case REPLACED:
logger.debug("Replacing entry in cache: " + logEntryPath.getPath());
doEntryCacheReplace(entryCache, repository, logEntryPath, revision);
break;
case MODIFIED:
logger.debug("Updating modified entry in cache: " + logEntryPath.getPath());
doEntryCacheModify(entryCache, repository, logEntryPath, revision);
break;
default :
throw new RuntimeException("Unknown log entry type: " + logEntryPath.getType() + " in rev " + logEntry.getRevision());
}
}
} catch (SVNException svnex) {
logger.error("Unable to update entryCache", svnex);
}
}
entryCache.setCachedRevision(lastRevision);
logger.debug("Update completed");
}
}
|
diff --git a/core/src/visad/trunk/data/text/TextAdapter.java b/core/src/visad/trunk/data/text/TextAdapter.java
index dbc4f5269..ae9ec959a 100644
--- a/core/src/visad/trunk/data/text/TextAdapter.java
+++ b/core/src/visad/trunk/data/text/TextAdapter.java
@@ -1,1395 +1,1395 @@
//
// TextAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2007 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.data.text;
import java.io.IOException;
import java.io.*;
import java.util.*;
import visad.Set;
import java.net.URL;
import visad.*;
import visad.VisADException;
import visad.data.in.ArithProg;
/** this is an VisAD file adapter for comma-, tab- and blank-separated
* ASCII text file data. It will attempt to create a FlatField from
* the data and descriptions given in the file and/or the constructor.
*
* The text files contained delimited data. The delimiter is
* determined as follows: if the file has a well-known extension
* (.csv, .tsv, .bsv) then the delimiter is implied by the extension.
* In all other cases, the delimiter for the data (and for the
* "column labels") is determined by reading the first line and
* looking, in order, for a tab, comma, or blank. Which ever one
* is found first is taken as the delimiter.
*
* Two extra pieces of information are needed: the VisAD "MathType"
* which is specified as a string (e.g., (x,y)->(temperature))
* and may either be the first line of the file or passed in through
* one of the constructors.
*
* The second item are the "column labels" which contain the names
* of each field in the data. The names of all range components
* specified in the "MathType" must appear. The names of domain
* components are optional. The values in this string are separated
* by the delimiter, as defined above.
*
* See visad.data.text.README.text for more details.
*
* @author Tom Whittaker
*
*/
public class TextAdapter {
private static final String ATTR_COLSPAN = "colspan";
private static final String ATTR_VALUE = "value";
private static final String ATTR_OFFSET = "off";
private static final String ATTR_ERROR = "err";
private static final String ATTR_SCALE = "sca";
private static final String ATTR_POSITION ="pos";
private static final String ATTR_FORMAT = "fmt";
private static final String ATTR_UNIT= "unit";
private static final String ATTR_MISSING = "mis";
private static final String ATTR_INTERVAL = "int";
private static final String COMMA = ",";
private static final String SEMICOLON = ";";
private static final String TAB = "\t";
private static final String BLANK = " ";
private FlatField ff = null;
private Field field = null;
private boolean debug = false;
private String DELIM;
private boolean DOQUOTE = true;
private boolean GOTTIME = false;
HeaderInfo []infos;
double[] rangeErrorEstimates;
Unit[] rangeUnits;
Set[] rangeSets;
double[] domainErrorEstimates;
Unit[] domainUnits;
int[][] hdrColumns;
int[][] values_to_index;
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename) throws IOException, VisADException {
this(filename, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename, String map, String params)
throws IOException, VisADException {
InputStream is = new FileInputStream(filename);
DELIM = getDelimiter(filename);
readit(is, map, params);
}
/** Create a VisAD FlatField from a remote Text (comma-, tab- or
* blank-separated values) ASCII file
*
* @param url File URL.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url) throws IOException, VisADException {
this(url, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param url File URL.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url, String map, String params)
throws IOException, VisADException {
DELIM = getDelimiter(url.getFile());
InputStream is = url.openStream();
readit(is, map, params);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params)
throws IOException, VisADException {
DELIM = delimiter;
readit(inputStream, map, params);
}
public static String getDelimiter(String filename) {
if(filename == null) return null;
filename = filename.trim().toLowerCase();
if (filename.endsWith(".csv")) return COMMA;
if (filename.endsWith(".tsv")) return TAB;
if (filename.endsWith(".bsv")) return BLANK;
return null;
}
/**
* Is the given text line a comment
*
* @return is it a comment line
*/
public static boolean isComment(String line) {
return (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("%") ||
line.length() < 1);
}
public static String readLine(BufferedReader bis)
throws IOException {
while (true) {
String line = bis.readLine();
if (line == null) return null;
if (!isText(line)) return null;
if (isComment(line)) continue;
return line;
}
}
void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
StringTokenizer sthdr = new StringTokenizer(hdr,hdrDelim);
int nhdr = sthdr.countTokens();
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr.nextToken().trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
StringTokenizer stcl = new StringTokenizer(cl," ");
int ncl = stcl.countTokens();
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
while (stcl.hasMoreTokens()) {
String s = stcl.nextToken().trim();
StringTokenizer sts = new StringTokenizer(s,"=");
if (sts.countTokens() != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts.nextToken().trim();
String val = sts.nextToken();
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2 = stcl.nextToken("\"");
stcl.nextToken(" ");
String v3 = val.substring(1)+v2;
val = v3;
} catch (NoSuchElementException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
StringTokenizer stp = new StringTokenizer(val,":");
if (stp.countTokens() != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp.nextToken().trim());
hdrColumns[1][i] = Integer.parseInt(stp.nextToken().trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
StringTokenizer sct = new StringTokenizer(ss,":");
String first = sct.nextToken().trim();
String second = sct.nextToken().trim();
String third = "1";
if (sct.hasMoreTokens()) third = sct.nextToken().trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
StringTokenizer st = new StringTokenizer(s,dataDelim);
int n = st.countTokens();
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st.nextToken().trim();
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
for (int i=0; i<n; i++) {
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else {
sa = st.nextToken().trim();
int moreColumns = infos[i].colspan-1;
- if(moreColumns>0) {
+ while (moreColumns>0) {
sa = sa + " " + st.nextToken().trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
try {
String sa2 = st.nextToken("\"");
sThisText = sa.substring(1)+sa2;
} catch (NoSuchElementException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
// munges a pseudo MathType string into something legal
private String makeMT(String s) {
int k = s.indexOf("->");
if (k < 0) {
// System.out.println("TextAdapter: invalid MathType form; -> required");
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i=0; i<s.length(); i++) {
String r = s.substring(i,i+1);
if (!r.equals(" ") && !r.equals("\t") && !r.equals("\n")) {
sb.append(r);
}
}
String t = sb.toString();
k = t.indexOf("->");
if (t.charAt(k-1) != ')' ) {
if (t.charAt(k+2) != '(' ) {
String t2 = "("+t.substring(0,k) + ")->("+t.substring(k+2)+")";
t = t2;
} else {
String t2 = "("+t.substring(0,k) + ")"+t.substring(k);
t = t2;
}
} else if (t.charAt(k+2) != '(' ) {
String t2 = t.substring(0,k+2)+"("+t.substring(k+2)+")";
t = t2;
}
if (!t.startsWith("((") ) {
String t2= "("+t+")";
t = t2;
}
return t;
}
private static final boolean isText(String s)
{
final int len = (s == null ? -1 : s.length());
if (len <= 0) {
// well, it's not really *binary*, so pretend it's text
return true;
}
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
if (Character.isISOControl(ch) && !Character.isWhitespace(ch)) {
// we might want to special-case formfeed/linefeed/newline here...
return false;
}
}
return true;
}
/**
* generate a DateTime from a string
* @param string - Formatted date/time string
*
* @return - the equivalent VisAD DateTime for the string
*
* (lifted from au.gov.bom.aifs.common.ada.VisADXMLAdapter.java)
*/
private static visad.DateTime makeDateTimeFromString(String string,
String format)
throws java.text.ParseException
{
visad.DateTime dt = null;
// try to parse the string using the supplied DateTime format
try {
dt = visad.DateTime.createDateTime(string, format);
} catch (VisADException e) {}
if (dt==null) {
throw new java.text.ParseException("Couldn't parse visad.DateTime from \""
+string+"\"", -1);
} else {
return dt;
}
}
double getVal(String s, int k) {
int i = values_to_index[2][k];
if (i < 0 || s == null || s.length()<1 || s.equals(infos[i].missingString)) {
return Double.NaN;
}
// try parsing as a double first
if (infos[i].formatString == null) {
// no format provided : parse as a double
try {
double v = Double.parseDouble(s);
if (v == infos[i].missingValue) {
return Double.NaN;
}
v = v * infos[i].scale + infos[i].offset;
return v;
} catch (java.lang.NumberFormatException ne) {
System.out.println("Invalid number format for "+s);
}
} else {
// a format was specified: only support DateTime format
// so try to parse as a DateTime
try{
visad.DateTime dt = makeDateTimeFromString(s, infos[i].formatString);
return dt.getReal().getValue();
} catch (java.text.ParseException pe) {
System.out.println("Invalid number/time format for "+s);
}
}
return Double.NaN;
}
// get the samples from the ArrayList.
float[][] getDomSamples(int comp, int numDomValues, ArrayList domValues) {
float [][] a = new float[1][numDomValues];
for (int i=0; i<numDomValues; i++) {
double[] d = (double[])(domValues.get(i));
a[0][i] = (float)d[comp];
}
return a;
}
/** get the data
* @return a Field of the data read from the file
*
*/
public Field getData() {
return field;
}
/**
* Returns an appropriate 1D domain.
*
* @param type the math-type of the domain
* @param numSamples the number of samples in the domain
* @param domValues domain values are extracted from this array list.
*
* @return a Linear1DSet if the domain samples form an arithmetic
* progression, a Gridded1DDoubleSet if the domain samples are ordered
* but do not form an arithmetic progression, otherwise an Irregular1DSet.
*
* @throws VisADException there was a problem creating the domain set.
*/
private Set createAppropriate1DDomain(MathType type, int numSamples,
ArrayList domValues)
throws VisADException {
if (0 == numSamples) {
// Can't create a domain set with zero samples.
return null;
}
// Extract the first element from each element of the array list.
double[][] values = new double[1][numSamples];
for (int i=0; i<numSamples; ++i) {
double[] d = (double []) domValues.get(i);
values[0][i] = d[0];
}
// This implementation for testing that the values are ordered
// is based on visad.Gridded1DDoubleSet.java
boolean ordered = true;
boolean ascending = values[0][numSamples -1] > values[0][0];
if (ascending) {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] < values[0][i - 1]) {
ordered = false;
break;
}
}
} else {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] > values[0][i - 1]) {
ordered = false;
break;
}
}
}
Set set = null;
if (ordered) {
ArithProg arithProg = new ArithProg();
if (arithProg.accumulate(values[0])) {
// The domain values form an arithmetic progression (ordered and
// equally spaced) so use a linear set.
set = new Linear1DSet(type, values[0][0], values[0][numSamples - 1],
numSamples);
} else {
// The samples are ordered, so use a gridded set.
set = new Gridded1DDoubleSet(type, values, numSamples);
}
} else {
set = new Irregular1DSet(type, Set.doubleToFloat(values));
}
return set;
}
private static class HeaderInfo {
String name;
Unit unit;
double missingValue = Double.NaN;
String missingString;
String formatString;
int isInterval = 0;
double errorEstimate=0;
double scale=1.0;
double offset=0.0;
String fixedValue;
int colspan = 1;
public boolean isParam(String param) {
return name.equals(param) || name.equals(param+"(Text)");
}
public String toString() {
return name;
}
}
// uncomment to test
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Must supply a filename");
System.exit(1);
}
RealType.getRealType("foobar");
TextAdapter ta = new TextAdapter(args[0]);
System.out.println(ta.getData().getType());
new visad.jmet.DumpType().dumpMathType(ta.getData().getType(),System.out);
new visad.jmet.DumpType().dumpDataType(ta.getData(),System.out);
System.out.println("#### Data = "+ta.getData());
System.out.println("EOF... ");
}
}
| true | true | void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
StringTokenizer sthdr = new StringTokenizer(hdr,hdrDelim);
int nhdr = sthdr.countTokens();
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr.nextToken().trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
StringTokenizer stcl = new StringTokenizer(cl," ");
int ncl = stcl.countTokens();
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
while (stcl.hasMoreTokens()) {
String s = stcl.nextToken().trim();
StringTokenizer sts = new StringTokenizer(s,"=");
if (sts.countTokens() != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts.nextToken().trim();
String val = sts.nextToken();
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2 = stcl.nextToken("\"");
stcl.nextToken(" ");
String v3 = val.substring(1)+v2;
val = v3;
} catch (NoSuchElementException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
StringTokenizer stp = new StringTokenizer(val,":");
if (stp.countTokens() != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp.nextToken().trim());
hdrColumns[1][i] = Integer.parseInt(stp.nextToken().trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
StringTokenizer sct = new StringTokenizer(ss,":");
String first = sct.nextToken().trim();
String second = sct.nextToken().trim();
String third = "1";
if (sct.hasMoreTokens()) third = sct.nextToken().trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
StringTokenizer st = new StringTokenizer(s,dataDelim);
int n = st.countTokens();
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st.nextToken().trim();
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
for (int i=0; i<n; i++) {
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else {
sa = st.nextToken().trim();
int moreColumns = infos[i].colspan-1;
if(moreColumns>0) {
sa = sa + " " + st.nextToken().trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
try {
String sa2 = st.nextToken("\"");
sThisText = sa.substring(1)+sa2;
} catch (NoSuchElementException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
| void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
StringTokenizer sthdr = new StringTokenizer(hdr,hdrDelim);
int nhdr = sthdr.countTokens();
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr.nextToken().trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
StringTokenizer stcl = new StringTokenizer(cl," ");
int ncl = stcl.countTokens();
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
while (stcl.hasMoreTokens()) {
String s = stcl.nextToken().trim();
StringTokenizer sts = new StringTokenizer(s,"=");
if (sts.countTokens() != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts.nextToken().trim();
String val = sts.nextToken();
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2 = stcl.nextToken("\"");
stcl.nextToken(" ");
String v3 = val.substring(1)+v2;
val = v3;
} catch (NoSuchElementException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
StringTokenizer stp = new StringTokenizer(val,":");
if (stp.countTokens() != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp.nextToken().trim());
hdrColumns[1][i] = Integer.parseInt(stp.nextToken().trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
StringTokenizer sct = new StringTokenizer(ss,":");
String first = sct.nextToken().trim();
String second = sct.nextToken().trim();
String third = "1";
if (sct.hasMoreTokens()) third = sct.nextToken().trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
StringTokenizer st = new StringTokenizer(s,dataDelim);
int n = st.countTokens();
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st.nextToken().trim();
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
for (int i=0; i<n; i++) {
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else {
sa = st.nextToken().trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st.nextToken().trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
try {
String sa2 = st.nextToken("\"");
sThisText = sa.substring(1)+sa2;
} catch (NoSuchElementException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
|
diff --git a/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java b/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java
index 826eeada..85f32164 100644
--- a/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java
+++ b/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java
@@ -1,72 +1,72 @@
/***************************************
* Copyright (c) 2008
* Bjoern Wagner
*
* 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 org.b3mn.poem.handler;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.batik.transcoder.TranscoderException;
import org.b3mn.poem.Identity;
import org.b3mn.poem.Representation;
import org.b3mn.poem.util.ExportHandler;
@ExportHandler(uri="/svg", formatName="SVG", iconUrl="/backend/images/silk/page_white_vector.png")
public class ImageRenderer extends HandlerBase {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) {
setResponseHeaders(res);
try {
Representation representation = object.read();
String SvgRepresentation = representation.getSvg();
if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){
SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " +
"xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " +
"height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " +
"svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" +
"Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" +
- "Please load the process with the Oryx Editor and push the Save button.</tspan></text></svg>";
+ "Please load the process in Oryx Editor and press the Save button.</tspan></text></svg>";
}
transcode(SvgRepresentation, res.getOutputStream(), representation);
} catch (TranscoderException e) {
e.printStackTrace();
} catch (Exception ie) {
ie.printStackTrace();
}
}
protected void setResponseHeaders(HttpServletResponse res) {
res.setContentType("image/svg+xml");
res.setStatus(200);
}
protected void transcode(String in_s, OutputStream out, Representation representation) throws TranscoderException, IOException {
out.write(in_s.getBytes("UTF-8"));
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) {
setResponseHeaders(res);
try {
Representation representation = object.read();
String SvgRepresentation = representation.getSvg();
if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){
SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " +
"xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " +
"height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " +
"svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" +
"Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" +
"Please load the process with the Oryx Editor and push the Save button.</tspan></text></svg>";
}
transcode(SvgRepresentation, res.getOutputStream(), representation);
} catch (TranscoderException e) {
e.printStackTrace();
} catch (Exception ie) {
ie.printStackTrace();
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) {
setResponseHeaders(res);
try {
Representation representation = object.read();
String SvgRepresentation = representation.getSvg();
if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){
SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " +
"xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " +
"height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " +
"svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" +
"Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" +
"Please load the process in Oryx Editor and press the Save button.</tspan></text></svg>";
}
transcode(SvgRepresentation, res.getOutputStream(), representation);
} catch (TranscoderException e) {
e.printStackTrace();
} catch (Exception ie) {
ie.printStackTrace();
}
}
|
diff --git a/plugins/net.refractions.udig.catalog.wms/src/net/refractions/udig/catalog/wmsc/server/WMSCComplexTypes.java b/plugins/net.refractions.udig.catalog.wms/src/net/refractions/udig/catalog/wmsc/server/WMSCComplexTypes.java
index 0a450628b..8a96d1ff3 100644
--- a/plugins/net.refractions.udig.catalog.wms/src/net/refractions/udig/catalog/wmsc/server/WMSCComplexTypes.java
+++ b/plugins/net.refractions.udig.catalog.wms/src/net/refractions/udig/catalog/wmsc/server/WMSCComplexTypes.java
@@ -1,822 +1,827 @@
/* uDig - User Friendly Desktop Internet GIS client
* http://udig.refractions.net
* (C) 2008, Refractions Research Inc.
*
* 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;
* version 2.1 of the License.
*
* 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.
*/
package net.refractions.udig.catalog.wmsc.server;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.naming.OperationNotSupportedException;
import net.refractions.udig.catalog.internal.wms.WmsPlugin;
import net.refractions.udig.catalog.wmsc.server.WMSCSchema.WMSCAttribute;
import net.refractions.udig.catalog.wmsc.server.WMSCSchema.WMSCComplexType;
import net.refractions.udig.catalog.wmsc.server.WMSCSchema.WMSCElement;
import org.geotools.data.ows.CRSEnvelope;
import org.geotools.data.ows.Service;
import org.geotools.xml.PrintHandler;
import org.geotools.xml.schema.Attribute;
import org.geotools.xml.schema.Element;
import org.geotools.xml.schema.ElementGrouping;
import org.geotools.xml.schema.ElementValue;
import org.geotools.xml.schema.Sequence;
import org.geotools.xml.schema.impl.SequenceGT;
import org.geotools.xml.xsi.XSISimpleTypes;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* WMS-C getCapabilities xml complex types (part of the capabilities document).
*
* @author Emily Gouge (Refractions Research, Inc.)
* @since 1.1.0
*/
public interface WMSCComplexTypes {
public static class _BoundingBoxType extends WMSCComplexType {
private static final WMSCComplexType instance = new _BoundingBoxType();
private static Attribute[] attrs = new Attribute[]{
new WMSCAttribute(null, "CRS", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.String.getInstance(), Attribute.OPTIONAL, null, null, false),
new WMSCAttribute(null, "SRS", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.String.getInstance(), Attribute.OPTIONAL, null, null, false),
new WMSCAttribute(null, "minx", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.Double.getInstance(), Attribute.REQUIRED, null, null, false),
new WMSCAttribute(null, "miny", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.Double.getInstance(), Attribute.REQUIRED, null, null, false),
new WMSCAttribute(null, "maxx", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.Double.getInstance(), Attribute.REQUIRED, null, null, false),
new WMSCAttribute(null, "maxy", WMSCSchema.NAMESPACE, //$NON-NLS-1$
XSISimpleTypes.Double.getInstance(), Attribute.REQUIRED, null, null, false),
new WMSCAttribute("resx", XSISimpleTypes.Double.getInstance()), //$NON-NLS-1$
new WMSCAttribute("resy", XSISimpleTypes.Double.getInstance())}; //$NON-NLS-1$
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return attrs;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return null;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return null;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue( Element element, ElementValue[] value, Attributes attrs, Map hints )
throws SAXException, OperationNotSupportedException {
CRSEnvelope bbox = new CRSEnvelope();
String crs = attrs.getValue("CRS"); //$NON-NLS-1$
if (crs == null || crs.length() == 0) {
crs = attrs.getValue("crs"); //$NON-NLS-1$
}
if (crs == null || crs.length() == 0) {
crs = attrs.getValue("SRS"); //$NON-NLS-1$
}
if (crs == null || crs.length() == 0) {
crs = attrs.getValue("srs"); //$NON-NLS-1$
}
if (crs == null || crs.length() == 0) {
throw new SAXException("Bounding Box element contains no CRS/SRS attribute"); //$NON-NLS-1$
}
bbox.setEPSGCode(crs.toUpperCase());
bbox.setMinX(Double.parseDouble(attrs.getValue("minx"))); //$NON-NLS-1$
bbox.setMaxX(Double.parseDouble(attrs.getValue("maxx"))); //$NON-NLS-1$
bbox.setMinY(Double.parseDouble(attrs.getValue("miny"))); //$NON-NLS-1$
bbox.setMaxY(Double.parseDouble(attrs.getValue("maxy"))); //$NON-NLS-1$
return bbox;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "BoundingBox"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class< ? > getInstanceType() {
return CRSEnvelope.class;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode( Element element, Object value, Map hints ) {
return false;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode( Element element, Object value, PrintHandler output, Map hints )
throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
public static class _TileSetType extends WMSCComplexType {
private static final WMSCComplexType instance = new _TileSetType();
private static Element[] elems = new Element[]{
new WMSCElement("SRS", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
new WMSCElement("BoundingBox", _BoundingBoxType.getInstance()), //$NON-NLS-1$
new WMSCElement("Resolutions", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
new WMSCElement("Width", XSISimpleTypes.Integer.getInstance()), //$NON-NLS-1$
new WMSCElement("Height", XSISimpleTypes.Integer.getInstance()), //$NON-NLS-1$
new WMSCElement("Format", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
new WMSCElement("Layers", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
new WMSCElement("Styles", XSISimpleTypes.String.getInstance()) //$NON-NLS-1$
};
private static Sequence seq = new SequenceGT(elems);
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return null;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return seq;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return elems;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue( Element element, ElementValue[] value, Attributes attrs, Map hints )
throws SAXException, OperationNotSupportedException {
TileSet tileset = new WMSTileSet();
for( int i = 0; i < value.length; i++ ) {
if (sameName(elems[0], value[i])) {
String srs = (String) value[i].getValue();
tileset.setCoorindateReferenceSystem(srs);
}
if (sameName(elems[1], value[i])) {
CRSEnvelope bbox = (CRSEnvelope) value[i].getValue();
tileset.setBoundingBox(bbox);
}
if (sameName(elems[2], value[i])) {
String resolutions = (String) value[i].getValue();
tileset.setResolutions(resolutions);
}
if (sameName(elems[3], value[i])) {
Integer width = (Integer) value[i].getValue();
tileset.setWidth(width);
}
if (sameName(elems[4], value[i])) {
Integer height = (Integer) value[i].getValue();
tileset.setHeight(height);
}
if (sameName(elems[5], value[i])) {
String format = (String) value[i].getValue();
tileset.setFormat(format);
}
if (sameName(elems[6], value[i])) {
String layers = (String) value[i].getValue();
tileset.setLayers(layers);
}
if (sameName(elems[7], value[i])) {
String styles = (String)value[i].getValue();
tileset.setStyles(styles);
}
}
if( tileset.getCoordinateReferenceSystem() == null ){
// we are unable to use this one; we do not support
//this projection
return null;
}
return tileset;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "WMSTileSet"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class< ? > getInstanceType() {
return WMSTileSet.class;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode( Element element, Object value, Map hints ) {
return false;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode( Element element, Object value, PrintHandler output, Map hints )
throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
public static class _VendorSpecificCapabilitiesType extends WMSCComplexType {
private static final WMSCComplexType instance = new _VendorSpecificCapabilitiesType();
private static Element[] elems = new Element[]{
new WMSCElement("TileSet", _TileSetType.getInstance()) //$NON-NLS-1$
};
private static Sequence seq = new SequenceGT(elems);
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return null;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return seq;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return elems;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue( Element element, ElementValue[] value, Attributes attrs, Map hints )
throws SAXException, OperationNotSupportedException {
VendorSpecificCapabilities capabilities = new VendorSpecificCapabilities();
for( int i = 0; i < value.length; i++ ) {
if (sameName(elems[0], value[i])) {
WMSTileSet tile = (WMSTileSet) value[i].getValue();
if( tile != null ){
capabilities.addTile(tile);
}
}
}
return capabilities;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "VendorSpecificCapabilities"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class< ? > getInstanceType() {
return VendorSpecificCapabilities.class;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode( Element element, Object value, Map hints ) {
return false;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode( Element element, Object value, PrintHandler output, Map hints )
throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
public static class _WMT_MS_CapabilitiesType extends WMSCComplexType {
private static final WMSCComplexType instance = new _WMT_MS_CapabilitiesType();
/*
* The vendor specific capabilities in this list should not be necessary once
* geowebcache returns a valid wms document. This is currently in there to support
* the geowebcache current getCapabilities document
*/
private static Element[] elems = new Element[] {
new WMSCElement("Service", _ServiceType.getInstance()), //$NON-NLS-1$
new WMSCElement("Capability", _CapabilityType.getInstance()), //$NON-NLS-1$
new WMSCElement("VendorSpecificCapabilities", _VendorSpecificCapabilitiesType.getInstance()) }; //$NON-NLS-1$
private static Sequence seq = new SequenceGT(elems);
private static Attribute[] attrs = new Attribute[]{
new WMSCAttribute(
null,
"version", WMSCSchema.NAMESPACE, XSISimpleTypes.String.getInstance(), Attribute.REQUIRED, null, null, false), //$NON-NLS-1$
new WMSCAttribute("updateSequence", XSISimpleTypes.String.getInstance())}; //$NON-NLS-1$
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return attrs;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return seq;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return elems;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue( Element element, ElementValue[] value, Attributes attrs, Map hints )
throws SAXException, OperationNotSupportedException {
WMSCCapabilities capabilities = new WMSCCapabilities();
for( int i = 0; i < value.length; i++ ) {
if (sameName(elems[0], value[i])) {
Service x = ((Service)value[i].getValue());
capabilities.setService(x);
}
if (sameName(elems[1], value[i])) {
Capability c = ((Capability)value[i].getValue());
capabilities.setCapabilitiy(c);
}
if (sameName(elems[2], value[i])) {
//vendor specific capabilities for 1.0alpha version of
//geowebcache; once geowebcache fixed up this should not be necessary as
//this should be inside a capabilities
Capability c= new Capability();
VendorSpecificCapabilities cs = ((VendorSpecificCapabilities)value[i].getValue());
c.setVendorCapabilities(cs);
capabilities.setCapabilitiy(c);
}
}
capabilities.setVersion(attrs.getValue("", "version")); //$NON-NLS-1$ //$NON-NLS-2$
capabilities.setUpdateSequence(attrs.getValue("", "updateSequence")); //$NON-NLS-1$//$NON-NLS-2$
return capabilities;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "WMT_MS_Capabilities"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class< ? > getInstanceType() {
return WMSCCapabilities.class;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode( Element element, Object value, Map hints ) {
return false;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode( Element element, Object value, PrintHandler output, Map hints )
throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
public static class _CapabilityType extends WMSCComplexType {
private static final WMSCComplexType instance = new _CapabilityType();
private static Element[] elems = new Element[]{new WMSCElement(
"VendorSpecificCapabilities", _VendorSpecificCapabilitiesType.getInstance()) //$NON-NLS-1$
};
private static Sequence seq = new SequenceGT(elems);
private static Attribute[] attrs = new Attribute[]{};
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return attrs;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return seq;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return elems;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue( Element element, ElementValue[] value, Attributes attrs, Map hints )
throws SAXException, OperationNotSupportedException {
Capability capabilities = new Capability();
for( int i = 0; i < value.length; i++ ) {
if (sameName(elems[0], value[i])) {
VendorSpecificCapabilities vc = ((VendorSpecificCapabilities) value[i]
.getValue());
capabilities.setVendorCapabilities(vc);
}
}
return capabilities;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "Capability"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class< ? > getInstanceType() {
return Capability.class;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode( Element element, Object value, Map hints ) {
return false;
}
/*
* (non-Javadoc)
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode( Element element, Object value, PrintHandler output, Map hints )
throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
/**
* Represents a service complex type from wmsc. Currently this only parses out
* the Name, Title and OnlineResrouce attributes.
*
* @author Emily Gouge (Refractions Research, Inc).
* @since 1.1.0
*/
public static class _ServiceType extends WMSCComplexType {
private static final WMSCComplexType instance = new _ServiceType();
private static Element[] elems = new Element[] {
new WMSCElement("Name", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
new WMSCElement("Title", XSISimpleTypes.String.getInstance()), //$NON-NLS-1$
// new WMSCElement("Abstract", XSISimpleTypes.String.getInstance(),0, 1),
// new WMSCElement("KeywordList", XSISimpleTypes.String.getInstance(),0, 1),
new WMSCElement("OnlineResource", XSISimpleTypes.String.getInstance()) //$NON-NLS-1$
// new WMSCElement("ContactInformation", XSISimpleTypes.String.getInstance(), 0, 1),
// new WMSCElement("Fees", XSISimpleTypes.String.getInstance(), 0,
// 1),
// new WMSCElement("AccessConstraints", XSISimpleTypes.String
// .getInstance(), 0, 1),
// new WMSCElement("LayerLimit", XSISimpleTypes.PositiveInteger
// .getInstance(), 0, 1),
// new WMSCElement("MaxWidth", XSISimpleTypes.PositiveInteger
// .getInstance(), 0, 1),
// new WMSCElement("MaxHeight", XSISimpleTypes.PositiveInteger
// .getInstance(), 0, 1),
// new WMSCElement("Keywords", XSISimpleTypes.String.getInstance(), 0, 1) };
};
private static Sequence seq = new SequenceGT(elems);
// private static Sequence seq = new SequenceGT(
// new ElementGrouping[] {
// elems[0],
// elems[1],
// elems[2],
// new ChoiceGT(null, 0, 1, new Element[] { elems[3],
// elems[11] }), elems[4], elems[5], elems[6],
// elems[7], elems[8], elems[9], elems[10] });
public static WMSCComplexType getInstance() {
return instance;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.ComplexType#getAttributes()
*/
public Attribute[] getAttributes() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.ComplexType#getChild()
*/
public ElementGrouping getChild() {
return seq;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.ComplexType#getChildElements()
*/
public Element[] getChildElements() {
return elems;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element,
* org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes,
* java.util.Map)
*/
@SuppressWarnings("unchecked")
public Object getValue(Element element, ElementValue[] value,
Attributes attrs, Map hints) throws SAXException,
OperationNotSupportedException {
Service service = new Service();
for (int i = 0; i < value.length; i++) {
if (sameName(elems[0], value[i])) {
service.setName((String) value[i].getValue());
}
if (sameName(elems[1], value[i])) {
service.setTitle((String) value[i].getValue());
}
// if (sameName(elems[2], value[i])) {
// service.set_abstract((String) value[i].getValue());
// }
//
// if (sameName(elems[3], value[i])
// || sameName(elems[11], value[i])) {
// service.setKeywordList((String[]) value[i].getValue());
// }
if (sameName(elems[2], value[i])) {
+ String spec = (String) value[i].getValue();
+ if( spec == null || spec.length() == 0){
+ // Service not avaialble
+ WmsPlugin.log("WMS Capabilies document does contain VendorSpecificCapabilities describing WMS-C tileset",null);
+ }
try {
- service.setOnlineResource(new URL((String)value[i].getValue()));
+ service.setOnlineResource(new URL( spec ));
} catch (MalformedURLException e) {
- WmsPlugin.log("Cannot convert string to url: " + (String)value[i].getValue(), e); //$NON-NLS-1$
+ WmsPlugin.log("Cannot convert string to url: " +spec, e); //$NON-NLS-1$
}
}
// if (sameName(elems[5], value[i])) {
// ResponsiblePartyImpl contactInfo = (ResponsiblePartyImpl) value[i].getValue();
// service.setContactInformation(contactInfo);
// }
// if (sameName(elems[6], value[i])) {
// //TODO fees not implemented, ignoring
// }
// if (sameName(elems[7], value[i])) {
// //TODO access constraints not implemented, ignoring
// }
// if (sameName(elems[8], value[i])) {
// service.setLayerLimit(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[9], value[i])) {
// service.setMaxWidth(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[10], value[i])) {
// service.setMaxHeight(((Integer) value[i].getValue())
// .intValue());
// }
}
return service;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.Type#getName()
*/
public String getName() {
return "Service"; //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.Type#getInstanceType()
*/
public Class<?> getInstanceType() {
return Service.class;
// return null;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.Type#canEncode(org.geotools.xml.schema.Element,
* java.lang.Object, java.util.Map)
*/
@SuppressWarnings("unchecked")
public boolean canEncode(Element element, Object value, Map hints) {
return false;
}
/*
* (non-Javadoc)
*
* @see org.geotools.xml.schema.Type#encode(org.geotools.xml.schema.Element,
* java.lang.Object, org.geotools.xml.PrintHandler, java.util.Map)
*/
@SuppressWarnings("unchecked")
public void encode(Element element, Object value, PrintHandler output,
Map hints) throws IOException, OperationNotSupportedException {
throw new OperationNotSupportedException();
}
}
}
| false | true | public Object getValue(Element element, ElementValue[] value,
Attributes attrs, Map hints) throws SAXException,
OperationNotSupportedException {
Service service = new Service();
for (int i = 0; i < value.length; i++) {
if (sameName(elems[0], value[i])) {
service.setName((String) value[i].getValue());
}
if (sameName(elems[1], value[i])) {
service.setTitle((String) value[i].getValue());
}
// if (sameName(elems[2], value[i])) {
// service.set_abstract((String) value[i].getValue());
// }
//
// if (sameName(elems[3], value[i])
// || sameName(elems[11], value[i])) {
// service.setKeywordList((String[]) value[i].getValue());
// }
if (sameName(elems[2], value[i])) {
try {
service.setOnlineResource(new URL((String)value[i].getValue()));
} catch (MalformedURLException e) {
WmsPlugin.log("Cannot convert string to url: " + (String)value[i].getValue(), e); //$NON-NLS-1$
}
}
// if (sameName(elems[5], value[i])) {
// ResponsiblePartyImpl contactInfo = (ResponsiblePartyImpl) value[i].getValue();
// service.setContactInformation(contactInfo);
// }
// if (sameName(elems[6], value[i])) {
// //TODO fees not implemented, ignoring
// }
// if (sameName(elems[7], value[i])) {
// //TODO access constraints not implemented, ignoring
// }
// if (sameName(elems[8], value[i])) {
// service.setLayerLimit(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[9], value[i])) {
// service.setMaxWidth(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[10], value[i])) {
// service.setMaxHeight(((Integer) value[i].getValue())
// .intValue());
// }
}
return service;
}
| public Object getValue(Element element, ElementValue[] value,
Attributes attrs, Map hints) throws SAXException,
OperationNotSupportedException {
Service service = new Service();
for (int i = 0; i < value.length; i++) {
if (sameName(elems[0], value[i])) {
service.setName((String) value[i].getValue());
}
if (sameName(elems[1], value[i])) {
service.setTitle((String) value[i].getValue());
}
// if (sameName(elems[2], value[i])) {
// service.set_abstract((String) value[i].getValue());
// }
//
// if (sameName(elems[3], value[i])
// || sameName(elems[11], value[i])) {
// service.setKeywordList((String[]) value[i].getValue());
// }
if (sameName(elems[2], value[i])) {
String spec = (String) value[i].getValue();
if( spec == null || spec.length() == 0){
// Service not avaialble
WmsPlugin.log("WMS Capabilies document does contain VendorSpecificCapabilities describing WMS-C tileset",null);
}
try {
service.setOnlineResource(new URL( spec ));
} catch (MalformedURLException e) {
WmsPlugin.log("Cannot convert string to url: " +spec, e); //$NON-NLS-1$
}
}
// if (sameName(elems[5], value[i])) {
// ResponsiblePartyImpl contactInfo = (ResponsiblePartyImpl) value[i].getValue();
// service.setContactInformation(contactInfo);
// }
// if (sameName(elems[6], value[i])) {
// //TODO fees not implemented, ignoring
// }
// if (sameName(elems[7], value[i])) {
// //TODO access constraints not implemented, ignoring
// }
// if (sameName(elems[8], value[i])) {
// service.setLayerLimit(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[9], value[i])) {
// service.setMaxWidth(((Integer) value[i].getValue())
// .intValue());
// }
//
// if (sameName(elems[10], value[i])) {
// service.setMaxHeight(((Integer) value[i].getValue())
// .intValue());
// }
}
return service;
}
|
diff --git a/protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/SearchHandler.java b/protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/SearchHandler.java
index e391f9d3d4..7b004f82e4 100644
--- a/protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/SearchHandler.java
+++ b/protocol-ldap/src/main/java/org/apache/directory/server/ldap/support/SearchHandler.java
@@ -1,443 +1,443 @@
/*
* 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.directory.server.ldap.support;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ReferralException;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import org.apache.directory.server.core.configuration.StartupConfiguration;
import org.apache.directory.server.core.jndi.ServerLdapContext;
import org.apache.directory.server.core.partition.PartitionNexus;
import org.apache.directory.server.ldap.SessionRegistry;
import org.apache.directory.shared.ldap.codec.util.LdapResultEnum;
import org.apache.directory.shared.ldap.exception.LdapException;
import org.apache.directory.shared.ldap.exception.OperationAbandonedException;
import org.apache.directory.shared.ldap.filter.PresenceNode;
import org.apache.directory.shared.ldap.message.AbandonListener;
import org.apache.directory.shared.ldap.message.LdapResult;
import org.apache.directory.shared.ldap.message.ManageDsaITControl;
import org.apache.directory.shared.ldap.message.PersistentSearchControl;
import org.apache.directory.shared.ldap.message.ReferralImpl;
import org.apache.directory.shared.ldap.message.Response;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
import org.apache.directory.shared.ldap.message.ScopeEnum;
import org.apache.directory.shared.ldap.message.SearchRequest;
import org.apache.directory.shared.ldap.message.SearchResponseDone;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.directory.shared.ldap.util.ArrayUtils;
import org.apache.directory.shared.ldap.util.ExceptionUtils;
import org.apache.mina.common.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A handler for processing search requests.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
public class SearchHandler implements LdapMessageHandler
{
private static final Logger log = LoggerFactory.getLogger( SearchHandler.class );
private static final String DEREFALIASES_KEY = "java.naming.ldap.derefAliases";
private StartupConfiguration cfg;
/** Speedup for logs */
private static final boolean IS_DEBUG = log.isDebugEnabled();
/**
* Builds the JNDI search controls for a SearchRequest.
*
* @param req the search request.
* @param ids the ids to return
* @return the SearchControls to use with the ApacheDS server side JNDI provider
*/
private SearchControls getSearchControls( SearchRequest req, String[] ids, boolean isAdmin )
{
// prepare all the search controls
SearchControls controls = new SearchControls();
// take the minimum of system limit with request specified value
if ( isAdmin )
{
controls.setCountLimit( req.getSizeLimit() );
// The setTimeLimit needs a number of milliseconds
// when the search control is expressed in seconds
int timeLimit = req.getTimeLimit();
// Just check that we are not exceeding the maximum for a long
if ( timeLimit > Integer.MAX_VALUE / 1000 )
{
timeLimit = 0;
}
// The maximum time we can wait is around 24 days ...
// Is it enough ? ;)
controls.setTimeLimit( timeLimit * 1000 );
}
else
{
controls.setCountLimit( Math.min( req.getSizeLimit(), cfg.getMaxSizeLimit() ) );
controls.setTimeLimit( ( int ) Math.min( req.getTimeLimit(), cfg.getMaxTimeLimit() ) );
}
controls.setSearchScope( req.getScope().getValue() );
controls.setReturningObjFlag( req.getTypesOnly() );
controls.setReturningAttributes( ids );
controls.setDerefLinkFlag( true );
return controls;
}
/**
* Determines if a search request is on the RootDSE of the server.
*
* @param req the request issued
* @return true if the search is on the RootDSE false otherwise
*/
private static boolean isRootDSESearch( SearchRequest req )
{
boolean isBaseIsRoot = req.getBase().isEmpty();
boolean isBaseScope = req.getScope() == ScopeEnum.BASEOBJECT;
boolean isRootDSEFilter = false;
if ( req.getFilter() instanceof PresenceNode )
{
isRootDSEFilter = ( ( PresenceNode ) req.getFilter() ).getAttribute().equalsIgnoreCase( "objectClass" );
}
return isBaseIsRoot && isBaseScope && isRootDSEFilter;
}
/**
* Main message handing method for search requests.
*/
public void messageReceived( IoSession session, Object request ) throws Exception
{
if ( IS_DEBUG )
{
log.debug( "Message received : " + request.toString() );
}
ServerLdapContext ctx;
SearchRequest req = ( SearchRequest ) request;
NamingEnumeration list = null;
String[] ids = null;
Collection retAttrs = new HashSet();
retAttrs.addAll( req.getAttributes() );
// add the search request to the registry of outstanding requests for this session
SessionRegistry.getSingleton().addOutstandingRequest( session, req );
// check the attributes to see if a referral's ref attribute is included
if ( retAttrs.size() > 0 && !retAttrs.contains( "ref" ) )
{
retAttrs.add( "ref" );
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
else if ( retAttrs.size() > 0 )
{
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
try
{
// ===============================================================
// Find session context
// ===============================================================
boolean isRootDSESearch = isRootDSESearch( req );
// bypass checks to disallow anonymous binds for search on RootDSE with base obj scope
if ( isRootDSESearch )
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContextOnRootDSEAccess( session, null );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
}
// all those search operations are subject to anonymous bind checks when anonymous binda are disallowed
else
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContext( session, null, true );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
Control[] controls = ( Control[] ) req.getControls().values().toArray( new Control[0] );
ctx.setRequestControls( controls );
}
ctx.addToEnvironment( DEREFALIASES_KEY, req.getDerefAliases().getName() );
if ( req.getControls().containsKey( ManageDsaITControl.CONTROL_OID ) )
{
ctx.addToEnvironment( Context.REFERRAL, "ignore" );
}
else
{
ctx.addToEnvironment( Context.REFERRAL, "throw-finding-base" );
}
// ===============================================================
// Handle annonymous binds
// ===============================================================
boolean allowAnonymousBinds = cfg.isAllowAnonymousAccess();
boolean isAnonymousUser = ( ( ServerLdapContext ) ctx ).getPrincipal().getName().trim().equals( "" );
if ( isAnonymousUser && !allowAnonymousBinds && !isRootDSESearch )
{
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( ResultCodeEnum.INSUFFICIENTACCESSRIGHTS );
String msg = "Bind failure: Anonymous binds have been disabled!";
result.setErrorMessage( msg );
session.write( req.getResultResponse() );
return;
}
// ===============================================================
// Set search limits differently based on user's identity
// ===============================================================
SearchControls controls = null;
if ( isAnonymousUser )
{
controls = getSearchControls( req, ids, false );
}
else if ( ( ( ServerLdapContext ) ctx ).getPrincipal().getName()
- .trim().equals( PartitionNexus.ADMIN_PRINCIPAL ) )
+ .trim().equals( PartitionNexus.ADMIN_PRINCIPAL_NORMALIZED ) )
{
controls = getSearchControls( req, ids, true );
}
else
{
controls = getSearchControls( req, ids, false );
}
// ===============================================================
// Handle psearch differently
// ===============================================================
PersistentSearchControl psearchControl = ( PersistentSearchControl ) req.getControls().get(
PersistentSearchControl.CONTROL_OID );
if ( psearchControl != null )
{
// there are no limits for psearch processing
controls.setCountLimit( 0 );
controls.setTimeLimit( 0 );
if ( !psearchControl.isChangesOnly() )
{
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(),
controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
Response resp = ( Response ) it.next();
if ( resp instanceof SearchResponseDone )
{
// ok if normal search beforehand failed somehow quickly abandon psearch
ResultCodeEnum rcode = ( ( SearchResponseDone ) resp ).getLdapResult().getResultCode();
if ( rcode.getValue() != LdapResultEnum.SUCCESS )
{
session.write( resp );
return;
}
// if search was fine then we returned all entries so now
// instead of returning the DONE response we break from the
// loop and user the notification listener to send back
// notificationss to the client in never ending search
else
break;
}
else
{
session.write( resp );
}
}
}
}
// now we process entries for ever as they change
PersistentSearchListener handler = new PersistentSearchListener( ctx, session, req );
StringBuffer buf = new StringBuffer();
req.getFilter().printToBuffer( buf );
ctx.addNamingListener( req.getBase(), buf.toString(), controls, handler );
return;
}
// ===============================================================
// Handle regular search requests from here down
// ===============================================================
/*
* Iterate through all search results building and sending back responses
* for each search result returned.
*/
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(), controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
else
{
list.close();
req.getResultResponse().getLdapResult().setResultCode( ResultCodeEnum.SUCCESS );
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
}
catch ( ReferralException e )
{
LdapResult result = req.getResultResponse().getLdapResult();
ReferralImpl refs = new ReferralImpl();
result.setReferral( refs );
result.setResultCode( ResultCodeEnum.REFERRAL );
result.setErrorMessage( "Encountered referral attempting to handle add request." );
/* coming up null causing a NPE */
// result.setMatchedDn( e.getResolvedName().toString() );
do
{
refs.addLdapUrl( ( String ) e.getReferralInfo() );
}
while ( e.skipReferral() );
session.write( req.getResultResponse() );
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
return;
}
catch ( NamingException e )
{
/*
* From RFC 2251 Section 4.11:
*
* In the event that a server receives an Abandon Request on a Search
* operation in the midst of transmitting responses to the Search, that
* server MUST cease transmitting entry responses to the abandoned
* request immediately, and MUST NOT send the SearchResultDone. Of
* course, the server MUST ensure that only properly encoded LDAPMessage
* PDUs are transmitted.
*
* SO DON'T SEND BACK ANYTHING!!!!!
*/
if ( e instanceof OperationAbandonedException )
{
return;
}
String msg = "failed on search operation: " + e.getMessage();
if ( log.isDebugEnabled() )
{
msg += ":\n" + req + ":\n" + ExceptionUtils.getStackTrace( e );
}
ResultCodeEnum code = null;
if ( e instanceof LdapException )
{
code = ( ( LdapException ) e ).getResultCode();
}
else
{
code = ResultCodeEnum.getBestEstimate( e, req.getType() );
}
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( code );
result.setErrorMessage( msg );
if ( ( e.getResolvedName() != null )
&& ( ( code == ResultCodeEnum.NOSUCHOBJECT ) || ( code == ResultCodeEnum.ALIASPROBLEM )
|| ( code == ResultCodeEnum.INVALIDDNSYNTAX ) || ( code == ResultCodeEnum.ALIASDEREFERENCINGPROBLEM ) ) )
{
result.setMatchedDn( (LdapDN)e.getResolvedName() );
}
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
}
finally
{
if ( list != null )
{
try
{
list.close();
}
catch ( NamingException e )
{
log.error( "failed on list.close()", e );
}
}
}
}
public void init( StartupConfiguration cfg )
{
this.cfg = cfg;
}
}
| true | true | public void messageReceived( IoSession session, Object request ) throws Exception
{
if ( IS_DEBUG )
{
log.debug( "Message received : " + request.toString() );
}
ServerLdapContext ctx;
SearchRequest req = ( SearchRequest ) request;
NamingEnumeration list = null;
String[] ids = null;
Collection retAttrs = new HashSet();
retAttrs.addAll( req.getAttributes() );
// add the search request to the registry of outstanding requests for this session
SessionRegistry.getSingleton().addOutstandingRequest( session, req );
// check the attributes to see if a referral's ref attribute is included
if ( retAttrs.size() > 0 && !retAttrs.contains( "ref" ) )
{
retAttrs.add( "ref" );
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
else if ( retAttrs.size() > 0 )
{
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
try
{
// ===============================================================
// Find session context
// ===============================================================
boolean isRootDSESearch = isRootDSESearch( req );
// bypass checks to disallow anonymous binds for search on RootDSE with base obj scope
if ( isRootDSESearch )
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContextOnRootDSEAccess( session, null );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
}
// all those search operations are subject to anonymous bind checks when anonymous binda are disallowed
else
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContext( session, null, true );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
Control[] controls = ( Control[] ) req.getControls().values().toArray( new Control[0] );
ctx.setRequestControls( controls );
}
ctx.addToEnvironment( DEREFALIASES_KEY, req.getDerefAliases().getName() );
if ( req.getControls().containsKey( ManageDsaITControl.CONTROL_OID ) )
{
ctx.addToEnvironment( Context.REFERRAL, "ignore" );
}
else
{
ctx.addToEnvironment( Context.REFERRAL, "throw-finding-base" );
}
// ===============================================================
// Handle annonymous binds
// ===============================================================
boolean allowAnonymousBinds = cfg.isAllowAnonymousAccess();
boolean isAnonymousUser = ( ( ServerLdapContext ) ctx ).getPrincipal().getName().trim().equals( "" );
if ( isAnonymousUser && !allowAnonymousBinds && !isRootDSESearch )
{
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( ResultCodeEnum.INSUFFICIENTACCESSRIGHTS );
String msg = "Bind failure: Anonymous binds have been disabled!";
result.setErrorMessage( msg );
session.write( req.getResultResponse() );
return;
}
// ===============================================================
// Set search limits differently based on user's identity
// ===============================================================
SearchControls controls = null;
if ( isAnonymousUser )
{
controls = getSearchControls( req, ids, false );
}
else if ( ( ( ServerLdapContext ) ctx ).getPrincipal().getName()
.trim().equals( PartitionNexus.ADMIN_PRINCIPAL ) )
{
controls = getSearchControls( req, ids, true );
}
else
{
controls = getSearchControls( req, ids, false );
}
// ===============================================================
// Handle psearch differently
// ===============================================================
PersistentSearchControl psearchControl = ( PersistentSearchControl ) req.getControls().get(
PersistentSearchControl.CONTROL_OID );
if ( psearchControl != null )
{
// there are no limits for psearch processing
controls.setCountLimit( 0 );
controls.setTimeLimit( 0 );
if ( !psearchControl.isChangesOnly() )
{
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(),
controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
Response resp = ( Response ) it.next();
if ( resp instanceof SearchResponseDone )
{
// ok if normal search beforehand failed somehow quickly abandon psearch
ResultCodeEnum rcode = ( ( SearchResponseDone ) resp ).getLdapResult().getResultCode();
if ( rcode.getValue() != LdapResultEnum.SUCCESS )
{
session.write( resp );
return;
}
// if search was fine then we returned all entries so now
// instead of returning the DONE response we break from the
// loop and user the notification listener to send back
// notificationss to the client in never ending search
else
break;
}
else
{
session.write( resp );
}
}
}
}
// now we process entries for ever as they change
PersistentSearchListener handler = new PersistentSearchListener( ctx, session, req );
StringBuffer buf = new StringBuffer();
req.getFilter().printToBuffer( buf );
ctx.addNamingListener( req.getBase(), buf.toString(), controls, handler );
return;
}
// ===============================================================
// Handle regular search requests from here down
// ===============================================================
/*
* Iterate through all search results building and sending back responses
* for each search result returned.
*/
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(), controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
else
{
list.close();
req.getResultResponse().getLdapResult().setResultCode( ResultCodeEnum.SUCCESS );
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
}
catch ( ReferralException e )
{
LdapResult result = req.getResultResponse().getLdapResult();
ReferralImpl refs = new ReferralImpl();
result.setReferral( refs );
result.setResultCode( ResultCodeEnum.REFERRAL );
result.setErrorMessage( "Encountered referral attempting to handle add request." );
/* coming up null causing a NPE */
// result.setMatchedDn( e.getResolvedName().toString() );
do
{
refs.addLdapUrl( ( String ) e.getReferralInfo() );
}
while ( e.skipReferral() );
session.write( req.getResultResponse() );
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
return;
}
catch ( NamingException e )
{
/*
* From RFC 2251 Section 4.11:
*
* In the event that a server receives an Abandon Request on a Search
* operation in the midst of transmitting responses to the Search, that
* server MUST cease transmitting entry responses to the abandoned
* request immediately, and MUST NOT send the SearchResultDone. Of
* course, the server MUST ensure that only properly encoded LDAPMessage
* PDUs are transmitted.
*
* SO DON'T SEND BACK ANYTHING!!!!!
*/
if ( e instanceof OperationAbandonedException )
{
return;
}
String msg = "failed on search operation: " + e.getMessage();
if ( log.isDebugEnabled() )
{
msg += ":\n" + req + ":\n" + ExceptionUtils.getStackTrace( e );
}
ResultCodeEnum code = null;
if ( e instanceof LdapException )
{
code = ( ( LdapException ) e ).getResultCode();
}
else
{
code = ResultCodeEnum.getBestEstimate( e, req.getType() );
}
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( code );
result.setErrorMessage( msg );
if ( ( e.getResolvedName() != null )
&& ( ( code == ResultCodeEnum.NOSUCHOBJECT ) || ( code == ResultCodeEnum.ALIASPROBLEM )
|| ( code == ResultCodeEnum.INVALIDDNSYNTAX ) || ( code == ResultCodeEnum.ALIASDEREFERENCINGPROBLEM ) ) )
{
result.setMatchedDn( (LdapDN)e.getResolvedName() );
}
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
}
finally
{
if ( list != null )
{
try
{
list.close();
}
catch ( NamingException e )
{
log.error( "failed on list.close()", e );
}
}
}
}
| public void messageReceived( IoSession session, Object request ) throws Exception
{
if ( IS_DEBUG )
{
log.debug( "Message received : " + request.toString() );
}
ServerLdapContext ctx;
SearchRequest req = ( SearchRequest ) request;
NamingEnumeration list = null;
String[] ids = null;
Collection retAttrs = new HashSet();
retAttrs.addAll( req.getAttributes() );
// add the search request to the registry of outstanding requests for this session
SessionRegistry.getSingleton().addOutstandingRequest( session, req );
// check the attributes to see if a referral's ref attribute is included
if ( retAttrs.size() > 0 && !retAttrs.contains( "ref" ) )
{
retAttrs.add( "ref" );
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
else if ( retAttrs.size() > 0 )
{
ids = ( String[] ) retAttrs.toArray( ArrayUtils.EMPTY_STRING_ARRAY );
}
try
{
// ===============================================================
// Find session context
// ===============================================================
boolean isRootDSESearch = isRootDSESearch( req );
// bypass checks to disallow anonymous binds for search on RootDSE with base obj scope
if ( isRootDSESearch )
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContextOnRootDSEAccess( session, null );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
}
// all those search operations are subject to anonymous bind checks when anonymous binda are disallowed
else
{
LdapContext unknown = SessionRegistry.getSingleton().getLdapContext( session, null, true );
if ( !( unknown instanceof ServerLdapContext ) )
{
ctx = ( ServerLdapContext ) unknown.lookup( "" );
}
else
{
ctx = ( ServerLdapContext ) unknown;
}
Control[] controls = ( Control[] ) req.getControls().values().toArray( new Control[0] );
ctx.setRequestControls( controls );
}
ctx.addToEnvironment( DEREFALIASES_KEY, req.getDerefAliases().getName() );
if ( req.getControls().containsKey( ManageDsaITControl.CONTROL_OID ) )
{
ctx.addToEnvironment( Context.REFERRAL, "ignore" );
}
else
{
ctx.addToEnvironment( Context.REFERRAL, "throw-finding-base" );
}
// ===============================================================
// Handle annonymous binds
// ===============================================================
boolean allowAnonymousBinds = cfg.isAllowAnonymousAccess();
boolean isAnonymousUser = ( ( ServerLdapContext ) ctx ).getPrincipal().getName().trim().equals( "" );
if ( isAnonymousUser && !allowAnonymousBinds && !isRootDSESearch )
{
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( ResultCodeEnum.INSUFFICIENTACCESSRIGHTS );
String msg = "Bind failure: Anonymous binds have been disabled!";
result.setErrorMessage( msg );
session.write( req.getResultResponse() );
return;
}
// ===============================================================
// Set search limits differently based on user's identity
// ===============================================================
SearchControls controls = null;
if ( isAnonymousUser )
{
controls = getSearchControls( req, ids, false );
}
else if ( ( ( ServerLdapContext ) ctx ).getPrincipal().getName()
.trim().equals( PartitionNexus.ADMIN_PRINCIPAL_NORMALIZED ) )
{
controls = getSearchControls( req, ids, true );
}
else
{
controls = getSearchControls( req, ids, false );
}
// ===============================================================
// Handle psearch differently
// ===============================================================
PersistentSearchControl psearchControl = ( PersistentSearchControl ) req.getControls().get(
PersistentSearchControl.CONTROL_OID );
if ( psearchControl != null )
{
// there are no limits for psearch processing
controls.setCountLimit( 0 );
controls.setTimeLimit( 0 );
if ( !psearchControl.isChangesOnly() )
{
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(),
controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
Response resp = ( Response ) it.next();
if ( resp instanceof SearchResponseDone )
{
// ok if normal search beforehand failed somehow quickly abandon psearch
ResultCodeEnum rcode = ( ( SearchResponseDone ) resp ).getLdapResult().getResultCode();
if ( rcode.getValue() != LdapResultEnum.SUCCESS )
{
session.write( resp );
return;
}
// if search was fine then we returned all entries so now
// instead of returning the DONE response we break from the
// loop and user the notification listener to send back
// notificationss to the client in never ending search
else
break;
}
else
{
session.write( resp );
}
}
}
}
// now we process entries for ever as they change
PersistentSearchListener handler = new PersistentSearchListener( ctx, session, req );
StringBuffer buf = new StringBuffer();
req.getFilter().printToBuffer( buf );
ctx.addNamingListener( req.getBase(), buf.toString(), controls, handler );
return;
}
// ===============================================================
// Handle regular search requests from here down
// ===============================================================
/*
* Iterate through all search results building and sending back responses
* for each search result returned.
*/
list = ( ( ServerLdapContext ) ctx ).search( req.getBase(), req.getFilter(), controls );
if ( list instanceof AbandonListener )
{
req.addAbandonListener( ( AbandonListener ) list );
}
if ( list.hasMore() )
{
Iterator it = new SearchResponseIterator( req, ctx, list, controls.getSearchScope(), session );
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
else
{
list.close();
req.getResultResponse().getLdapResult().setResultCode( ResultCodeEnum.SUCCESS );
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
return;
}
}
catch ( ReferralException e )
{
LdapResult result = req.getResultResponse().getLdapResult();
ReferralImpl refs = new ReferralImpl();
result.setReferral( refs );
result.setResultCode( ResultCodeEnum.REFERRAL );
result.setErrorMessage( "Encountered referral attempting to handle add request." );
/* coming up null causing a NPE */
// result.setMatchedDn( e.getResolvedName().toString() );
do
{
refs.addLdapUrl( ( String ) e.getReferralInfo() );
}
while ( e.skipReferral() );
session.write( req.getResultResponse() );
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
return;
}
catch ( NamingException e )
{
/*
* From RFC 2251 Section 4.11:
*
* In the event that a server receives an Abandon Request on a Search
* operation in the midst of transmitting responses to the Search, that
* server MUST cease transmitting entry responses to the abandoned
* request immediately, and MUST NOT send the SearchResultDone. Of
* course, the server MUST ensure that only properly encoded LDAPMessage
* PDUs are transmitted.
*
* SO DON'T SEND BACK ANYTHING!!!!!
*/
if ( e instanceof OperationAbandonedException )
{
return;
}
String msg = "failed on search operation: " + e.getMessage();
if ( log.isDebugEnabled() )
{
msg += ":\n" + req + ":\n" + ExceptionUtils.getStackTrace( e );
}
ResultCodeEnum code = null;
if ( e instanceof LdapException )
{
code = ( ( LdapException ) e ).getResultCode();
}
else
{
code = ResultCodeEnum.getBestEstimate( e, req.getType() );
}
LdapResult result = req.getResultResponse().getLdapResult();
result.setResultCode( code );
result.setErrorMessage( msg );
if ( ( e.getResolvedName() != null )
&& ( ( code == ResultCodeEnum.NOSUCHOBJECT ) || ( code == ResultCodeEnum.ALIASPROBLEM )
|| ( code == ResultCodeEnum.INVALIDDNSYNTAX ) || ( code == ResultCodeEnum.ALIASDEREFERENCINGPROBLEM ) ) )
{
result.setMatchedDn( (LdapDN)e.getResolvedName() );
}
Iterator it = Collections.singleton( req.getResultResponse() ).iterator();
while ( it.hasNext() )
{
session.write( it.next() );
}
SessionRegistry.getSingleton().removeOutstandingRequest( session, req.getMessageId() );
}
finally
{
if ( list != null )
{
try
{
list.close();
}
catch ( NamingException e )
{
log.error( "failed on list.close()", e );
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.