answer
stringlengths 17
10.2M
|
|---|
package org.jboss.aesh.extensions.ls;
import org.jboss.aesh.cl.Arguments;
import org.jboss.aesh.cl.CommandDefinition;
import org.jboss.aesh.cl.Option;
import org.jboss.aesh.console.Config;
import org.jboss.aesh.console.command.Command;
import org.jboss.aesh.console.command.CommandResult;
import org.jboss.aesh.console.command.invocation.CommandInvocation;
import org.jboss.aesh.extensions.grep.AeshPosixFilePermissions;
import org.jboss.aesh.parser.Parser;
import org.jboss.aesh.terminal.Color;
import org.jboss.aesh.terminal.Shell;
import org.jboss.aesh.terminal.TerminalColor;
import org.jboss.aesh.terminal.TerminalString;
import org.jboss.aesh.util.FileLister;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.nio.file.attribute.PosixFileAttributes;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
@CommandDefinition(name = "ls", description = "[OPTION]... [FILE]...\n" +
"List information about the FILEs (the current directory by default).\n" +
"Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n")
public class Ls implements Command {
@Option(shortName = 'H', name = "help", hasValue = false,
description = "display this help and exit")
private boolean help;
@Option(shortName = 'a', name = "all", hasValue = false,
description = "do not ignore entries starting with .")
private boolean all;
@Option(shortName = 'd', name = "directory", hasValue = false,
description = "list directory entries instead of contents, and do not dereference symbolic links")
private boolean directory;
@Option(shortName = 'l', name = "longlisting", hasValue = false,
description = "use a long listing format")
private boolean longListing;
@Option(shortName = 's', name = "size", hasValue = false,
description = "print the allocated size of each file, in blocks")
private boolean size;
@Arguments
private List<File> arguments;
private static final char SPACE = ' ';
private static final Class<? extends BasicFileAttributes> fileAttributes =
Config.isOSPOSIXCompatible() ? PosixFileAttributes.class : DosFileAttributes.class;
private static DateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd hh:mm");
public Ls() {
}
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws IOException {
//just display help and return
if(help) {
commandInvocation.getShell().out().println(commandInvocation.getHelpInfo("ls"));
return CommandResult.SUCCESS;
}
if(arguments == null) {
arguments = new ArrayList<>(1);
arguments.add(commandInvocation.getAeshContext().getCurrentWorkingDirectory());
}
for(File f : arguments) {
if(f.isDirectory())
displayDirectory(f, commandInvocation.getShell());
else if(f.isFile())
displayFile(f,commandInvocation.getShell());
else if(!f.exists()) {
commandInvocation.getShell().out().println("ls: cannot access "+
f.toString()+": No such file or directory");
}
}
return CommandResult.SUCCESS;
}
private void displayDirectory(File input, Shell shell) {
if(longListing) {
if(all) {
File[] files = input.listFiles();
Arrays.sort(files, new PosixFileNameComparator());
shell.out().println(
displayLongListing(files));
}
else {
File[] files = input.listFiles(new FileLister.FileAndDirectoryNoDotNamesFilter());
Arrays.sort(files, new PosixFileNameComparator());
shell.out().println(
displayLongListing(files));
}
}
else {
if(all)
shell.out().println(Parser.formatDisplayListTerminalString(
formatFileList(input.listFiles()),
shell.getSize().getHeight(), shell.getSize().getWidth()));
else
shell.out().println(Parser.formatDisplayListTerminalString(
formatFileList(input.listFiles(new FileLister.FileAndDirectoryNoDotNamesFilter())),
shell.getSize().getHeight(), shell.getSize().getWidth()));
}
}
private List<TerminalString> formatFileList(File[] fileList) {
ArrayList<TerminalString> list = new ArrayList<TerminalString>(fileList.length);
for(File file : fileList) {
if(file.isDirectory())
list.add(new TerminalString(file.getName(),
new TerminalColor(Color.BLUE, Color.DEFAULT)));
else
list.add(new TerminalString(file.getName()));
}
Collections.sort(list, new PosixTerminalStringNameComparator());
return list;
}
private void displayFile(File input, Shell shell) {
}
private String displayLongListing(File[] files) {
StringGroup access = new StringGroup(files.length);
StringGroup size = new StringGroup(files.length);
StringGroup owner = new StringGroup(files.length);
StringGroup group = new StringGroup(files.length);
StringGroup modified = new StringGroup(files.length);
try {
int counter = 0;
for(File file : files) {
BasicFileAttributes attr = Files.readAttributes(file.toPath(), fileAttributes);
access.addString(AeshPosixFilePermissions.toString(((PosixFileAttributes) attr)), counter);
size.addString(String.valueOf(attr.size()), counter);
if(Config.isOSPOSIXCompatible())
owner.addString(((PosixFileAttributes) attr).owner().getName(), counter);
else
owner.addString("", counter);
if(Config.isOSPOSIXCompatible())
group.addString(((PosixFileAttributes) attr).group().getName(), counter);
else
owner.addString("", counter);
modified.addString(DATE_FORMAT.format(new Date(attr.lastModifiedTime().toMillis())), counter);
counter++;
}
}
catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
StringBuilder builder = new StringBuilder();
TerminalColor directoryColor = new TerminalColor(Color.BLUE, Color.DEFAULT, Color.Intensity.BRIGHT);
for(int i=0; i < files.length; i++) {
if(files[i].isDirectory()) {
builder.append(access.getString(i))
.append(owner.getFormattedString(i))
.append(group.getFormattedString(i))
.append(size.getFormattedString(i))
.append(SPACE)
.append(modified.getString(i))
.append(SPACE);
builder.append(new TerminalString(files[i].getName(), directoryColor))
.append(Config.getLineSeparator());
}
else {
builder.append(access.getString(i))
.append(owner.getFormattedString(i))
.append(group.getFormattedString(i))
.append(size.getFormattedString(i))
.append(SPACE)
.append(modified.getString(i))
.append(SPACE)
.append(files[i].getName())
.append(Config.getLineSeparator());
}
}
return builder.toString();
}
class PosixTerminalStringNameComparator implements Comparator<TerminalString> {
private static final char DOT = '.';
@Override
public int compare(TerminalString o1, TerminalString o2) {
if(o1.getCharacters().length() > 1 && o2.getCharacters().length() > 1) {
if(o1.getCharacters().indexOf(DOT) == 0) {
if(o2.getCharacters().indexOf(DOT) == 0)
return o1.getCharacters().substring(1).compareToIgnoreCase(o2.getCharacters().substring(1));
else
return o1.getCharacters().substring(1).compareToIgnoreCase(o2.getCharacters());
}
else {
if(o2.getCharacters().indexOf(DOT) == 0)
return o1.getCharacters().compareToIgnoreCase(o2.getCharacters().substring(1));
else
return o1.getCharacters().compareToIgnoreCase(o2.getCharacters());
}
}
else
return 0;
}
}
class PosixFileNameComparator implements Comparator<File> {
private static final char DOT = '.';
@Override
public int compare(File o1, File o2) {
if(o1.getName().length() > 1 && o2.getName().length() > 1) {
if(o1.getName().indexOf(DOT) == 0) {
if(o2.getName().indexOf(DOT) == 0)
return o1.getName().substring(1).compareToIgnoreCase(o2.getName().substring(1));
else
return o1.getName().substring(1).compareToIgnoreCase(o2.getName());
}
else {
if(o2.getName().indexOf(DOT) == 0)
return o1.getName().compareToIgnoreCase(o2.getName().substring(1));
else
return o1.getName().compareToIgnoreCase(o2.getName());
}
}
else
return 0;
}
}
}
|
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
*
*/
public class Watcher implements Runnable {
private static final String DEPLOY_THREAD_NAME = "watch_thread";
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
private static final long SLEEP_TIME = 5500L;
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
private Set<DeploymentDirectory> deployments;
private Set<String> dataSources;
private static final Logger LOG = Logger.getLogger(Watcher.class);
/**
* Defines file types for watch service
*
* @author Levan
*
*/
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
*
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
private static Set<DeploymentDirectory> getDeployDirectories() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& CollectionUtils.available(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
private static Set<String> getDataSourcePaths() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus()
&& CollectionUtils.available(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (CollectionUtils.available(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = ObjectUtils.notEquals(deploymantPath,
parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (CollectionUtils.available(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (CollectionUtils.available(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (CollectionUtils.available(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
List<File> list = new ArrayList<File>();
if (CollectionUtils.available(deploymetDirss)) {
String path;
DeployFiletr filter = new DeployFiletr();
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(filter);
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (CollectionUtils.available(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
List<File> list = new ArrayList<File>();
if (CollectionUtils.available(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (currentEvent == null) {
return;
}
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count);
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count);
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count);
redeployFile(fileName);
}
}
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
private void registerPaths(File[] files, FileSystem fs, WatchService watch)
throws IOException {
String path;
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (CollectionUtils.available(files)) {
registerPaths(files, fs, watch);
}
} else {
registerPath(fs, path, watch);
}
}
}
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (ObjectUtils.available(deployments)) {
registerPaths(deployments, fs, watch);
}
if (ObjectUtils.available(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
ConnectionContainer.closeConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
}
|
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
public class Watcher implements Runnable {
// Name of deployment watch service thread
private static final String DEPLOY_THREAD_NAME = "watch_thread";
// Priority of deployment watch service thread
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
// Sleep time of thread between watch service status scans
private static final long SLEEP_TIME = 5500L;
// Thread pool for watch service threads
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
// Sets of directories of application deployments
private Set<DeploymentDirectory> deployments;
// Sets of data source descriptor file paths
private Set<String> dataSources;
private static final int ERROR_EXIT = -1;
private static final Logger LOG = Logger.getLogger(Watcher.class);
/**
* Defines file types for watch service
*
* @author Levan
* @since 0.0.45-SNAPSHOT
*/
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
/**
* Clears and gets file {@link URL} by file name
*
* @param fileName
* @return {@link URL}
* @throws IOException
*/
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
/**
* Gets {@link Set} of {@link DeploymentDirectory} instances from
* configuration
*
* @return {@link Set}<code><DeploymentDirectory></code>
*/
private static Set<DeploymentDirectory> getDeployDirectories() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
/**
* Gets {@link Set} of data source paths from configuration
*
* @return {@link Set}<code><String></code>
*/
private static Set<String> getDataSourcePaths() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
/**
* Checks and gets appropriated {@link WatchFileType} by passed file name
*
* @param fileName
* @return {@link WatchFileType}
*/
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (CollectionUtils.valid(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = ObjectUtils.notEquals(deploymantPath,
parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (CollectionUtils.valid(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (CollectionUtils.valid(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(deploymetDirss)) {
String path;
DeployFiletr filter = new DeployFiletr();
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(filter);
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
List<File> list = new ArrayList<File>();
if (CollectionUtils.valid(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
/**
* Deploys application or data source file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
/**
* Deploys application or data source file by passed {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
/**
* Removes from deployments application or data source file by passed
* {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
/**
* Removes from deployments application or data source file by passed file
* name
*
* @param fileName
* @throws IOException
*/
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
/**
* Removes from deployments and deploys again application or data source
* file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
/**
* Handles file change event
*
* @param dir
* @param currentEvent
* @throws IOException
*/
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (ObjectUtils.notNull(currentEvent)) {
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count);
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count);
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count);
redeployFile(fileName);
}
}
}
/**
* Runs file watch service
*
* @param watch
* @throws IOException
*/
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Registers path to watch service
*
* @param fs
* @param path
* @param watch
* @throws IOException
*/
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
/**
* Registers passed {@link File} array to watch service
*
* @param files
* @param fs
* @param watch
* @throws IOException
*/
private void registerPaths(File[] files, FileSystem fs, WatchService watch)
throws IOException {
String path;
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
/**
* Registers deployments directories to watch service
*
* @param deploymentDirss
* @param fs
* @param watch
* @throws IOException
*/
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (CollectionUtils.valid(files)) {
registerPaths(files, fs, watch);
}
} else {
registerPath(fs, path, watch);
}
}
}
/**
* Registers data source path to watch service
*
* @param paths
* @param fs
* @param watch
* @throws IOException
*/
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (CollectionUtils.valid(deployments)) {
registerPaths(deployments, fs, watch);
}
if (CollectionUtils.valid(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
ConnectionContainer.closeConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
/**
* Starts watch service for application and data source files
*/
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
}
|
package org.lightmare.utils;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Utility class to help with general object checks
*
* @author levan
*
*/
public class ObjectUtils {
private static final int FIRST_INDEX = 0;
public static final String EMPTY_STRING = "";
public static boolean notTrue(boolean statement) {
return !statement;
}
public static boolean notNull(Object data) {
return (data != null);
}
public static boolean notNullAll(Object... datas) {
boolean valid = datas != null;
if (valid) {
int length = datas.length;
for (int i = 0; i < length && valid; i++) {
valid = datas[i] != null;
}
}
return valid;
}
public static boolean available(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
public static boolean available(Map<?, ?> map) {
return map != null && !map.isEmpty();
}
public static boolean notAvailable(Map<?, ?> map) {
return !available(map);
}
public static boolean notAvailable(Collection<?> collection) {
return !available(collection);
}
public static boolean notAvailable(Collection<?>... collections) {
return !available(collections);
}
public static boolean availableAll(Map<?, ?>... maps) {
boolean avaliable = notNull(maps);
if (avaliable) {
Map<?, ?> map;
for (int i = 0; i < maps.length && avaliable; i++) {
map = maps[i];
avaliable = avaliable && available(map);
}
}
return avaliable;
}
public static boolean available(Object[] collection) {
return collection != null && collection.length > 0;
}
public static boolean notAvailable(Object[] collection) {
return !available(collection);
}
public static boolean available(CharSequence chars) {
return chars != null && chars.length() > 0;
}
public static boolean notAvailable(CharSequence chars) {
return !available(chars);
}
public static boolean availableAll(Collection<?>... collections) {
boolean avaliable = notNull(collections);
if (avaliable) {
Collection<?> collection;
for (int i = 0; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && available(collection);
}
}
return avaliable;
}
public static boolean availableAll(Object[]... collections) {
boolean avaliable = notNull(collections);
if (avaliable) {
Object[] collection;
for (int i = 0; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && available(collection);
}
}
return avaliable;
}
public static boolean notEmpty(Collection<?> collection) {
return !collection.isEmpty();
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> collection, Class<T> type) {
T[] array;
if (notNull(collection)) {
array = (T[]) Array.newInstance(type, collection.size());
array = collection.toArray(array);
} else {
array = null;
}
return array;
}
public static void close(Closeable closeable) throws IOException {
if (ObjectUtils.notNull(closeable)) {
closeable.close();
}
}
private static <T> T getFirstFromList(List<T> list) {
T value;
if (available(list)) {
value = list.get(FIRST_INDEX);
} else {
value = null;
}
return value;
}
/**
* Peaks first element from collection
*
* @param collection
* @return T
*/
public static <T> T getFirst(Collection<T> collection) {
T value;
if (available(collection)) {
if (collection instanceof List) {
value = getFirstFromList(((List<T>) collection));
} else {
Iterator<T> iterator = collection.iterator();
value = iterator.next();
}
} else {
value = null;
}
return value;
}
/**
* Peaks first element from array
*
* @param collection
* @return T
*/
public static <T> T getFirst(T[] values) {
T value;
if (available(values)) {
value = values[FIRST_INDEX];
} else {
value = null;
}
return value;
}
public static boolean isFalse(Boolean data) {
return !data;
}
}
|
package org.lightmare.utils;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Utility class to help with general object checks
*
* @author levan
*
*/
public class ObjectUtils {
public static final int EMPRTY_ARRAY_LENGTH = 0;
private static final int FIRST_INDEX = 0;
public static final String EMPTY_STRING = "";
public static boolean notTrue(boolean statement) {
return !statement;
}
public static boolean notNull(Object data) {
return (data != null);
}
public static boolean notNullAll(Object... datas) {
boolean valid = datas != null;
if (valid) {
int length = datas.length;
for (int i = 0; i < length && valid; i++) {
valid = datas[i] != null;
}
}
return valid;
}
public static boolean available(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
public static boolean available(Map<?, ?> map) {
return map != null && !map.isEmpty();
}
public static boolean notAvailable(Map<?, ?> map) {
return !available(map);
}
public static boolean notAvailable(Collection<?> collection) {
return !available(collection);
}
public static boolean notAvailable(Collection<?>... collections) {
return !available(collections);
}
public static boolean availableAll(Map<?, ?>... maps) {
boolean avaliable = notNull(maps);
if (avaliable) {
Map<?, ?> map;
for (int i = 0; i < maps.length && avaliable; i++) {
map = maps[i];
avaliable = avaliable && available(map);
}
}
return avaliable;
}
public static boolean available(Object[] collection) {
return collection != null && collection.length > 0;
}
public static boolean notAvailable(Object[] collection) {
return !available(collection);
}
public static boolean available(CharSequence chars) {
return chars != null && chars.length() > 0;
}
public static boolean notAvailable(CharSequence chars) {
return !available(chars);
}
public static boolean availableAll(Collection<?>... collections) {
boolean avaliable = notNull(collections);
if (avaliable) {
Collection<?> collection;
for (int i = 0; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && available(collection);
}
}
return avaliable;
}
public static boolean availableAll(Object[]... collections) {
boolean avaliable = notNull(collections);
if (avaliable) {
Object[] collection;
for (int i = 0; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && available(collection);
}
}
return avaliable;
}
public static boolean notEmpty(Collection<?> collection) {
return !collection.isEmpty();
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> collection, Class<T> type) {
T[] array;
if (notNull(collection)) {
array = (T[]) Array.newInstance(type, collection.size());
array = collection.toArray(array);
} else {
array = null;
}
return array;
}
public static Object[] getEmptyArray() {
return new Object[EMPRTY_ARRAY_LENGTH];
}
@SuppressWarnings("unchecked")
public static <T> T[] getEmptyArray(Class<T> componentType) {
return (T[]) Array.newInstance(componentType, EMPRTY_ARRAY_LENGTH);
}
public static void close(Closeable closeable) throws IOException {
if (ObjectUtils.notNull(closeable)) {
closeable.close();
}
}
/**
* Peaks first element from list
*
* @param list
* @return T
*/
private static <T> T getFirstFromList(List<T> list) {
T value;
if (available(list)) {
value = list.get(FIRST_INDEX);
} else {
value = null;
}
return value;
}
/**
* Peaks first element from collection
*
* @param collection
* @return T
*/
public static <T> T getFirst(Collection<T> collection) {
T value;
if (available(collection)) {
if (collection instanceof List) {
value = getFirstFromList(((List<T>) collection));
} else {
Iterator<T> iterator = collection.iterator();
value = iterator.next();
}
} else {
value = null;
}
return value;
}
public static <T> T[] emptyArray(Class<T> type) {
@SuppressWarnings("unchecked")
T[] empty = (T[]) new Object[EMPRTY_ARRAY_LENGTH];
return empty;
}
/**
* Peaks first element from array
*
* @param collection
* @return T
*/
public static <T> T getFirst(T[] values) {
T value;
if (available(values)) {
value = values[FIRST_INDEX];
} else {
value = null;
}
return value;
}
public static boolean isFalse(Boolean data) {
return !data;
}
}
|
package dr.app.tools;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.evolution.io.Importer;
import dr.evolution.io.NewickImporter;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.geo.KMLCoordinates;
import dr.geo.KernelDensityEstimator2D;
import dr.geo.Polygon2D;
import dr.geo.contouring.*;
import dr.geo.math.SphericalPolarCoordinates;
import dr.inference.trace.Trace;
import dr.inference.trace.TraceDistribution;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.util.HeapSort;
import dr.util.Version;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import java.awt.geom.Point2D;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author Marc A. Suchard
* @author Philippe Lemey
* <p/>
* example for location slices through time:
* -burnin500 -trait location -sliceFileHeights sliceTimes -summary true -mrsd 2007.63 -format KML -progress true -impute true -noise true -HPD 95 WNV_relaxed_gamma_geo.trees output.kml
* <p/>
* example for Markov reward o backbone summary (note we cannot imput here):
* -burnin50 -trait AC1R,AC2R,AC4R,AC8R,AC10R,AC11R,AC15R,AC19R,AC22R,AC23R,AC26R,AC30R,AC31R,AC32R,AC33R,AC34R,AC35R,AC37R,AC46R -sliceTimes2002,2002.25,2002.5,2002.75,2003,2003.25,2003.5,2003.75,2004,2004.25,2004.5,2004.75,2005,2005.25,2005.5,2005.75,2006 -summary true -mrsd 2007 -branchNorm true -format TAB -progress true -backbonetaxa december2006taxa.txt -branchset backbone airCommunities_1.trees TSoutput.txt
* example of 1D antigenic summary
* -burnin0 -trait antigenic -sliceFileTimes timeInterval -summary true -mrsd 2007 -format TAB -progress true -impute true -noise false -HPD 95 H3N2_antigenic_sub.trees antigenic.txt
*/
public class TimeSlicer {
public static final String sep = "\t";
public static final String PRECISION_STRING = "precision";
public static final String RATE_STRING = "rate"; // TODO the rate used is supposed to be the relaxed diffusion rate, but relaxed clock models will also result in a "rate attribute", we somehow need to distinguis between them!
public static final String SLICE_ELEMENT = "slice";
public static final String REGIONS_ELEMENT = "hpdRegion";
public static final String NODE_ELEMENT = "node";
public static final String ROOT_ELEMENT = "root";
public static final String TRAIT = "trait";
public static final String NAME = "name";
public static final String DENSITY_VALUE = "density";
public static final String SLICE_VALUE = "time";
public static final String STYLE = "Style";
public static final String ID = "id";
public static final String WIDTH = "0.5";
public static final String startHPDColor = "FFFFFF"; //blue=B36600
public static final String endHPDColor = "00F1D6"; //red=0000FF
public static final String opacity = "6f";
public static final String BURNIN = "burnin";
public static final String SKIP = "skip";
public static final String SLICE_TIMES = "sliceTimes";
public static final String SLICE_HEIGHTS = "sliceHeights";
public static final String SLICE_COUNT = "sliceCount";
public static final String START_TIME = "startTime";
public static final String SLICE_FILE_HEIGHTS = "sliceFileHeights";
public static final String SLICE_FILE_TIMES = "sliceFileTimes";
public static final String SLICE_MODE = "sliceMode";
public static final String MRSD = "mrsd";
public static final String HELP = "help";
public static final String NOISE = "noise";
public static final String IMPUTE = "impute";
public static final String SUMMARY = "summary";
public static final String FORMAT = "format";
public static final String CONTOUR_MODE = "contourMode";
public static final String NORMALIZATION = "normalization";
public static final String HPD = "hpd";
public static final String SDR = "sdr";
public static final String PROGRESS = "progress";
public static final double treeLengthPercentage = 0.00;
public static final String BRANCH_NORMALIZE = "branchnorm";
public static final String BRANCHSET = "branchset";
public static final String BACKBONETAXA = "backbonetaxa";
public static final String ICON = "http://maps.google.com/mapfiles/kml/pal4/icon49.png";
public static final int GRIDSIZE = 200;
public static final double[] BANDWIDTHS = new double[]{1.0,1.0};
public static final String[] falseTrue = {"false", "true"};
private final static Calendar calendar = GregorianCalendar.getInstance();
private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public TimeSlicer(String treeFileName, int burnin, int skipEvery, String[] traits, double[] sliceHeights, boolean impute,
boolean trueNoise, double mrsd, ContourMode contourMode, SliceMode sliceMode,
Normalization normalize, boolean getSRD, String progress, boolean branchNormalization, BranchSet branchset, Set backboneTaxa) {
this.traits = traits;
traitCount = traits.length;
sliceCount = 1;
doSlices = false;
mostRecentSamplingDate = mrsd;
this.contourMode = contourMode;
this.sliceMode = sliceMode;
sdr = getSRD;
if (progress != null) {
if (progress.equalsIgnoreCase("true")) {
sliceProgressReport = true;
} else if (progress.equalsIgnoreCase("check")) {
sliceProgressReport = true;
checkSliceContours = true;
}
}
if (sliceHeights != null) {
sliceCount = sliceHeights.length;
doSlices = true;
this.sliceHeights = sliceHeights;
}
if ((mostRecentSamplingDate - sliceHeights[sliceHeights.length - 1]) < 0) {
ancient = true;
}
values = new ArrayList<List<List<Trait>>>(sliceCount);
for (int i = 0; i < sliceCount; i++) {
List<List<Trait>> thisSlice = new ArrayList<List<Trait>>(traitCount);
values.add(thisSlice);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = new ArrayList<Trait>();
thisSlice.add(thisTraitSlice);
}
}
rootValues = new ArrayList<List<Trait>>(traitCount);
for (int k = 0; k < traitCount; k++) {
List<Trait> thisTrait = new ArrayList<Trait>();
rootValues.add(thisTrait);
}
try {
readAndAnalyzeTrees(treeFileName, burnin, skipEvery, traits, sliceHeights, impute, trueNoise, normalize, branchNormalization, branchset, backboneTaxa);
} catch (IOException e) {
System.err.println("Error reading file: " + treeFileName);
System.exit(-1);
} catch (Importer.ImportException e) {
System.err.println("Error parsing trees in file: " + treeFileName);
System.exit(-1);
}
if (values.get(0).get(0).size() == 0) {
System.err.println("Trait(s) values missing from trees.");
System.exit(-1);
}
progressStream.println(treesRead + " trees read.");
progressStream.println(treesAnalyzed + " trees analyzed.");
}
public void output(String outFileName, boolean summaryOnly) {
output(outFileName, summaryOnly, OutputFormat.XML, 0.80, null);
}
private Element rootElement;
private Element documentElement;
private Element contourFolderElement;
private Element nodeFolderElement;
private StringBuffer tabOutput = new StringBuffer();
public void output(String outFileName, boolean summaryOnly, OutputFormat outputFormat, double hpdValue, String sdrFile) {
resultsStream = System.out;
if (outFileName != null) {
try {
resultsStream = new PrintStream(new File(outFileName));
} catch (IOException e) {
System.err.println("Error opening file: " + outFileName);
System.exit(-1);
}
}
if (!summaryOnly) {
outputHeader(traits);
if (sliceHeights == null || sliceHeights.length == 0) {
outputSlice(0, Double.NaN);
} else {
for (int i = 0; i < sliceHeights.length; i++) {
outputSlice(i, sliceHeights[i]);
}
}
} else { // Output summaries
if (outputFormat == OutputFormat.XML) {
rootElement = new Element("xml");
} else if (outputFormat == OutputFormat.KML) {
// <Schema name="HPD_Schema" id="HPD_Schema">
// <SimpleField name="Name" type="string">
// <displayName>Name</displayName>
// </SimpleField>
// <SimpleField name="Description" type="string">
// <displayName>Description</displayName>
// </SimpleField>
// <SimpleField name="Time" type="double">
// <displayName>Time</displayName>
// </SimpleField>
// </Schema>
Element hpdSchema = new Element("Schema");
hpdSchema.setAttribute("schemaUrl", "HPD_Schema");
hpdSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Name")
.setAttribute("type", "string")
.addContent(new Element("displayName").addContent("Name")));
hpdSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Description")
.setAttribute("type", "string")
.addContent(new Element("displayName").addContent("Description")));
hpdSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Time")
.setAttribute("type", "double")
.addContent(new Element("displayName").addContent("Time")));
Element tipSchema = new Element("Schema");
tipSchema.setAttribute("schemaUrl", "Tip_Schema");
tipSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Name")
.setAttribute("type", "string")
.addContent(new Element("displayName").addContent("Name")));
tipSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Description")
.setAttribute("type", "string")
.addContent(new Element("displayName").addContent("Description")));
tipSchema.addContent(new Element("SimpleField")
.setAttribute("name", "Time")
.setAttribute("type", "double")
.addContent(new Element("displayName").addContent("Time")));
contourFolderElement = new Element("Folder");
Element contourFolderNameElement = new Element("name");
contourFolderNameElement.addContent("surface HPD regions");
contourFolderElement.addContent(contourFolderNameElement);
nodeFolderElement = new Element("Folder");
Element nodeFolderNameElement = new Element("name");
nodeFolderNameElement.addContent("nodes");
nodeFolderElement.addContent(nodeFolderNameElement);
Element documentNameElement = new Element("name");
String documentName = outFileName;
if (documentName == null)
documentName = "default";
if (documentName.endsWith(".kml"))
documentName = documentName.replace(".kml", "");
documentNameElement.addContent(documentName);
documentElement = new Element("Document");
documentElement.addContent(documentNameElement);
documentElement.addContent(hpdSchema);
documentElement.addContent(tipSchema);
documentElement.addContent(contourFolderElement);
if (sliceMode == SliceMode.NODES) {
documentElement.addContent(nodeFolderElement);
}
rootElement = new Element("kml");
rootElement.addContent(documentElement);
}
if (sliceHeights == null)
summarizeSlice(0, Double.NaN, outputFormat, hpdValue);
else {
if (outputFormat == OutputFormat.TAB) {
if (mostRecentSamplingDate > 0) {
tabOutput.append("trait\t" + "sliceTime\t" + "mean\t" + "stdev\t" + "HPDlow\t" + "HPDup");
} else {
tabOutput.append("trait\t" + "sliceHeight\t" + "mean\t" + "stdev\t" + "HPDlow\t" + "HPDup");
}
}
for (int i = 0; i < sliceHeights.length; i++)
summarizeSlice(i, sliceHeights[i], outputFormat, hpdValue);
}
summarizeRoot(outputFormat, hpdValue);
if (outputFormat == OutputFormat.TAB) {
resultsStream.println(tabOutput);
} else {
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
try {
xmlOutputter.output(rootElement, resultsStream);
} catch (IOException e) {
System.err.println("IO Exception encountered: " + e.getMessage());
System.exit(-1);
}
}
}
// writes out dispersal rate summaries for the whole tree, there is a beast xml statistic that can do this now
// if (containsLocation) {
// try{
// PrintWriter dispersalRateFile = new PrintWriter(new FileWriter("dispersalRates.log"), true);
// dispersalRateFile.print("state"+"\t"+"dispersalRate(native units)"+"\t"+"dispersalRate(great circle distance, km)\r");
// for(int x = 0; x < dispersalrates.size(); x++ ) {
// dispersalRateFile.print(x+"\t"+dispersalrates.get(x)+"\r");
// } catch (IOException e) {
// System.err.println("IO Exception encountered: "+e.getMessage());
// System.exit(-1);
if (sdr) {
double[][] sliceTreeWeightedAverageRates = new double[sliceTreeDistanceArrays.size()][sliceCount];
double[][] sliceTreeMaxRates = new double[sliceTreeDistanceArrays.size()][sliceCount];
double[][] sliceTreeDistances = new double[sliceCount][sliceTreeDistanceArrays.size()];
double[][] sliceTreeTimes = new double[sliceCount][sliceTreeDistanceArrays.size()];
//double[][] sliceTreeMaxDistances = new double[sliceCount][sliceTreeMaxDistanceArrays.size()];
double[][] sliceTreeMaxDistances = new double[sliceTreeMaxDistanceArrays.size()][sliceCount];
double[][] sliceTreeTimesFromRoot = new double[sliceCount][sliceTreeTimeFromRootArrays.size()];
double[][] sliceTreeDiffusionCoefficients = new double[sliceTreeDiffusionCoefficientArrays.size()][sliceCount];
//double[][] sliceTreeWeightedAverageDiffusionCoefficients = new double[sliceTreeDistanceArrays.size()][sliceCount];
for (int q = 0; q < sliceTreeDistanceArrays.size(); q++) {
double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(q);
double[] timeArray = (double[]) sliceTreeTimeArrays.get(q);
double[] maxDistanceArray = (double[]) sliceTreeMaxDistanceArrays.get(q);
double[] timeFromRootArray = (double[]) sliceTreeTimeFromRootArrays.get(q);
double[] diffusionCoefficientArray = (double[]) sliceTreeDiffusionCoefficientArrays.get(q);
for (int r = 0; r < distanceArray.length; r++) {
sliceTreeDistances[r][q] = distanceArray[r];
sliceTreeTimes[r][q] = timeArray[r];
sliceTreeMaxDistances[q][r] = maxDistanceArray[r];
sliceTreeTimesFromRoot[r][q] = timeFromRootArray[r];
sliceTreeDiffusionCoefficients[q][r] = diffusionCoefficientArray[r];
}
}
//print2DArray(sliceTreeDistances,"sliceTreeDistances.txt");
//print2DArray(sliceTreeTimes,"sliceTreeTimes.txt");
//print2DTransposedArray(sliceTreeDiffusionCoefficients,"sliceTreeDiffusionCoefficients.txt");
//print2DArray(sliceTreeTimesFromRoot,"sliceTreeTimesFromRoot.txt");
if (sliceCount > 1) {
for (int s = 0; s < sliceTreeDistanceArrays.size(); s++) {
double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(s);
double[] timeArray = (double[]) sliceTreeTimeArrays.get(s);
double[] maxDistanceArray = (double[]) sliceTreeMaxDistanceArrays.get(s);
double[] timeFromRoot = (double[]) sliceTreeTimeFromRootArrays.get(s);
for (int t = 0; t < (sliceCount - 1); t++) {
sliceTreeMaxRates[s][t] = (maxDistanceArray[t]) / (timeFromRoot[t]);
if ((timeArray[t] - timeArray[t + 1]) > ((Double) treeLengths.get(s) * treeLengthPercentage)) {
sliceTreeWeightedAverageRates[s][t] = (distanceArray[t] - distanceArray[t + 1]) / (timeArray[t] - timeArray[t + 1]);
//sliceTreeWeightedAverageRates[s][t] = (sliceTreeDistances[t][s] - sliceTreeDistances[t+1][s])/(sliceTreeTimes[t][s] - sliceTreeTimes[t+1][s]);
//sliceTreeWeightedAverageDiffusionCoefficients[s][t] = Math.pow((distanceArray[t] - distanceArray[t+1]),2.0)/(4.0*(timeArray[t] - timeArray[t+1]));
} else {
if (timeArray[t] > 0) {
if (t == 0) {
throw new RuntimeException("Philippe to fix: the time slices are expected in ascending height order");
}
sliceTreeWeightedAverageRates[s][t] = sliceTreeWeightedAverageRates[s][t - 1];
//sliceTreeWeightedAverageDiffusionCoefficients[s][t] = sliceTreeWeightedAverageDiffusionCoefficients[s][t-1];
} else {
//set it to NaN, we ignore NaNs when getting summary stats
sliceTreeWeightedAverageRates[s][t] = Double.NaN;
//sliceTreeWeightedAverageDiffusionCoefficients[s][t] = Double.NaN;
}
}
}
if ((timeArray[sliceCount - 1]) > ((Double) treeLengths.get(s) * treeLengthPercentage)) {
sliceTreeWeightedAverageRates[s][sliceCount - 1] = (distanceArray[sliceCount - 1]) / (timeArray[sliceCount - 1]);
//sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = Math.pow(distanceArray[sliceCount-1],2.0)/(4.0*timeArray[sliceCount-1]);
} else {
if ((timeArray[sliceCount - 1]) > 0) {
sliceTreeWeightedAverageRates[s][sliceCount - 1] = sliceTreeWeightedAverageRates[s][sliceCount - 2];
//sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-2];
} else {
sliceTreeWeightedAverageRates[s][sliceCount - 1] = (distanceArray[sliceCount - 1]) / (timeArray[sliceCount - 1]);
//sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = Math.pow(distanceArray[sliceCount-1],2.0)/(4.0*timeArray[sliceCount-1]);
}
}
sliceTreeMaxRates[s][sliceCount - 1] = maxDistanceArray[sliceCount - 1] / timeFromRoot[sliceCount - 1];
}
} else {
for (int s = 0; s < sliceTreeDistanceArrays.size(); s++) {
double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(s);
double[] timeArray = (double[]) sliceTreeTimeArrays.get(s);
double[] maxDistanceArray = (double[]) sliceTreeMaxDistanceArrays.get(s);
double[] timeFromRoot = (double[]) sliceTreeTimeFromRootArrays.get(s);
sliceTreeWeightedAverageRates[s][0] = distanceArray[0] / timeArray[0];
//sliceTreeWeightedAverageDiffusionCoefficients[s][0] = Math.pow(distanceArray[0],2.0)/(4.0*timeArray[0]);
sliceTreeMaxRates[s][0] = maxDistanceArray[0] / timeFromRoot[0];
}
}
//print2DArray(sliceTreeWeightedAverageRates,"sliceTreeWeightedAverageRates.txt");
try {
PrintWriter sliceDispersalRateFile = new PrintWriter(new FileWriter(sdrFile), true);
sliceDispersalRateFile.print("sliceTime" + "\t");
if (mostRecentSamplingDate > 0) {
sliceDispersalRateFile.print("realTime" + "\t");
}
sliceDispersalRateFile.print("mean dispersalRate" + "\t" + "hpd low" + "\t" + "hpd up" + "\t" + "mean MaxDispersalRate" + "\t" + "hpd low" + "\t" + "hpd up" + "\t" + "mean MaxDispersalDistance" + "\t" + "hpd low" + "\t" + "hpd up" + "\t" + "mean cumulative DiffusionCoefficient" + "\t" + "hpd low" + "\t" + "hpd up" + "\r");
double[] meanWeightedAverageDispersalRates = meanColNoNaN(sliceTreeWeightedAverageRates);
double[][] hpdWeightedAverageDispersalRates = getArrayHPDintervals(sliceTreeWeightedAverageRates);
double[] meanMaxDispersalDistances = meanColNoNaN(sliceTreeMaxDistances);
double[][] hpdMaxDispersalDistances = getArrayHPDintervals(sliceTreeMaxDistances);
double[] meanMaxDispersalRates = meanColNoNaN(sliceTreeMaxRates);
double[][] hpdMaxDispersalRates = getArrayHPDintervals(sliceTreeMaxRates);
double[] meanDiffusionCoefficients = meanColNoNaN(sliceTreeDiffusionCoefficients);
double[][] hpdDiffusionCoefficients = getArrayHPDintervals(sliceTreeDiffusionCoefficients);
//double[] meanWeightedAverageDiffusionCoefficients = meanColNoNaN(sliceTreeWeightedAverageDiffusionCoefficients);
//double[][] hpdWeightedAverageDiffusionCoefficients = getArrayHPDintervals(sliceTreeWeightedAverageDiffusionCoefficients);
for (int u = 0; u < sliceCount; u++) {
sliceDispersalRateFile.print(sliceHeights[u] + "\t");
if (mostRecentSamplingDate > 0) {
sliceDispersalRateFile.print((mostRecentSamplingDate - sliceHeights[u]) + "\t");
}
sliceDispersalRateFile.print(meanWeightedAverageDispersalRates[u] + "\t" + hpdWeightedAverageDispersalRates[u][0] + "\t" + hpdWeightedAverageDispersalRates[u][1] + "\t" + meanMaxDispersalRates[u] + "\t" + hpdMaxDispersalRates[u][0] + "\t" + hpdMaxDispersalRates[u][1] + "\t" + meanMaxDispersalDistances[u] + "\t" + hpdMaxDispersalDistances[u][0] + "\t" + hpdMaxDispersalDistances[u][1] + "\t" + meanDiffusionCoefficients[u] + "\t" + hpdDiffusionCoefficients[u][0] + "\t" + hpdDiffusionCoefficients[u][1] + "\r");
}
sliceDispersalRateFile.close();
} catch (IOException e) {
System.err.println("IO Exception encountered: " + e.getMessage());
System.exit(-1);
}
}
}
enum Normalization {
LENGTH,
HEIGHT,
NONE
}
enum OutputFormat {
TAB,
KML,
XML
}
enum BranchSet {
ALL,
INT,
EXT,
BACKBONE
}
enum SliceMode {
BRANCHES,
NODES,
}
public static <T extends Enum<T>> String[] enumNamesToStringArray(T[] values) {
int i = 0;
String[] result = new String[values.length];
for (T value : values) {
result[i++] = value.name();
}
return result;
}
private void addDimInfo(Element element, int j, int dim) {
if (dim > 1)
element.setAttribute("dim", Integer.toString(j + 1));
}
private void summarizeRoot(OutputFormat outputFormat, double hpdValue){
for (int traitIndex = 0; traitIndex < rootValues.size(); traitIndex++) {
List<Trait> thisTrait = rootValues.get(traitIndex);
if (thisTrait.size() == 0) {
return;
}
boolean isNumber = thisTrait.get(0).isNumber();
boolean isMultivariate = thisTrait.get(0).isMultivariate();
int dim = thisTrait.get(0).getDim();
boolean isBivariate = isMultivariate && dim == 2;
if (isNumber) {
if (isBivariate) {
if(sliceMode == SliceMode.NODES) {
if (outputFormat == OutputFormat.KML) {
int count = thisTrait.size();
Double[][] x = new Double[dim][count];
double[][] y = new double[dim][count];
for (int i = 0; i < count; i++) {
Trait trait = thisTrait.get(i);
double[] value = trait.getValue();
for (int j = 0; j < dim; j++) {
x[j][i] = value[j];
y[j][i] = x[j][i];
}
}
Element nodeSliceElement = generateNodeSliceElement(Double.NaN, y, -1);
nodeFolderElement.addContent(nodeSliceElement);
if (useStyles) {
Element styleElement = new Element(STYLE);
constructNodeStyleElement(styleElement, Double.NaN);
documentElement.addContent(styleElement);
//also add contour
Element stylePolygonElement = new Element(STYLE);
constructPolygonStyleElement(stylePolygonElement, Double.NaN);
documentElement.addContent(stylePolygonElement);
}
ContourMaker contourMaker;
if (contourMode == ContourMode.JAVA)
contourMaker = new KernelDensityEstimator2D(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else if (contourMode == ContourMode.R)
contourMaker = new ContourWithR(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else if (contourMode == ContourMode.SNYDER)
contourMaker = new ContourWithSynder(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else
throw new RuntimeException("Unimplemented ContourModel!");
ContourPath[] paths = contourMaker.getContourPaths(hpdValue);
int pathCounter = 1;
for (ContourPath path : paths) {
KMLCoordinates coords = new KMLCoordinates(path.getAllX(), path.getAllY());
if (outputFormat == OutputFormat.XML) {
// to be implemented
}
// only if the trait is location we will write KML
if (outputFormat == OutputFormat.KML) {
//because KML polygons require long,lat,alt we need to switch lat and long first
coords.switchXY();
Element placemarkElement = generatePlacemarkElementWithPolygon(Double.NaN, coords, -1, pathCounter);
//testing how many points are within the polygon
contourFolderElement.addContent(placemarkElement);
}
pathCounter ++;
}
}
}
}
}
}
}
private void summarizeSliceTrait(Element sliceElement, int slice, List<Trait> thisTrait, int traitIndex, double sliceValue,
OutputFormat outputFormat,
double hpdValue) {
if (thisTrait.size() == 0) {
return;
}
boolean isNumber = thisTrait.get(0).isNumber();
boolean isMultivariate = thisTrait.get(0).isMultivariate();
int dim = thisTrait.get(0).getDim();
boolean isBivariate = isMultivariate && dim == 2;
if (sliceProgressReport) {
progressStream.print("slice " + sliceValue + "\t");
if (mostRecentSamplingDate > 0) {
progressStream.print("time=" + (mostRecentSamplingDate - sliceValue) + "\t");
}
progressStream.print("trait=" + traits[traitIndex] + "\t");
}
if (isNumber) {
Element traitElement = null;
if (outputFormat == OutputFormat.XML || outputFormat == OutputFormat.TAB) {
traitElement = new Element(TRAIT);
traitElement.setAttribute(NAME, traits[traitIndex]);
}
if (outputFormat == OutputFormat.KML) {
if (useStyles) {
Element styleElement = new Element(STYLE);
constructPolygonStyleElement(styleElement, sliceValue);
documentElement.addContent(styleElement);
}
}
int count = thisTrait.size();
Double[][] x = new Double[dim][count];
double[][] y = new double[dim][count];
for (int i = 0; i < count; i++) {
Trait trait = thisTrait.get(i);
double[] value = trait.getValue();
for (int j = 0; j < dim; j++) {
x[j][i] = value[j];
y[j][i] = x[j][i];
}
}
if (outputFormat == OutputFormat.XML || outputFormat == OutputFormat.TAB) {
// Compute marginal means and standard deviations
for (int j = 0; j < dim; j++) {
TraceDistribution trace = new TraceDistribution(x[j]);
Element statsElement = new Element("stats");
addDimInfo(statsElement, j, dim);
StringBuffer sb = new StringBuffer();
sb.append(KMLCoordinates.NEWLINE);
tabOutput.append(KMLCoordinates.NEWLINE);
tabOutput.append(traits[traitIndex] + "\t");
if (mostRecentSamplingDate > 0) {
tabOutput.append((mostRecentSamplingDate - sliceValue) + "\t");
} else {
tabOutput.append(sliceValue + "\t");
}
sb.append(String.format(KMLCoordinates.FORMAT,
trace.getMean())).append(KMLCoordinates.SEPARATOR);
tabOutput.append(String.format(KMLCoordinates.FORMAT,
trace.getMean())).append("\t");
sb.append(String.format(KMLCoordinates.FORMAT,
trace.getStdError())).append(KMLCoordinates.SEPARATOR);
tabOutput.append(String.format(KMLCoordinates.FORMAT,
trace.getStdError())).append("\t");
sb.append(String.format(KMLCoordinates.FORMAT,
trace.getLowerHPD())).append(KMLCoordinates.SEPARATOR);
tabOutput.append(String.format(KMLCoordinates.FORMAT,
trace.getLowerHPD())).append("\t");
sb.append(String.format(KMLCoordinates.FORMAT,
trace.getUpperHPD())).append(KMLCoordinates.NEWLINE);
tabOutput.append(String.format(KMLCoordinates.FORMAT,
trace.getUpperHPD())).append("\t");
statsElement.addContent(sb.toString());
traitElement.addContent(statsElement);
}
}
if (isBivariate) {
if(sliceMode == SliceMode.NODES) {
Element nodeSliceElement = generateNodeSliceElement(sliceValue, y, slice);
nodeFolderElement.addContent(nodeSliceElement);
if (useStyles) {
Element styleElement = new Element(STYLE);
constructNodeStyleElement(styleElement, sliceValue);
documentElement.addContent(styleElement);
}
}
//to test how much points are within the polygons
double numberOfPointsInPolygons = 0;
double totalArea = 0;
ContourMaker contourMaker;
if (contourMode == ContourMode.JAVA)
contourMaker = new KernelDensityEstimator2D(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else if (contourMode == ContourMode.R)
contourMaker = new ContourWithR(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else if (contourMode == ContourMode.SNYDER)
contourMaker = new ContourWithSynder(Trace.arrayConvert(x[0]), Trace.arrayConvert(x[1]), GRIDSIZE);
else
throw new RuntimeException("Unimplemented ContourModel!");
ContourPath[] paths = contourMaker.getContourPaths(hpdValue);
int pathCounter = 1;
for (ContourPath path : paths) {
KMLCoordinates coords = new KMLCoordinates(path.getAllX(), path.getAllY());
if (outputFormat == OutputFormat.XML) {
Element regionElement = new Element(REGIONS_ELEMENT);
regionElement.setAttribute(DENSITY_VALUE, Double.toString(hpdValue));
regionElement.addContent(coords.toXML());
traitElement.addContent(regionElement);
}
// only if the trait is location we will write KML
if (outputFormat == OutputFormat.KML) {
//because KML polygons require long,lat,alt we need to switch lat and long first
coords.switchXY();
Element placemarkElement = generatePlacemarkElementWithPolygon(sliceValue, coords, slice, pathCounter);
//testing how many points are within the polygon
if (checkSliceContours) {
Element testElement = new Element("test");
testElement.addContent(coords.toXML());
Polygon2D testPolygon = new Polygon2D(testElement);
totalArea += testPolygon.calculateArea();
double[][] dest = new double[x.length][x[0].length];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[0].length; j++) {
dest[i][j] = x[j][i].doubleValue();
}
}
numberOfPointsInPolygons += getNumberOfPointsInPolygon(dest, testPolygon);
}
sliceElement.addContent(placemarkElement);
// contourFolderElement.addContent(placemarkElement);
}
pathCounter ++;
}
if (checkSliceContours) {
progressStream.print("numberOfContours=" + paths.length + "\tfreqOfPointsInContour=" + numberOfPointsInPolygons / count + "\ttotalArea = " + totalArea);
}
}
if (outputFormat == OutputFormat.XML)
sliceElement.addContent(traitElement);
} // else skip
if (sliceProgressReport) {
progressStream.print("\r");
}
}
public static int getNumberOfPointsInPolygon(double[][] pointsArray, Polygon2D testPolygon) {
int numberOfPointsInPolygon = 0;
for (int x = 0; x < pointsArray[0].length; x++) {
if (testPolygon.containsPoint2D(new Point2D.Double(pointsArray[0][x], pointsArray[1][x]))) {
numberOfPointsInPolygon++;
}
}
return numberOfPointsInPolygon;
}
private void summarizeSlice(int slice, double sliceValue, OutputFormat outputFormat, double hpdValue) {
//if (outputFormat == OutputFormat.TAB)
// throw new RuntimeException("Only XML/KML output is implemented");
Element sliceElement = new Element("Folder");
if (outputFormat == OutputFormat.XML) {
sliceElement = new Element(SLICE_ELEMENT);
sliceElement.setAttribute(SLICE_VALUE, Double.toString(sliceValue));
}
List<List<Trait>> thisSlice = values.get(slice);
int traitCount = thisSlice.size();
// Element folder = new Element("Folder");
// if (outputFormat == OutputFormat.KML) {
// Element name = new Element("name");
// name.addContent("sliceValue");
// folder.addContent(name);
if (outputFormat == OutputFormat.KML) {
Element name = new Element("name");
name.addContent(Double.toString(sliceValue));
sliceElement.addContent(name);
}
for (int traitIndex = 0; traitIndex < traitCount; traitIndex++) {
// if (outputFormat == OutputFormat.KML) {
// summarizeSliceTrait(folder, slice, thisSlice.get(traitIndex), traitIndex, sliceValue,
// outputFormat,
// hpdValue);
// } else {
summarizeSliceTrait(sliceElement, slice, thisSlice.get(traitIndex), traitIndex, sliceValue,
outputFormat,
hpdValue);
}
if (outputFormat == OutputFormat.KML) {
contourFolderElement.addContent(sliceElement);
}
if (outputFormat == OutputFormat.XML) {
rootElement.addContent(sliceElement);
}
}
private void constructPolygonStyleElement(Element styleElement, double sliceValue) {
double date;
if (Double.isNaN(sliceValue)){
date = Double.NaN;
styleElement.setAttribute(ID, ROOT_ELEMENT + "_hpd" + "_style");
} else {
date = mostRecentSamplingDate - sliceValue;
styleElement.setAttribute(ID, REGIONS_ELEMENT + date + "_style");
}
Element lineStyle = new Element("LineStyle");
Element width = new Element("width");
width.addContent(WIDTH);
lineStyle.addContent(width);
Element polyStyle = new Element("PolyStyle");
Element color = new Element("color");
double[] minMax = new double[2];
minMax[0] = sliceHeights[0];
minMax[1] = sliceHeights[(sliceHeights.length - 1)];
String colorString;
if (sliceValue == Double.NaN){
colorString = startHPDColor;
} else {
colorString = getKMLColor(sliceValue, minMax, endHPDColor, startHPDColor);
}
color.addContent(opacity + colorString);
Element outline = new Element("outline");
outline.addContent("0");
polyStyle.addContent(color);
polyStyle.addContent(outline);
styleElement.addContent(lineStyle);
styleElement.addContent(polyStyle);
}
private void constructNodeStyleElement(Element styleElement, double sliceValue) {
double date;
if (Double.isNaN(sliceValue)){
date = Double.NaN;
styleElement.setAttribute(ID, ROOT_ELEMENT + date + "_style");
} else {
date = mostRecentSamplingDate - sliceValue;
styleElement.setAttribute(ID, NODE_ELEMENT + date + "_style");
}
Element iconStyle = new Element("IconStyle");
Element scale = new Element("scale");
scale.addContent("1");
iconStyle.addContent(scale);
Element icon = new Element("Icon");
Element href = new Element("href");
href.addContent(ICON);
icon.addContent(href);
iconStyle.addContent(icon);
Element color = new Element("color");
double[] minMax = new double[2];
minMax[0] = sliceHeights[0];
minMax[1] = sliceHeights[(sliceHeights.length - 1)];
String colorString;
if (sliceValue == Double.NaN){
colorString = startHPDColor;
} else {
colorString = getKMLColor(sliceValue, minMax, endHPDColor, startHPDColor);
}
color.addContent(opacity + colorString);
iconStyle.addContent(color);
Element colorMode = new Element("colorMode");
colorMode.addContent("normal");
iconStyle.addContent(colorMode);
styleElement.addContent(iconStyle);
}
private Element generatePlacemarkElementWithPolygon(double sliceValue, KMLCoordinates coords, int sliceInteger, int pathCounter) {
double date;
Element placemarkElement = new Element("Placemark");
String name;
Element placemarkNameElement = new Element("name");
if (sliceInteger == -1){
date = Double.NaN;
name = "hpdRegion"+"_"+ROOT_ELEMENT+"_path_"+pathCounter;
placemarkNameElement.addContent(name);
} else {
date = mostRecentSamplingDate - sliceValue;
name = "hpdRegion" + date + "_path_" + pathCounter;
}
placemarkNameElement.addContent(name);
placemarkElement.addContent(placemarkNameElement);
Element visibility = new Element("visibility");
if (sliceInteger == -1){
visibility.addContent("0");
} else {
visibility.addContent("1");
}
placemarkElement.addContent(visibility);
if (sliceCount > 1) {
Element timeSpan = new Element("TimeSpan");
Element begin = new Element("begin");
if (!ancient) {
calendar.set(Calendar.YEAR, (int) Math.floor(date));
calendar.set(Calendar.DAY_OF_YEAR, (int) (365 * (date - Math.floor(date))));
begin.addContent(dateFormat.format(calendar.getTime()));
} else {
begin.addContent(Integer.toString((int)Math.round(date)));
}
timeSpan.addContent(begin);
// if (sliceInteger > 1) {
// Element end = new Element("end");
// end.addContent(Double.toString(mostRecentSamplingDate- sliceHeights[(sliceInteger-1)]));
// timeSpan.addContent(end);
placemarkElement.addContent(timeSpan);
}
if (useStyles) {
Element style = new Element("styleUrl");
if (sliceInteger == -1){
style.addContent("#" + ROOT_ELEMENT + "_hpd" + "_style");
} else {
style.addContent("#" + REGIONS_ELEMENT + date + "_style");
}
placemarkElement.addContent(style);
}
placemarkElement.addContent(generateExtendedData(name, date));
Element polygonElement = new Element("Polygon");
Element altitudeMode = new Element("altitudeMode");
altitudeMode.addContent("clampToGround");
polygonElement.addContent(altitudeMode);
Element tessellate = new Element("tessellate");
tessellate.addContent("1");
polygonElement.addContent(tessellate);
Element outerBoundaryIs = new Element("outerBoundaryIs");
Element LinearRing = new Element("LinearRing");
LinearRing.addContent(coords.toXML());
outerBoundaryIs.addContent(LinearRing);
polygonElement.addContent(outerBoundaryIs);
placemarkElement.addContent(polygonElement);
return placemarkElement;
}
private Element generateNodeSliceElement(double sliceValue, double[][] nodes, int sliceInteger) {
double date;
Element nodeSliceElement = new Element("Folder");
Element nameNodeSliceElement = new Element("name");
String name;
if (sliceInteger == -1){
date = Double.NaN;
name = ROOT_ELEMENT+"_"+date;
} else {
date = mostRecentSamplingDate - sliceValue;
name = "nodeSlice_"+sliceInteger+"_"+date;
}
nameNodeSliceElement.addContent(name);
nodeSliceElement.addContent(nameNodeSliceElement);
Element initialVisibility = new Element("visibility");
initialVisibility.addContent("0");
if (sliceInteger == -1){
nodeSliceElement.addContent(initialVisibility);
}
for (int a = 0; a < nodes[0].length; a++) {
Element placemarkElement = new Element("Placemark");
// Element visibility = new Element("visibility");
// visibility.addContent("1");
// placemarkElement.addContent(visibility);
if (sliceCount > 1) {
Element timeSpan = new Element("TimeSpan");
Element begin = new Element("begin");
if (!ancient) {
calendar.set(Calendar.YEAR, (int) Math.floor(date));
calendar.set(Calendar.DAY_OF_YEAR, (int) (365 * (date - Math.floor(date))));
begin.addContent(dateFormat.format(calendar.getTime()));
} else {
begin.addContent(Integer.toString((int)Math.round(date)));
}
timeSpan.addContent(begin);
placemarkElement.addContent(timeSpan);
}
placemarkElement.addContent(generateExtendedData(name, date));
if (useStyles) {
Element style = new Element("styleUrl");
if (sliceInteger == -1){
style.addContent("#" + ROOT_ELEMENT + date + "_style");
} else {
style.addContent("#" + NODE_ELEMENT + date + "_style");
}
placemarkElement.addContent(style);
}
Element pointElement = new Element("Point");
// Element altitudeMode = new Element("altitudeMode");
// altitudeMode.addContent("clampToGround");
// polygonElement.addContent(altitudeMode);
// Element tessellate = new Element("tessellate");
// tessellate.addContent("1");
// polygonElement.addContent(tessellate);
Element coordinates = new Element("coordinates");
coordinates.addContent(nodes[1][a]+","+nodes[0][a]+",0");
pointElement.addContent(coordinates);
placemarkElement.addContent(pointElement);
nodeSliceElement.addContent(placemarkElement);
}
return nodeSliceElement;
}
private Element generateExtendedData(String name, double date) {
Element data = new Element("ExtendedData");
Element schemaData = new Element("SchemaData");
schemaData.setAttribute("schemaUrl", "HPD_Schema");
schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(name));
// schemaData.addContent(new Element("SimpleData").setAttribute("name", "Description"));
schemaData.addContent(new Element("SimpleData").setAttribute("name", "Time").addContent(Double.toString(date)));
data.addContent(schemaData);
return data;
}
private void outputHeader(String[] traits) {
StringBuffer sb = new StringBuffer("slice");
for (int i = 0; i < traits.length; i++) {
// Load first value to check dimensionality
Trait trait = values.get(0).get(i).get(0);
if (trait.isMultivariate()) {
int dim = trait.getDim();
for (int j = 1; j <= dim; j++)
sb.append(sep).append(traits[i]).append(j);
} else
sb.append(sep).append(traits[i]);
}
sb.append("\n");
resultsStream.print(sb);
}
// private List<Tree> importTrees(String treeFileName, int burnin) throws IOException, Importer.ImportException {
// int totalTrees = 10000;
// progressStream.println("Reading trees (bar assumes 10,000 trees)...");
// progressStream.println("0 25 50 75 100");
// int stepSize = totalTrees / 60;
// if (stepSize < 1) stepSize = 1;
// List<Tree> treeList = new ArrayList<Tree>();
// BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
// String line1 = reader1.readLine();
// TreeImporter importer1;
// if (line1.toUpperCase().startsWith("#NEXUS")) {
// importer1 = new NexusImporter(new FileReader(treeFileName));
// } else {
// importer1 = new NewickImporter(new FileReader(treeFileName));
// totalTrees = 0;
// while (importer1.hasTree()) {
// Tree treeTime = importer1.importNextTree();
// if (totalTrees > burnin)
// treeList.add(treeTime);
// if (totalTrees > 0 && totalTrees % stepSize == 0) {
// progressStream.print("*");
// progressStream.flush();
// totalTrees++;
// return treeList;
private void readAndAnalyzeTrees(String treeFileName, int burnin, int skipEvery,
String[] traits, double[] slices,
boolean impute, boolean trueNoise, Normalization normalize,
boolean divideByBranchLength, BranchSet branchset, Set backboneTaxa)
throws IOException, Importer.ImportException {
int totalTrees = 10000;
int totalStars = 0;
progressStream.println("Reading and analyzing trees (bar assumes 10,000 trees)...");
progressStream.println("0 25 50 75 100");
progressStream.println("|
int stepSize = totalTrees / 60;
if (stepSize < 1) stepSize = 1;
BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
String line1 = reader1.readLine();
TreeImporter importer1;
if (line1.toUpperCase().startsWith("#NEXUS")) {
importer1 = new NexusImporter(new FileReader(treeFileName));
} else {
importer1 = new NewickImporter(new FileReader(treeFileName));
}
totalTrees = 0;
while (importer1.hasTree()) {
Tree treeTime = importer1.importNextTree();
if (totalTrees % skipEvery == 0) {
treesRead++;
if (totalTrees >= burnin) {
analyzeTree(treeTime, traits, slices, impute, trueNoise, normalize, divideByBranchLength, branchset, backboneTaxa);
}
}
if (totalTrees > 0 && totalTrees % stepSize == 0) {
progressStream.print("*");
totalStars++;
if (totalStars % 61 == 0)
progressStream.print("\n");
progressStream.flush();
}
totalTrees++;
}
progressStream.print("\n");
}
class Trait {
Trait(Object obj) {
this.obj = obj;
if (obj instanceof Object[]) {
isMultivariate = true;
array = (Object[]) obj;
}
}
public boolean isMultivariate() {
return isMultivariate;
}
public boolean isNumber() {
if (!isMultivariate)
return (obj instanceof Double);
return (array[0] instanceof Double);
}
public int getDim() {
if (isMultivariate) {
return array.length;
}
return 1;
}
public double[] getValue() {
int dim = getDim();
double[] result = new double[dim];
if (!isMultivariate) {
result[0] = (Double) obj;
} else {
for (int i = 0; i < dim; i++)
result[i] = (Double) array[i];
}
return result;
}
public void multiplyBy(double factor) {
if (!isMultivariate) {
obj = ((Double) obj * factor);
} else {
for (int i = 0; i < array.length; i++) {
array[i] = ((Double) array[i] * factor);
}
}
}
private Object obj;
private Object[] array;
private boolean isMultivariate = false;
public String toString() {
if (!isMultivariate)
return obj.toString();
StringBuffer sb = new StringBuffer(array[0].toString());
for (int i = 1; i < array.length; i++)
sb.append(sep).append(array[i]);
return sb.toString();
}
}
private List<List<List<Trait>>> values;
private List<List<Trait>> rootValues;
private void outputSlice(int slice, double sliceValue) {
List<List<Trait>> thisSlice = values.get(slice);
int traitCount = thisSlice.size();
int valueCount = thisSlice.get(0).size();
StringBuffer sb = new StringBuffer();
for (int v = 0; v < valueCount; v++) {
if (Double.isNaN(sliceValue))
sb.append("All");
else
sb.append(sliceValue);
for (int t = 0; t < traitCount; t++) {
sb.append(sep);
sb.append(thisSlice.get(t).get(v));
}
sb.append("\n");
}
resultsStream.print(sb);
}
private static boolean onBackbone(Tree tree, NodeRef node, Set targetSet) {
if (tree.isExternal(node)) return false;
Set leafSet = Tree.Utils.getDescendantLeaves(tree, node);
int size = leafSet.size();
leafSet.retainAll(targetSet);
if (leafSet.size() > 0) {
// if all leaves below are in target then check just above.
if (leafSet.size() == size) {
Set superLeafSet = Tree.Utils.getDescendantLeaves(tree, tree.getParent(node));
superLeafSet.removeAll(targetSet);
// the branch is on ancestral path if the super tree has some non-targets in it
return (superLeafSet.size() > 0);
} else return true;
} else return false;
}
private void analyzeTree(Tree treeTime, String[] traits, double[] slices, boolean impute,
boolean trueNoise, Normalization normalize, boolean divideByBranchlength, BranchSet branchset, Set backboneTaxa) {
double[][] precision = null;
if (impute) {
Object o = treeTime.getAttribute(PRECISION_STRING);
double treeNormalization = 1; // None
if (normalize == Normalization.LENGTH) {
treeNormalization = Tree.Utils.getTreeLength(treeTime, treeTime.getRoot());
} else if (normalize == Normalization.HEIGHT) {
treeNormalization = treeTime.getNodeHeight(treeTime.getRoot());
}
if (o != null) {
Object[] array = (Object[]) o;
int dim = (int) Math.sqrt(1 + 8 * array.length) / 2;
precision = new double[dim][dim];
int c = 0;
for (int i = 0; i < dim; i++) {
for (int j = i; j < dim; j++) {
precision[j][i] = precision[i][j] = ((Double) array[c++]) * treeNormalization;
}
}
}
}
// employed to get dispersal rates across the whole tree
// double treeNativeDistance = 0;
// double treeKilometerGreatCircleDistance = 0;
double[] treeSliceTime = new double[sliceCount];
double[] treeSliceDistance = new double[sliceCount];
double[] treeSliceMaxDistance = new double[sliceCount];
double[] treeTimeFromRoot = new double[sliceCount];
double[] maxDistanceFromRoot = new double[sliceCount];
//this one will used for weighted average (WA)
//double[] treeSliceDiffusionCoefficientWA = new double[sliceCount];
//this one is used for simple average
double[] treeSliceDiffusionCoefficientA = new double[sliceCount];
double[] treeSliceBranchCount = new double[sliceCount];
treeLengths.add(Tree.Utils.getTreeLength(treeTime, treeTime.getRoot()));
for (int x = 0; x < treeTime.getNodeCount(); x++) {
NodeRef node = treeTime.getNode(x);
if (!(treeTime.isRoot(node))) {
double nodeHeight = treeTime.getNodeHeight(node);
double parentHeight = treeTime.getNodeHeight(treeTime.getParent(node));
double oneOverBranchLength = 1.0;
if (divideByBranchlength) {
oneOverBranchLength = 1.0 / treeTime.getBranchLength(node);
}
boolean proceed = false;
if (branchset == BranchSet.ALL) {
proceed = true;
} else if (branchset == BranchSet.EXT && treeTime.isExternal(node)) {
proceed = true;
} else if (branchset == BranchSet.INT && !treeTime.isExternal(node)) {
proceed = true;
} else if (branchset == BranchSet.BACKBONE && onBackbone(treeTime, node, backboneTaxa)) {
proceed = true;
}
// employed to get dispersal rates across the whole tree
// if (containsLocation){
// Trait nodeLocationTrait = new Trait (treeTime.getNodeAttribute(node, LOCATIONTRAIT));
// Trait parentNodeLocationTrait = new Trait (treeTime.getNodeAttribute(treeTime.getParent(node), LOCATIONTRAIT));
// treeNativeDistance += getNativeDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue());
// treeKilometerGreatCircleDistance += getKilometerGreatCircleDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue());
for (int i = 0; i < sliceCount; i++) {
//System.out.println(slices[i]);
if (sdr) {
if (!doSlices ||
(slices[i] < nodeHeight)
) {
if (proceed) {
treeSliceTime[i] += (parentHeight - nodeHeight);
//TreeModel model = new TreeModel(treeTime, true);
//treeSliceDistance[i] += getKilometerGreatCircleDistance(model.getMultivariateNodeTrait(node, LOCATIONTRAIT),model.getMultivariateNodeTrait(model.getParent(node), LOCATIONTRAIT));
Trait nodeLocationTrait = new Trait(treeTime.getNodeAttribute(node, traits[0]));
Trait parentNodeLocationTrait = new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[0]));
treeSliceDistance[i] += getGeographicalDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue());
//treeSliceDiffusionCoefficientWA[i] += (Math.pow((getGeographicalDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue())),2.0)/(4.0*(parentHeight-nodeHeight)))*(parentHeight-nodeHeight);
treeSliceDiffusionCoefficientA[i] += (Math.pow((getGeographicalDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue())), 2.0) / (4.0 * (parentHeight - nodeHeight)));
treeSliceBranchCount[i]++;
}
}
}
double height = Double.MAX_VALUE;
if (i < sliceCount - 1) {
height = slices[i + 1];
}
if (!doSlices ||
((sliceMode == SliceMode.BRANCHES) && (slices[i] >= nodeHeight && slices[i] < parentHeight)) ||
((sliceMode == SliceMode.NODES) && (slices[i] < nodeHeight && height >= nodeHeight))
) {
if (proceed) {
List<List<Trait>> thisSlice = values.get(i);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = thisSlice.get(j);
Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
if (tmpTrait == null) {
System.err.println("Trait '" + traits[j] + "' not found on branch.");
System.exit(-1);
}
Trait trait = new Trait(tmpTrait);
//System.out.println("trees "+treesAnalyzed+"\tslice "+slices[i]+"\t"+trait.toString());
if (divideByBranchlength) {
trait.multiplyBy(oneOverBranchLength);
}
if (impute && (sliceMode == SliceMode.BRANCHES)) {
Double rateAttribute = (Double) treeTime.getNodeAttribute(node, RATE_STRING);
double rate = 1.0;
if (rateAttribute != null) {
rate = rateAttribute;
if (outputRateWarning) {
progressStream.println("Warning: using a rate attribute during imputation!");
outputRateWarning = false;
}
}
if (trueNoise && precision == null) {
progressStream.println("Error: not precision available for imputation with correct noise!");
System.exit(-1);
}
// if (slices[i] > nodeHeight) {
trait = imputeValue(trait, new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[j])),
slices[i], nodeHeight, parentHeight, precision, rate, trueNoise);
// QUESTION to PL: MAS does not see how slices[i] is ever less than nodeHeight
// } else if (impute && (sliceMode == SliceMode.NODES)) {
// progressStream.println("no imputation for slice mode = nodes");
}
thisTraitSlice.add(trait);
//System.out.println("trees "+treesAnalyzed+"\tslice "+slices[i]+"\t"+trait.toString());
//if trait is location
if (sdr) {
treeSliceTime[i] += (parentHeight - slices[i]);
Trait parentTrait = new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[j]));
treeSliceDistance[i] += getGeographicalDistance(trait.getValue(), parentTrait.getValue());
treeSliceDiffusionCoefficientA[i] += (Math.pow((getGeographicalDistance(trait.getValue(), parentTrait.getValue())), 2.0) / (4.0 * (parentHeight - slices[i])));
treeSliceBranchCount[i]++;
double tempDistanceFromRoot = getDistanceFromRoot(treeTime, traits[j], trait.getValue());
if (maxDistanceFromRoot[i] < tempDistanceFromRoot) {
maxDistanceFromRoot[i] = tempDistanceFromRoot;
treeSliceMaxDistance[i] = getPathDistance(treeTime, node, traits[j], trait.getValue());
//putting this below here ensures that treeTimeFromRoot is never < 0
treeTimeFromRoot[i] = treeTime.getNodeHeight(treeTime.getRoot()) - slices[i];
}
}
}
}
}
}
} else {
if (sliceMode == SliceMode.NODES) {
double nodeHeight = treeTime.getNodeHeight(node);
for (int i = 0; i < sliceCount; i++) {
double height = Double.MAX_VALUE;
if (i < sliceCount - 1) {
height = slices[i + 1];
}
if ((slices[i] < nodeHeight && height >= nodeHeight)){
List<List<Trait>> thisSlice = values.get(i);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = thisSlice.get(j);
Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
if (tmpTrait == null) {
System.err.println("Trait '" + traits[j] + "' not found on node.");
System.exit(-1);
}
Trait trait = new Trait(tmpTrait);
thisTraitSlice.add(trait);
}
}
}
for (int j = 0; j < traitCount; j++) {
List<Trait> thisRootTrait = rootValues.get(j);
Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
if (tmpTrait == null) {
System.err.println("Trait '" + traits[j] + "' not found on root node.");
System.exit(-1);
}
Trait trait = new Trait(tmpTrait);
thisRootTrait.add(trait);
}
}
}
}
//System.out.println(Tree.Utils.getTreeLength(treeTime, treeTime.getRoot())+"\t"+test);
if (sdr) {
sliceTreeDistanceArrays.add(treeSliceDistance);
sliceTreeTimeArrays.add(treeSliceTime);
sliceTreeMaxDistanceArrays.add(treeSliceMaxDistance);
sliceTreeTimeFromRootArrays.add(treeTimeFromRoot);
for (int i = 0; i < treeSliceDiffusionCoefficientA.length; i++) {
//treeSliceDiffusionCoefficientWA[i] = treeSliceDiffusionCoefficientWA[i]/treeSliceTime[i];
treeSliceDiffusionCoefficientA[i] = treeSliceDiffusionCoefficientA[i] / treeSliceBranchCount[i];
//System.out.println(treeSliceTime[i]+"\t"+treeLengths.get(i));
}
sliceTreeDiffusionCoefficientArrays.add(treeSliceDiffusionCoefficientA);
}
// employed to get dispersal rates across the whole tree
// if (containsLocation) {
// double treelength = Tree.Utils.getTreeLength(treeTime, treeTime.getRoot());
// double dispersalNativeRate = treeNativeDistance/treelength;
// double dispersalKilometerRate = treeKilometerGreatCircleDistance/treelength;
//System.out.println(dispersalNativeRate+"\t"+dispersalKilometerRate);
// dispersalrates.add(dispersalNativeRate+"\t"+dispersalKilometerRate);
treesAnalyzed++;
}
// employed to get dispersal rates across the whole tree
// private static double getNativeDistance(double[] location1, double[] location2) {
// return Math.sqrt(Math.pow((location2[0]-location1[0]),2.0)+Math.pow((location2[1]-location1[1]),2.0));
private static double getGeographicalDistance(double[] location1, double[] location2) {
if (location1.length == 1) {
// assume we only have latitude so put them on the prime meridian
return getKilometerGreatCircleDistance(new double[] { location1[0], 0.0}, new double[] { location2[0], 0.0});
} else if (location1.length == 2) {
return getKilometerGreatCircleDistance(location1, location2);
}
throw new RuntimeException("Distances can only be calculated for longitude and latitude (or just latitude)");
}
private static double getKilometerGreatCircleDistance(double[] location1, double[] location2) {
SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(location1[0], location1[1]);
SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(location2[0], location2[1]);
return (coord1.distance(coord2));
}
private double getPathDistance(Tree tree, NodeRef node, String locationTrait, double[] sliceTrait) {
double pathDistance = 0;
NodeRef parentNode = tree.getParent(node);
Trait parentTrait = new Trait(tree.getNodeAttribute(parentNode, locationTrait));
pathDistance += getGeographicalDistance(sliceTrait, parentTrait.getValue());
while (parentNode != tree.getRoot()) {
node = tree.getParent(node);
parentNode = tree.getParent(parentNode);
Trait nodeTrait = new Trait(tree.getNodeAttribute(node, locationTrait));
parentTrait = new Trait(tree.getNodeAttribute(parentNode, locationTrait));
pathDistance += getGeographicalDistance(nodeTrait.getValue(), parentTrait.getValue());
}
return pathDistance;
}
private double getDistanceFromRoot(Tree tree, String locationTrait, double[] sliceTrait) {
NodeRef rootNode = tree.getRoot();
Trait rootTrait = new Trait(tree.getNodeAttribute(rootNode, locationTrait));
return getGeographicalDistance(sliceTrait, rootTrait.getValue());
}
private int traitCount;
private int sliceCount;
private String[] traits;
private double[] sliceHeights;
private boolean sliceProgressReport;
private boolean checkSliceContours;
private boolean doSlices;
private int treesRead = 0;
private int treesAnalyzed = 0;
private double mostRecentSamplingDate;
private ContourMode contourMode;
private SliceMode sliceMode;
private boolean ancient = false;
private boolean useStyles = false;
// employed to get dispersal rates across the whole tree
// private static boolean containsLocation = false;
// private static ArrayList dispersalrates = new ArrayList();
// private void run(List<Tree> trees, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
// for (Tree treeTime : trees) {
// analyzeTree(treeTime, traits, slices, impute, trueNoise);
private ArrayList sliceTreeDistanceArrays = new ArrayList();
private ArrayList sliceTreeTimeArrays = new ArrayList();
private ArrayList sliceTreeMaxDistanceArrays = new ArrayList();
private ArrayList sliceTreeTimeFromRootArrays = new ArrayList();
private ArrayList sliceTreeDiffusionCoefficientArrays = new ArrayList();
private boolean sdr;
private ArrayList treeLengths = new ArrayList();
private boolean outputRateWarning = true;
private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) {
if (!nodeTrait.isNumber()) {
System.err.println("Can only impute numbers!");
System.exit(-1);
}
int dim = nodeTrait.getDim();
double[] nodeValue = nodeTrait.getValue();
double[] parentValue = parentTrait.getValue();
final double scaledTimeChild = (time - nodeHeight) * rate;
final double scaledTimeParent = (parentHeight - time) * rate;
final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent;
if (scaledTimeChild == 0)
return nodeTrait;
if (scaledTimeParent == 0)
return parentTrait;
// Find mean value, weighted average
double[] mean = new double[dim];
double[][] scaledPrecision = new double[dim][dim];
for (int i = 0; i < dim; i++) {
mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal;
if (trueNoise) {
for (int j = i; j < dim; j++)
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal;
}
}
if (trueNoise) {
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision);
}
Object[] result = new Object[dim];
for (int i = 0; i < dim; i++)
result[i] = mean[i];
return new Trait(result);
}
// Messages to stderr, output to stdout
private static PrintStream progressStream = System.err;
private PrintStream resultsStream;
private final static Version version = new BeastVersion();
private static final String commandName = "timeslicer";
public static void printUsage(Arguments arguments) {
arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: " + commandName + " test.trees out.kml");
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printTitle() {
progressStream.println();
centreLine("TimeSlicer " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC Output analysis", 60);
centreLine("by", 60);
centreLine("Marc A. Suchard, Philippe Lemey,", 60);
centreLine("Alexei J. Drummond and Andrew Rambaut", 60);
progressStream.println();
centreLine("Department of Biomathematics", 60);
centreLine("University of California, Los Angeles", 60);
centreLine("msuchard@ucla.edu", 60);
progressStream.println();
centreLine("Rega Institute for Medical Research", 60);
centreLine("Katholieke Universiteit Leuven", 60);
centreLine("philippe.lemey@gmail.com", 60);
progressStream.println();
centreLine("Department of Computer Science", 60);
centreLine("University of Auckland", 60);
centreLine("alexei@cs.auckland.ac.nz", 60);
progressStream.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
progressStream.println();
progressStream.println();
}
public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
List<Double> returnList = new ArrayList<Double>();
StringTokenizer st = new StringTokenizer(inString, ",");
while (st.hasMoreTokens()) {
try {
returnList.add(Double.parseDouble(st.nextToken()));
} catch (NumberFormatException e) {
throw new Arguments.ArgumentException();
}
}
if (returnList.size() > 0) {
double[] doubleArray = new double[returnList.size()];
for (int i = 0; i < doubleArray.length; i++)
doubleArray[i] = returnList.get(i);
return doubleArray;
}
return null;
}
private static String[] parseVariableLengthStringArray(String inString) {
List<String> returnList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(inString, ",");
while (st.hasMoreTokens()) {
returnList.add(st.nextToken());
}
if (returnList.size() > 0) {
String[] stringArray = new String[returnList.size()];
stringArray = returnList.toArray(stringArray);
return stringArray;
}
return null;
}
private static double[] parseFileWithArray(String file) {
List<Double> returnList = new ArrayList<Double>();
try {
BufferedReader readerTimes = new BufferedReader(new FileReader(file));
String line = readerTimes.readLine();
while (line != null && !line.equals("")) {
returnList.add(Double.valueOf(line));
line = readerTimes.readLine();
}
} catch (IOException e) {
System.err.println("Error reading " + file);
System.exit(1);
}
if (returnList.size() > 0) {
double[] doubleArray = new double[returnList.size()];
for (int i = 0; i < doubleArray.length; i++)
doubleArray[i] = returnList.get(i);
//System.out.println(doubleArray.length);
return doubleArray;
}
return null;
}
public static String getKMLColor(double value, double[] minMaxMedian, String startColor, String endColor) {
startColor = startColor.toLowerCase();
String startBlue = startColor.substring(0, 2);
String startGreen = startColor.substring(2, 4);
String startRed = startColor.substring(4, 6);
endColor = endColor.toLowerCase();
String endBlue = endColor.substring(0, 2);
String endGreen = endColor.substring(2, 4);
String endRed = endColor.substring(4, 6);
double proportion = (value - minMaxMedian[0]) / (minMaxMedian[1] - minMaxMedian[0]);
// generate an array with hexadecimal code for each RGB entry number
String[] colorTable = new String[256];
int colorTableCounter = 0;
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
colorTable[colorTableCounter] = a + "" + b;
colorTableCounter++;
}
for (int c = (int) ('a'); c < 6 + (int) ('a'); c++) {
colorTable[colorTableCounter] = a + "" + (char) c;
colorTableCounter++;
}
}
for (int d = (int) ('a'); d < 6 + (int) ('a'); d++) {
for (int e = 0; e < 10; e++) {
colorTable[colorTableCounter] = (char) d + "" + e;
colorTableCounter++;
}
for (int f = (int) ('a'); f < 6 + (int) ('a'); f++) {
colorTable[colorTableCounter] = (char) d + "" + (char) f;
colorTableCounter++;
}
}
int startBlueInt = 0;
int startGreenInt = 0;
int startRedInt = 0;
int endBlueInt = 0;
int endGreenInt = 0;
int endRedInt = 0;
for (int i = 0; i < colorTable.length; i++) {
if (colorTable[i].equals(startBlue)) {
startBlueInt = i;
}
if (colorTable[i].equals(startGreen)) {
startGreenInt = i;
}
if (colorTable[i].equals(startRed)) {
startRedInt = i;
}
if (colorTable[i].equals(endBlue)) {
endBlueInt = i;
}
if (colorTable[i].equals(endGreen)) {
endGreenInt = i;
}
if (colorTable[i].equals(endRed)) {
endRedInt = i;
}
}
int blueInt = startBlueInt + (int) Math.round((endBlueInt - startBlueInt) * proportion);
int greenInt = startGreenInt + (int) Math.round((endGreenInt - startGreenInt) * proportion);
int redInt = startRedInt + (int) Math.round((endRedInt - startRedInt) * proportion);
String blue = null;
String green = null;
String red = null;
for (int j = 0; j < colorTable.length; j++) {
if (j == blueInt) {
blue = colorTable[j];
}
if (j == greenInt) {
green = colorTable[j];
}
if (j == redInt) {
red = colorTable[j];
}
}
return blue + green + red;
}
private static double[] getHPDInterval(double proportion, double[] array, int[] indices) {
double returnArray[] = new double[2];
double minRange = Double.MAX_VALUE;
int hpdIndex = 0;
int diff = (int) Math.round(proportion * (double) array.length);
for (int i = 0; i <= (array.length - diff); i++) {
double minValue = array[indices[i]];
double maxValue = array[indices[i + diff - 1]];
double range = Math.abs(maxValue - minValue);
if (range < minRange) {
minRange = range;
hpdIndex = i;
}
}
returnArray[0] = array[indices[hpdIndex]];
returnArray[1] = array[indices[hpdIndex + diff - 1]];
return returnArray;
}
private static void print2DArray(double[][] array, String name) {
try {
PrintWriter outFile = new PrintWriter(new FileWriter(name), true);
for (double[] anArray : array) {
for (int j = 0; j < array[0].length; j++) {
outFile.print(anArray[j] + "\t");
}
outFile.println("");
}
outFile.close();
} catch (IOException io) {
System.err.print("Error writing to file: " + name);
}
}
private static void print2DTransposedArray(double[][] array, String name) {
try {
PrintWriter outFile = new PrintWriter(new FileWriter(name), true);
for (int i = 0; i < array[0].length; i++) {
for (double[] anArray : array) {
outFile.print(anArray[i] + "\t");
}
outFile.println("");
}
outFile.close();
} catch (IOException io) {
System.err.print("Error writing to file: " + name);
}
}
private static double[] meanColNoNaN(double[][] x) {
double[] returnArray = new double[x[0].length];
for (int i = 0; i < x[0].length; i++) {
double m = 0.0;
int lenNoZero = 0;
for (int j = 0; j < x.length; j++) {
if (!(((Double) x[j][i]).isNaN())) {
m += x[j][i];
lenNoZero += 1;
}
}
returnArray[i] = m / (double) lenNoZero;
}
return returnArray;
}
private static double[][] getArrayHPDintervals(double[][] array) {
double[][] returnArray = new double[array[0].length][2];
for (int col = 0; col < array[0].length; col++) {
int counter = 0;
for (int row = 0; row < array.length; row++) {
if (!(((Double) array[row][col]).isNaN())) {
counter += 1;
}
}
if (counter > 0) {
double[] columnNoNaNArray = new double[counter];
int index = 0;
for (int row = 0; row < array.length; row++) {
if (!(((Double) array[row][col]).isNaN())) {
columnNoNaNArray[index] = array[row][col];
index += 1;
}
}
int[] indices = new int[counter];
HeapSort.sort(columnNoNaNArray, indices);
double hpdBinInterval[] = getHPDInterval(0.95, columnNoNaNArray, indices);
returnArray[col][0] = hpdBinInterval[0];
returnArray[col][1] = hpdBinInterval[1];
} else {
returnArray[col][0] = Double.NaN;
returnArray[col][1] = Double.NaN;
}
}
return returnArray;
}
private static Set getTargetSet(String x) {
Set targetSet = null;
targetSet = new HashSet();
try {
BufferedReader reader = new BufferedReader(new FileReader(x));
try {
String line = reader.readLine().trim();
while (line != null && !line.equals("")) {
targetSet.add(line);
line = reader.readLine();
if (line != null) line = line.trim();
}
}
catch (IOException io) {
System.err.println("Error reading " + x);
}
}
catch (FileNotFoundException a) {
System.err.println("Error finding " + x);
}
return targetSet;
}
public static void main(String[] args) throws IOException {
String inputFileName = null;
String outputFileName = null;
String[] traitNames = null;
double[] sliceHeights = null;
OutputFormat outputFormat = OutputFormat.KML;
boolean impute = false;
boolean trueNoise = true;
boolean summaryOnly = false;
ContourMode contourMode = ContourMode.SNYDER;
Normalization normalize = Normalization.LENGTH;
int burnin = -1;
int skipEvery = 1;
double mrsd = 0;
double hpdValue = 0.80;
String outputFileSDR = null;
boolean getSDR = false;
String progress = null;
boolean branchNormalization = false;
BranchSet set = BranchSet.ALL;
Set backboneTaxa = null;
SliceMode sliceMode = SliceMode.BRANCHES;
// if (args.length == 0) {
// // TODO Make flash GUI
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"),
new Arguments.IntegerOption(SKIP, "skip every i'th tree [default = 0]"),
new Arguments.StringOption(TRAIT, "trait_name", "specifies an attribute-list to use to create a density map [default = location.rate]"),
new Arguments.StringOption(SLICE_TIMES, "slice_times", "specifies a slice time-list [default=none]"),
new Arguments.StringOption(SLICE_HEIGHTS, "slice_heights", "specifies a slice height-list [default=none]"),
new Arguments.StringOption(SLICE_FILE_HEIGHTS, "heights_file", "specifies a file with a slice heights-list, is overwritten by command-line specification of slice heights [default=none]"),
new Arguments.StringOption(SLICE_FILE_TIMES, "Times_file", "specifies a file with a slice Times-list, is overwritten by command-line specification of slice times [default=none]"),
new Arguments.IntegerOption(SLICE_COUNT, "the number of time slices to use [default=0]"),
new Arguments.StringOption(SLICE_MODE, "Slice_mode", "specifies how to perform the slicing [default=branches]"),
new Arguments.RealOption(START_TIME, "the time of the earliest slice [default=0]"),
new Arguments.RealOption(MRSD, "specifies the most recent sampling data in fractional years to rescale time [default=0]"),
new Arguments.Option(HELP, "option to print this message"),
new Arguments.StringOption(NOISE, falseTrue, false,
"add true noise [default = true])"),
new Arguments.StringOption(IMPUTE, falseTrue, false,
"impute trait at time-slice [default = false]"),
new Arguments.StringOption(SUMMARY, falseTrue, false,
"compute summary statistics [default = true]"),
new Arguments.StringOption(FORMAT, enumNamesToStringArray(OutputFormat.values()), false,
"summary output format [default = KML]"),
new Arguments.IntegerOption(HPD, "mass (1 - 99%) to include in HPD regions [default = 80]"),
new Arguments.StringOption(CONTOUR_MODE, enumNamesToStringArray(ContourMode.values()), false,
"contouring model [default = snyder]"),
new Arguments.StringOption(NORMALIZATION, enumNamesToStringArray(Normalization.values()), false,
"tree normalization [default = length"),
new Arguments.StringOption(SDR, "sliceDispersalRate", "specifies output file name for dispersal rates for each slice (from previous sliceTime[or root of the trees] up to current sliceTime"),
new Arguments.StringOption(PROGRESS, "progress report", "reports slice progress and checks the bivariate contour HPD regions by calculating what fraction of points the polygons for a given slice contain [default = false]"),
new Arguments.StringOption(BRANCH_NORMALIZE, falseTrue, false,
"devide a branch trait by branch length (can be useful for 'rewards' [default = false]"),
new Arguments.StringOption(BRANCHSET, TimeSlicer.enumNamesToStringArray(BranchSet.values()), false,
"branch set [default = all]"),
new Arguments.StringOption(BACKBONETAXA, "Backbone taxa file", "specifies a file with taxa that define the backbone"),
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption(HELP)) {
printUsage(arguments);
System.exit(0);
}
try { // Make sense of arguments
String sliceHeightsFileString = arguments.getStringOption(SLICE_FILE_HEIGHTS);
if (sliceHeightsFileString != null) {
sliceHeights = parseFileWithArray(sliceHeightsFileString);
}
if (arguments.hasOption(MRSD)) {
mrsd = arguments.getRealOption(MRSD);
}
String sliceTimesFileString = arguments.getStringOption(SLICE_FILE_TIMES);
if (sliceTimesFileString != null) {
//System.out.println(sliceTimesFileString);
double[] sliceTimes = parseFileWithArray(sliceTimesFileString);
sliceHeights = new double[sliceTimes.length];
for (int i = 0; i < sliceTimes.length; i++) {
if (mrsd == 0) {
sliceHeights[i] = sliceTimes[i];
} else {
//System.out.println((mrsd - sliceTimes[i]));
sliceHeights[i] = mrsd - sliceTimes[i];
}
}
}
String sliceModeString = arguments.getStringOption(SLICE_MODE);
if (sliceModeString != null) {
sliceMode = SliceMode.valueOf(sliceModeString.toUpperCase());
}
if (arguments.hasOption(BURNIN)) {
burnin = arguments.getIntegerOption(BURNIN);
System.err.println("Ignoring a burnin of " + burnin + " trees.");
}
if (arguments.hasOption(SKIP)) {
skipEvery = arguments.getIntegerOption(SKIP);
System.err.println("Skipping every " + skipEvery + " trees.");
}
if (skipEvery < 1) {
skipEvery = 1;
}
if (arguments.hasOption(HPD)) {
int intValue = arguments.getIntegerOption(HPD);
if (intValue < 1 || intValue > 99) {
progressStream.println("HPD Region mass falls outside of 1 - 99% range.");
System.exit(-1);
}
hpdValue = intValue / 100.0;
}
String traitString = arguments.getStringOption(TRAIT);
if (traitString != null) {
traitNames = parseVariableLengthStringArray(traitString);
//employed to get dispersal rates across the whole tree
// for (int y = 0; y < traitNames.length; y++) {
// if (traitNames[y].equals(LOCATIONTRAIT)){
// containsLocation = true;
}
if (traitNames == null) {
traitNames = new String[1];
traitNames[0] = "location.rate";
}
String sliceTimeString = arguments.getStringOption(SLICE_TIMES);
if (sliceTimeString != null) {
double[] sliceTimes = parseVariableLengthDoubleArray(sliceTimeString);
sliceHeights = new double[sliceTimes.length];
for (int i = 0; i < sliceTimes.length; i++) {
if (mrsd == 0) {
sliceHeights[i] = sliceTimes[i];
} else {
sliceHeights[i] = mrsd - sliceTimes[i];
}
}
}
String sliceHeightString = arguments.getStringOption(SLICE_HEIGHTS);
if (sliceHeightString != null) {
if (sliceTimeString != null) {
progressStream.println("Either sliceTimes, sliceHeights, timesFile or sliceCount" +
"nt.");
System.exit(-1);
}
sliceHeights = parseVariableLengthDoubleArray(sliceHeightString);
}
if (arguments.hasOption(SLICE_COUNT)) {
int sliceCount = arguments.getIntegerOption(SLICE_COUNT);
double startTime = arguments.getRealOption(START_TIME);
double delta;
if (mrsd != 0) {
delta = (mrsd - startTime) / (sliceCount - 1);
} else {
delta = startTime / (sliceCount - 1);
}
sliceHeights = new double[sliceCount];
// double height = mrsd - startTime;
// for (int i = 0; i < sliceCount; i++) {
// sliceHeights[i] = height;
// height -= delta;
double height = 0;
for (int i = 0; i < sliceCount; i++) {
sliceHeights[i] = height;
height += delta;
}
}
//sorting sliceHeights
Arrays.sort(sliceHeights);
String imputeString = arguments.getStringOption(IMPUTE);
if (imputeString != null && imputeString.compareToIgnoreCase("true") == 0)
impute = true;
String branchNormString = arguments.getStringOption(BRANCH_NORMALIZE);
if (branchNormString != null && branchNormString.compareToIgnoreCase("true") == 0)
branchNormalization = true;
String noiseString = arguments.getStringOption(NOISE);
if (noiseString != null && noiseString.compareToIgnoreCase("false") == 0)
trueNoise = false;
String summaryString = arguments.getStringOption(SUMMARY);
if (summaryString != null && summaryString.compareToIgnoreCase("true") == 0)
summaryOnly = true;
String modeString = arguments.getStringOption(CONTOUR_MODE);
if (modeString != null) {
contourMode = ContourMode.valueOf(modeString.toUpperCase());
if (contourMode == ContourMode.R && !ContourWithR.processWithR)
contourMode = ContourMode.SNYDER;
}
String normalizeString = arguments.getStringOption(NORMALIZATION);
if (normalizeString != null) {
normalize = Normalization.valueOf(normalizeString.toUpperCase());
}
String summaryFormat = arguments.getStringOption(FORMAT);
if (summaryFormat != null) {
outputFormat = OutputFormat.valueOf(summaryFormat.toUpperCase());
}
String sdrString = arguments.getStringOption(SDR);
if (sdrString != null) {
outputFileSDR = sdrString;
getSDR = true;
}
String progressString = arguments.getStringOption(PROGRESS);
if (progressString != null) {
progress = progressString;
}
String branch = arguments.getStringOption(BRANCHSET);
if (branch != null) {
set = BranchSet.valueOf(branch.toUpperCase());
System.out.println("Using the branch set: " + set.name());
}
if (set == set.BACKBONE) {
if (arguments.hasOption(BACKBONETAXA)) {
backboneTaxa = getTargetSet(arguments.getStringOption(BACKBONETAXA));
} else {
System.err.println("you want to summarize the backbone, but have no taxa to define it??");
}
}
} catch (Arguments.ArgumentException e) {
progressStream.println(e);
printUsage(arguments);
System.exit(-1);
}
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 0:
printUsage(arguments);
System.exit(1);
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
System.err.println("Unknown option: " + args2[2]);
System.err.println();
printUsage(arguments);
System.exit(1);
}
}
TimeSlicer timeSlicer = new TimeSlicer(inputFileName, burnin, skipEvery, traitNames, sliceHeights, impute,
trueNoise, mrsd, contourMode, sliceMode, normalize, getSDR, progress, branchNormalization, set, backboneTaxa);
timeSlicer.output(outputFileName, summaryOnly, outputFormat, hpdValue, outputFileSDR);
System.exit(0);
}
}
|
package org.links.objecthash;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* TODO(phad): docs.
*/
public class ObjectHash implements Comparable<ObjectHash> {
private static final int SHA256_BLOCK_SIZE = 32;
private static final String SHA256 = "SHA-256";
private static final Logger LOG = Logger.getLogger(ObjectHash.class.getName());
private byte[] hash;
private MessageDigest digester;
private enum JsonType {
BOOLEAN,
ARRAY,
OBJECT,
INT,
FLOAT,
STRING,
NULL,
UNKNOWN
}
private ObjectHash() throws NoSuchAlgorithmException {
this.hash = new byte[SHA256_BLOCK_SIZE];
this.digester = MessageDigest.getInstance(SHA256);
}
private void hashAny(Object obj) throws NoSuchAlgorithmException,
JSONException {
digester.reset();
JsonType outerType = getType(obj);
switch (outerType) {
case ARRAY: {
hashList((JSONArray) obj);
break;
}
case OBJECT: {
hashObject((JSONObject) obj);
break;
}
case INT: {
hashInteger(obj);
break;
}
case STRING: {
hashString((String) obj);
break;
}
case NULL: {
hashNull();
break;
}
case BOOLEAN: {
hashBoolean((Boolean) obj);
break;
}
case FLOAT: {
hashDouble((Double) obj);
break;
}
default: {
throw new IllegalArgumentException("Illegal type in JSON: "
+ obj.getClass());
}
}
}
private void hashTaggedBytes(char tag, byte[] bytes)
throws NoSuchAlgorithmException {
digester.reset();
digester.update((byte) tag);
digester.update(bytes);
hash = digester.digest();
}
private void hashString(String str) throws NoSuchAlgorithmException {
hashTaggedBytes('u', str.getBytes());
}
private void hashInteger(Object value) throws NoSuchAlgorithmException {
String str = value.toString();
hashTaggedBytes('i', str.getBytes());
}
private void hashDouble(Double value) throws NoSuchAlgorithmException {
String normalized = normalizeFloat(value);
hashTaggedBytes('f', normalized.getBytes());
}
private void hashNull() throws NoSuchAlgorithmException {
hashTaggedBytes('n', "".getBytes());
}
private void hashBoolean(boolean bool) throws NoSuchAlgorithmException {
hashTaggedBytes('b', (bool ? "1" : "0").getBytes());
}
private void hashList(JSONArray list) throws NoSuchAlgorithmException,
JSONException {
digester.reset();
digester.update((byte) ('l'));
for (int n = 0; n < list.length(); ++n) {
ObjectHash innerObject = new ObjectHash();
innerObject.hashAny(list.get(n));
digester.update(innerObject.hash());
}
hash = digester.digest();
}
private String debugString(Iterable<ByteBuffer> buffers) {
StringBuilder sb = new StringBuilder();
for (ByteBuffer buff : buffers) {
sb.append('\n');
sb.append(toHex(buff.array()));
}
return sb.toString();
}
private void hashObject(JSONObject obj) throws NoSuchAlgorithmException,
JSONException {
List<ByteBuffer> buffers = new ArrayList<ByteBuffer>();
Comparator<ByteBuffer> ordering = new Comparator<ByteBuffer>() {
@Override
public int compare(ByteBuffer left, ByteBuffer right) {
return toHex(left.array()).compareTo(toHex(right.array()));
}
};
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
ByteBuffer buff = ByteBuffer.allocate(2 * SHA256_BLOCK_SIZE);
String key = keys.next();
// TODO(phad): would be nice to chain all these calls builder-stylee.
ObjectHash hKey = new ObjectHash();
hKey.hashString(key);
ObjectHash hVal = new ObjectHash();
hVal.hashAny(obj.get(key));
buff.put(hKey.hash());
buff.put(hVal.hash());
buffers.add(buff);
}
Collections.sort(buffers, ordering);
digester.reset();
digester.update((byte) 'd');
for (ByteBuffer buff : buffers) {
digester.update(buff.array());
}
hash = digester.digest();
}
private static int parseHex(char digit) {
assert ((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f'));
if (digit >= '0' && digit <= '9') {
return digit - '0';
} else {
return 10 + digit - 'a';
}
}
public static ObjectHash fromHex(String hex) throws NoSuchAlgorithmException {
ObjectHash h = new ObjectHash();
hex = hex.toLowerCase();
if (hex.length() % 2 == 1) {
hex = '0' + hex;
}
// TODO(phad): maybe just use Int.valueOf(s).intValue()
int pos = SHA256_BLOCK_SIZE;
for (int idx = hex.length(); idx > 0; idx -= 2) {
h.hash[--pos] = (byte) (16 * parseHex(hex.charAt(idx - 2))
+ parseHex(hex.charAt(idx - 1)));
}
return h;
}
private static JsonType getType(Object jsonObj) {
if (jsonObj == JSONObject.NULL) {
return JsonType.NULL;
} else if (jsonObj instanceof JSONArray) {
return JsonType.ARRAY;
} else if (jsonObj instanceof JSONObject) {
return JsonType.OBJECT;
} else if (jsonObj instanceof String) {
return JsonType.STRING;
} else if (jsonObj instanceof Integer || jsonObj instanceof Long) {
return JsonType.INT;
} else if (jsonObj instanceof Double) {
return JsonType.FLOAT;
} else if (jsonObj instanceof Boolean) {
return JsonType.BOOLEAN;
} else {
LOG.warning("jsonObj is_a " + jsonObj.getClass());
return JsonType.UNKNOWN;
}
}
public static ObjectHash commonJsonHash(String json)
throws JSONException, NoSuchAlgorithmException {
// TODO(phad): implement 'commonizing' of JSON values.
return new ObjectHash();
}
public static ObjectHash pythonJsonHash(String json)
throws JSONException, NoSuchAlgorithmException {
ObjectHash h = new ObjectHash();
h.hashAny(new JSONTokener(json).nextValue());
return h;
}
@Override
public String toString() {
return this.toHex();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if (this.getClass() != other.getClass()) return false;
return this.toHex().equals(((ObjectHash) other).toHex());
}
@Override
public int compareTo(ObjectHash other) {
return toHex().compareTo(other.toHex());
}
public byte[] hash() {
return hash;
}
private static String toHex(byte[] buffer) {
StringBuffer hexString = new StringBuffer();
for (int idx = 0; idx < buffer.length; ++idx) {
String hex = Integer.toHexString(0xff & buffer[idx]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public String toHex() {
return toHex(hash);
}
static String normalizeFloat(double f) {
// Early out for zero.
if (f == 0.0) {
return "+0:";
}
StringBuffer sb = new StringBuffer();
// Sign
sb.append(f < 0.0 ? '-' : '+');
if (f < 0.0) f = -f;
// Exponent
int e = 0;
while (f > 1) {
f /= 2;
e += 1;
}
while (f < 0.5) {
f *= 2;
e -= 1;
}
sb.append(e);
sb.append(':');
// Mantissa
if (f > 1 || f <= 0.5) {
throw new IllegalStateException("wrong range for mantissa");
}
while (f != 0) {
if (f >= 1) {
sb.append('1');
f -= 1;
} else {
sb.append('0');
}
if (f >= 1) {
throw new IllegalStateException("oops, f is too big");
}
if (sb.length() > 1000) {
throw new IllegalStateException("things have got out of hand");
}
f *= 2;
}
return sb.toString();
}
}
|
package org.mariadb.jdbc;
import org.mariadb.jdbc.internal.SQLExceptionMapper;
import org.mariadb.jdbc.internal.common.QueryException;
import org.mariadb.jdbc.internal.common.Utils;
import org.mariadb.jdbc.internal.common.query.MySQLQuery;
import org.mariadb.jdbc.internal.common.query.Query;
import org.mariadb.jdbc.internal.common.queryresults.ModifyQueryResult;
import org.mariadb.jdbc.internal.common.queryresults.QueryResult;
import org.mariadb.jdbc.internal.common.queryresults.ResultSetType;
import org.mariadb.jdbc.internal.mysql.MySQLProtocol;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
public class MySQLStatement implements Statement {
/**
* the protocol used to talk to the server.
*/
private final MySQLProtocol protocol;
/**
* the Connection object.
*/
protected MySQLConnection connection;
/**
* The actual query result.
*/
private QueryResult queryResult;
/**
* are warnings cleared?
*/
private boolean warningsCleared;
private int queryTimeout;
private boolean escapeProcessing;
private int fetchSize;
private int maxRows;
boolean isClosed;
private static volatile Timer timer;
private TimerTask timerTask;
boolean isTimedout;
volatile boolean executing;
List<Query> batchQueries;
Queue<Object> cachedResultSets;
protected boolean isRewriteable = true;
protected String firstRewrite = null;
protected ResultSet batchResultSet = null;
public boolean isStreaming() {
return fetchSize == Integer.MIN_VALUE;
}
/**
* Creates a new Statement.
* @param connection the connection to return in getConnection.
*/
public MySQLStatement(MySQLConnection connection) {
this.protocol = connection.getProtocol();
this.connection = connection;
this.escapeProcessing = true;
cachedResultSets = new LinkedList<Object>();
}
/**
* returns the protocol.
*
* @return the protocol used.
*/
public MySQLProtocol getProtocol() {
return protocol;
}
private static Timer getTimer() {
Timer result = timer;
if (result == null) {
synchronized(MySQLStatement.class) {
result = timer;
if (result == null) {
timer = result = new Timer("MariaDB-JDBC-Timer", true);
}
}
}
return result;
}
// Part of query prolog - setup timeout timer
private void setTimerTask() {
assert(timerTask == null);
timerTask = new TimerTask() {
@Override
public void run() {
try {
isTimedout = true;
protocol.cancelCurrentQuery();
} catch (Throwable e) {
}
}
};
getTimer().schedule(timerTask, queryTimeout*1000);
}
// Part of query prolog - check if connection is broken and reconnect
private void checkReconnect() throws SQLException {
if (protocol.shouldReconnect()) {
try {
protocol.connect();
} catch (QueryException qe) {
SQLExceptionMapper.throwException(qe, connection, this);
}
} else if (protocol.shouldTryFailback()) {
try {
protocol.reconnectToMaster();
} catch (Exception e) {
// Do nothing
}
}
}
void executeQueryProlog() throws SQLException{
if (isClosed()) {
throw new SQLException("execute() is called on closed statement");
}
checkReconnect();
if (protocol.isClosed()){
throw new SQLException("execute() is called on closed connection");
}
if (protocol.hasUnreadData()) {
throw new SQLException("There is an open result set on the current connection, "+
"which must be closed prior to executing a query");
}
if (protocol.hasMoreResults()) {
// Skip remaining result sets. CallableStatement might return many of them -
// not only the "select" result sets, but also the "update" results
while(getMoreResults(true)) {
}
}
cachedResultSets.clear();
MySQLConnection conn = (MySQLConnection)getConnection();
conn.reenableWarnings();
try {
protocol.setMaxRows(maxRows);
} catch(QueryException qe) {
SQLExceptionMapper.throwException(qe, connection, this);
}
if (queryTimeout != 0) {
setTimerTask();
}
}
private void cacheMoreResults() {
if (isStreaming())
return;
QueryResult saveResult = queryResult;
for(;;) {
try {
if (protocol.hasMoreResults()) {
getMoreResults(false);
cachedResultSets.add(queryResult);
} else {
break;
}
} catch(SQLException e) {
cachedResultSets.add(e);
break;
}
}
queryResult = saveResult;
}
/*
Reset timeout after query, re-throw SQL exception
*/
private void executeQueryEpilog(QueryException e, Query query) throws SQLException{
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (isTimedout) {
isTimedout = false;
e = new QueryException("Query timed out", 1317, "JZ0002", e);
}
if (e == null)
return;
/* Include query into exception message, if dumpQueriesOnException is true,
* or on SQL syntax error (MySQL error code 1064).
*
* If SQL query is too long, truncate it to reasonable (for exception messages)
* length.
*/
if (protocol.getInfo().getProperty("dumpQueriesOnException", "false").equalsIgnoreCase("true")
|| e.getErrorCode() == 1064 ) {
String queryString = query.toString();
if (queryString.length() > 4096) {
queryString = queryString.substring(0, 4096);
}
e.setMessage(e.getMessage()+ "\nQuery is:\n" + queryString);
}
SQLExceptionMapper.throwException(e, connection, this);
}
/**
* executes a query.
*
* @param query the query
* @return true if there was a result set, false otherwise.
* @throws SQLException
*/
protected boolean execute(Query query) throws SQLException {
//System.out.println(query);
synchronized (protocol) {
if (protocol.activeResult != null) {
protocol.activeResult.close();
}
executing = true;
QueryException exception = null;
executeQueryProlog();
try {
batchResultSet = null;
queryResult = protocol.executeQuery(query, isStreaming());
cacheMoreResults();
return (queryResult.getResultSetType() == ResultSetType.SELECT);
} catch (QueryException e) {
exception = e;
return false;
} finally {
executeQueryEpilog(exception, query);
executing = false;
}
}
}
/**
* Execute statements. if many queries, those queries will be rewritten
* if isRewritable = false, the query will be agreggated :
* INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...')
* INSERT INTO jdbc (`name`) VALUES ('Line 2: Lorem ipsum ...')
* will be agreggate as
* INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...');INSERT INTO jdbc (`name`) VALUES ('Line 2: Lorem ipsum ...')
* and if isRewritable, agreggated as
* INSERT INTO jdbc (`name`) VALUES ('Line 1: Lorem ipsum ...'),('Line 2: Lorem ipsum ...')
* @param queries list of queries
* @param isRewritable are the queries of the same type to be agreggated
* @param rewriteOffset offset of the parameter if query are similar
* @return true if there was a result set, false otherwise.
* @throws SQLException
*/
protected boolean execute(List<Query> queries, boolean isRewritable, int rewriteOffset) throws SQLException {
//System.out.println(query);
synchronized (protocol) {
if (protocol.activeResult != null) {
protocol.activeResult.close();
}
executing = true;
QueryException exception = null;
executeQueryProlog();
try {
batchResultSet = null;
queryResult = protocol.executeQuery(queries, isStreaming(), isRewritable, rewriteOffset);
cacheMoreResults();
return (queryResult.getResultSetType() == ResultSetType.SELECT);
} catch (QueryException e) {
exception = e;
return false;
} finally {
executeQueryEpilog(exception, queries.get(0));
executing = false;
}
}
}
/**
* executes a select query.
*
* @param query the query to send to the server
* @return a result set
* @throws SQLException if something went wrong
*/
protected ResultSet executeQuery(Query query) throws SQLException {
if (execute(query)) {
return getResultSet();
}
//throw new SQLException("executeQuery() with query '" + query +"' did not return a result set");
return MySQLResultSet.EMPTY;
}
/**
* Executes an update.
*
* @param query the update query.
* @return update count
* @throws SQLException if the query could not be sent to server.
*/
protected int executeUpdate(Query query) throws SQLException {
if (execute(query))
return 0;
return getUpdateCount();
}
private Query stringToQuery(String queryString) throws SQLException {
if (escapeProcessing) {
queryString = Utils.nativeSQL(queryString,connection.noBackslashEscapes);
}
return new MySQLQuery(queryString);
}
/**
* executes a query.
*
* @param queryString the query
* @return true if there was a result set, false otherwise.
* @throws SQLException if the query could not be sent to server
*/
public boolean execute(String queryString) throws SQLException {
return execute(stringToQuery(queryString));
}
/**
* Executes an update.
*
* @param queryString the update query.
* @return update count
* @throws SQLException if the query could not be sent to server.
*/
public int executeUpdate(String queryString) throws SQLException {
return executeUpdate(stringToQuery(queryString));
}
/**
* executes a select query.
*
* @param queryString the query to send to the server
* @return a result set
* @throws SQLException if something went wrong
*/
public ResultSet executeQuery(String queryString) throws SQLException {
return executeQuery(stringToQuery(queryString));
}
/**
* Releases this <code>Statement</code> object's database and JDBC resources immediately instead of waiting for this
* to happen when it is automatically closed. It is generally good practice to release resources as soon as you are
* finished with them to avoid tying up database resources.
*
* Calling the method <code>close</code> on a <code>Statement</code> object that is already closed has no effect.
*
* <B>Note:</B>When a <code>Statement</code> object is closed, its current <code>ResultSet</code> object, if one
* exists, is also closed.
*
* @throws java.sql.SQLException if a database access error occurs
*/
public void close() throws SQLException {
if (queryResult != null) {
queryResult.close();
queryResult = null;
}
// No possible future use for the cached results, so these can be cleared
// This makes the cache eligible for garbage collection earlier if the statement is not
// immediately garbage collected
cachedResultSets.clear();
if (isStreaming()) {
synchronized (protocol) {
// Skip all outstanding result sets
while(getMoreResults(true)) {
}
}
}
isClosed = true;
}
/**
* Retrieves the maximum number of bytes that can be returned for character and binary column values in a
* <code>ResultSet</code> object produced by this <code>Statement</code> object. This limit applies only to
* <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>, <code>VARCHAR</code>,
* <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and <code>LONGVARCHAR</code> columns. If
* the limit is exceeded, the excess data is silently discarded.
*
* @return the current column size limit for columns storing character and binary values; zero means there is no
* limit
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #setMaxFieldSize
*/
public int getMaxFieldSize() throws SQLException {
return 0;
}
/**
* Sets the limit for the maximum number of bytes that can be returned for character and binary column values in a
* <code>ResultSet</code> object produced by this <code>Statement</code> object.
*
* This limit applies only to <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>,
* <code>CHAR</code>, <code>VARCHAR</code>, <code>NCHAR</code>, <code>NVARCHAR</code>, <code>LONGNVARCHAR</code> and
* <code>LONGVARCHAR</code> fields. If the limit is exceeded, the excess data is silently discarded. For maximum
* portability, use values greater than 256.
*
* @param max the new column size limit in bytes; zero means there is no limit
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the condition max >= 0 is not satisfied
* @see #getMaxFieldSize
*/
public void setMaxFieldSize(final int max) throws SQLException {
//we dont support max field sizes
}
/**
* Retrieves the maximum number of rows that a <code>ResultSet</code> object produced by this <code>Statement</code>
* object can contain. If this limit is exceeded, the excess rows are silently dropped.
*
* @return the current maximum number of rows for a <code>ResultSet</code> object produced by this
* <code>Statement</code> object; zero means there is no limit
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #setMaxRows
*/
public int getMaxRows() throws SQLException {
return maxRows;
}
/**
* Sets the limit for the maximum number of rows that any <code>ResultSet</code> object generated by this
* <code>Statement</code> object can contain to the given number. If the limit is exceeded, the excess rows are
* silently dropped.
*
* @param max the new max rows limit; zero means there is no limit
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the condition max >= 0 is not satisfied
* @see #getMaxRows
*/
public void setMaxRows(final int max) throws SQLException {
if (max < 0) {
throw new SQLException("max rows is negative");
}
maxRows = max;
}
/**
* Sets escape processing on or off. If escape scanning is on (the default), the driver will do escape substitution
* before sending the SQL statement to the database.
*
* Note: Since prepared statements have usually been parsed prior to making this call, disabling escape processing
* for <code>PreparedStatements</code> objects will have no effect.
*
* @param enable <code>true</code> to enable escape processing; <code>false</code> to disable it
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
*/
public void setEscapeProcessing(final boolean enable) throws SQLException {
escapeProcessing = enable;
}
/**
* Retrieves the number of seconds the driver will wait for a <code>Statement</code> object to execute. If the limit
* is exceeded, a <code>SQLException</code> is thrown.
*
* @return the current query timeout limit in seconds; zero means there is no limit
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #setQueryTimeout
*/
public int getQueryTimeout() throws SQLException {
return queryTimeout;
}
/**
* Sets the number of seconds the driver will wait for a <code>Statement</code> object to execute to the given
* number of seconds. If the limit is exceeded, an <code>SQLException</code> is thrown. A JDBC driver must apply
* this limit to the <code>execute</code>, <code>executeQuery</code> and <code>executeUpdate</code> methods. JDBC
* driver implementations may also apply this limit to <code>ResultSet</code> methods (consult your driver vendor
* documentation for details).
*
* @param seconds the new query timeout limit in seconds; zero means there is no limit
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the condition seconds >= 0 is not satisfied
* @see #getQueryTimeout
*/
public void setQueryTimeout(final int seconds) throws SQLException {
this.queryTimeout = seconds;
}
/**
* Sets the inputStream that will be used for the next execute that uses
* "LOAD DATA LOCAL INFILE". The name specified as local file/URL will be
* ignored.
*
* @param inputStream inputStream instance, that will be used to send data to server
*/
public void setLocalInfileInputStream(InputStream inputStream) {
protocol.setLocalInfileInputStream(inputStream);
}
/**
* Cancels this <code>Statement</code> object if both the DBMS and driver support aborting an SQL statement. This
* method can be used by one thread to cancel a statement that is being executed by another thread.
*
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
*/
public void cancel() throws SQLException {
try {
if (!executing) {
return;
}
protocol.cancelCurrentQuery();
} catch (QueryException e) {
SQLExceptionMapper.throwException(e, connection, this);
}
catch (IOException e) {
// connection gone, query is definitely canceled
}
}
/**
* Retrieves the first warning reported by calls on this <code>Statement</code> object. Subsequent
* <code>Statement</code> object warnings will be chained to this <code>SQLWarning</code> object.
*
* The warning chain is automatically cleared each time a statement is (re)executed. This method may not be
* called on a closed <code>Statement</code> object; doing so will cause an <code>SQLException</code> to be thrown.
*
* <P><B>Note:</B> If you are processing a <code>ResultSet</code> object, any warnings associated with reads on that
* <code>ResultSet</code> object will be chained on it rather than on the <code>Statement</code> object that
* produced it.
*
* @return the first <code>SQLWarning</code> object or <code>null</code> if there are no warnings
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
*/
public SQLWarning getWarnings() throws SQLException {
if (!warningsCleared) {
return this.connection.getWarnings();
}
return null;
}
/**
* Clears all the warnings reported on this <code>Statement</code> object. After a call to this method, the method
* <code>getWarnings</code> will return <code>null</code> until a new warning is reported for this
* <code>Statement</code> object.
*
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
*/
public void clearWarnings() throws SQLException {
warningsCleared = true;
}
/**
* Sets the SQL cursor name to the given <code>String</code>, which will be used by subsequent
* <code>Statement</code> object <code>execute</code> methods. This name can then be used in SQL positioned update
* or delete statements to identify the current row in the <code>ResultSet</code> object generated by this
* statement. If the database does not support positioned update/delete, this method is a noop. To insure that a
* cursor has the proper isolation level to support updates, the cursor's <code>SELECT</code> statement should have
* the form <code>SELECT FOR UPDATE</code>. If <code>FOR UPDATE</code> is not present, positioned updates may
* fail.
*
* <P><B>Note:</B> By definition, the execution of positioned updates and deletes must be done by a different
* <code>Statement</code> object than the one that generated the <code>ResultSet</code> object being used for
* positioning. Also, cursor names must be unique within a connection.
*
* @param name the new cursor name, which must be unique within a connection
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
*/
public void setCursorName(final String name) throws SQLException {
throw SQLExceptionMapper.getFeatureNotSupportedException("Cursors are not supported");
}
/**
* gets the connection that created this statement
*
* @return the connection
* @throws SQLException if connection is invalid
*/
public Connection getConnection() throws SQLException {
return this.connection;
}
/**
* Moves to this <code>Statement</code> object's next result, deals with any current <code>ResultSet</code>
* object(s) according to the instructions specified by the given flag, and returns <code>true</code> if the next
* result is a <code>ResultSet</code> object.
*
* There are no more results when the following is true: <pre> // stmt is a Statement object
* ((stmt.getMoreResults(current) == false) && (stmt.getUpdateCount() == -1))</pre>
*
*
* @param current one of the following <code>Statement</code> constants indicating what should happen to current
* <code>ResultSet</code> objects obtained using the method <code>getResultSet</code>:
* <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code>, or
* <code>Statement.CLOSE_ALL_RESULTS</code>
* @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an
* update count or there are no more results
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the argument supplied is not one of the following:
* <code>Statement.CLOSE_CURRENT_RESULT</code>, <code>Statement.KEEP_CURRENT_RESULT</code>
* or <code>Statement.CLOSE_ALL_RESULTS</code>
* @throws java.sql.SQLFeatureNotSupportedException
* if <code>DatabaseMetaData.supportsMultipleOpenResults</code> returns
* <code>false</code> and either <code>Statement.KEEP_CURRENT_RESULT</code> or
* <code>Statement.CLOSE_ALL_RESULTS</code> are supplied as the argument.
* @see #execute
* @since 1.4
*/
public boolean getMoreResults(final int current) throws SQLException {
return getMoreResults();
}
/**
* Retrieves any auto-generated keys created as a result of executing this <code>Statement</code> object. If this
* <code>Statement</code> object did not generate any keys, an empty <code>ResultSet</code> object is returned.
*
* <B>Note:</B>If the columns which represent the auto-generated keys were not specified, the JDBC driver
* implementation will determine the columns which best represent the auto-generated keys.
*
* @return a <code>ResultSet</code> object containing the auto-generated key(s) generated by the execution of this
* <code>Statement</code> object
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
* @since 1.4
*/
public ResultSet getGeneratedKeys() throws SQLException {
if (batchResultSet != null) {
return batchResultSet;
}
if (queryResult != null && queryResult.getResultSetType() == ResultSetType.MODIFY) {
long insertId = ((ModifyQueryResult)queryResult).getInsertId();
if (insertId == 0) {
return MySQLResultSet.createEmptyGeneratedKeysResultSet(connection);
}
int updateCount = getUpdateCount();
return MySQLResultSet.createGeneratedKeysResultSet(insertId, updateCount, connection);
}
return MySQLResultSet.EMPTY;
}
/**
* Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys
* produced by this <code>Statement</code> object should be made available for retrieval. The driver will ignore
* the flag if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement able to return
* auto-generated keys (the list of such statements is vendor-specific).
*
* @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>,
* <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing,
* such as a DDL statement.
* @param autoGeneratedKeys a flag indicating whether auto-generated keys should be made available for retrieval;
* one of the following constants: <code>Statement.RETURN_GENERATED_KEYS</code>
* <code>Statement.NO_GENERATED_KEYS</code>
* @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements
* that return nothing
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code>, the given SQL statement returns a <code>ResultSet</code>
* object, or the given constant is not one of those allowed
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method with a constant of
* Statement.RETURN_GENERATED_KEYS
* @since 1.4
*/
public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException {
return executeUpdate(sql);
}
/**
* Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array
* should be made available for retrieval. This array contains the indexes of the columns in the target table that
* contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL
* statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the
* list of such statements is vendor-specific).
*
* @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>,
* <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such
* as a DDL statement.
* @param columnIndexes an array of column indexes indicating the columns that should be returned from the inserted
* row
* @return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements
* that return nothing
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object,
* or the second argument supplied to this method is not an <code>int</code> array
* whose elements are valid column indexes
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
* @since 1.4
*/
public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException {
return executeUpdate(sql);
}
/**
* Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array
* should be made available for retrieval. This array contains the names of the columns in the target table that
* contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL
* statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the
* list of such statements is vendor-specific).
*
* @param sql an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>,
* <code>UPDATE</code> or <code>DELETE</code>; or an SQL statement that returns nothing, such as
* a DDL statement.
* @param columnNames an array of the names of the columns that should be returned from the inserted row
* @return either the row count for <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code> statements, or
* 0 for SQL statements that return nothing
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code>, the SQL statement returns a <code>ResultSet</code> object,
* or the second argument supplied to this method is not a <code>String</code> array
* whose elements are valid column names
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
* @since 1.4
*/
public int executeUpdate(final String sql, final String[] columnNames) throws SQLException {
return executeUpdate(sql);
}
/**
* Executes the given SQL statement, which may return multiple results, and signals the driver that any
* auto-generated keys should be made available for retrieval. The driver will ignore this signal if the SQL
* statement is not an <code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the
* list of such statements is vendor-specific).
*
* In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts.
* Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple
* results or (2) you are dynamically executing an unknown SQL string.
*
* The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must
* then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and
* <code>getMoreResults</code> to move to any subsequent result(s).
*
* @param sql any SQL statement
* @param autoGeneratedKeys a constant indicating whether auto-generated keys should be made available for retrieval
* using the method <code>getGeneratedKeys</code>; one of the following constants:
* <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>
* @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an
* update count or there are no results
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the second parameter supplied to this method is not
* <code>Statement.RETURN_GENERATED_KEYS</code> or <code>Statement.NO_GENERATED_KEYS</code>.
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method with a constant of
* Statement.RETURN_GENERATED_KEYS
* @see #getResultSet
* @see #getUpdateCount
* @see #getMoreResults
* @see #getGeneratedKeys
* @since 1.4
*/
public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException {
return execute(sql); // auto generated keys are always available
}
/**
* Executes the given SQL statement, which may return multiple results, and signals the driver that the
* auto-generated keys indicated in the given array should be made available for retrieval. This array contains the
* indexes of the columns in the target table that contain the auto-generated keys that should be made available.
* The driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL
* statement able to return auto-generated keys (the list of such statements is vendor-specific).
*
* Under some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts.
* Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple
* results or (2) you are dynamically executing an unknown SQL string.
*
* The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must
* then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and
* <code>getMoreResults</code> to move to any subsequent result(s).
*
* @param sql any SQL statement
* @param columnIndexes an array of the indexes of the columns in the inserted row that should be made available
* for retrieval by a call to the method <code>getGeneratedKeys</code>
* @return <code>true</code> if the first result is a <code>ResultSet</code> object; <code>false</code> if it is an
* update count or there are no results
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the elements in the <code>int</code> array passed to this
* method are not valid column indexes
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
* @see #getResultSet
* @see #getUpdateCount
* @see #getMoreResults
* @since 1.4
*/
public boolean execute(final String sql, final int[] columnIndexes) throws SQLException {
return execute(sql);
}
/**
* Executes the given SQL statement, which may return multiple results, and signals the driver that the
* auto-generated keys indicated in the given array should be made available for retrieval. This array contains the
* names of the columns in the target table that contain the auto-generated keys that should be made available. The
* driver will ignore the array if the SQL statement is not an <code>INSERT</code> statement, or an SQL statement
* able to return auto-generated keys (the list of such statements is vendor-specific).
*
* In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts.
* Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple
* results or (2) you are dynamically executing an unknown SQL string.
*
* The <code>execute</code> method executes an SQL statement and indicates the form of the first result. You must
* then use the methods <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the result, and
* <code>getMoreResults</code> to move to any subsequent result(s).
*
* @param sql any SQL statement
* @param columnNames an array of the names of the columns in the inserted row that should be made available for
* retrieval by a call to the method <code>getGeneratedKeys</code>
* @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an
* update count or there are no more results
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the elements of the <code>String</code> array passed to
* this method are not valid column names
* @throws java.sql.SQLFeatureNotSupportedException
* if the JDBC driver does not support this method
* @see #getResultSet
* @see #getUpdateCount
* @see #getMoreResults
* @see #getGeneratedKeys
* @since 1.4
*/
public boolean execute(final String sql, final String[] columnNames) throws SQLException {
return execute(sql);
}
/**
* Retrieves the result set holdability for <code>ResultSet</code> objects generated by this <code>Statement</code>
* object.
*
* @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @since 1.4
*/
public int getResultSetHoldability() throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
/**
* Retrieves whether this <code>Statement</code> object has been closed. A <code>Statement</code> is closed if the
* method close has been called on it, or if it is automatically closed.
*
* @return true if this <code>Statement</code> object is closed; false if it is still open
* @throws java.sql.SQLException if a database access error occurs
* @since 1.6
*/
public boolean isClosed() throws SQLException {
return isClosed;
}
/**
* Requests that a <code>Statement</code> be pooled or not pooled. The value specified is a hint to the statement
* pool implementation indicating whether the applicaiton wants the statement to be pooled. It is up to the
* statement pool manager as to whether the hint is used.
*
* The poolable value of a statement is applicable to both internal statement caches implemented by the driver and
* external statement caches implemented by application servers and other applications.
*
* By default, a <code>Statement</code> is not poolable when created, and a <code>PreparedStatement</code> and
* <code>CallableStatement</code> are poolable when created.
*
*
* @param poolable requests that the statement be pooled if true and that the statement not be pooled if false
*
* @throws java.sql.SQLException if this method is called on a closed <code>Statement</code>
*
* @since 1.6
*/
public void setPoolable(final boolean poolable) throws SQLException {
}
/**
* Returns a value indicating whether the <code>Statement</code> is poolable or not.
*
*
* @return <code>true</code> if the <code>Statement</code> is poolable; <code>false</code> otherwise
*
* @throws java.sql.SQLException if this method is called on a closed <code>Statement</code>
*
* @see java.sql.Statement#setPoolable(boolean) setPoolable(boolean)
* @since 1.6
*
*/
public boolean isPoolable() throws SQLException {
return false;
}
public ResultSet getResultSet() throws SQLException {
if (queryResult == null || queryResult.getResultSetType() != ResultSetType.SELECT) {
return null; /* Result is an update count, or there are no more results */
}
return new MySQLResultSet(queryResult,this,protocol, connection.cal);
}
public int getUpdateCount() throws SQLException {
if (queryResult == null || queryResult.getResultSetType() == ResultSetType.SELECT) {
return -1; /* Result comes from SELECT , or there are no more results */
}
return (int) ((ModifyQueryResult) queryResult).getUpdateCount();
}
private boolean getMoreResults(boolean streaming) throws SQLException {
try {
synchronized(protocol) {
if (queryResult != null) {
queryResult.close();
}
queryResult = protocol.getMoreResults(streaming);
if(queryResult == null) return false;
warningsCleared = false;
connection.reenableWarnings();
return true;
}
} catch (QueryException e) {
SQLExceptionMapper.throwException(e, connection, this);
return false;
}
}
/**
* Moves to this <code>Statement</code> object's next result, returns <code>true</code> if it is a
* <code>ResultSet</code> object, and implicitly closes any current <code>ResultSet</code> object(s) obtained with
* the method <code>getResultSet</code>.
*
* There are no more results when the following is true: <pre> // stmt is a Statement object
* ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1)) </pre>
*
* @return <code>true</code> if the next result is a <code>ResultSet</code> object; <code>false</code> if it is an
* update count or there are no more results
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #execute
*/
public boolean getMoreResults() throws SQLException {
if (!isStreaming()) {
/* return pre-cached result set, if available */
if(cachedResultSets.isEmpty()) {
queryResult = null;
return false;
}
Object o = cachedResultSets.remove();
if (o instanceof SQLException)
throw (SQLException)o;
queryResult = (QueryResult)o;
return true;
}
return getMoreResults(false);
}
/**
* Gives the driver a hint as to the direction in which rows will be processed in <code>ResultSet</code> objects
* created using this <code>Statement</code> object. The default value is <code>ResultSet.FETCH_FORWARD</code>.
*
* Note that this method sets the default fetch direction for result sets generated by this <code>Statement</code>
* object. Each result set has its own methods for getting and setting its own fetch direction.
*
* @param direction the initial direction for processing rows
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the given direction is not one of
* <code>ResultSet.FETCH_FORWARD</code>, <code>ResultSet.FETCH_REVERSE</code>, or
* <code>ResultSet.FETCH_UNKNOWN</code>
* @see #getFetchDirection
* @since 1.2
*/
public void setFetchDirection(final int direction) throws SQLException {
}
/**
* Retrieves the direction for fetching rows from database tables that is the default for result sets generated from
* this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch direction by
* calling the method <code>setFetchDirection</code>, the return value is implementation-specific.
*
* @return the default fetch direction for result sets generated from this <code>Statement</code> object
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #setFetchDirection
* @since 1.2
*/
public int getFetchDirection() throws SQLException {
return ResultSet.FETCH_FORWARD;
}
/**
* Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are
* needed for <code>ResultSet</code> objects genrated by this <code>Statement</code>. If the value specified is
* zero, then the hint is ignored. The default value is zero.
*
* @param rows the number of rows to fetch
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the condition <code>rows >= 0</code> is not satisfied.
* @see #getFetchSize
* @since 1.2
*/
public void setFetchSize(final int rows) throws SQLException {
if (rows < 0 && rows != Integer.MIN_VALUE)
throw new SQLException("invalid fetch size");
this.fetchSize = rows;
}
/**
* Retrieves the number of result set rows that is the default fetch size for <code>ResultSet</code> objects
* generated from this <code>Statement</code> object. If this <code>Statement</code> object has not set a fetch size
* by calling the method <code>setFetchSize</code>, the return value is implementation-specific.
*
* @return the default fetch size for result sets generated from this <code>Statement</code> object
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @see #setFetchSize
* @since 1.2
*/
public int getFetchSize() throws SQLException {
return this.fetchSize;
}
/**
* Retrieves the result set concurrency for <code>ResultSet</code> objects generated by this <code>Statement</code>
* object.
*
* @return either <code>ResultSet.CONCUR_READ_ONLY</code> or <code>ResultSet.CONCUR_UPDATABLE</code>
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @since 1.2
*/
public int getResultSetConcurrency() throws SQLException {
return ResultSet.CONCUR_READ_ONLY;
}
/**
* Retrieves the result set type for <code>ResultSet</code> objects generated by this <code>Statement</code>
* object.
*
* @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @throws java.sql.SQLException if a database access error occurs or this method is called on a closed
* <code>Statement</code>
* @since 1.2
*/
public int getResultSetType() throws SQLException {
// TODO: this will change when the async protocol is implemented
return ResultSet.TYPE_SCROLL_INSENSITIVE;
}
/**
* Adds the given SQL command to the current list of commmands for this <code>Statement</code> object. The commands
* in this list can be executed as a batch by calling the method <code>executeBatch</code>.
*
*
* @param sql typically this is a SQL <code>INSERT</code> or <code>UPDATE</code> statement
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the driver does not support batch updates
* @see #executeBatch
* @see java.sql.DatabaseMetaData#supportsBatchUpdates
* @since 1.2
*/
public void addBatch(final String sql) throws SQLException {
if (batchQueries == null) {
batchQueries = new ArrayList<Query>();
}
isInsertRewriteable(sql);
batchQueries.add(new MySQLQuery(sql));
}
/**
* Parses the sql string to understand whether it is compatible with rewritten batches.
* @param sql the sql string
*/
protected void isInsertRewriteable(String sql) {
if (!isRewriteable) {
return;
}
int index = getInsertIncipit(sql);
if (index == -1) {
isRewriteable = false;
return;
}
if (firstRewrite == null) {
firstRewrite = sql.substring(0, index);
}
boolean isRewrite = sql.startsWith(firstRewrite);
if (isRewrite) {
isRewriteable = isRewriteable && true;
}
}
/**
* Parses the input string to understand if it is an INSERT statement.
* Returns the position of the round bracket after the VALUE(S) SQL keyword,
* or -1 if it cannot understand it is an INSERT statement.
* Multiple statements cannot be parsed.
* @param sql the input SQL statement
* @return the position of the round bracket after the VALUE(S) SQL keyword,
* or -1 if it cannot be parsed as an INSERT statement
*/
protected int getInsertIncipit(String sql) {
String sqlUpper = sql.toUpperCase();
if (! sqlUpper.startsWith("INSERT"))
return -1;
int idx = sqlUpper.indexOf(" VALUE");
int startBracket = sqlUpper.indexOf("(", idx);
int endBracket = sqlUpper.indexOf(")", startBracket);
// Check for semicolons. Allow them inside the VALUES() brackets, otherwise return -1
// there can be multiple, so let's loop through them
int semicolonPos = sqlUpper.indexOf(';');
while (semicolonPos > -1)
{
if (semicolonPos < startBracket || semicolonPos > endBracket)
return -1;
semicolonPos = sqlUpper.indexOf(';', semicolonPos + 1);
}
return startBracket;
}
/**
* Empties this <code>Statement</code> object's current list of SQL commands.
*
*
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the driver does not support batch updates
* @see #addBatch
* @see java.sql.DatabaseMetaData#supportsBatchUpdates
* @since 1.2
*/
public void clearBatch() throws SQLException {
if (batchQueries != null) {
batchQueries.clear();
}
firstRewrite = null;
isRewriteable = true;
}
/**
* Submits a batch of commands to the database for execution and if all commands execute successfully, returns an
* array of update counts. The <code>int</code> elements of the array that is returned are ordered to correspond to
* the commands in the batch, which are ordered according to the order in which they were added to the batch. The
* elements in the array returned by the method <code>executeBatch</code> may be one of the following: <OL> <LI>A
* number greater than or equal to zero -- indicates that the command was processed successfully and is an update
* count giving the number of rows in the database that were affected by the command's execution <LI>A value of
* <code>SUCCESS_NO_INFO</code> -- indicates that the command was processed successfully but that the number of rows
* affected is unknown
*
* If one of the commands in a batch update fails to execute properly, this method throws a
* <code>BatchUpdateException</code>, and a JDBC driver may or may not continue to process the remaining commands in
* the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to
* process commands or never continuing to process commands. If the driver continues processing after a failure,
* the array returned by the method <code>BatchUpdateException.getUpdateCounts</code> will contain as many elements
* as there are commands in the batch, and at least one of the elements will be the following:
*
* <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command failed to execute successfully and
* occurs only if a driver continues to process commands after a command fails </OL>
*
* The possible implementations and return values have been modified in the Java 2 SDK, Standard Edition, version
* 1.3 to accommodate the option of continuing to proccess commands in a batch update after a
* <code>BatchUpdateException</code> obejct has been thrown.
*
* @return an array of update counts containing one element for each command in the batch. The elements of the
* array are ordered according to the order in which commands were added to the batch.
* @throws java.sql.SQLException if a database access error occurs, this method is called on a closed
* <code>Statement</code> or the driver does not support batch statements. Throws
* {@link java.sql.BatchUpdateException} (a subclass of <code>SQLException</code>) if
* one of the commands sent to the database fails to execute properly or attempts to
* return a result set.
* @see #addBatch
* @see java.sql.DatabaseMetaData#supportsBatchUpdates
* @since 1.3
*/
public int[] executeBatch() throws SQLException {
if (batchQueries == null || batchQueries.size() == 0) return new int[0];
int[] ret = new int[batchQueries.size()];
int i = 0;
MySQLResultSet rs = null;
boolean allowMultiQueries = "true".equals(getProtocol().getInfo().getProperty("allowMultiQueries"));
boolean rewriteBatchedStatements = "true".equals(getProtocol().getInfo().getProperty("rewriteBatchedStatements"));
if (rewriteBatchedStatements) allowMultiQueries=true;
try {
synchronized (this.protocol) {
if (allowMultiQueries) {
int size = batchQueries.size();
boolean rewrittenBatch = isRewriteable && rewriteBatchedStatements;
MySQLStatement ps = (MySQLStatement) connection.createStatement();
ps.execute(batchQueries, rewrittenBatch, rewrittenBatch?firstRewrite.length():0);
return rewrittenBatch?getUpdateCountsForReWrittenBatch(ps, size):getUpdateCounts(ps, size);
} else {
for(; i < batchQueries.size(); i++) {
execute(batchQueries.get(i));
int updateCount = getUpdateCount();
if (updateCount == -1) {
ret[i] = SUCCESS_NO_INFO;
} else {
ret[i] = updateCount;
}
if (i == 0) {
rs = (MySQLResultSet)getGeneratedKeys();
} else {
rs = rs.joinResultSets((MySQLResultSet)getGeneratedKeys());
}
}
}
}
} catch (SQLException sqle) {
throw new BatchUpdateException(sqle.getMessage(), sqle.getSQLState(), sqle.getErrorCode(), Arrays.copyOf(ret, i), sqle);
} finally {
clearBatch();
}
batchResultSet = rs;
return ret;
}
/**
* Retrieves the update counts for the batched statements rewritten as
* a multi query. The rewritten statement must have been executed already.
* @param statement the rewritten statement
* @return an array of update counts containing one element for each command in the batch.
* The elements of the array are ordered according to the order in which commands were added to the batch.
* @param size
* @throws SQLException
*/
protected int[] getUpdateCounts(Statement statement, int size) throws SQLException {
int[] result = new int[size];
int updateCount;
for (int count=0; count<size; count++) {
updateCount = statement.getUpdateCount();
if (updateCount == -1) {
result[count] = SUCCESS_NO_INFO;
} else {
result[count] = updateCount;
}
statement.getMoreResults();
}
return result;
}
protected int[] getUpdateCountsForReWrittenBatch(Statement statement, int size) throws SQLException {
int[] result = new int[size];
int resultVal = statement.getUpdateCount() == size ? 1 : SUCCESS_NO_INFO;
for (int count = 0; count < size; count++) {
result[count] = resultVal;
}
return result;
}
/**
* Returns an object that implements the given interface to allow access to non-standard methods, or standard
* methods not exposed by the proxy.
*
* If the receiver implements the interface then the result is the receiver or a proxy for the receiver. If the
* receiver is a wrapper and the wrapped object implements the interface then the result is the wrapped object or a
* proxy for the wrapped object. Otherwise return the the result of calling <code>unwrap</code> recursively on the
* wrapped object or a proxy for that result. If the receiver is not a wrapper and does not implement the interface,
* then an <code>SQLException</code> is thrown.
*
* @param iface A Class defining an interface that the result must implement.
* @return an object that implements the interface. May be a proxy for the actual implementing object.
* @throws java.sql.SQLException If no object found that implements the interface
* @since 1.6
*/
@SuppressWarnings("unchecked")
public <T> T unwrap(final Class<T> iface) throws SQLException {
try {
if (isWrapperFor(iface)) {
return (T)this;
} else {
throw new SQLException("The receiver is not a wrapper and does not implement the interface");
}
} catch (Exception e) {
throw new SQLException("The receiver is not a wrapper and does not implement the interface");
}
}
/**
* Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an
* object that does. Returns false otherwise. If this implements the interface then return true, else if this is a
* wrapper then return the result of recursively calling <code>isWrapperFor</code> on the wrapped object. If this
* does not implement the interface and is not a wrapper, return false. This method should be implemented as a
* low-cost operation compared to <code>unwrap</code> so that callers can use this method to avoid expensive
* <code>unwrap</code> calls that may fail. If this method returns true then calling <code>unwrap</code> with the
* same argument should succeed.
*
* @param interfaceOrWrapper a Class defining an interface.
* @return true if this implements the interface or directly or indirectly wraps an object that does.
* @throws java.sql.SQLException if an error occurs while determining whether this is a wrapper for an object with
* the given interface.
* @since 1.6
*/
public boolean isWrapperFor(final Class<?> interfaceOrWrapper) throws SQLException {
return interfaceOrWrapper.isInstance(this);
}
/**
* returns the query result.
*
* @return the queryresult
*/
protected QueryResult getQueryResult() {
return queryResult;
}
/**
* sets the current query result
*
* @param result
*/
protected void setQueryResult(final QueryResult result) {
this.queryResult = result;
}
public void closeOnCompletion() throws SQLException {
// TODO Auto-generated method stub
}
public boolean isCloseOnCompletion() throws SQLException {
// TODO Auto-generated method stub
return false;
}
public static void unloadDriver() {
if (timer != null)
timer.cancel();
}
}
|
package com.kierdavis.kmail;
import java.util.Arrays;
import java.util.Iterator;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class KMailCommandExecutor implements CommandExecutor {
private KMail plugin;
public KMailCommandExecutor(KMail plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length < 1) {
return doHelp(sender, args);
}
String subcmd = args[0];
args = Arrays.copyOfRange(args, 1, args.length);
if (subcmd.equalsIgnoreCase("help")) {
return doHelp(sender, args);
}
if (subcmd.equalsIgnoreCase("send")) {
return doSend(sender, args);
}
if (subcmd.equalsIgnoreCase("read")) {
return doRead(sender, args);
}
if (subcmd.equalsIgnoreCase("list")) {
return doList(sender, args);
}
sender.sendMessage("Invalid subcommand: " + subcmd);
return false;
}
private boolean doHelp(CommandSender sender, String[] args) {
if (args.length < 1) {
sender.sendMessage("KMail Help: (<required> [optional])");
sender.sendMessage(" /kmail send <address> [message]");
sender.sendMessage(" /kmail read");
sender.sendMessage("");
sender.sendMessage("Do /kmail help <command> for help on any subcommand.");
sender.sendMessage("Other help topics: addresses");
return true;
}
String topic = args[0];
if (topic.equalsIgnoreCase("send")) {
sender.sendMessage("/kmail send <address> [message]");
sender.sendMessage("Send a message to the specified address. If the message is not specified in the command, all future chat messages (until one consisting of a single period ('.') is sent) will be used as the body of the message.");
sender.sendMessage("See also: /kmail help addresses");
return true;
}
if (topic.equalsIgnoreCase("read")) {
sender.sendMessage("/kmail read");
sender.sendMessage("Displays the oldest unread message and marks it as read.");
return true;
}
if (topic.equalsIgnoreCase("list")) {
sender.sendMessage("/kmail list <tag>");
sender.sendMessage("Lists messages with the given tag.");
return true;
}
if (topic.equalsIgnoreCase("addresses")) {
sender.sendMessage("An address can be:");
sender.sendMessage(" kierdavis");
sender.sendMessage(" - The username of a player on the local server");
sender.sendMessage(" kierdavis@mc.example.net");
sender.sendMessage(" - A user on another server (replace 'mc.example.net' with the same IP address/domain name used to connect to it from the Minecraft client)");
sender.sendMessage(" *");
sender.sendMessage(" - All players on the local server");
return true;
}
sender.sendMessage("Invalid help topic: " + topic);
return false;
}
private boolean doSend(CommandSender sender, String[] args) {
if (args.length < 1) {
sender.sendMessage("Usage: /kmail send <address> [message]");
sender.sendMessage("See /kmail help send for more info.");
return false;
}
String srcUsername;
if (sender instanceof Player) {
srcUsername = ((Player) sender).getName();
}
else {
srcUsername = "CONSOLE";
}
Address srcAddress = new Address(srcUsername, "local");
Address destAddress = new Address(args[0]);
Message msg = new Message(srcAddress, destAddress);
if (args.length >= 2) {
StringBuilder bodyBuilder = new StringBuilder();
bodyBuilder.append(args[1]);
for (int i = 2; i < args.length; i++) {
bodyBuilder.append(" ").append(args[i]);
}
msg.setBody(bodyBuilder.toString());
plugin.sendMessage(msg);
sender.sendMessage("Mail queued.");
return true;
}
else {
if (!(sender instanceof Player)) {
sender.sendMessage("This command must be run as a player.");
return false;
}
Player player = (Player) sender;
PartialMessage pm = new PartialMessage(msg);
plugin.putPartialMessage(player, pm);
sender.sendMessage("Now type your mail message in normal chat (not with commands).");
sender.sendMessage("End the message with a single chat message containing a dot (period).");
return true;
}
}
private boolean doRead(CommandSender sender, String[] args) {
Mailbox mb = plugin.getMailbox(getUsername(sender));
Iterator it = mb.iterator();
while (it.hasNext()) {
Message msg = (Message) it.next();
if (!msg.isRead()) {
displayMessage(sender, msg);
msg.setRead(true);
return true;
}
}
sender.sendMessage("No unread messages.");
return true;
}
private boolean doList(CommandSender sender, String[] args) {
if (args.length < 1) {
sender.sendMessage("Usage: /kmail list <tag>");
sender.sendMessage("See /kmail help list for more info.");
return false;
}
Mailbox mb = plugin.getMailbox(getUsername(sender));
Iterator it = mb.iterator();
while (it.hasNext()) {
Message msg = (Message) it.next();
if (msg.hasTag(tag)) {
displayMessageSummary(sender, msg);
}
}
return true;
}
private String getUsername(CommandSender sender) {
if (sender instanceof Player) {
return ((Player) sender).getName();
}
else {
return "CONSOLE";
}
}
private void displayMessage(CommandSender sender, Message msg) {
sender.sendMessage("================================");
sender.sendMessage("From: " + msg.getSrcAddress().toString());
sender.sendMessage("To: " + msg.getDestAddress().toString());
sender.sendMessage("Sent: " + msg.getSentDate().toString());
sender.sendMessage("Recieved: " + msg.getReceivedDate().toString());
sender.sendMessage("");
sender.sendMessage(msg.getBody());
sender.sendMessage("================================");
}
private void displayMessageSummary(CommandSender sender, Message msg) {
sender.sendMessage(msg.getLocalID().toString() + " " + msg.getSrcAddress().toString() + ": " + msg.getBody().substring(20));
}
}
|
package org.minimalj.frontend.form;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.FormContent;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.form.element.BigDecimalFormElement;
import org.minimalj.frontend.form.element.CheckBoxFormElement;
import org.minimalj.frontend.form.element.CodeFormElement;
import org.minimalj.frontend.form.element.Enable;
import org.minimalj.frontend.form.element.EnumFormElement;
import org.minimalj.frontend.form.element.EnumSetFormElement;
import org.minimalj.frontend.form.element.FormElement;
import org.minimalj.frontend.form.element.FormElement.FormElementListener;
import org.minimalj.frontend.form.element.IntegerFormElement;
import org.minimalj.frontend.form.element.LocalDateFormElement;
import org.minimalj.frontend.form.element.LocalTimeFormElement;
import org.minimalj.frontend.form.element.LongFormElement;
import org.minimalj.frontend.form.element.StringFormElement;
import org.minimalj.frontend.form.element.TextFormElement;
import org.minimalj.frontend.form.element.TypeUnknownFormElement;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.annotation.Enabled;
import org.minimalj.model.properties.Properties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.model.validation.ValidationMessage;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.ExceptionUtils;
import org.minimalj.util.mock.Mocking;
import org.minimalj.util.resources.Resources;
public class Form<T> {
private static Logger logger = Logger.getLogger(Form.class.getSimpleName());
public static final boolean EDITABLE = true;
public static final boolean READ_ONLY = false;
protected final boolean editable;
private final int columns;
private final FormContent formContent;
private final LinkedHashMap<PropertyInterface, FormElement<?>> elements = new LinkedHashMap<PropertyInterface, FormElement<?>>();
private final FormPanelChangeListener formPanelChangeListener = new FormPanelChangeListener();
private final FormPanelActionListener formPanelActionListener = new FormPanelActionListener();
private FormChangeListener<T> changeListener;
private boolean changeFromOutsite;
private final Map<PropertyInterface, List<PropertyInterface>> dependencies = new HashMap<>();
@SuppressWarnings("rawtypes")
private final Map<PropertyInterface, Map<PropertyInterface, PropertyUpdater>> propertyUpdater = new HashMap<>();
private T object;
public Form() {
this(EDITABLE);
}
public Form(boolean editable) {
this(editable, 1);
}
public Form(int columns) {
this(EDITABLE, columns);
}
public Form(boolean editable, int columns) {
this.editable = editable;
this.columns = columns;
this.formContent = Frontend.getInstance().createFormContent(columns, getColumnWidthPercentage());
}
protected int getColumnWidthPercentage() {
return 100;
}
// Methods to create the form
public FormContent getContent() {
return formContent;
}
public FormElement<?> createElement(Object key) {
FormElement<?> element;
PropertyInterface property;
if (key == null) {
throw new NullPointerException("Key must not be null");
} else if (key instanceof FormElement) {
element = (FormElement<?>) key;
property = element.getProperty();
if (property == null) throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key");
} else {
property = Keys.getProperty(key);
// if ths happens for a getter-method there is the special line missing
if (property == null) throw new IllegalArgumentException("" + key);
element = createElement(property);
}
return element;
}
protected FormElement<?> createElement(PropertyInterface property) {
Class<?> fieldClass = property.getClazz();
boolean editable = this.editable && !property.isFinal();
if (fieldClass == String.class) {
return editable ? new StringFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Boolean.class) {
return new CheckBoxFormElement(property, editable);
} else if (fieldClass == Integer.class) {
return new IntegerFormElement(property, editable);
} else if (fieldClass == Long.class) {
return new LongFormElement(property, editable);
} else if (fieldClass == BigDecimal.class) {
return new BigDecimalFormElement(property, editable);
} else if (fieldClass == LocalDate.class) {
return new LocalDateFormElement(property, editable);
} else if (fieldClass == LocalTime.class) {
return new LocalTimeFormElement(property, editable);
} else if (Code.class.isAssignableFrom(fieldClass)) {
return editable ? new CodeFormElement(property) : new TextFormElement(property);
} else if (Enum.class.isAssignableFrom(fieldClass)) {
return editable ? new EnumFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Set.class) {
return new EnumSetFormElement(property, this.editable); // 'this.editable' instead 'editable': the set field is always final. That doesn't mean its read only.
}
logger.severe("No FormElement could be created for: " + property.getName() + " of class " + fieldClass.getName());
return new TypeUnknownFormElement(property);
}
public void line(Object key) {
FormElement<?> element = createElement(key);
add(element, columns);
}
public void line(Object... keys) {
if (keys.length > columns) throw new IllegalArgumentException("More keys than specified in the constructor");
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i<keys.length; i++) {
Object key = keys[i];
FormElement<?> element = createElement(key);
add(element, i < keys.length - 1 ? span : rest);
rest = rest - span;
}
}
/**
* Use with care. Validation messages cannot be displayed without caption.
* At the moment this method is only meant to be used for the selection
* of elements in a Set of Enum.
*
* @param key field that should be in the form without caption
*/
public void lineWithoutCaption(Object key) {
FormElement<?> element = createElement(key);
formContent.add(element.getComponent());
registerNamedElement(element);
}
private void add(FormElement<?> element, int span) {
String captionText = caption(element);
formContent.add(captionText, element.getComponent(), span);
registerNamedElement(element);
}
public void text(String text) {
IComponent label = Frontend.getInstance().createLabel(text);
formContent.add(label);
}
public void addTitle(String text) {
IComponent label = Frontend.getInstance().createTitle(text);
formContent.add(label);
}
/**
* Declares that if the property with fromKey changes all
* the properties with toKey could change. This is normally used
* if the to property is a getter that calculates something that
* depends on the fromKey in a simple way.
*
* @param fromKey the key of the field triggering the update
* @param toKey the field possible changed its value implicitly
*/
public void addDependecy(Object fromKey, Object... toKey) {
PropertyInterface fromProperty = Keys.getProperty(fromKey);
if (!dependencies.containsKey(fromProperty)) {
dependencies.put(fromProperty, new ArrayList<PropertyInterface>());
}
List<PropertyInterface> list = dependencies.get(fromProperty);
for (Object key : toKey) {
list.add(Keys.getProperty(key));
}
}
/**
* Declares that if the property with fromKey changes the specified
* updater should be called and after its return the toKey property
* could have changed.<p>
*
* This is used if there is a more complex relation between two properities.
*
* @param <FROM> the type (class) of the fromKey / field
* @param <TO> the type (class) of the toKey / field
* @param fromKey the key of the field triggering the update
* @param updater the updater doing the change of the to field
* @param toKey the changed field by the udpater
*/
@SuppressWarnings("rawtypes")
public <FROM, TO> void addDependecy(FROM fromKey, PropertyUpdater<FROM, TO, T> updater, TO toKey) {
PropertyInterface fromProperty = Keys.getProperty(fromKey);
if (!propertyUpdater.containsKey(fromProperty)) {
propertyUpdater.put(fromProperty, new HashMap<PropertyInterface, PropertyUpdater>());
}
PropertyInterface toProperty = Keys.getProperty(toKey);
propertyUpdater.get(fromProperty).put(toProperty, updater);
addDependecy(fromKey, toKey);
}
public interface PropertyUpdater<FROM, TO, EDIT_OBJECT> {
/**
*
* @param input The new value of the property that has changed
* @param copyOfEditObject The current object of the This reference should <b>not</b> be changed.
* It should be treated as a read only version or a copy of the object.
* It's probably not a real copy as it is to expensive to copy the object for every call.
* @return The new value the updater wants to set to the toKey property
*/
public TO update(FROM input, EDIT_OBJECT copyOfEditObject);
}
private void registerNamedElement(FormElement<?> field) {
elements.put(field.getProperty(), field);
field.setChangeListener(formPanelChangeListener);
}
public final void mock() {
changeFromOutsite = true;
try {
fillWithDemoData(object);
} catch (Exception x) {
logger.log(Level.SEVERE, "Fill with demo data failed", x);
} finally {
readValueFromObject();
changeFromOutsite = false;
}
}
protected void fillWithDemoData(T object) {
for (FormElement<?> field : elements.values()) {
PropertyInterface property = field.getProperty();
if (field instanceof Mocking) {
Mocking demoEnabledElement = (Mocking) field;
demoEnabledElement.mock();
property.setValue(object, field.getValue());
}
}
}
protected String caption(FormElement<?> field) {
return Resources.getObjectFieldName(field.getProperty());
}
/**
*
* @return Collection provided by a LinkedHashMap so it will be a ordered set
*/
public Collection<PropertyInterface> getProperties() {
return elements.keySet();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void set(PropertyInterface property, Object value) {
FormElement element = elements.get(property);
try {
element.setValue(value);
} catch (Exception x) {
ExceptionUtils.logReducedStackTrace(logger, x);
}
}
private void setValidationMessage(PropertyInterface property, List<String> validationMessages) {
FormElement<?> field = elements.get(property);
formContent.setValidationMessages(field.getComponent(), validationMessages);
}
public void setObject(T object) {
if (editable && changeListener == null) throw new IllegalStateException("Listener has to be set on a editable Form");
changeFromOutsite = true;
this.object = object;
readValueFromObject();
changeFromOutsite = false;
}
private void readValueFromObject() {
for (PropertyInterface property : getProperties()) {
Object propertyValue = property.getValue(object);
set(property, propertyValue);
}
updateEnable();
}
private String getName(FormElement<?> field) {
PropertyInterface property = field.getProperty();
return property.getName();
}
public void setChangeListener(FormChangeListener<T> changeListener) {
if (changeListener == null) throw new IllegalArgumentException("Listener on Form must not be null");
if (this.changeListener != null) throw new IllegalStateException("Listener on Form cannot be changed");
this.changeListener = changeListener;
}
public interface FormChangeListener<S> {
public void changed(PropertyInterface property, Object newValue);
public void commit();
}
private class FormPanelChangeListener implements FormElementListener {
@Override
public void valueChanged(FormElement<?> changedField) {
if (changeFromOutsite) return;
if (changeListener == null) {
if (editable) logger.severe("Editable Form must have a listener");
return;
}
logger.fine("ChangeEvent from " + getName(changedField));
PropertyInterface property = changedField.getProperty();
Object newValue = changedField.getValue();
// Call updaters before set the new value (so they also can read the old value)
executeUpdater(property, newValue);
refreshDependendFields(property);
property.setValue(object, newValue);
// update enable/disable fields
updateEnable();
changeListener.changed(property, newValue);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void refreshDependendFields(PropertyInterface property) {
if (dependencies.containsKey(property)) {
List<PropertyInterface> dependendProperties = dependencies.get(property);
for (PropertyInterface dependendProperty : dependendProperties) {
Object newDependedValue = dependendProperty.getValue(object);
((FormElement) elements.get(dependendProperty)).setValue(newDependedValue);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void executeUpdater(PropertyInterface property, Object value) {
if (propertyUpdater.containsKey(property)) {
Map<PropertyInterface, PropertyUpdater> updaters = propertyUpdater.get(property);
for (Map.Entry<PropertyInterface, PropertyUpdater> entry : updaters.entrySet()) {
Object ret = entry.getValue().update(value, CloneHelper.clone(object));
entry.getKey().setValue(object, ret);
}
}
}
}
private void updateEnable() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
Enabled enabled = property.getAnnotation(Enabled.class);
if (enabled != null) {
String methodName = enabled.value();
boolean invert = methodName.startsWith("!");
if (invert) methodName = methodName.substring(1);
try {
Object o = findParentObject(property);
Class<?> clazz = o.getClass();
Method method = clazz.getMethod(methodName);
boolean e = (Boolean) method.invoke(o);
if (element.getValue() instanceof Enable) {
((Enable) element.getValue()).setEnabled(e ^ invert);
} else {
if (editable) {
logger.severe("element " + property.getPath() + " should implement Enable");
} else {
logger.fine("element " + property.getPath() + " should maybe implement Enable");
}
}
} catch (Exception x) {
String fieldName = property.getName();
if (!fieldName.equals(property.getPath())) {
fieldName += " (" + property.getPath() + ")";
}
logger.log(Level.SEVERE, "Update enable of " + fieldName + " failed" , x);
}
}
}
}
public void indicate(List<ValidationMessage> validationMessages) {
for (PropertyInterface property : getProperties()) {
List<String> filteredValidationMessages = ValidationMessage.filterValidationMessage(validationMessages, property);
setValidationMessage(property, filteredValidationMessages);
}
}
private Object findParentObject(PropertyInterface property) {
Object result = object;
String fieldPath = property.getPath();
while (fieldPath.indexOf(".") > -1) {
int pos = property.getPath().indexOf(".");
PropertyInterface p2 = Properties.getProperty(result.getClass(), fieldPath.substring(0, pos));
result = p2.getValue(result);
fieldPath = fieldPath.substring(pos + 1);
}
return result;
}
public class FormPanelActionListener implements Runnable {
@Override
public void run() {
if (changeListener != null) {
changeListener.commit();
}
}
}
}
|
package org.mobicents.protocols.asn;
/**
*
* @author amit bhayani
*
*/
public class Tag {
/**
* Class of tag used with primitives
*/
public static final int CLASS_UNIVERSAL = 0x0;
public static final int CLASS_APPLICATION = 0x1;
public static final int CLASS_CONTEXT_SPECIFIC = 0x2;
public static final int CLASS_PRIVATE = 0x3;
// first two bits encode the class
protected static final int CLASS_MASK = 0x30;
// The next bit (bit six) is called the primitive/constructed (P/C) bit
protected static final int PC_MASK = 0x20;
// The last five bits (bits 5 to 1) encode the number of the tag in tag octet
protected static final int NUMBER_MASK = 0x1F;
// Universal class tag assignments as per X.680-0207, Section 8.4
public static final int BOOLEAN = 0x01;
public static final int INTEGER = 0x02;
public static final int STRING_BIT = 0x03;
public static final int STRING_OCTET = 0x04;
public static final int NULL = 0x05;
public static final int REAL = 0x09;
public static final int ENUMERATED = 0x0A;
int tagClass = -1;
boolean isPrimitive;
int value = -1;
public Tag(int tagClass, boolean isPrimitive, int value) {
this.tagClass = tagClass;
this.isPrimitive = isPrimitive;
this.value = value;
}
public int getTagClass() {
return tagClass;
}
public boolean isPrimitive() {
return isPrimitive;
}
public int getValue() {
return value;
}
}
|
// $RCSfile: ImportReplay.java,v $
// @version $Revision: 1.18 $
// $Log: ImportReplay.java,v $
// Revision 1.18 2007/06/01 13:46:08 ian.mayo
// Improve performance of export text to clipboard
// Revision 1.17 2006/08/08 12:55:30 Ian.Mayo
// Restructure loading narrative entries (so we can see it from CMAP)
// Revision 1.16 2006/07/17 11:04:21 Ian.Mayo
// Append to the clipboard, don't keep writing afresh
// Revision 1.15 2006/05/24 15:01:28 Ian.Mayo
// Reflect change in exportThis method
// Revision 1.14 2006/05/23 14:53:55 Ian.Mayo
// Make readLine public (so our data-importers can read it in)
// Revision 1.13 2006/02/13 16:19:06 Ian.Mayo
// Sort out problem with creating sensor data
// Revision 1.12 2005/12/13 09:04:37 Ian.Mayo
// Tidying - as recommended by Eclipse
// Revision 1.11 2005/05/12 14:11:45 Ian.Mayo
// Allow import of typed-narrative entry
// Revision 1.10 2005/05/12 09:52:42 Ian.Mayo
// Stop it being final - since in CMAP we want to override line counting method
// Revision 1.9 2004/12/17 15:53:57 Ian.Mayo
// Get on top of some problems plotting sensor & tma data.
// Revision 1.8 2004/11/25 10:24:18 Ian.Mayo
// Switch to Hi Res dates
// Revision 1.7 2004/11/22 13:53:28 Ian.Mayo
// Replace variable name previously used for counting through enumeration - now part of JDK1.5
// Revision 1.6 2004/11/22 13:40:56 Ian.Mayo
// Replace old variable name used for stepping through enumeration, since it is now part of language (Jdk1.5)
// Revision 1.5 2004/11/11 11:52:44 Ian.Mayo
// Reflect new directory structure
// Revision 1.4 2004/09/09 10:22:58 Ian.Mayo
// Reflect method name change in Layer interface
// Revision 1.3 2004/08/20 08:18:04 Ian.Mayo
// Allow 4-figure dates in REP files
// Revision 1.2 2003/08/12 09:28:43 Ian.Mayo
// Include import of DTF files
// Revision 1.1.1.2 2003/07/21 14:47:51 Ian.Mayo
// Re-import Java files to keep correct line spacing
// Revision 1.11 2003-07-03 15:47:03+01 ian_mayo
// Improved error checking
// Revision 1.10 2003-06-23 13:39:36+01 ian_mayo
// Add TMA Handling code
// Revision 1.9 2003-06-23 08:39:38+01 ian_mayo
// Initialise colours on request - not just in constructor (support for testing)
// Revision 1.8 2003-06-16 11:49:41+01 ian_mayo
// Output completed message which was failing ANT built
// Revision 1.7 2003-04-30 16:05:46+01 ian_mayo
// Correctly set GMT time zone for importing narratives
// Revision 1.6 2003-03-19 15:37:29+00 ian_mayo
// improvements according to IntelliJ inspector
// Revision 1.5 2003-02-25 14:36:08+00 ian_mayo
// Just use \n as line-break when exporting to clipboard
// Revision 1.4 2003-02-14 10:16:11+00 ian_mayo
// Set the symbol type according to symbology in Replay file
// Revision 1.3 2002-10-01 15:40:18+01 ian_mayo
// improve testing
// Revision 1.2 2002-05-28 11:34:21+01 ian_mayo
// Implemented correct way of breaking out of a loop
// Revision 1.1 2002-05-28 09:12:09+01 ian_mayo
// Initial revision
// Revision 1.1 2002-04-23 12:29:39+01 ian_mayo
// Initial revision
// Revision 1.15 2002-03-12 09:18:00+00 administrator
// Provide "Fallback" handler for missing milliseconds
// Revision 1.14 2002-02-18 09:20:19+00 administrator
// Change tests so that we no longer write progress statements to screen
// Revision 1.13 2002-02-01 12:37:37+00 administrator
// Allow track colours to be specified per-fix instead of one colour for the whole track
// Revision 1.12 2002-01-29 07:53:14+00 administrator
// Use Trace method instead of System.out
// Revision 1.11 2001-11-14 19:48:49+00 administrator
// Handle lines beginning with comment, but report error for unrecognised lines
// Revision 1.10 2001-11-14 19:39:14+00 administrator
// Add error message for when annotation not recognised
// Revision 1.9 2001-11-13 21:11:32+00 administrator
// improve testing
// Revision 1.8 2001-10-02 09:29:28+01 administrator
// improve debug comments
// Revision 1.7 2001-09-09 08:40:49+01 administrator
// Add read/write testing
// Revision 1.6 2001-08-29 19:16:53+01 administrator
// Remove ContactWrapper stuff
// Revision 1.5 2001-08-21 15:17:45+01 administrator
// Allow use of dsf suffix
// Revision 1.4 2001-08-17 07:59:57+01 administrator
// Clear up memory leaks
// Revision 1.3 2001-08-13 12:53:34+01 administrator
// Provide support for line styles, and support Sensor data
// Revision 1.2 2001-08-06 12:46:19+01 administrator
// Use our monitor instead of a normal buffered reader
// Revision 1.1 2001-08-01 20:07:39+01 administrator
// Provide interface for, and handle a list of formatting objects which apply some kind of formatting to imported data
// Revision 1.0 2001-07-17 08:41:33+01 administrator
// Initial revision
// Revision 1.2 2001-07-09 14:01:58+01 novatech
// add narrative importer to list of importers, and handle creation of layer for Narratives
// Revision 1.1 2001-01-03 13:40:46+00 novatech
// Initial revision
// Revision 1.1.1.1 2000/12/12 20:47:24 ianmayo
// initial import of files
// Revision 1.22 2000-11-17 09:10:45+00 ian_mayo
// reflect changes in parent
// Revision 1.21 2000-11-08 11:48:50+00 ian_mayo
// insert debug line
// Revision 1.20 2000-11-03 12:08:49+00 ian_mayo
// add support for importBearing, reflect new status of TrackWrapper as layer, not just plottable
// Revision 1.19 2000-11-02 16:45:50+00 ian_mayo
// changing Layer into Interface, replaced by BaseLayer, also changed TrackWrapper so that it implements Layer, and as we read in files, we put them into track and add Track to Layers, not to Layer then Layers
// Revision 1.18 2000-10-09 13:37:35+01 ian_mayo
// Switch stackTrace to go to file
// Revision 1.17 2000-10-03 14:18:25+01 ian_mayo
// add reference to ImportWheel class
// Revision 1.16 2000-09-28 12:09:32+01 ian_mayo
// switch to GMT time zone
// Revision 1.15 2000-09-21 12:22:39+01 ian_mayo
// check for an empty clipboard
// Revision 1.14 2000-04-19 11:24:01+01 ian_mayo
// add new import types
// Revision 1.13 2000-03-17 13:37:25+00 ian_mayo
// Handle replay text colour symbols more tidily
// Revision 1.12 2000-03-07 14:48:16+00 ian_mayo
// optimised algorithms
// Revision 1.11 2000-02-22 13:49:19+00 ian_mayo
// ImportManager location changed, and export now receives Plottable, not PlainWrapper
// Revision 1.10 2000-02-02 14:27:35+00 ian_mayo
// ensure that the "Importers" static vector is initialised before use
// Revision 1.9 2000-01-12 15:40:19+00 ian_mayo
// added concept of contacts
// Revision 1.8 1999-12-03 14:41:05+00 ian_mayo
// remove d-line
// Revision 1.7 1999-12-02 09:44:28+00 ian_mayo
// removed "Sleep" command, Boy what speed gains this provided!
// Revision 1.6 1999-11-26 15:51:40+00 ian_mayo
// tidying up
// Revision 1.5 1999-11-12 14:36:36+00 ian_mayo
// make classes do export aswell as import
// Revision 1.4 1999-11-09 11:26:41+00 ian_mayo
// added ellipses
// Revision 1.3 1999-10-14 12:00:33+01 ian_mayo
// added support for lines
// Revision 1.2 1999-10-13 17:24:01+01 ian_mayo
// add support for Rectangles
// Revision 1.1 1999-10-12 15:34:12+01 ian_mayo
// Initial revision
// Revision 1.3 1999-07-27 09:27:28+01 administrator
// added more error handlign
// Revision 1.2 1999-07-12 08:09:22+01 administrator
// Property editing added
// Revision 1.6 1999-06-16 15:24:23+01 sm11td
// before move around/ end of phase 1
// Revision 1.5 1999-06-04 08:45:26+01 sm11td
// Ending phase 1, adding colours to annotations
// Revision 1.4 1999-06-01 16:49:17+01 sm11td
// Reading in tracks aswell as fixes, commenting large portions of source code
// Revision 1.3 1999-02-04 08:02:24+00 sm11td
// Plotting to canvas, scaling canvas,
// Revision 1.2 1999-02-01 16:08:47+00 sm11td
// creating new sessions & panes, starting import management
// Revision 1.1 1999-01-31 13:33:04+00 sm11td
// Initial revision
package Debrief.ReaderWriter.Replay;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.NarrativeWrapper;
import Debrief.Wrappers.SensorContactWrapper;
import Debrief.Wrappers.SensorWrapper;
import Debrief.Wrappers.TMAContactWrapper;
import Debrief.Wrappers.TMAWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.TrackSegment;
import MWC.GUI.Editable;
import MWC.GUI.ExportLayerAsSingleItem;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.ToolParent;
import MWC.GUI.Shapes.Symbols.SymbolFactory;
import MWC.GUI.Tools.Action;
import MWC.GenericData.HiResDate;
import MWC.GenericData.Watchable;
import MWC.TacticalData.NarrativeEntry;
import MWC.Utilities.ReaderWriter.PlainImporterBase;
import MWC.Utilities.ReaderWriter.PlainLineImporter;
import MWC.Utilities.ReaderWriter.ReaderMonitor;
import MWC.Utilities.TextFormatting.DebriefFormatDateTime;
/**
* class to read in a complete replay file. The class knows of the types of data
* in Replay format, and users the correct import filters accordingly.
*/
public class ImportReplay extends PlainImporterBase
{
/**
* interface for class that is able to retrieve the import mode from the user
*
* @author ianmayo
* @see ImportReplay.TRACK_IMPORT_MODE
*/
public static interface ProvidesModeSelector
{
public String getSelectedImportMode(final String trackName);
}
/**
* the format we use to parse text
*/
private static final java.text.DateFormat dateFormat = new java.text.SimpleDateFormat(
"yyMMdd HHmmss.SSS");
private static Vector<PlainLineImporter> _theImporters;
static private Vector<doublet> colors; // list of Replay colours
static public final String NARRATIVE_LAYER = "Narratives";
static private final String ANNOTATION_LAYER = "Annotations";
/**
* the prefs provider
*
*/
private static ToolParent _myParent;
/**
* the list of formatting objects we know about
*/
private final LayersFormatter[] _myFormatters =
{ new FormatTracks() };
private Vector<SensorWrapper> _sensorNames;
/**
* the property name we use for importing tracks (DR/ATG)
*
*/
public final static String TRACK_IMPORT_MODE = "TRACK_IMPORT_MODE";
/**
* the property values for importing modes
*
*/
public final static String IMPORT_AS_DR = "DR_IMPORT";
public final static String IMPORT_AS_OTG = "OTG_IMPORT";
public final static String ASK_THE_AUDIENCE = "ASK_AUDIENCE";
/**
* constructor, initialise Vector with the list of non-Fix items which we will
* be reading in
*/
public ImportReplay()
{
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
_myTypes = new String[]
{ ".rep", ".dsf", ".dtf" };
checkImporters();
initialiseColours();
}
private static void initialiseColours()
{
// create a list of colours
if (colors == null)
{
colors = new Vector<doublet>(0, 1);
colors.addElement(new doublet("@", Color.white));
colors.addElement(new doublet("A", Color.blue));
colors.addElement(new doublet("B", Color.green));
colors.addElement(new doublet("C", Color.red));
colors.addElement(new doublet("D", Color.yellow));
colors.addElement(new doublet("E", new Color(169, 1, 132)));
colors.addElement(new doublet("F", Color.orange));
colors.addElement(new doublet("G", new Color(188, 93, 6)));
colors.addElement(new doublet("H", Color.cyan));
colors.addElement(new doublet("I", new Color(100, 240, 100)));
colors.addElement(new doublet("J", new Color(230, 200, 20)));
colors.addElement(new doublet("K", Color.pink));
}
}
/**
* format a date using our format
*/
public static String formatThis(final HiResDate val)
{
final String res = DebriefFormatDateTime.toStringHiRes(val);
return res;
}
/**
* initialise the tool, so that it knows where to get its prefs details
*
* @param theParent
*/
public static void initialise(final ToolParent theParent)
{
_myParent = theParent;
}
/**
* function to initialise the list of importers
*/
private static void checkImporters()
{
if (_theImporters == null)
{
// create the array of import handlers, by
_theImporters = new Vector<PlainLineImporter>(0, 1);
// adding handler we (currently) know of
_theImporters.addElement(new ImportCircle());
_theImporters.addElement(new ImportRectangle());
_theImporters.addElement(new ImportLine());
_theImporters.addElement(new ImportVector());
_theImporters.addElement(new ImportEllipse());
_theImporters.addElement(new ImportPeriodText());
_theImporters.addElement(new ImportTimeText());
_theImporters.addElement(new ImportLabel());
_theImporters.addElement(new ImportWheel());
_theImporters.addElement(new ImportBearing());
_theImporters.addElement(new ImportNarrative());
_theImporters.addElement(new ImportNarrative2());
_theImporters.addElement(new ImportSensor());
_theImporters.addElement(new ImportSensor2());
_theImporters.addElement(new ImportSensor3());
_theImporters.addElement(new ImportTMA_Pos());
_theImporters.addElement(new ImportTMA_RngBrg());
_theImporters.addElement(new ImportPolygon());
_theImporters.addElement(new ImportPolyline());
// note that we don't rely on ImportFix for importing Replay fixes, since
// they are handled by the ImportReplay method. We are including it in
// this list so that we can use it as an exporter
_theImporters.addElement(new ImportFix());
}
}
private HiResDate processReplayFix(final ReplayFix rf)
{
final HiResDate res = rf.theFix.getTime();
// find the track name
final String theTrack = rf.theTrackName;
final Color thisColor = replayColorFor(rf.theSymbology);
// create the wrapper for this annotation
final FixWrapper thisWrapper = new FixWrapper(rf.theFix);
// overwrite the label, if there's one there
if(rf.label != null)
{
thisWrapper.setLabel(rf.label);
thisWrapper.setUserLabelSupplied(true);
}
// keep track of the wrapper for this track
// is there a layer for this track?
TrackWrapper trkWrapper = (TrackWrapper) getLayerFor(theTrack);
// have we found the layer?
if (trkWrapper == null)
{
// ok, see if we're importing it as DR or ATG (or ask the audience)
String importMode = _myParent.getProperty(TRACK_IMPORT_MODE);
// catch a missing import mode
if (importMode == null)
{
// belt & braces it is then...
importMode = ImportReplay.ASK_THE_AUDIENCE;
}
if (importMode.equals(ImportReplay.ASK_THE_AUDIENCE))
{
if (_myParent instanceof ProvidesModeSelector)
{
final ProvidesModeSelector selector = (ProvidesModeSelector) _myParent;
importMode = selector.getSelectedImportMode(theTrack);
}
}
TrackSegment initialLayer = null;
if (importMode == null)
{
// and drop out of the whole affair
throw new RuntimeException("User cancelled import");
}
else if (importMode.equals(ImportReplay.IMPORT_AS_OTG))
{
initialLayer = new TrackSegment();
initialLayer.setPlotRelative(false);
}
else if (importMode.equals(ImportReplay.IMPORT_AS_DR))
{
initialLayer = new TrackSegment();
initialLayer.setPlotRelative(true);
}
// now create the wrapper
trkWrapper = new TrackWrapper();
// give it the data container
trkWrapper.add(initialLayer);
// get the colour for this track
trkWrapper.setColor(thisColor);
trkWrapper.setSymbolColor(thisColor);
// set the sym type for the track
final String theSymType = replayTrackSymbolFor(rf.theSymbology);
trkWrapper.setSymbolType(theSymType);
// store the track-specific data
trkWrapper.setName(theTrack);
// add our new layer to the Layers object
addLayer(trkWrapper);
}
// add the fix to the track
trkWrapper.addFix((FixWrapper) thisWrapper);
// let's also tell the fix about it's track
((FixWrapper) thisWrapper).setTrackWrapper(trkWrapper);
// also, see if this fix is specifying a different colour to use
if (thisColor != trkWrapper.getColor())
{
// give this fix it's unique colour
thisWrapper.setColor(thisColor);
}
return res;
}
private HiResDate processSensorContactWrapper(final SensorContactWrapper sw)
{
final HiResDate res = sw.getTime();
SensorWrapper thisSensor = null;
// do we have a sensor capable of handling this contact?
final String sensorName = sw.getSensorName();
String trackName = sw.getTrackName();
Object val = getLayerFor(trackName);
// if we failed to get the trackname, try shortening it -
// it may have been mangled by BabelFish
if (val == null)
val = getLayerFor(trackName = trackName.substring(6));
// did we get anything?
// is this indeed a sensor?
if (val == null || !(val instanceof TrackWrapper))
return res;
// so, we've found a track - see if it holds this sensor
final TrackWrapper theTrack = (TrackWrapper) val;
final Enumeration<Editable> iter = theTrack.getSensors().elements();
// step through this track' sensors
if (iter != null)
{
while (iter.hasMoreElements())
{
final SensorWrapper sensorw = (SensorWrapper) iter.nextElement();
// is this our sensor?
if (sensorw.getName().equals(sensorName))
{
// cool, drop out
thisSensor = sensorw;
break;
}
} // looping through the sensors
} // whether there are any sensors
// did we find it?
if (thisSensor == null)
{
// then create it
thisSensor = new SensorWrapper(sensorName);
// remember it
_sensorNames.add(thisSensor);
// set it's colour to the colour of the first data point
thisSensor.setColor(sw.getColor());
// also set it's name
thisSensor.setTrackName(sw.getTrackName());
theTrack.add(thisSensor);
}
// so, we now have the wrapper. have a look to see if the colour
// of this data item is the same
// as the sensor - in which case we will erase the colour for
// this data item so that it always takes the colour of it's parent
if (sw.getColor().equals(thisSensor.getColor()))
{
// clear the colour - so it takes it form it's parent
sw.setColor(null);
}
// now add the new contact to this sensor
thisSensor.add(sw);
return res;
}
private HiResDate processContactWrapper(final TMAContactWrapper sw)
{
final HiResDate res = sw.getTime();
TMAWrapper thisWrapper = null;
// do we have a sensor capable of handling this contact?
final String solutionName = sw.getSolutionName();
String trackName = sw.getTrackName();
Object val = getLayerFor(trackName);
// if we failed to get the trackname, try shortening it -
// it may have been mangled by BabelFish
if (val == null)
val = getLayerFor(trackName = trackName.substring(6));
// did we get anything?
// is this indeed a sensor?
if (val == null || !(val instanceof TrackWrapper))
return res;
// so, we've found a track - see if it holds this solution
final TrackWrapper theTrack = (TrackWrapper) val;
final Enumeration<Editable> iter = theTrack.getSolutions().elements();
// step through this track's solutions
if (iter != null)
{
while (iter.hasMoreElements())
{
final TMAWrapper sensorw = (TMAWrapper) iter.nextElement();
// is this our sensor?
if (sensorw.getName().equals(solutionName))
{
// cool, drop out
thisWrapper = sensorw;
break;
}
} // looping through the sensors
} // whether there are any sensors
// did we find it?
if (thisWrapper == null)
{
// then create it
thisWrapper = new TMAWrapper(solutionName);
// set it's colour to the colour of the first data point
thisWrapper.setColor(sw.getColor());
// also set it's name
thisWrapper.setTrackName(sw.getTrackName());
theTrack.add(thisWrapper);
}
// so, we now have the wrapper. have a look to see if the colour
// of this data item is the same
// as the sensor - in which case we will erase the colour for
// this data item so that it
// always takes the colour of it's parent
if (sw.getColor().equals(thisWrapper.getColor()))
{
// clear the colour - so it takes it form it's parent
sw.setColor(null);
}
// lastly inform the sensor contact of it's parent
sw.setTMATrack(thisWrapper);
// now add the new contact to this sensor
thisWrapper.add(sw);
return res;
}
/**
* parse this line
*
* @param theLine
* the line to parse
*/
public HiResDate readLine(final String theLine) throws java.io.IOException
{
HiResDate res = null;
// is this line invalid
if (theLine.length() <= 0)
return null;
// ok, trim any leading/trailing whitespace
final String line = theLine.trim();
// what type of item is this?
final PlainLineImporter thisOne = getImporterFor(line);
// check that we have found an importer
if (thisOne == null)
{
// just check it wasn't a comment
if (line.startsWith(";;"))
{
// don't bother, it's just a comment
}
else
{
MWC.Utilities.Errors.Trace
.trace("Annotation type not recognised for:" + line);
}
return null;
}
// now read it in.
final Object thisObject = thisOne.readThisLine(line);
// see if we are going to do any special processing
// is this a fix?
if (thisObject instanceof ReplayFix)
{
res = processReplayFix((ReplayFix) thisObject);
}
else if (thisObject instanceof SensorContactWrapper)
{
res = processSensorContactWrapper((SensorContactWrapper) thisObject);
}
else if (thisObject instanceof TMAContactWrapper)
{
res = processContactWrapper((TMAContactWrapper) thisObject);
}
else if (thisObject instanceof NarrativeEntry)
{
final NarrativeEntry entry = (NarrativeEntry) thisObject;
// remember the dtg
res = entry.getDTG();
// have we got a narrative wrapper?
Layer dest = getLayerFor(NARRATIVE_LAYER);
if (dest == null)
{
dest = new NarrativeWrapper(NARRATIVE_LAYER);
addLayer(dest);
}
addToLayer(entry, dest);
}
// PlainWrapper is our "fallback" operator, so it's important to leave it
// to last
else if (thisObject instanceof PlainWrapper)
{
// create the wrapper for this annotation
final PlainWrapper thisWrapper = (PlainWrapper) thisObject;
// remember the dtg
if (thisWrapper instanceof Watchable)
{
final Watchable wat = (Watchable) thisWrapper;
res = wat.getTime();
}
// not fix, must be annotation, just add it to the correct
// layer
Layer dest = getLayerFor(ANNOTATION_LAYER);
if (dest == null)
{
dest = createLayer(ANNOTATION_LAYER);
addLayer(dest);
}
addToLayer(thisWrapper, dest);
}
return res;
}
/**
* import data from this stream
*/
public final void importThis(final String fName, final java.io.InputStream is)
{
// declare linecounter
int lineCounter = 0;
final int numLines = countLinesFor(fName);
final Reader reader = new InputStreamReader(is);
final BufferedReader br = new ReaderMonitor(reader, numLines, fName);
String thisLine = null;
try
{
// check stream is valid
if (is.available() > 0)
{
thisLine = br.readLine();
final long start = System.currentTimeMillis();
// loop through the lines
while (thisLine != null)
{
// keep line counter
lineCounter++;
// catch import problems
readLine(thisLine);
// read another line
thisLine = br.readLine();
}
// lastly have a go at formatting these tracks
for (int k = 0; k < _myFormatters.length; k++)
{
_myFormatters[k].formatLayers(getLayers());
}
final long end = System.currentTimeMillis();
System.out.print(" |Elapsed:" + (end - start) + " ");
}
}
catch (final java.lang.NumberFormatException e)
{
// produce the error message
MWC.Utilities.Errors.Trace.trace(e);
// show the message dialog
super.readError(fName, lineCounter, "Number format error", thisLine);
}
catch (final IOException e)
{
// produce the error message
MWC.Utilities.Errors.Trace.trace(e);
// show the message dialog
super.readError(fName, lineCounter, "Unknown read error:" + e, thisLine);
}
catch (final java.util.NoSuchElementException e)
{
// produce the error message
MWC.Utilities.Errors.Trace.trace(e);
// show the message dialog
super.readError(fName, lineCounter, "Missing field error", thisLine);
}
}
private PlainLineImporter getImporterFor(final String rawString)
{
PlainLineImporter res = null;
// trim any leading whitespace
final String theLine = rawString.trim();
// check it's not an empty line
if(theLine.length() > 0)
{
// so, determine if this is a comment
if (theLine.charAt(0) == ';')
{
// look through types of import handler
final Enumeration<PlainLineImporter> iter = _theImporters.elements();
// get the type for this comment
final StringTokenizer st = new StringTokenizer(theLine);
final String type = st.nextToken();
// cycle through my types
while (iter.hasMoreElements())
{
final PlainLineImporter thisImporter = iter.nextElement();
// get the handler correct type?
final String thisType = thisImporter.getYourType();
if (thisType == null)
{
MWC.Utilities.Errors.Trace.trace("null returned by: " + thisImporter);
return null;
}
// does this one fit?
if (thisType.equals(type))
{
res = thisImporter;
break;
}
}
}
else
{
res = new ImportFix();
}
}
// done
return res;
}
/**
* convert the item to text, add it to the block we're building up
*/
public final void exportThis(final Plottable item)
{
// check it's real
if (item == null)
throw new IllegalArgumentException("duff wrapper");
checkImporters();
// just see if it is a track which we are trying to export
if ((item instanceof Layer) && !(item instanceof ExportLayerAsSingleItem))
{
// ok, work through the layer
final Layer tw = (Layer) item;
// ha-ha! export the points one at a time
final java.util.Enumeration<Editable> iter = tw.elements();
while (iter.hasMoreElements())
{
final Plottable pt = (Plottable) iter.nextElement();
exportThis(pt);
}
// ta-da! done.
}
else
{
// check we have some importers
if (_theImporters != null)
{
final Enumeration<PlainLineImporter> iter = _theImporters.elements();
// step though our importers, to see if any will 'do the deal;
while (iter.hasMoreElements())
{
final PlainLineImporter thisImporter = iter.nextElement();
if (thisImporter.canExportThis(item))
{
// export it, add it to the data we're building up
final String thisLine = thisImporter.exportThis(item);
addThisToExport(thisLine);
// ok, we can drop out of the loop
break;
}
}
}
}
}
public final boolean canImportThisFile(final String theFile)
{
boolean res = false;
String theSuffix = null;
final int pos = theFile.lastIndexOf(".");
theSuffix = theFile.substring(pos, theFile.length());
for (int i = 0; i < _myTypes.length; i++)
{
if (theSuffix.equalsIgnoreCase(_myTypes[i]))
{
res = true;
break;
}
}
return res;
}
public Vector<SensorWrapper> getNewlyLoadedSensors()
{
return _sensorNames;
}
public void clearSensorList()
{
_sensorNames = new Vector<SensorWrapper>();
}
static public int replayLineStyleFor(final String theSym)
{
int res = 0;
final String theStyle = theSym.substring(0, 1);
if (theStyle.equals("@"))
{
res = MWC.GUI.CanvasType.SOLID;
}
else if (theStyle.equals("A"))
{
res = MWC.GUI.CanvasType.DOTTED;
}
else if (theStyle.equals("B"))
{
res = MWC.GUI.CanvasType.DOT_DASH;
}
else if (theStyle.equals("C"))
{
res = MWC.GUI.CanvasType.SHORT_DASHES;
}
else if (theStyle.equals("D"))
{
res = MWC.GUI.CanvasType.LONG_DASHES;
}
else if (theStyle.equals("E"))
{
res = MWC.GUI.CanvasType.UNCONNECTED;
}
return res;
}
public final static String replayTrackSymbolFor(final String theSym)
{
String res = null;
final String colorVal = theSym.substring(0, 1);
res = SymbolFactory.createSymbolFromId(colorVal);
// did we manage to find it?
if (res == null)
res = SymbolFactory.createSymbolFromId(SymbolFactory.DEFAULT_SYMBOL_TYPE);
return res;
}
static public Color replayColorFor(final int index)
{
Color res = null;
// check we have the colours
initialiseColours();
final int theIndex = index % colors.size();
res = colors.elementAt(theIndex).color;
return res;
}
static public Color replayColorFor(final String theSym)
{
Color res = null;
final String colorVal = theSym.substring(1, 2);
// check we have the colours
initialiseColours();
// step through our list of colours
final java.util.Enumeration<doublet> iter = colors.elements();
while (iter.hasMoreElements())
{
final doublet db = iter.nextElement();
if (db.label.equals(colorVal))
{
res = db.color;
break;
}
}
// if label not found, make it RED
if (res == null)
res = Color.red;
return res;
}
static public String replaySymbolFor(final Color theCol, final String theSymbol)
{
String res = null;
// step through our list of colours
final java.util.Enumeration<doublet> iter = colors.elements();
while (iter.hasMoreElements())
{
final doublet db = iter.nextElement();
if (db.color.equals(theCol))
{
res = db.label;
continue;
}
}
String symTxt;
if(theSymbol == null)
{
symTxt = "@";
}
else
{
symTxt = SymbolFactory.findIdForSymbolType(theSymbol);
}
// label not found, make it RED
if (res == null)
res = "A";
res = symTxt + res;
return res;
}
public final void exportThis(final String val)
{
if (val != null)
{
final java.awt.datatransfer.Clipboard cl = java.awt.Toolkit.getDefaultToolkit()
.getSystemClipboard();
final java.awt.datatransfer.StringSelection ss = new java.awt.datatransfer.StringSelection(
val);
cl.setContents(ss, ss);
}
}
final static class doublet
{
public final String label;
public final Color color;
public doublet(final String theLabel, final Color theColor)
{
label = theLabel;
color = theColor;
}
}
/**
* interface which we use to implement class capable of formatting a set of
* layers once they've been read in
*/
public static interface LayersFormatter
{
public void formatLayers(Layers newData);
}
// testing for this class
static public final class testImport extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
private static String fileName = "test.rep";
boolean fileFinished = false;
boolean allFilesFinished = false;
public testImport(final String val)
{
super(val);
final String fileRoot = "../org.mwc.debrief.legacy/src";
assertNotNull("Check data directory is configured", fileRoot);
fileName = fileRoot + File.separator + fileName;
// and check the file exists
final java.io.File iFile = new File(fileName);
assertTrue("Test file not found", iFile.exists());
}
public final void testReadREP()
{
java.io.File testFile = null;
// specify the parent object - so our processing can retrieve the
// OTG setting
ImportReplay.initialise(new ToolParent()
{
public void addActionToBuffer(final Action theAction)
{
// TODO Auto-generated method stub
}
public Map<String, String> getPropertiesLike(final String pattern)
{
// TODO Auto-generated method stub
return null;
}
public String getProperty(final String name)
{
return ImportReplay.IMPORT_AS_OTG;
}
public void restoreCursor()
{
// TODO Auto-generated method stub
}
public void setCursor(final int theCursor)
{
// TODO Auto-generated method stub
}
public void setProperty(final String name, final String value)
{
// TODO Auto-generated method stub
}
public void logError(final int status, final String text, final Exception e)
{
// TODO Auto-generated method stub
}
});
// can we load it directly
testFile = new java.io.File(fileName);
if (!testFile.exists())
{
// first try to get the URL of the image
final java.lang.ClassLoader loader = getClass().getClassLoader();
if (loader != null)
{
final java.net.URL imLoc = loader.getResource(fileName);
if (imLoc != null)
{
testFile = new java.io.File(imLoc.getFile());
}
}
else
{
fail("Failed to find class loader");
}
}
// did we find it?
assertTrue("Failed to find file:" + fileName, testFile.exists());
// ok, now try to read it in
final MWC.GUI.Layers _theLayers = new MWC.GUI.Layers();
final File[] _theFiles = new File[]
{ testFile };
// add the REP importer
MWC.Utilities.ReaderWriter.ImportManager
.addImporter(new Debrief.ReaderWriter.Replay.ImportReplay());
// get our thread to import this
final MWC.Utilities.ReaderWriter.ImportManager.BaseImportCaller reader = new MWC.Utilities.ReaderWriter.ImportManager.BaseImportCaller(
_theFiles, _theLayers)
{
// handle the completion of each file
public void fileFinished(final File fName, final Layers newData)
{
fileFinished = true;
}
// handle completion of the full import process
public void allFilesFinished(final File[] fNames, final Layers newData)
{
allFilesFinished = true;
}
};
// and start it running
reader.start();
// wait for the results
while (reader.isAlive())
{
try
{
Thread.sleep(100);
}
catch (final java.lang.InterruptedException e)
{
}
}
// check it went ok
assertTrue("File finished received", fileFinished);
assertTrue("All Files finished received", allFilesFinished);
assertEquals("Count of layers", 3, _theLayers.size());
// area of coverage
final MWC.GenericData.WorldArea area = _theLayers.elementAt(0).getBounds();
super.assertEquals("tl lat of first layer", area.getTopLeft().getLat(),
11.92276, 0.001);
super.assertEquals("tl long of first layer", area.getTopLeft().getLong(),
-11.59394, 0.00001);
super.assertEquals("tl depth of first layer", area.getTopLeft()
.getDepth(), 0, 0.00001);
super.assertEquals("br lat of first layer", area.getBottomRight()
.getLat(), 11.89421, 0.001);
super.assertEquals("br long of first layer", area.getBottomRight()
.getLong(), -11.59376, 0.00001);
super.assertEquals("br depth of first layer", area.getBottomRight()
.getDepth(), 0, 0.00001);
// check those narrative lines got read in
NarrativeWrapper narratives = (NarrativeWrapper) _theLayers.elementAt(2);
assertEquals("have read in both narrative entries",2, narratives.size());
}
}
public static void main(final String[] args)
{
System.setProperty("dataDir", "d:\\dev\\debrief\\src\\java\\Debrief");
final testImport ti = new testImport("some name");
ti.testReadREP();
System.exit(0);
}
}
|
package org.narwhal.pool;
import org.narwhal.core.DatabaseConnection;
import org.narwhal.core.DatabaseInformation;
import org.narwhal.query.QueryCreator;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* The <code>ConnectionPool</code> class implements
* basic functionality that allows end-users persist
* variable number of database connection.
* This class provides database connection pool and
* takes care of lifetime and resource management.
*
* @author Miron Aseev
*/
public class ConnectionPool {
private static final int DEFAULT_POOL_SIZE = 5;
private static final int DEFAULT_ACQUIRE_INCREMENT = 5;
private int size;
private int acquireIncrement;
private DatabaseInformation databaseInformation;
private Lock connectionsLock;
private Lock variableLock;
private List<DatabaseConnection> connections;
private QueryCreator queryCreator;
/**
* Initializes a new instance of the ConnectionPool class.
* The instance is specified by DatabaseInformation instance that
* keeps all the information to be able to make connection to the database.
* Default pool size is 5.
* Acquire increment is 5.
*
* @param databaseInformation instance of {@code DatabaseInformation} class that includes
* all the information for making connection to the database.
* @throws SQLException If any database access problems happened.
* */
public ConnectionPool(DatabaseInformation databaseInformation, QueryCreator queryCreator) throws SQLException {
this(databaseInformation, DEFAULT_POOL_SIZE, DEFAULT_ACQUIRE_INCREMENT, queryCreator);
}
/**
* Initializes a new instance of the ConnectionPool class.
* The instance is specified by DatabaseInformation instance that
* keeps all the information to make connection to the database.
* Instance is also specified by the size and acquireIncrement variable.
*
* @param databaseInformation instance of {@code DatabaseInformation} class that includes
* all the information for making connection to the database.
* @param size the size of the pool.
* @param acquireIncrement the acquire increment of the pool.
* @throws SQLException If any database access problems happened.
* */
public ConnectionPool(DatabaseInformation databaseInformation, int size,
int acquireIncrement, QueryCreator queryCreator) throws SQLException {
if (size < 1) {
throw new IllegalArgumentException("Argument value must be equal or greater than 1: " + size);
}
if (acquireIncrement < 1) {
throw new IllegalArgumentException("Argument value must be equal or greater than 1: " + acquireIncrement);
}
this.databaseInformation = databaseInformation;
this.size = size;
this.acquireIncrement = acquireIncrement;
this.queryCreator = queryCreator;
connectionsLock = new ReentrantLock();
variableLock = new ReentrantLock();
connections = createDatabaseConnections(size, queryCreator);
}
/**
* Returns DatabaseConnection object from the pool.
* This method removes connection from the pool collection.
* After working with DatabaseConnection object you should
* return connection to the pool by invoking returnConnection() method.
*
* @return DatabaseConnection object.
* @throws SQLException If any database access problems happened.
* */
public DatabaseConnection getConnection() throws SQLException {
connectionsLock.lock();
try {
if (connections.isEmpty()) {
connections.addAll(createDatabaseConnections(getAcquireIncrement(), queryCreator));
variableLock.lock();
try {
size += acquireIncrement;
} finally {
variableLock.unlock();
}
}
return connections.remove(connections.size() - 1);
} finally {
connectionsLock.unlock();
}
}
/**
* Returns connection to the pool.
*
* @param connection Database connection which is going to be added to the pool.
* */
public void returnConnection(DatabaseConnection connection) {
connectionsLock.lock();
try {
if (connections.size() == getSize()) {
throw new IllegalArgumentException("Pool is full");
}
connections.add(connection);
} finally {
connectionsLock.unlock();
}
}
/**
* Closes all the database connections that is waiting in the pool.
*
* @throws SQLException If any database access problems happened.
* */
public void close() throws SQLException {
connectionsLock.lock();
try {
for (DatabaseConnection connection : connections) {
if (!connection.isClosed()) {
connection.close();
}
}
connections.clear();
} finally {
connectionsLock.unlock();
}
}
/**
* Returns size of the pool.
*
* @return Size of the pool.
* */
public int getSize() {
variableLock.lock();
try {
return size;
} finally {
variableLock.unlock();
}
}
/**
* Sets new size of the pool. If the new size of the pool is smaller than initial size,
* then pool will be condensed to the new size. Unnecessary connections will be closed.
*
* @throws SQLException If any database access problems happened.
* @param newSize The new pool's size.
* */
public void setSize(int newSize) throws SQLException {
if (newSize < 1) {
throw new IllegalArgumentException("Argument value must be equal or greater than 1: " + newSize);
}
connectionsLock.lock();
try {
variableLock.lock();
try {
int numberOfConnections = Math.abs(newSize - size);
if (newSize > size) {
connections.addAll(createDatabaseConnections(numberOfConnections, queryCreator));
} else {
while (numberOfConnections > 0 && !connections.isEmpty()) {
connections.remove(connections.size() - 1).close();
numberOfConnections
}
}
this.size = newSize;
} finally {
variableLock.unlock();
}
} finally {
connectionsLock.unlock();
}
}
/**
* Returns acquire increment value.
*
* @return Acquire increment value.
* */
public int getAcquireIncrement() {
variableLock.lock();
try {
return acquireIncrement;
} finally {
variableLock.unlock();
}
}
/**
* Sets new acquire increment value.
*
* @param newAcquireIncrement New acquire increment value.
* */
public void setAcquireIncrement(int newAcquireIncrement) {
if (newAcquireIncrement < 0) {
throw new IllegalArgumentException("Argument value must be equal or greater than 1:" + newAcquireIncrement);
}
variableLock.lock();
try {
this.acquireIncrement = newAcquireIncrement;
} finally {
variableLock.unlock();
}
}
/**
* Creates necessary number of database connections.
*
* @param requiredSize Number of the database connection.
* @return List of the database connections.
* @throws SQLException If any database access problems happened.
* */
private List<DatabaseConnection> createDatabaseConnections(int requiredSize, QueryCreator queryCreator) throws SQLException {
List<DatabaseConnection> conn = new ArrayList<>(requiredSize);
for (int i = 0; i < requiredSize; ++i) {
conn.add(new DatabaseConnection(databaseInformation, queryCreator));
}
return conn;
}
}
|
package org.ndexbio.task;
import java.sql.Timestamp;
import java.util.Set;
import java.util.UUID;
import org.ndexbio.common.util.NdexUUIDFactory;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.object.Status;
import org.ndexbio.model.object.Task;
import org.ndexbio.model.object.TaskType;
import org.ndexbio.model.object.network.VisibilityType;
public abstract class NdexSystemTask {
private UUID taskId ;
public NdexSystemTask() {
taskId = NdexUUIDFactory.INSTANCE.createNewNDExUUID();
}
public final UUID getTaskId() {return taskId;}
public abstract void run () throws Exception;
public abstract TaskType getTaskType();
public Task createTask() {
Timestamp t = new Timestamp(System.currentTimeMillis());
Task task = new Task();
task.setExternalId(taskId);
task.setCreationTime(t);
task.setTaskType(getTaskType());
task.setStatus(Status.QUEUED);
return task;
}
public static NdexSystemTask createSystemTask(Task t) throws NdexException {
switch (t.getTaskType()) {
case SYS_SOLR_DELETE_NETWORK:
return new SolrTaskDeleteNetwork(UUID.fromString(t.getResource()),
Boolean.getBoolean((String)t.getAttribute(SolrTaskDeleteNetwork.globalIdxAttr)));
case SYS_SOLR_REBUILD_NETWORK_INDEX:
return new SolrTaskRebuildNetworkIdx(UUID.fromString(t.getResource()), SolrIndexScope.valueOf((String)t.getAttribute(SolrTaskRebuildNetworkIdx.AttrScope)),
((Boolean)t.getAttribute(SolrTaskRebuildNetworkIdx.AttrCreateOnly)).booleanValue(),
(Set<String>)t.getAttribute("fields"));
case SYS_LOAD_NETWORK:
return new CXNetworkLoadingTask (UUID.fromString(t.getResource()),(String)t.getAttribute("owner"),
(Boolean)t.getAttribute("isUpdate"),
(t.getAttribute("visibility") != null ? VisibilityType.valueOf((String)t.getAttribute("visibility")): null),
(Set<String>)t.getAttribute("nodeIndexes"));
default:
throw new NdexException("Unknow system task: " + t.getExternalId() + " - " + t.getTaskType());
}
}
}
|
package project.v_trainning;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import java.util.Vector;
//import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
//import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
//import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import project.gps.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
public class TrainningActivity extends Activity implements LocationListener{
/***
* @param mode, MYPREFS_SETTINGS
* Variables estaticas del modo en que se guardarn las preferencias
* */
final int mode = Activity.MODE_PRIVATE;
final String MYPREFS_SETTINGS = "MyPreferencesSettings";
SharedPreferences myPreferences, myPreferencesRecover;
boolean isActivatedAjustes=false;
TextView txtActividad;
TextView txtDistancia;
Button btnTrainActStart;
GPS gps;
/*
* Variables para almacenar lo que devuelve el GPS
*/
public Vector<Long> Tiempo=new Vector();
public Vector<Float> Velocidad=new Vector();
public Vector<Float> Distancia=new Vector();
public int index=0;
/***
* @param isTrainingActive
* Variable que indica si esta activo el modo entrenamiento
* */
boolean isTrainingActive=false; //Agregado por Marlon
/**
* @param TM
* Se utiliza para el monitoreo de la actividad
*/
TrainingMonitor TM; //Agregado por Marlon
/**
* Timer
*
*
* */
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private TextView txtTiempo;
private Runnable updateTimerThread;
/***
*
* GPS
*
* */
/***
* @param E
* array de strings con posibles estados del gps
*/
private static final String[] E = { "fuera de servicio",
"temporalmente no disponible ", "disponible" };
/***
* @param manejador
* manejador del gps
*/
private LocationManager manejador;
/***
* @param salida
* para mostrar la salida en el textview
*/
//private TextView salida;
/***
* @param pointsCuantity
* para llevar orden de obtencion de las coordenadas gps
*/
private int pointsCuantity;
/***
* @param velocity
* almacena la velocidad en metros/segundo en cada punto de
* coordenadas obtenido
*/
private float velocity;
/***
* @param latitude
* almacena la latitud en grados de cada punto de coordenadas
* obtenido
*/
private double latitude;
/***
* @param longitude
* almacena la longitud en grados de cada punto de coordenadas
* obtenido
*/
private double longitude;
/***
* @param time
* almacena el tiempo UTC en milisegundos desde el 1 de enero de
* 1970 en cada punto de coordenadas obtenido
*/
private long time;
/***
* @param altitude
* almacena la altura en metros desde el nivel del mar en cada
* punto de coordenadas obtenido
*/
private double altitude;
/***
* @param distance
* almacena la distancia en metros entre el punto actual y el
* anterior
*/
private float distance;
/***
* @param lastLoc
* almacena las coordenadas del punto anterior para poder
* calcular la distancia
*/
private Location lastLoc;
/***
* @param minTime
* marca el tiempo minimo en milisegundos entre obtencion de
* coordenadas
*/
private int minTime;
/***
* @param minDist
* marca la distancia minima en metros para la obtencion de
* coordenadas
*/
private int minDist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trainning);
System.out.println("Creando Trainning");
gps = new GPS(this);
timerCore();
createWidget();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println(isActivatedAjustes);
if(isActivatedAjustes){
showSavedPreferencesSettings();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.trainning, menu);
return true;
}
private void createWidget(){
txtActividad=(TextView)findViewById(R.id.tViewTrainActAct);
txtDistancia=(TextView)findViewById(R.id.tViewTrainActDist);
txtTiempo=(TextView)findViewById(R.id.txtTiempo);
btnTrainActStart=(Button)findViewById(R.id.btnTrainActStart);
btnTrainActStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//startTraining();
System.out.println("click start");
if(!isTrainingActive){
System.out.println(isTrainingActive);
startTime();
isTrainingActive=true;
}else{
stopTime();
isTrainingActive=false;
}
}
});
}
/**
* Method to launch Settings
* */
public void launchSettingActivity(View view){
isActivatedAjustes=true;
startActivity(new Intent(TrainningActivity.this,AjustesActivity.class));
//isActivatedAjustes=true;
}
/**
* Method to launch Resume
* */
public void launchResumeActivity(View view){
startActivity(new Intent(TrainningActivity.this,ResumenActivity.class));
}
private void showSavedPreferencesSettings() {
// TODO Auto-generated method stub
myPreferencesRecover = getSharedPreferences(MYPREFS_SETTINGS,mode);
System.out.println(myPreferencesRecover.getString("nombre_actividad", "").toString());
txtActividad.setText(myPreferencesRecover.getString("nombre_actividad", "").toString());
TM=new TrainingMonitor((String) txtActividad.getText());
//actividad.setText(myPreferencesRecover.getString("nombre_actividad", ""));
}
/**
* startTraining inicia o termina la funcin de entrenmiento
* @param view
*/
public void startTraining(){
System.out.println("trainingactive="+isTrainingActive);
if (!isTrainingActive){
System.out.println("ActivedAjustes="+isActivatedAjustes);
if (isActivatedAjustes){
System.out.println("Verificando si GPS esta activo");
if (gps.isGPSactive()){
isTrainingActive=true;
// startTime();
TM.run();
}else{
Toast.makeText(getApplicationContext(), R.string.msgNoGPS, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), R.string.msgNoAjustes, Toast.LENGTH_LONG).show();
}
}
else{
isTrainingActive=false;
stopTime();
TM.showResults();
}
}
/**
*
* @author MNM
* clase encargada del monitoreo de la actividad
*/
public class TrainingMonitor extends Thread{
private String Actividad;
private boolean isActive;
TrainingMonitor(String activ){
Actividad=activ;
isActive=false;
Tiempo.clear();
Velocidad.clear();
Distancia.clear();
Tiempo.add(Long.parseLong("0"));
Velocidad.add(Float.parseFloat("0"));
Distancia.add(Float.parseFloat("0"));
index=0;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
startTrainingMonitoring();
//startTime();
}
@Override
public synchronized void start() {
// TODO Auto-generated method stub
super.start();
}
@Override
public void interrupt() {
// TODO Auto-generated method stub
super.interrupt();
isActive=false;
}
/**
* startTrainingMonitoring ejecuta el monitoreo secuencial del recorrido
*/
public void startTrainingMonitoring(){
isActive=true;
while (isActive){
try {
sleep(5000);
index=index+1;
Tiempo.add((long) (index*5));
gps.localizador();
Velocidad.add(gps.getLastSpeed());
Distancia.add(gps.getLastDistance());
//txtTiempo.setText(String.valueOf(Tiempo.get(index)));
txtDistancia.setText(String.valueOf(Distancia.get(index)));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* showResults muestra los resultados al volver a pulsar el boton play
*/
public void showResults(){
this.interrupt();
}
}
/**
* Timer
* */
private void startTime(){
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
private void stopTime(){
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
private void timerCore(){
updateTimerThread = new Runnable() {
boolean primerMultiplo=true;
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
System.out.println("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
if(GPS5Seg(secs, 5)){
if(primerMultiplo){
System.out.println("GPSSSSSS");
startGPS();
txtDistancia.setText(String.valueOf(getLastDistance()));
primerMultiplo=false;
}
}else{
primerMultiplo=true;
}
txtTiempo.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
public boolean GPS5Seg(int num1,int num2){
int resto=0;
resto=num1%num2;
if(resto==0){
return true;
}
return false;
}
};
}
public void startGPS(){
pointsCuantity = 0;
minTime = 30000;
minDist = 1;
manejador = (LocationManager) getSystemService(LOCATION_SERVICE);
log("Esperando recepcion GPS");
//Esta localizacion esta cacheada, no hay que mostrarla, es solo para comenzar mas rapido la recepcion GPS
Location lastKnownLocation = manejador.getLastKnownLocation(LocationManager.GPS_PROVIDER);
muestraLocaliz(lastKnownLocation);
manejador.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDist, this);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
log("Nueva localizaciÛn: ");
if (pointsCuantity == 1) {
lastLoc = new Location(location);
}
muestraLocaliz(location);
}
@Override
public void onProviderDisabled(String proveedor) {
// TODO Auto-generated method stub
log("Proveedor deshabilitado: " + proveedor + "\n");
}
@Override
public void onProviderEnabled(String proveedor) {
// TODO Auto-generated method stub
log("Proveedor habilitado: " + proveedor + "\n");
}
@Override
public void onStatusChanged(String proveedor, int estado, Bundle extras) {
// TODO Auto-generated method stub
log("Cambia estado proveedor: " + proveedor + ", estado="
+ E[Math.max(0, estado)] + "\n");
}
private void log(String cadena) {
//salida.append(cadena + "\n");
}
private void muestraLocaliz(Location localizacion) {
if (localizacion == null)
log("LocalizaciÛn desconocida\n");
else
if (pointsCuantity <= 1) {
distance = 0;
if (pointsCuantity == 1)
log("FirstLocation");
if (pointsCuantity == 0)
log("LastKnownLocation");
}
else {
distance = localizacion.distanceTo(lastLoc);
lastLoc = new Location(localizacion);
}
//los datos a guardar son los sigientes, mas la distance (0 para el primer punto y la diferencia entre los anteriores para el resto
//solo se necesita guardar a partir de pointsCuantity = 1, la que el 0 es el LastKnownLocation que es la cacheada
latitude = localizacion.getLatitude();
altitude = localizacion.getAltitude();
longitude = localizacion.getLongitude();
velocity = localizacion.getSpeed();
time = localizacion.getTime();
log("Localizacion[ " + "Orden=" + pointsCuantity + ", Latitud(grados)="
+ latitude +
", Longitud(grados)=" + longitude +
", Altitud(metros)=" + altitude +
", Velocidad(m/s)=" + velocity +
", Distancia(metros)=" + velocity +
", Tiempo(UTC millisegundos)=" + time + " ]\n");
pointsCuantity++;
}
public float getLastDistance(){
return distance;
}
public float getLastSpeed(){
return velocity;
}
}
|
package com4j;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
/**
* Collection of living objects of a {@link ComThread}. This collection does not hold any strong references to the objects. This way the garbage collector can
* clean up the objects. This class uses a special combination of a {@link HashMap} and {@link LinkedList}s to provide a (almost) constant runtime performance.
* @author Michael Schnell (ScM)
*/
/*package*/class LiveObjectCollection
{
/**
* The objects of this collection are weakly referenced and stored in linked lists. One list for every pointer value. This guarantees to have constant times
* for {@link #add(Com4jObject)} and {@link #remove(Com4jObject)}, assuming every COM object has a different pointer value. Since this is not necessarily the
* case for all COM references ({@link Com4jObject#queryInterface(Class)} often returns the same pointer value) the runtime of {@link #remove(Com4jObject)} is
* slightly slower, since we need to search the object in a (short) linked list.
*/
private HashMap<Integer, LinkedList<WeakReference<Com4jObject>>> objects = new HashMap<Integer, LinkedList<WeakReference<Com4jObject>>>(20);
/** The count of objects in this collection */
private int count = 0;
/**
* Adds the given object to the collection
* @param object the object to add
*/
public synchronized void add(Com4jObject object) {
LinkedList<WeakReference<Com4jObject>> list = objects.get(object.getPtr());
if (list == null) {
list = new LinkedList<WeakReference<Com4jObject>>();
objects.put(object.getPtr(), list);
}
list.add(new WeakReference<Com4jObject>(object));
count++;
}
/**
* Removes the given object from the collection
* @param object the object to remove
*/
public synchronized void remove(Com4jObject object) {
int key = object.getPtr();
List<WeakReference<Com4jObject>> list = objects.get(key);
if (list == null) {
throw new NoSuchElementException("The Com4jObject " + object + " is not in this collection!");
}
Iterator<WeakReference<Com4jObject>> it = list.iterator();
while (it.hasNext()) {
Com4jObject colObject = it.next().get();
if (colObject == null || colObject == object) {
// if colObject == null, then colObject was already finalized! This is the object we want to remove!
// There should be only one finalized object for every call of remove, because every finalization of a Wrapper calls dispose() -> calls
// dispose0() -> calls thread.removeLiveObject() -> calls this method.
it.remove();
count
break;
}
}
if (list.isEmpty())
objects.remove(key); // the list is now empty
}
/**
* Returns the count of objects in this collection.
* @return the count of objects in this collection
*/
public synchronized int getCount() {
return count;
}
/**
* Returns a snapshot of the collection as a list.
* @return a snapshot of the collection as a list
*/
public synchronized List<WeakReference<Com4jObject>> getSnapshot() {
ArrayList<WeakReference<Com4jObject>> snapshot = new ArrayList<WeakReference<Com4jObject>>(count);
Iterator<Entry<Integer, LinkedList<WeakReference<Com4jObject>>>> i = objects.entrySet().iterator();
while (i.hasNext()) {
Entry<Integer, LinkedList<WeakReference<Com4jObject>>> e = i.next();
// clean up the list since we are walking the list anyway
for (Iterator<WeakReference<Com4jObject>> j = e.getValue().iterator(); j.hasNext();) {
if (j.next().get() == null) {
j.remove();
count
}
}
if (e.getValue().isEmpty()) {
i.remove();
continue;
}
snapshot.addAll(e.getValue());
}
return snapshot;
}
/**
* Returns whether this collection is empty.
* @return whether this collection is empty
*/
public boolean isEmpty() {
return count == 0;
}
}
|
package org.openforis.ceo.users;
import static org.openforis.ceo.utils.JsonUtils.findInJsonArray;
import static org.openforis.ceo.utils.JsonUtils.intoJsonArray;
import static org.openforis.ceo.utils.JsonUtils.parseJson;
import static org.openforis.ceo.utils.JsonUtils.toStream;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.GenericData;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.openforis.ceo.env.CeoConfig;
import org.openforis.ceo.local.Users;
import org.openforis.ceo.utils.Mail;
import spark.Request;
import spark.Response;
public class OfUsers {
private static final String OF_USERS_API_URL = CeoConfig.ofUsersApiUrl;
private static final String SMTP_USER = CeoConfig.smtpUser;
private static final String SMTP_SERVER = CeoConfig.smtpServer;
private static final String SMTP_PORT = CeoConfig.smtpPort;
private static final String SMTP_PASSWORD = CeoConfig.smtpPassword;
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String AUTHENTICATION_TOKEN_NAME = "of-token";
private static HttpRequestFactory createRequestFactory() {
return HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
}
private static HttpRequestFactory createPatchRequestFactory() {
return HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
}
private static HttpRequest prepareGetRequest(String url) throws IOException {
return createRequestFactory().buildGetRequest(new GenericUrl(url));
}
private static HttpRequest preparePatchRequest(String url, GenericData data) throws IOException {
return createPatchRequestFactory()
.buildPostRequest(new GenericUrl(url),
new JsonHttpContent(new JacksonFactory(), data));
}
private static HttpRequest preparePostRequest(String url, GenericData data) throws IOException {
return createRequestFactory()
.buildPostRequest(new GenericUrl(url),
new JsonHttpContent(new JacksonFactory(), data));
}
private static HttpRequest prepareDeleteRequest(String url) throws IOException {
return createRequestFactory().buildDeleteRequest(new GenericUrl(url));
}
private static JsonElement getResponseAsJson(HttpResponse response) throws IOException {
return parseJson(response.parseAsString());
}
/**
* Call Of-Users' REST API to QUERY the database.
* @param req
* @param res
* @return
*/
public static Request login(Request req, Response res) {
String inputEmail = req.queryParams("email");
String inputPassword = req.queryParams("password");
try {
GenericData data = new GenericData();
data.put("username", inputEmail);
data.put("rawPassword", inputPassword);
HttpResponse response = preparePostRequest(OF_USERS_API_URL + "login", data).execute(); // login
if (response.isSuccessStatusCode()) {
// Authentication successful
String token = getResponseAsJson(response).getAsJsonObject().get("token").getAsString();
setAuthenticationToken(req, res, token);
HttpRequest userRequest = prepareGetRequest(OF_USERS_API_URL + "user"); // get user
userRequest.getUrl().put("username", inputEmail);
String userId = getResponseAsJson(userRequest.execute()).getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString();
HttpRequest roleRequest = prepareGetRequest(OF_USERS_API_URL + "user/" + userId + "/groups"); // get roles
JsonArray jsonRoles = getResponseAsJson(roleRequest.execute()).getAsJsonArray();
Optional<JsonObject> matchingRole = findInJsonArray(jsonRoles, jsonRole -> jsonRole.get("groupId").getAsString().equals("1"));
String role = matchingRole.isPresent() ? "admin" : "user";
req.session().attribute("token", token);
req.session().attribute("userid", userId);
req.session().attribute("username", inputEmail);
req.session().attribute("role", role);
res.redirect(CeoConfig.documentRoot + "/home");
} else {
// Authentication failed
req.session().attribute("flash_messages", new String[]{"Invalid email/password combination."});
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
return req;
}
public static Request register(Request req, Response res) {
String inputEmail = req.queryParams("email");
String inputPassword = req.queryParams("password");
String inputPasswordConfirmation = req.queryParams("password-confirmation");
try {
// Validate input params and assign flash_messages if invalid
if (!Users.isEmail(inputEmail)) {
req.session().attribute("flash_messages", new String[]{inputEmail + " is not a valid email address."});
} else if (inputPassword.length() < 8) {
req.session().attribute("flash_messages", new String[]{"Password must be at least 8 characters."});
} else if (!inputPassword.equals(inputPasswordConfirmation)) {
req.session().attribute("flash_messages", new String[]{"Password and Password confirmation do not match."});
} else {
HttpRequest userRequest = prepareGetRequest(OF_USERS_API_URL + "user"); // get user
userRequest.getUrl().put("username", inputEmail);
HttpResponse response = userRequest.execute();
if (response.isSuccessStatusCode()) {
JsonArray users = getResponseAsJson(response).getAsJsonArray();
if (users.size() > 0) {
req.session().attribute("flash_messages", new String[]{"Account " + inputEmail + " already exists."});
} else {
// Add a new user to the database
GenericData data = new GenericData();
data.put("username", inputEmail);
data.put("rawPassword", inputPassword);
response = preparePostRequest(OF_USERS_API_URL + "user", data).execute(); // register
if (response.isSuccessStatusCode()) {
String newUserId = getResponseAsJson(response).getAsJsonObject().get("id").getAsString();
// Assign the username and role session attributes
req.session().attribute("userid", newUserId);
req.session().attribute("username", inputEmail);
req.session().attribute("role", "user");
response = preparePostRequest(OF_USERS_API_URL + "login", data).execute(); // login
if (response.isSuccessStatusCode()) {
// Authentication successful
String token = getResponseAsJson(response).getAsJsonObject().get("token").getAsString();
setAuthenticationToken(req, res, token);
}
// Redirect to the Home page
res.redirect(CeoConfig.documentRoot + "/home");
}
}
} else {
throw new IOException();
}
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
return req;
}
public static Request logout(Request req, Response res) {
GenericData data = new GenericData();
data.put("username", req.session().attribute("username"));
data.put("token", req.session().attribute("token"));
try {
preparePostRequest(OF_USERS_API_URL + "logout", data).execute();
} catch (IOException e) {
e.printStackTrace();
} finally {
req.session().removeAttribute("userid");
req.session().removeAttribute("username");
req.session().removeAttribute("role");
req.session().removeAttribute("token");
// FIXME: Does the new code do what the commented out code used to do?
// res.removeCookie("/", AUTHENTICATION_TOKEN_NAME);
res.removeCookie(AUTHENTICATION_TOKEN_NAME);
}
return req;
}
public static Request updateAccount(Request req, Response res) {
String userId = req.session().attribute("userid");
String inputEmail = req.queryParams("email");
String inputPassword = req.queryParams("password");
String inputPasswordConfirmation = req.queryParams("password-confirmation");
String inputCurrentPassword = req.queryParams("current-password");
// Validate input params and assign flash_messages if invalid
if (!Users.isEmail(inputEmail)) {
req.session().attribute("flash_messages", new String[]{inputEmail + " is not a valid email address."});
} else if (inputPassword.length() < 8) {
req.session().attribute("flash_messages", new String[]{"Password must be at least 8 characters."});
} else if (!inputPassword.equals(inputPasswordConfirmation)) {
req.session().attribute("flash_messages", new String[]{"Password and Password confirmation do not match."});
} else {
try {
GenericData data = new GenericData();
data.put("username", inputEmail);
data.put("rawPassword", inputCurrentPassword);
HttpResponse response = preparePostRequest(OF_USERS_API_URL + "login", data).execute();
if (response.isSuccessStatusCode()) {
data = new GenericData();
data.put("username", inputEmail);
String url = String.format(OF_USERS_API_URL + "user/%s", userId);
preparePatchRequest(url, data).execute();
data = new GenericData();
data.put("username", inputEmail);
data.put("newPassword", inputPassword);
preparePostRequest(OF_USERS_API_URL + "change-password", data).execute();
req.session().attribute("username", inputEmail);
req.session().attribute("flash_messages", new String[]{"The user has been updated."});
} else {
req.session().attribute("flash_messages", new String[]{"Invalid password."});
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
}
return req;
}
public static Request getPasswordResetKey(Request req, Response res) {
String inputEmail = req.queryParams("email");
try {
GenericData data = new GenericData();
data.put("username", inputEmail);
HttpResponse response = preparePostRequest(OF_USERS_API_URL + "reset-password", data).execute(); // reset password key request
if (response.isSuccessStatusCode()) {
JsonObject user = getResponseAsJson(response).getAsJsonObject();
String body = "Hi "
+ inputEmail
+ ",\n\n"
+ " To reset your password, simply click the following link:\n\n"
+ " http://ceo.sig-gis.com/password-reset?email="
+ inputEmail
+ "&password-reset-key="
+ user.get("resetKey").getAsString();
Mail.sendMail(SMTP_USER, inputEmail, SMTP_SERVER, SMTP_PORT, SMTP_PASSWORD, "Password reset on CEO", body);
req.session().attribute("flash_messages", new String[]{"The reset key has been sent to your email."});
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
return req;
}
public static Request resetPassword(Request req, Response res) {
String inputEmail = req.queryParams("email");
String inputResetKey = req.queryParams("password-reset-key");
String inputPassword = req.queryParams("password");
String inputPasswordConfirmation = req.queryParams("password-confirmation");
// Validate input params and assign flash_messages if invalid
if (inputPassword.length() < 8) {
req.session().attribute("flash_messages", new String[]{"Password must be at least 8 characters."});
} else if (!inputPassword.equals(inputPasswordConfirmation)) {
req.session().attribute("flash_messages", new String[]{"Password and Password confirmation do not match."});
} else {
try {
GenericData data = new GenericData();
data.put("username", inputEmail);
data.put("resetKey", inputResetKey);
data.put("newPassword", inputPassword);
HttpResponse response = preparePostRequest(OF_USERS_API_URL + "reset-password", data).execute(); // reset password request
if (response.isSuccessStatusCode()) {
req.session().attribute("flash_messages", new String[]{"The password has been changed."});
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
}
return req;
}
public static String getAllUsers(Request req, Response res) {
String institutionId = req.queryParams("institutionId");
try {
return getAllUsers(institutionId).toString();
} catch (Exception e) {
req.session().attribute("flash_messages", new String[]{e.getMessage()});
return new JsonArray().toString();
}
}
public static JsonArray getAllUsers(String institutionId) {
try {
if (institutionId != null) {
String url = String.format(OF_USERS_API_URL + "group/%s/users", institutionId);
HttpResponse response = prepareGetRequest(url).execute(); // get group's users
if (response.isSuccessStatusCode()) {
JsonArray groupUsers = getResponseAsJson(response).getAsJsonArray();
return toStream(groupUsers)
.map(groupUser -> {
groupUser.getAsJsonObject("user").addProperty("institutionRole",
groupUser.get("roleCode").getAsString().equals("ADM") ? "admin"
: groupUser.get("roleCode").getAsString().equals("OWN") ? "admin"
: groupUser.get("roleCode").getAsString().equals("OPR") ? "member"
: groupUser.get("roleCode").getAsString().equals("VWR") ? "member"
: groupUser.get("statusCode").getAsString().equals("P") ? "pending"
: "not-member");
return groupUser.getAsJsonObject("user");
})
.map(user -> {
user.addProperty("email", user.get("username").getAsString());
return user;
})
.filter(user -> !user.get("email").getAsString().equals("admin@sig-gis.com"))
.collect(intoJsonArray);
} else {
throw new RuntimeException("An error occurred. Please try again later.");
}
} else {
HttpResponse response = prepareGetRequest(OF_USERS_API_URL + "user").execute(); // get all the users
if (response.isSuccessStatusCode()) {
JsonArray users = getResponseAsJson(response).getAsJsonArray();
return toStream(users)
.map(user -> {
user.addProperty("email", user.get("username").getAsString());
return user;
})
.filter(user -> !user.get("email").getAsString().equals("admin@sig-gis.com"))
.collect(intoJsonArray);
} else {
throw new RuntimeException("An error occurred. Please try again later.");
}
}
} catch (IOException e) {
e.printStackTrace(); //TODO
// FIXME: Raise a red flag that an error just occurred in communicating with the database
return new JsonArray();
}
}
public static Map<Integer, String> getInstitutionRoles(int userId) {
try {
String url = String.format(OF_USERS_API_URL + "user/%d/groups", userId);
HttpResponse response = prepareGetRequest(url).execute(); // get user's groups
if (response.isSuccessStatusCode()) {
JsonArray userGroups = getResponseAsJson(response).getAsJsonArray();
return toStream(userGroups)
.collect(Collectors.toMap(userGroup -> userGroup.get("groupId").getAsInt(),
userGroup -> {
String roleCode = userGroup.get("roleCode").getAsString();
return roleCode.equals("ADM") || roleCode.equals("OWN") ? "admin"
: roleCode.equals("OPR") || roleCode.equals("VWR") ? "member"
: "not-member";},
(a, b) -> b));
} else {
// FIXME: Raise a red flag that an error just occurred in communicating with the database
return new HashMap<Integer, String>();
}
} catch (IOException e) {
e.printStackTrace(); //TODO
// FIXME: Raise a red flag that an error just occurred in communicating with the database
return new HashMap<Integer, String>();
}
}
private static JsonObject groupToInstitution(String groupId) {
JsonObject group = new JsonObject();
String url = String.format(OF_USERS_API_URL + "group/%s", groupId);
HttpResponse response;
try {
response = prepareGetRequest(url).execute();
if (response.isSuccessStatusCode()) {
group = getResponseAsJson(response).getAsJsonObject();
url = String.format(OF_USERS_API_URL + "group/%s/users", groupId);
response = prepareGetRequest(url).execute();
JsonArray groupUsers = getResponseAsJson(response).getAsJsonArray();
JsonArray members = new JsonArray();
JsonArray admins = new JsonArray();
JsonArray pending = new JsonArray();
toStream(groupUsers).forEach(groupUser -> {
if (groupUser.get("statusCode").getAsString().equals("P")) pending.add(groupUser.get("userId"));
else if (groupUser.get("roleCode").getAsString().equals("ADM")) admins.add(groupUser.get("userId"));
else if (groupUser.get("roleCode").getAsString().equals("OWN")) admins.add(groupUser.get("userId"));
else if (groupUser.get("roleCode").getAsString().equals("OPR")) members.add(groupUser.get("userId"));
else if (groupUser.get("roleCode").getAsString().equals("VWR")) members.add(groupUser.get("userId"));
});
group.add("admins", admins);
group.add("members", members);
group.add("pending", pending);
}
} catch (IOException e) {
e.printStackTrace();
}
return group;
}
public static Optional<JsonObject> updateInstitutionRole(Request req, Response res) {
JsonObject jsonInputs = parseJson(req.body()).getAsJsonObject();
String userId = jsonInputs.get("userId").getAsString();
String groupId = jsonInputs.get("institutionId").getAsString();
String role = jsonInputs.get("role").getAsString();
try {
String url = String.format(OF_USERS_API_URL + "group/%s/user/%s", groupId, userId);
try {
HttpResponse response = prepareGetRequest(url).execute();
if (response.isSuccessStatusCode()) {
String newRoleCode = "";
if (role.equals("member")) {
newRoleCode = "OPR";
} else if (role.equals("admin")) {
newRoleCode = "ADM";
}
if (!newRoleCode.isEmpty()) {
GenericData data = new GenericData();
data.put("roleCode", newRoleCode);
data.put("statusCode", "A");
preparePatchRequest(url, data).execute();
} else {
prepareDeleteRequest(url).execute();
}
}
} catch (HttpResponseException e) {
if (e.getStatusCode() == 404) {
GenericData data = new GenericData();
data.put("roleCode", "OPR");
data.put("statusCode", "A");
preparePostRequest(url, data).execute(); // add user to a group (as accepted)
} else {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
}
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
}
JsonObject group = groupToInstitution(groupId);
return Optional.ofNullable(group);
}
public static String requestInstitutionMembership(Request req, Response res) {
JsonObject jsonInputs = parseJson(req.body()).getAsJsonObject();
String userId = jsonInputs.get("userId").getAsString();
String groupId = jsonInputs.get("institutionId").getAsString();
try {
String url = String.format(OF_USERS_API_URL + "group/%s/user/%s", groupId, userId);
GenericData data = new GenericData();
data.put("roleCode", "OPR");
data.put("statusCode", "P");
preparePostRequest(url, data).execute(); // add user to a group (as pending)
return "";
} catch (IOException e) {
e.printStackTrace(); //TODO
req.session().attribute("flash_messages", new String[]{"An error occurred. Please try again later."});
return "";
}
}
private static void setAuthenticationToken(Request req, Response res, String token) {
String host = req.host();
if (host.indexOf(':') > -1) {
host = host.substring(0, host.lastIndexOf(':')); //remove port from host
}
// FIXME: Does the new code do what the commented out code used to do?
// res.cookie(host, "/", AUTHENTICATION_TOKEN_NAME, token, -1, false, false);
res.cookie(AUTHENTICATION_TOKEN_NAME, token);
}
}
|
package com.vimeo.networking.model.error;
import com.google.gson.annotations.SerializedName;
import com.vimeo.stag.UseStag;
@SuppressWarnings("unused")
@UseStag
public enum ErrorCode {
// The default code that will be returned if the code returned from the server isn't enumerated below
// If that is the case, check the raw response for the code [KV]
DEFAULT,
// <editor-fold desc="General">
@SerializedName("1000")
BAD_REQUEST,
@SerializedName("1001")
UNAUTHORIZED,
@SerializedName("1002")
FORBIDDEN,
@SerializedName("1003")
NOT_FOUND,
@SerializedName("1004")
INTERNAL_SERVER_ERROR,
@SerializedName("1005")
NOT_IMPLEMENTED,
@SerializedName("1006")
SERVICE_UNAVAILABLE,
@SerializedName("2000")
MISSING_REQUIRED_HEADER,
@SerializedName("2001")
MISSING_REQUIRED_QUERY_PARAM,
@SerializedName("2002")
MISSING_REQUIRED_BODY,
@SerializedName("2100")
UNSUPPORTED_HEADER,
@SerializedName("2101")
UNSUPPORTED_QUERY_PARAM,
@SerializedName("2200")
INVALID_HEADER_VALUE,
@SerializedName("2201")
INVALID_QUERY_PARAM_VALUE,
@SerializedName("2202")
INVALID_URI,
@SerializedName("2203")
INVALID_AUTHENTICATION_INFO,
@SerializedName("2204")
INVALID_INPUT,
@SerializedName("2205")
INVALID_BODY,
@SerializedName("2206")
INVALID_ACCEPT_HEADER,
@SerializedName("2207")
INVALID_NO_INPUT,
@SerializedName("2219")
INVALID_INPUT_GRANT_TYPE,
@SerializedName("2220")
INVALID_INPUT_EMBED_TYPE,
@SerializedName("2221")
INVALID_INPUT_VIEW_TYPE,
@SerializedName("2222")
INVALID_INPUT_VIDEO_PASSWORD_MISMATCH,
@SerializedName("2223")
INVALID_INPUT_VIDEO_NO_PASSWORD,
@SerializedName("2300")
INVALID_TOKEN,
@SerializedName("2301")
NON_EXISTENT_PROPERTY,
@SerializedName("2302")
MALFORMED_TOKEN,
@SerializedName("2315")
UNABLE_TO_CREATE_USER_CAN_NOT_VALIDATE_TOKEN,
@SerializedName("2500")
APP_DOES_NOT_HAVE_DELETE_CAPABILITY,
@SerializedName("2700")
INVALID_INPUT_NON_JSON_CONTENT_TYPE,
@SerializedName("2507")
PRODUCT_NOT_FOUND,
@SerializedName("3113")
INVALID_INPUT_GOOGLE_RECEIPT_VALIDATION_FAILED,
@SerializedName("3115")
INVALID_INPUT_RECEIPT_VALIDATION_UNSUCCESSFUL,
@SerializedName("4000")
OPERATION_TIMED_OUT,
@SerializedName("5000")
RESOURCE_NOT_FOUND,
@SerializedName("5001")
ACCESS_TOKEN_NOT_GENERATED,
@SerializedName("6000")
METHOD_NOT_IMPLEMENTED,
@SerializedName("7000")
SERVER_BUSY,
@SerializedName("7100")
SERVER_OVERLOADED,
@SerializedName("8000")
INVALID_CREDENTIALS,
@SerializedName("8001")
UNAUTHORIZED_CLIENT,
@SerializedName("8003")
EMPTY_AUTHENTICATION,
// </editor-fold>
// <editor-fold desc="Auth">
// Input
@SerializedName("2208")
INVALID_INPUT_NAME_TOO_LONG,
@SerializedName("2209")
INVALID_INPUT_NO_PASSWORD,
@SerializedName("2210")
INVALID_INPUT_PASSWORD_TOO_SHORT,
@SerializedName("2211")
INVALID_INPUT_PASSWORD_TOO_SIMPLE,
@SerializedName("2212")
INVALID_INPUT_PASSWORD_TOO_OBVIOUS,
@SerializedName("2213")
INVALID_INPUT_NO_NAME,
@SerializedName("2214")
INVALID_INPUT_NO_EMAIL,
@SerializedName("2215")
INVALID_INPUT_NO_RFC_822_EMAIL,
@SerializedName("2216")
INVALID_INPUT_EMAIL_TOO_LONG,
@SerializedName("2217")
INVALID_INPUT_EMAIL_NOT_RECOGNIZED,
@SerializedName("2218")
INVALID_INPUT_PASSWORD_EMAIL_MISMATCH,
@SerializedName("3102")
INVALID_INPUT_PASSWORD_TOO_LONG,
// Auth Errors
@SerializedName("2303")
UNABLE_TO_CREATE_USER_INVALID_TOKEN,
@SerializedName("2304")
UNABLE_TO_CREATE_USER_NON_EXISTENT_PROPERTY,
@SerializedName("2305")
UNABLE_TO_CREATE_USER_MALFORMED_TOKEN,
@SerializedName("2306")
UNABLE_TO_CREATE_USER_NO_TOKEN,
@SerializedName("2307")
UNABLE_TO_CREATE_USER_TOKEN_CAN_NOT_DECRYPT,
@SerializedName("2308")
UNABLE_TO_CREATE_USER_TOKEN_TOO_LONG,
@SerializedName("2310")
UNABLE_TO_LOGIN_NON_EXISTENT_PROPERTY,
@SerializedName("2311")
UNABLE_TO_LOGIN_MALFORMED_TOKEN,
@SerializedName("2312")
UNABLE_TO_LOGIN_NO_TOKEN,
@SerializedName("2313")
UNABLE_TO_LOGIN_TOKEN_CAN_NOT_DECRYPT,
@SerializedName("2314")
UNABLE_TO_LOGIN_TOKEN_TOO_LONG,
// Google Auth Errors
@SerializedName("2325")
UNABLE_TO_CREATE_USER_MISSING_EMAIL_GOOGLE,
@SerializedName("2326")
UNABLE_TO_CREATE_USER_TOKEN_TOO_LONG_GOOGLE,
@SerializedName("2327")
UNABLE_TO_LOGIN_NO_TOKEN_GOOGLE,
@SerializedName("2328")
UNABLE_TO_LOGIN_NON_EXISTENT_PROPERTY_GOOGLE,
@SerializedName("2329")
UNABLE_TO_LOGIN_EMAIL_NOT_FOUND_VIA_TOKEN_GOOGLE,
@SerializedName("2330")
UNABLE_TO_CREATE_USER_INSUFFICIENT_PERMISSIONS_GOOGLE,
@SerializedName("2331")
UNABLE_TO_CREATE_USER_CAN_NOT_VALIDATE_TOKEN_GOOGLE,
@SerializedName("2332")
UNABLE_TO_CREATE_USER_DAILY_LIMIT_GOOGLE,
@SerializedName("2333")
UNABLE_TO_LOGIN_INSUFFICIENT_PERMISSIONS_GOOGLE,
@SerializedName("2334")
UNABLE_TO_LOGIN_CAN_NOT_VALIDATE_TOKEN_GOOGLE,
@SerializedName("2335")
UNABLE_TO_LOGIN_DAILY_LIMIT_GOOGLE,
@SerializedName("2336")
UNABLE_TO_LOGIN_GOOGLE_COULD_NOT_VERIFY_TOKEN,
@SerializedName("2337")
UNABLE_TO_CREATE_USER_GOOGLE_COULD_NOT_VERIFY_TOKEN,
// Generic Auth Errors
@SerializedName("2400")
USER_EXISTS,
@SerializedName("2401")
EMAIL_BLOCKED,
@SerializedName("2402")
SPAMMER_USER,
@SerializedName("2403")
PURGATORY_USER,
@SerializedName("2404")
URL_UNAVAILABLE,
@SerializedName("2406")
USER_NOT_AUTHORIZED_TO_DELETE_ACCOUNT,
// </editor-fold>
// <editor-fold desc="Video Settings">
// Inputs
@SerializedName("2230")
INVALID_INPUT_BAD_UPLOAD_TYPE,
@SerializedName("2231")
INVALID_INPUT_NO_CLIP_NAME,
@SerializedName("2232")
INVALID_INPUT_BAD_CLIP_PRIVACY_VIEW,
@SerializedName("2233")
INVALID_INPUT_CLIP_PRIVACY_PASSWORD_MISSING_PASSWORD2233,
@SerializedName("2234")
INVALID_INPUT_BAD_LICENSE_TYPE,
@SerializedName("2235")
INVALID_INPUT_BAD_LANGUAGE_TYPE,
@SerializedName("2236")
INVALID_INPUT_BAD_REVIEW_LINK,
@SerializedName("2237")
INVALID_INPUT_BAD_CLIP_PRIVACY_ADD,
@SerializedName("2238")
INVALID_INPUT_BAD_CLIP_PRIVACY_DOWNLOAD,
@SerializedName("2239")
INVALID_INPUT_BAD_CLIP_PRIVACY_EMBED,
@SerializedName("2240")
INVALID_INPUT_BAD_CLIP_PRIVACY_COMMENTS,
@SerializedName("2241")
INVALID_INPUT_BAD_USER_URI,
@SerializedName("2242")
INVALID_INPUT_NO_USER_URI,
@SerializedName("2244")
INVALID_INPUT_NO_CLIP_USERS,
@SerializedName("2245")
INVALID_INPUT_EMPTY_USERS_ARRAY,
@SerializedName("2246")
CLIP_PRIVACY_NOT_SET_TO_USERS,
@SerializedName("2247")
INVALID_INPUT_NO_CLIP_PRIVACY_WHEN_SETTING_USERS,
@SerializedName("2248")
INVALID_INPUT_BAD_CLIP_PRIVACY_FOR_SETTING_USERS,
@SerializedName("2249")
INVALID_INPUT_BAD_CLIP_DESCRIPTION_TYPE,
@SerializedName("2250")
INVALID_INPUT_CLIP_NAME_TOO_LONG,
@SerializedName("2251")
INVALID_INPUT_CLIP_DESCRIPTION_TOO_LONG,
@SerializedName("2252")
INVALID_INPUT_BAD_CLIP_NAME_TYPE,
@SerializedName("2253")
INVALID_INPUT_EMPTY_USER_NAME,
@SerializedName("2409")
USER_NOT_ALLOWED_TO_SET_PUBLIC_OR_NOBODY_CLIP_PRIVACY,
@SerializedName("2410")
USER_NOT_ALLOWED_TO_SET_USERS_CLIP_PRIVACY,
@SerializedName("2411")
USER_NOT_ALLOWED_TO_SET_DISABLE_CLIP_PRIVACY,
@SerializedName("2412")
USER_NOT_ALLOWED_TO_SET_CONTACTS_CLIP_PRIVACY,
// Upload
@SerializedName("8002")
UNABLE_TO_UPLOAD_VIDEO_MISSING_USER_ID_FOR_AUTHENTICATION_TOKEN,
@SerializedName("3400")
USER_NOT_ALLOWED_TO_UPLOAD_VIDEO_UNVERIFIED_EMAIL,
@SerializedName("4003")
UPLOAD_TICKET_CREATION_ERROR,
@SerializedName("3428")
UPLOAD_QUOTA_SIZE_EXCEEDED_CAP,
@SerializedName("4101")
UPLOAD_QUOTA_SIZE_EXCEEDED,
@SerializedName("4102")
UPLOAD_QUOTA_COUNT_EXCEEDED,
// Albums
@SerializedName("3200")
ALBUM_THUMBNAIL_ACCESS_FORBIDDEN,
@SerializedName("3429")
ALBUM_EDIT_FORBIDDEN_FOR_AUTHENTICATED_USER,
@SerializedName("3433")
ADD_VIDEO_TO_ALBUM_FORBIDDEN,
@SerializedName("4016")
UNEXPECTED_ALBUM_THUMBNAIL_EXCEPTION,
// Unused
// These most likely won't affect the Vimeo app since we don't currently have these settings
@SerializedName("2254")
INVALID_INPUT_BAD_CLIP_SIZE_TYPE,
@SerializedName("2255")
INVALID_INPUT_BAD_CLIP_UPGRADE_TO_1080_TYPE,
@SerializedName("2256")
INVALID_INPUT_BAD_CLIP_REDIRECT_URL_TYPE,
@SerializedName("2257")
INVALID_INPUT_BAD_CLIP_MACHINE_ID_TYPE,
@SerializedName("2258")
INVALID_INPUT_BAD_CLIP_CREATE_CLIP_TYPE,
@SerializedName("2259")
INVALID_INPUT_BAD_CLIP_CONTENT_RATINGS_TYPE,
@SerializedName("2260")
INVALID_INPUT_BAD_CLIP_SHOW_LIKE_BUTTON_TYPE,
@SerializedName("2261")
INVALID_INPUT_BAD_CLIP_SHOW_WATCH_LATER_BUTTON,
@SerializedName("2262")
INVALID_INPUT_BAD_CLIP_SHOW_SHARE_BUTTON_TYPE,
@SerializedName("2263")
INVALID_INPUT_BAD_CLIP_SHOW_EMBED_BUTTON_TYPE,
@SerializedName("2264")
INVALID_INPUT_BAD_CLIP_ALLOW_HD_EMBED_TYPE,
@SerializedName("2265")
INVALID_INPUT_BAD_CLIP_SHOW_FULLSCREEN_BUTTON_TYPE,
@SerializedName("2266")
INVALID_INPUT_BAD_CLIP_SHOW_VIMEO_LOGO_TYPE,
@SerializedName("2267")
INVALID_INPUT_BAD_CLIP_SHOW_CUSTOM_LOGO_TYPE,
@SerializedName("2268")
INVALID_INPUT_BAD_CLIP_CUSTOM_LOGO_STICKY_TYPE,
@SerializedName("2269")
INVALID_INPUT_BAD_CLIP_CUSTOM_LOGO_LINK_URL_TYPE,
@SerializedName("2270")
INVALID_INPUT_BAD_CLIP_SHOW_PLAYBAR_URL_TYPE,
@SerializedName("2271")
INVALID_INPUT_BAD_CLIP_SHOW_VOLUME_TYPE,
@SerializedName("2272")
INVALID_INPUT_BAD_CLIP_COLOR_TYPE,
@SerializedName("2273")
INVALID_INPUT_BAD_CLIP_PRIVACY_PASSWORD_EMPTY_PASSWORD,
@SerializedName("2274")
INVALID_INPUT_BAD_CLIP_SHOW_BYLINE_TYPE,
@SerializedName("2275")
INVALID_INPUT_BAD_CLIP_SHOW_PORTRAIT_TYPE,
@SerializedName("2276")
INVALID_INPUT_BAD_CLIP_SHOW_TITLE_TYPE,
@SerializedName("2277")
INVALID_INPUT_BAD_CLIP_SHOW_SCALING_BUTTON_TYPE,
@SerializedName("2501")
APP_DOES_NOT_HAVE_PROTECTED_VIDEO_CAPABILITY,
// </editor-fold>
// DRM
// <editor-fold desc="DRM">
@SerializedName("2297")
INVALID_INPUT_DRM_NOT_ENABLED_ON_CLIP,
@SerializedName("2298")
INVALID_INPUT_BAD_LOGGING_PLAY_TYPE,
@SerializedName("3419")
USER_CANNOT_STREAM_CLIP,
@SerializedName("3420")
USER_HIT_STREAM_LIMITS_FOR_VIDEO,
@SerializedName("3421")
USER_HIT_DEVICE_LIMIT,
@SerializedName("8300")
DRM_INVALID_CREDENTIALS
// </editor-fold>
}
|
package com.gelvt.gofdp.visitor;
public class DirectoryStructureDisplayer implements FileInfoVisitor {
private int basePathDepth;
public DirectoryStructureDisplayer(int basePathDepth) {
this.basePathDepth = basePathDepth;
}
@Override
public void visitFile(RegularFileInfo file) {
int depth = file.getPath().split("/").length - basePathDepth - 1;
for(int i = 0; i < depth; i++){
System.out.printf(" ");
}
if (depth > 0){
System.out.printf("|
}
System.out.println(file.getName());
}
@Override
public void visitFile(DirectoryInfo directory) {
int depth = directory.getPath().split("/").length - basePathDepth - 1;
for(int i = 0; i < depth; i++){
System.out.printf(" ");
}
if (depth > 0){
System.out.printf("|
}
System.out.println(directory.getName() + "/");
}
}
|
package org.voovan.http.message;
import org.voovan.http.message.packet.Body;
import org.voovan.http.message.packet.Cookie;
import org.voovan.http.message.packet.Header;
import org.voovan.http.message.packet.ResponseProtocol;
import org.voovan.http.server.context.WebContext;
import org.voovan.network.IoSession;
import org.voovan.tools.FastThreadLocal;
import org.voovan.tools.buffer.TByteBuffer;
import org.voovan.tools.TString;
import org.voovan.tools.exception.MemoryReleasedException;
import org.voovan.tools.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class Response {
private static FastThreadLocal<StringBuilder> THREAD_STRING_BUILDER = FastThreadLocal.withInitial(()->new StringBuilder(512));
public static FastThreadLocal<ByteBuffer> THREAD_BYTE_BUFFER = FastThreadLocal.withInitial(()->TByteBuffer.allocateDirect());
private ResponseProtocol protocol;
private Header header;
private List<Cookie> cookies;
private Body body;
private boolean isCompress;
protected boolean basicSend = false;
private boolean autoSend = true;
private Long mark;
/**
*
*
* @param response
*/
protected Response(Response response) {
init(response);
}
public void init(Response response){
this.protocol = response.protocol;
this.header = response.header;
this.body = response.body;
this.cookies = response.cookies;
this.isCompress = response.isCompress;
this.basicSend = false;
this.mark = response.mark;
}
public Response() {
protocol = new ResponseProtocol();
header = new Header();
cookies = new ArrayList<Cookie>();
body = new Body();
isCompress = false;
this.basicSend = false;
}
public Long getMark() {
return mark;
}
public void setMark(Long mark) {
this.mark = mark;
}
/**
* true
*
* @return
*/
public boolean isCompress() {
return isCompress;
}
/**
*
*
* @param isCompress
*/
public void setCompress(boolean isCompress) {
this.isCompress = isCompress;
}
/**
*
* @return true: , false:
*/
public boolean isAutoSend() {
return autoSend;
}
/**
*
* @param autoSend true: , false:
*/
public void setAutoSend(boolean autoSend) {
this.autoSend = autoSend;
}
/**
*
*
* @return
*/
public ResponseProtocol protocol() {
return protocol;
}
/**
* Header
*
* @return HTTP-Header
*/
public Header header() {
return header;
}
/**
* Cookies, List
*
* @return Cookie
*/
public List<Cookie> cookies() {
return cookies;
}
/**
* Body
*
* @return Body
*/
public Body body() {
return body;
}
/**
* Header
*/
private void initHeader() {
// Header
if (body.size()!=0 && isCompress) {
header.put(HttpStatic.TRANSFER_ENCODING_STRING, HttpStatic.CHUNKED_STRING);
header.put(HttpStatic.CONTENT_ENCODING_STRING, HttpStatic.GZIP_STRING);
} else {
header.put(HttpStatic.CONTENT_LENGTH_STRING, Integer.toString((int)body.size()));
}
if (!header.contain(HttpStatic.CONTENT_TYPE_STRING)) {
header.put(HttpStatic.CONTENT_TYPE_STRING, HttpStatic.TEXT_HTML_STRING + WebContext.getWebServerConfig().getResponseCharacterSet());
} else {
header.put(HttpStatic.CONTENT_TYPE_STRING, header.get(HttpStatic.CONTENT_TYPE_STRING) + WebContext.getWebServerConfig().getResponseCharacterSet());
}
}
/**
* Cookie , HTTP Cookie
*
* @return Cookie
*/
private String genCookie() {
StringBuilder cookieString = new StringBuilder();
for (Cookie cookie : cookies) {
cookieString.append("Set-Cookie: ");
cookieString.append(cookie.toString());
cookieString.append(HttpStatic.LINE_MARK_STRING);
}
return cookieString.toString();
}
/**
* , Http
*
* @return ByteBuffer
*/
private byte[] readHead() {
StringBuilder stringBuilder = THREAD_STRING_BUILDER.get();
stringBuilder.setLength(0);
initHeader();
stringBuilder.append(protocol.toString());
stringBuilder.append(header.toString());
stringBuilder.append(genCookie());
return TString.toAsciiBytes(stringBuilder.toString());
}
public static byte[] EMPTY_BYTES = new byte[0];
private byte[] readEnd(){
if (isCompress) {
return TString.toAsciiBytes("0" + HttpStatic.BODY_MARK_STRING);
}else{
return EMPTY_BYTES;
}
}
/**
*
* @param session socket
* @throws IOException IO
*/
public void send(IoSession session) throws IOException {
try {
ByteBuffer byteBuffer = THREAD_BYTE_BUFFER.get();
byteBuffer.clear();
try {
byteBuffer.put(readHead());
byteBuffer.put(WebContext.RESPONSE_COMMON_HEADER);
} catch (Throwable e) {
if (!(e instanceof MemoryReleasedException)) {
Logger.error("Response writeToChannel error: ", (Exception) e);
}
}
if (isCompress) {
body.compress();
}
int readSize = 0;
try {
int totalBodySize = (int) body.size();
while ( totalBodySize > 0) {
// chunked
byteBuffer.limit(byteBuffer.capacity() - 10); //, 4,1-6
readSize = byteBuffer.remaining() > totalBodySize ? totalBodySize : byteBuffer.remaining();
totalBodySize = totalBodySize - readSize;
// chunked
if (isCompress() && readSize != 0) {
String chunkedLengthLine = Integer.toHexString(readSize) + HttpStatic.LINE_MARK_STRING;
byteBuffer.put(chunkedLengthLine.getBytes());
}
// Bytebuffer readSize
byteBuffer.limit(byteBuffer.position() + readSize);
body.read(byteBuffer);
byteBuffer.position(byteBuffer.limit());
byteBuffer.limit(byteBuffer.capacity());
// chunked
if (isCompress() && readSize != 0 && byteBuffer.remaining() > 0) {
byteBuffer.put(HttpStatic.LINE_MARK.getBytes());
}
if(byteBuffer.remaining() <= 10) {
byteBuffer.flip();
session.send(byteBuffer);
byteBuffer.clear();
}
}
byteBuffer.put(readEnd());
byteBuffer.flip();
session.send(byteBuffer);
} catch (Throwable e) {
if (!(e instanceof MemoryReleasedException)) {
Logger.error("Response writeToChannel error: ", (Exception) e);
}
return;
}
basicSend = true;
} finally {
if(!autoSend) {
session.flush();
}
clear();
}
}
public void release(){
body.release();
}
public void clear(){
this.header().clear();
this.cookies().clear();
this.protocol().clear();
this.body().clear();
isCompress = false;
basicSend = false;
autoSend = true;
this.mark = null;
}
@Override
public String toString() {
return new String(readHead());
}
}
|
package org.takes.facets.fork;
import java.util.regex.Pattern;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.cactoos.Text;
import org.cactoos.text.Lowered;
import org.cactoos.text.TextOf;
import org.cactoos.text.Trimmed;
import org.cactoos.text.UncheckedText;
@ToString
@EqualsAndHashCode
final class MediaType implements Comparable<MediaType> {
/**
* Pattern matching non-digit symbols.
*/
private static final Pattern NON_DIGITS = Pattern.compile("[^0-9\\.]");
/**
* Priority.
*/
private final Double prio;
/**
* High part.
*/
private final String high;
/**
* Low part.
*/
private final String low;
/**
* Ctor.
* @param text Text to parse
*/
MediaType(final String text) {
this.prio = MediaType.priority(text);
this.high = MediaType.highPart(text);
this.low = MediaType.lowPart(text);
}
@Override
public int compareTo(final MediaType type) {
int cmp = this.prio.compareTo(type.prio);
if (cmp == 0) {
cmp = this.high.compareTo(type.high);
if (cmp == 0) {
cmp = this.low.compareTo(type.low);
}
}
return cmp;
}
/**
* Matches.
* @param type Another type
* @return TRUE if matches
* @checkstyle BooleanExpressionComplexityCheck (10 lines)
*/
public boolean matches(final MediaType type) {
final String star = "*";
return (this.high.equals(star)
|| type.high.equals(star)
|| this.high.equals(type.high))
&& (this.low.equals(star)
|| type.low.equals(star)
|| this.low.equals(type.low));
}
/**
* Splits the text parts.
* @param text The text to be split.
* @return Two first parts of the media type.
*/
private static String[] split(final String text) {
return text.split(";", 2);
}
/**
* Returns the media type priority.
* @param text The media type text.
* @return The priority of the media type.
*/
private static Double priority(final String text) {
final String[] parts = MediaType.split(text);
final Double priority;
if (parts.length > 1) {
final String num =
MediaType.NON_DIGITS.matcher(parts[1]).replaceAll("");
if (num.isEmpty()) {
priority = 0.0d;
} else {
priority = Double.parseDouble(num);
}
} else {
priority = 1.0d;
}
return priority;
}
/**
* Returns the high part of the media type.
* @param text The media type text.
* @return The high part of the media type.
*/
private static String highPart(final String text) {
return MediaType.sectors(text)[0];
}
/**
* Returns the low part of the media type.
* @param text The media type text.
* @return The low part of the media type.
*/
private static String lowPart(final String text) {
final String[] sectors = MediaType.sectors(text);
Text sector = new TextOf("");
if (sectors.length > 1) {
sector = new Trimmed(new TextOf(sectors[1]));
}
return new UncheckedText(sector).asString();
}
/**
* Returns the media type sectors.
* @param text The media type text.
* @return String array with the sectors of the media type.
*/
private static String[] sectors(final String text) {
return new UncheckedText(
new Lowered(MediaType.split(text)[0])
).asString()
.split(
"/", 2
);
}
}
|
package org.project.openbaton.common.vnfm_sdk;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.project.openbaton.catalogue.mano.common.Event;
import org.project.openbaton.catalogue.mano.common.LifecycleEvent;
import org.project.openbaton.catalogue.mano.record.Status;
import org.project.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.project.openbaton.catalogue.nfvo.CoreMessage;
import org.project.openbaton.catalogue.nfvo.VnfmManagerEndpoint;
import org.project.openbaton.common.vnfm_sdk.exception.VnfmSdkException;
import org.project.openbaton.common.vnfm_sdk.interfaces.VNFLifecycleManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.JMSException;
import java.io.IOException;
import java.util.Properties;
public abstract class AbstractVnfm implements VNFLifecycleManagement {
protected String type;
protected String endpoint;
protected Properties properties;
protected Logger log = LoggerFactory.getLogger(this.getClass());
protected VnfmManagerEndpoint vnfmManagerEndpoint;
protected static final String nfvoQueue = "vnfm-core-actions";
protected Gson parser=new GsonBuilder().setPrettyPrinting().create();
@PreDestroy
private void shutdown(){
this.unregister(vnfmManagerEndpoint);
}
@PostConstruct
private void init(){
setup();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public abstract CoreMessage instantiate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
@Override
public abstract void query();
@Override
public abstract void scale(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
@Override
public abstract void checkInstantiationFeasibility();
@Override
public abstract void heal();
@Override
public abstract void updateSoftware();
@Override
public abstract CoreMessage modify(VirtualNetworkFunctionRecord vnfr);
@Override
public abstract void upgradeSoftware();
@Override
public abstract CoreMessage terminate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
public abstract CoreMessage handleError(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
protected void loadProperties() {
Resource resource = new ClassPathResource("conf.properties");
properties = new Properties();
try {
properties.load(resource.getInputStream());
} catch (IOException e) {
e.printStackTrace();
log.error(e.getLocalizedMessage());
}
this.endpoint = (String) properties.get("endpoint");
this.type = (String) properties.get("type");
}
protected void onAction(CoreMessage message) {
log.trace("VNFM: Received Message: " + message.getAction());
CoreMessage coreMessage = null;
switch (message.getAction()){
case ALLOCATE_RESOURCES:
break;
case SCALE:
this.scale(message.getPayload());
break;
case SCALING:
break;
case ERROR:
coreMessage = handleError(message.getPayload());
break;
case MODIFY:
coreMessage = this.modify(message.getPayload());
break;
case RELEASE_RESOURCES:
coreMessage = this.terminate(message.getPayload());
break;
case GRANT_OPERATION:
case INSTANTIATE:
coreMessage = this.instantiate(message.getPayload());
case SCALE_UP_FINISHED:
break;
case SCALE_DOWN_FINISHED:
break;
case RELEASE_RESOURCES_FINISH:
break;
case INSTANTIATE_FINISH:
break;
case CONFIGURE:
coreMessage = configure(message.getPayload());
break;
case START:
coreMessage = start(message.getPayload());
break;
}
if (coreMessage != null){
log.debug("send to NFVO");
sendToNfvo(coreMessage);
}
}
protected abstract CoreMessage start(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
private LifecycleEvent getLifecycleEvent(VirtualNetworkFunctionRecord vnfr,Event event,boolean history){
if(history){
for( LifecycleEvent lce : vnfr.getLifecycle_event_history())
if(lce.getEvent()==event){
return lce;
}
}
else for( LifecycleEvent lce : vnfr.getLifecycle_event())
if(lce.getEvent()==event){
return lce;
}
return null;
}
protected void updateVnfr(VirtualNetworkFunctionRecord vnfr, Event event,String command){
if(vnfr==null || event==null || command==null || command.isEmpty())
throw new NullPointerException("One of the arguments is null or the command is empty");
//Change vnfr status if the current command is the last script of the current event.
LifecycleEvent currentEvent= getLifecycleEvent(vnfr,event,false);
String lastScript=null;
while(currentEvent.getLifecycle_events().iterator().hasNext())
lastScript=currentEvent.getLifecycle_events().iterator().next();
if(lastScript.equalsIgnoreCase(command))
changeStatus(vnfr,currentEvent.getEvent());
//If the current vnfr is INITIALIZED and it hasn't a configure event, set it as INACTIVE
if(vnfr.getStatus()==Status.INITIAILZED && getLifecycleEvent(vnfr,Event.CONFIGURE,false)==null)
changeStatus(vnfr,Event.CONFIGURE);
//set the command in the history event
LifecycleEvent historyEvent = getLifecycleEvent(vnfr,event,true);
if(historyEvent!=null)
historyEvent.getLifecycle_events().add(command);
// If the history event doesn't exist create it
else{
LifecycleEvent newLce = new LifecycleEvent();
newLce.setEvent(event);
newLce.getLifecycle_events().add(command);
vnfr.getLifecycle_event_history().add(newLce);
}
}
private void changeStatus(VirtualNetworkFunctionRecord vnfr, Event event) {
switch (event){
case GRANTED:
break;
case ALLOCATE:
break;
case INSTALL:
break;
case SCALE:
break;
case RELEASE:
break;
case ERROR:
break;
case INSTANTIATE: vnfr.setStatus(Status.INITIAILZED);
break;
case TERMINATE: vnfr.setStatus(Status.TERMINATED);
break;
case CONFIGURE: vnfr.setStatus(Status.INACTIVE);
break;
case START: vnfr.setStatus(Status.ACTIVE);
break;
case STOP: vnfr.setStatus(Status.INACTIVE);
break;
case SCALE_OUT:
break;
case SCALE_IN:
break;
case SCALE_UP:
break;
case SCALE_DOWN:
break;
case UPDATE:
break;
case UPDATE_ROLLBACK:
break;
case UPGRADE:
break;
case UPGRADE_ROLLBACK:
break;
case RESET:
break;
}
}
protected abstract void executeActionOnEMS(String vduHostname, String command) throws JMSException, VnfmSdkException;
protected abstract CoreMessage configure(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
protected abstract void sendToNfvo(CoreMessage coreMessage);
protected abstract void unregister(VnfmManagerEndpoint endpoint);
protected abstract void setup();
protected void sendToEmsAndUpdate(VirtualNetworkFunctionRecord vnfr, Event event, String command, String emsEndpoint) throws VnfmSdkException, JMSException {
executeActionOnEMS(emsEndpoint, command);
updateVnfr(vnfr, event, command);
}
}
|
package org.threadly.litesockets;
import java.io.Closeable;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.threadly.concurrent.SubmitterExecutor;
import org.threadly.concurrent.event.ListenerHelper;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.litesockets.utils.IOUtils;
import org.threadly.litesockets.utils.MergedByteBuffers;
import org.threadly.litesockets.utils.SimpleByteStats;
import org.threadly.util.ArgumentVerifier;
import org.threadly.util.Clock;
/**
* <p>This is the base Client object for client communication. Anything that reads or writes data
* will use this object. The clients work by having buffered reads and writes for the socket. They tell the
* SocketExecuter when a read can be added or a write is ready for the socket.</p>
*
* <p>All reads are issued on a callback on a Reader in a single threaded manor.
* All writes will be sent in the order they are received. In general its better to write full protocol parsable
* packets with each write where possible. If not possible your own locking/ordering will have to be ensured.
* Close events will happen on there own Closer callback but it uses the same ThreadKey as the Reader thread.
* All Reads should be received before a close event happens.</p>
*
* The client object can not function with out being in a SocketExecuter. Writes can be added before its put
* in the executer, but it will not write to the socket until added to the executer.
*
* @author lwahlmeier
*
*/
public abstract class Client implements Closeable {
protected final MergedByteBuffers readBuffers = new MergedByteBuffers(false);
protected final SocketExecuterCommonBase se;
protected final SubmitterExecutor clientExecutor;
protected final long startTime = Clock.lastKnownForwardProgressingMillis();
protected final Object readerLock = new Object();
protected final Object writerLock = new Object();
protected final ClientByteStats stats = new ClientByteStats();
protected final AtomicBoolean closed = new AtomicBoolean(false);
protected final ConcurrentLinkedQueue<CloseListener> closerListener = new ConcurrentLinkedQueue<>();
protected volatile Runnable readerCaller = null;
protected volatile boolean useNativeBuffers = false;
protected volatile boolean keepReadBuffer = true;
protected volatile int maxBufferSize = IOUtils.DEFAULT_CLIENT_MAX_BUFFER_SIZE;
protected volatile int newReadBufferSize = IOUtils.DEFAULT_CLIENT_READ_BUFFER_SIZE;
private ByteBuffer readByteBuffer = IOUtils.EMPTY_BYTEBUFFER;
public Client(final SocketExecuterCommonBase se) {
this.se = se;
this.clientExecutor = se.getExecutorFor(this);
}
protected Client(final SocketExecuterCommonBase se, final SubmitterExecutor clientExecutor) {
this.se = se;
this.clientExecutor = clientExecutor;
}
/**
* <p>Used by SocketExecuter to set if there was a success or error when connecting, completing the
* {@link ListenableFuture}.</p>
*
* @param t if there was an error connecting this is provided otherwise a successful connect will pass {@code null}.
*/
protected abstract void setConnectionStatus(Throwable t);
/**
* <p>This provides the next available Write buffer. This is typically only called by the {@link SocketExecuter}.
* This is not threadsafe as the same {@link ByteBuffer} will be provided to any thread that calls this, until
* something consumes all byte available in it at which point another {@link ByteBuffer} will be provided.</p>
*
* <p>Assuming something actually removes data from the returned {@link ByteBuffer} an additional call to
* {@link #reduceWrite(int)} must be made</p>
*
*
* @return a {@link ByteBuffer} that can be used to Read new data off the socket for this client.
*/
protected abstract ByteBuffer getWriteBuffer();
/**
* <p>This is called after a write is written to the clients socket. This tells the client how much of that
* {@link ByteBuffer} was written and then reduces the writeBuffersSize accordingly.</p>
*
* @param size the size in bytes of data written on the socket.
*/
protected abstract void reduceWrite(int size);
/**
* <p>Returns the {@link SocketChannel} for this client. If the client does not have a {@link SocketChannel}
* it will return null (ie {@link UDPClient}).</p>
*
* @return the {@link SocketChannel} for this client.
*/
protected abstract SocketChannel getChannel();
/**
* This is called when the SocketExecuter detects the socket can read. This must be done on the clients ReadThread,
* and not the thread calling this.
*/
protected abstract void doSocketRead(boolean doLocal);
/**
* This is called when the SocketExecuter detects the socket can write. This must be done on the clients ReadThread,
* and not the thread calling this.
*/
protected abstract void doSocketWrite(boolean doLocal);
/**
*
* @return the remote {@link SocketAddress} this client is connected to.
*/
public abstract SocketAddress getRemoteSocketAddress();
/**
*
* @return the local {@link SocketAddress} this client is using.
*/
public abstract SocketAddress getLocalSocketAddress();
/**
* Returns true if this client has data pending in its write buffers. False if there is no data pending write.
*
* @return true if data is pending write, false if there is no data to write.
*/
public abstract boolean canWrite();
/**
* This allows you to set/get client options for this client connection. Not all options can
* be set for every client.
*
* @return a {@link ClientOptions} object to set/get options for this client.
*/
public abstract ClientOptions clientOptions();
/**
*
* <p>Called to connect this client to a host. This is done non-blocking.</p>
*
* <p>If there is an error connecting {@link #close()} will also be called on the client.</p>
*
* @return A {@link ListenableFuture} that will complete when the socket is connected, or fail if we cant connect.
*/
public abstract ListenableFuture<Boolean> connect();
/**
* Sets the connection timeout value for this client. This must be called before {@link #connect()} has called on this client.
*
* @param timeout the time in milliseconds to wait for the client to connect.
*/
public abstract void setConnectionTimeout(int timeout);
/**
* <p>This tells us if the client has timed out before it has been connected to the socket.
* If the client has connected fully this will return false from that point on (even on a closed connection).</p>
*
* @return false if the client has been connected, true if it has not connected and the timeout limit has been reached.
*/
public abstract boolean hasConnectionTimedOut();
/**
* <p>Used to get this clients connection timeout information.</p>
*
* @return the max amount of time to wait for a connection to connect on this socket.
*/
public abstract int getTimeout();
/**
* <p>This is used to get the current size of the unWriten writeBuffer.</p>
*
* @return the current size of the writeBuffer.
*/
public abstract int getWriteBufferSize();
/**
* <p>This is used by the {@link SocketExecuter} to help understand how to manage this client.
* Currently only UDP and TCP exist.</p>
*
* @return The IP protocol type of this client.
*/
public abstract WireProtocol getProtocol();
/**
* <p>This is called to write data to the clients socket. Its important to note that there is no back
* pressure when adding writes so care should be taken to now allow the clients {@link #getWriteBufferSize()} to get
* to big.</p>
*
* @param bb The {@link ByteBuffer} to write onto the clients socket.
* @return A {@link ListenableFuture} that will be completed once the data has been fully written to the socket.
*/
public abstract ListenableFuture<?> write(ByteBuffer bb);
public abstract ListenableFuture<?> lastWriteFuture();
/**
* <p>Closes this client. Reads can still occur after this it called. {@link CloseListener#onClose(Client)} will still be
* called (if set) once all reads are done.</p>
*/
public abstract void close();
/*Implemented functions*/
protected void addReadStats(final int size) {
stats.addRead(size);
}
protected void addWriteStats(final int size) {
stats.addWrite(size);
}
/**
* <p>When this clients socket has a read pending and {@link #canRead()} is true, this is where the ByteBuffer for the read comes from.
* In general this should only be used by the ReadThread in the {@link SocketExecuter} and it should be noted
* that it is not threadsafe.</p>
*
* @return A {@link ByteBuffer} to use during this clients read operations.
*/
protected ByteBuffer provideReadByteBuffer() {
if(keepReadBuffer) {
if(readByteBuffer.remaining() < IOUtils.DEFAULT_MIN_CLIENT_READ_BUFFER_SIZE) {
if(useNativeBuffers) {
readByteBuffer = ByteBuffer.allocateDirect(newReadBufferSize);
} else {
readByteBuffer = ByteBuffer.allocate(newReadBufferSize);
}
}
return readByteBuffer;
} else {
if(useNativeBuffers) {
return ByteBuffer.allocateDirect(newReadBufferSize);
} else {
return ByteBuffer.allocate(newReadBufferSize);
}
}
}
protected void callClosers() {
this.getClientsThreadExecutor().execute(()->{
while(!closerListener.isEmpty()) {
closerListener.poll().onClose(this);
}
});
}
protected void callReader() {
Runnable readerCaller = this.readerCaller;
if (readerCaller != null) {
getClientsThreadExecutor().execute(readerCaller);
}
}
/**
*
* <p>Adds a {@link ByteBuffer} to the Clients readBuffer. This is normally only used by the {@link SocketExecuter},
* though it could be used to artificially inject data through the client. Calling this will schedule a
* calling the currently set Reader on the client.</p>
*
*
* @param bb the {@link ByteBuffer} to add to the clients readBuffer.
*/
protected void addReadBuffer(final ByteBuffer bb) {
addReadStats(bb.remaining());
se.addReadAmount(bb.remaining());
int start;
int end;
start = readBuffers.remaining();
readBuffers.add(bb);
end = readBuffers.remaining();
if(end > 0 && start == 0){
callReader();
}
}
/**
* Returns true if this client can have reads added to it or false if its read buffers are full.
*
* @return true if more reads can be added, false if not.
*/
public boolean canRead() {
return readBuffers.remaining() < maxBufferSize;
}
/**
* <p>This is used to get the current size of the readBuffers pending reads.</p>
*
* @return the current size of the ReadBuffer.
*/
public int getReadBufferSize() {
return readBuffers.remaining();
}
/**
* <p> This returns this clients {@link SubmitterExecutor}.</p>
*
* <p> Its worth noting that operations done on this {@link SubmitterExecutor} can/will block Read callbacks on the
* client, but it does provide you the ability to execute things on the clients read thread.</p>
*
* @return The {@link SubmitterExecutor} for the client.
*/
public SubmitterExecutor getClientsThreadExecutor() {
return clientExecutor;
}
/**
* <p>This is used to get the clients {@link SocketExecuter}.</p>
*
* @return the {@link SocketExecuter} set for this client. if none, null is returned.
*/
public SocketExecuter getClientsSocketExecuter() {
return se;
}
/**
* <p>This adds a {@link CloseListener} for this client. Once set the client will call .onClose
* on it once it a socket close is detected.</p>
*
* @param closer sets this clients {@link CloseListener} callback.
*/
public void addCloseListener(final CloseListener closer) {
if(closed.get()) {
getClientsThreadExecutor().execute(()->closer.onClose(Client.this));
} else {
closerListener.add(closer);
if(closed.get() && !closerListener.isEmpty()) {
this.callClosers();
}
}
}
/**
* <p>This sets the Reader for the client. Once set data received on the socket will be callback
* on this Reader to be processed. If no reader is set before connecting the client read data will just
* queue up till we hit the the max buffer size</p>
*
* @param reader the {@link Reader} callback to set for this client.
*/
public void setReader(final Reader reader) {
if(! closed.get()) {
if (reader == null) {
readerCaller = null;
} else {
synchronized(readerLock) {
readerCaller = () -> reader.onRead(this);
if (this.getReadBufferSize() > 0) {
callReader();
}
}
}
}
}
/**
* <p>Whenever a the {@link Reader} Interfaces {@link Reader#onRead(Client)} is called the
* {@link #getRead()} should be called from the client.</p>
*
* @return a {@link MergedByteBuffers} of the current read data for this client.
*/
public MergedByteBuffers getRead() {
synchronized(readerLock) {
MergedByteBuffers mbb = readBuffers.duplicateAndClean();
if(mbb.remaining() >= maxBufferSize) {
se.setClientOperations(this);
}
return mbb;
}
}
/**
* <p>Returns if this client is closed or not. Once a client is marked closed there is no way to reOpen it.
* You must just make a new client. Just because this returns false does not mean the client is connected.
* Before a client connects, but has not yet closed this will be false.</p>
*
* @return true if the client is closed, false if the client has not yet been closed.
*/
public boolean isClosed() {
return closed.get();
}
protected boolean setClose() {
return closed.compareAndSet(false, true);
}
/**
* Returns the {@link SimpleByteStats} for this client.
*
* @return the byte stats for this client.
*/
public SimpleByteStats getStats() {
return stats;
}
/**
* Implementation of the SimpleByteStats.
*/
private static class ClientByteStats extends SimpleByteStats {
public ClientByteStats() {
super();
}
@Override
protected void addWrite(final int size) {
ArgumentVerifier.assertNotNegative(size, "size");
super.addWrite(size);
}
@Override
protected void addRead(final int size) {
ArgumentVerifier.assertNotNegative(size, "size");
super.addRead(size);
}
}
/**
* Used to notify when a Client there is data to Read for a Client.
*
* <p>Any client with this set will call .onRead(client) when a read is read from the socket.
* These will happen in a single threaded manor for that client. The thread used is the clients
* thread and should not be blocked for long. If it is the client will back up and stop reading until
* it is unblocked.</p>
*
* <p>The implementor of Reader should call {@link Client#getRead()}.</p>
*
* <p>If the same Reader is used by multiple clients each client will call the Reader on its own thread so be careful
* what objects your modifying if you do that.</p>
*
*
*
*/
public interface Reader {
/**
* <p>When this callback is called it will pass you the Client object
* that did the read. .getRead() should be called on once and only once
* before returning. If it is failed to be called or called more then once
* you could end up with uncalled data on the wire or getting a null.</p>
*
* @param client This is the client the read is being called for.
*/
public void onRead(Client client);
}
/**
* Used to notify when a Client is closed.
*
* <p>It is also single threaded on the same thread key as the reads.
* No action must be taken when this is called but it is usually advised to do some kind of clean up or something
* as this client object will no longer be used for anything.</p>
*
*/
public interface CloseListener {
/**
* This notifies the callback about the client being closed.
*
* @param client This is the client the close is being called for.
*/
public void onClose(Client client);
}
/**
* ClientOptions that can be changed depending on what kind of client you want.
*
* In general these should not be set unless you have a very specific use case.
*
* @author lwahlmeier
*
*/
public interface ClientOptions {
/**
* This is only available for connection backed by a TCP socket.
* It will turn on TcpNoDelay on the the connection at the System level.
* This means that data queued to go out the socket will not delay before being sent.
*
* @param enabled true means NoDelay is on, false means NoDelay is off.
* @return true if this was able to be set.
*/
public boolean setTcpNoDelay(boolean enabled);
/**
* Returns the current state of TcpNoDelay.
*
* @return true means NoDelay is on, false means NoDelay is off.
*/
public boolean getTcpNoDelay();
/**
* Sets this client to use Native or Direct ByteBuffers.
* This can save allocations to the Heap, but is generally only useful
* for things like pass through proxies.
*
* @param enabled true means use Native buffers false means use Heap buffers.
* @return true if this was able to be set.
*/
public boolean setNativeBuffers(boolean enabled);
/**
* Returns the current state of native buffers.
*
* @return true means native buffers are generated false means they are not.
*/
public boolean getNativeBuffers();
/**
* Sets reduced Read buffer allocations. This is accomplished by over allocating
* the read buffer and returning subsets of it. This can make reads much faster but
* does also use more memory.
*
* @param enabled true for enabled false for disabled.
* @return true if this was able to be set.
*/
public boolean setReducedReadAllocations(boolean enabled);
/**
* Returns the current state of ReducedReadAllocations.
*
* @return true for enabled false for disabled.
*/
public boolean getReducedReadAllocations();
/**
* Sets the max size of read buffer the client is allowed to have.
* Once this is reached the client will stop doing read operations until
* the Read buffers gets under this size. This can really effect performance
* especially if its set to small.
*
* @param size in bytes.
* @return true if this was able to be set.
*/
public boolean setMaxClientReadBuffer(int size);
/**
* Returns the currently set max Read buffer size in Bytes.
*
* @return size of max read buffer size.
*/
public int getMaxClientReadBuffer();
/**
* Sets the size of the ByteBuffer used for Reads. The larger this
* buffer is the more data we can read from the socket at once. If
* {@link #getReducedReadAllocations()} is true we will reuse the unused
* space in this buffer until it gets below the minimum read threshold.
*
* @param size in bytes.
* @return true if this was able to be set.
*/
public boolean setReadAllocationSize(int size);
/**
* Returns the current Read buffer allocation size in bytes.
*
* @return bytes allocated for reads.
*/
public int getReadAllocationSize();
/**
* This sets the System level socket send buffer size. Every OS
* has its own min and max values for this, if you go over or under that
* it will not be set.
*
* @param size buffer size in bytes.
* @return true if this was able to be set.
*/
public boolean setSocketSendBuffer(int size);
/**
* Returns the currently set send buffer size in bytes.
*
* @return send buffer size in bytes.
*/
public int getSocketSendBuffer();
/**
* This sets the System level socket receive buffer size. Every OS
* has its own min and max values for this, if you go over or under that
* it will not be set.
*
* @param size buffer size in bytes.
* @return true if this was able to be set.
*/
public boolean setSocketRecvBuffer(int size);
/**
* Returns the currently set receive buffer size in bytes.
*
* @return send buffer size in bytes.
*/
public int getSocketRecvBuffer();
/**
* Sets the UDP frame size. This only possible on UDP backed clients.
*
* @param size max frame size in bytes
* @return true if this was able to be set.
*/
public boolean setUdpFrameSize(int size);
/**
* Returns the currently set UDP frame size in bytes.
*
* @return frame size in bytes.
*/
public int getUdpFrameSize();
}
/**
*
* @author lwahlmeier
*
*/
protected class BaseClientOptions implements ClientOptions {
@Override
public boolean setNativeBuffers(boolean enabled) {
useNativeBuffers = enabled;
return true;
}
@Override
public boolean getNativeBuffers() {
return useNativeBuffers;
}
@Override
public boolean setReducedReadAllocations(boolean enabled) {
keepReadBuffer = enabled;
if(!keepReadBuffer) {
readByteBuffer = IOUtils.EMPTY_BYTEBUFFER;
}
return true;
}
@Override
public boolean getReducedReadAllocations() {
return keepReadBuffer;
}
@Override
public boolean setReadAllocationSize(int size) {
newReadBufferSize = size;
return true;
}
@Override
public int getReadAllocationSize() {
return newReadBufferSize;
}
@Override
public boolean setMaxClientReadBuffer(int size) {
maxBufferSize = size;
return true;
}
@Override
public int getMaxClientReadBuffer() {
return maxBufferSize;
}
@Override
public boolean setTcpNoDelay(boolean enabled) {
return false;
}
@Override
public boolean getTcpNoDelay() {
return false;
}
@Override
public boolean setSocketSendBuffer(int size) {
return false;
}
@Override
public int getSocketSendBuffer() {
return -1;
}
@Override
public boolean setSocketRecvBuffer(int size) {
return false;
}
@Override
public int getSocketRecvBuffer() {
return -1;
}
@Override
public boolean setUdpFrameSize(int size) {
return false;
}
@Override
public int getUdpFrameSize() {
return -1;
}
}
}
|
package org.project.openbaton.common.vnfm_sdk;
import org.project.openbaton.catalogue.mano.common.Ip;
import org.project.openbaton.catalogue.mano.descriptor.InternalVirtualLink;
import org.project.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.project.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor;
import org.project.openbaton.catalogue.mano.record.VNFCInstance;
import org.project.openbaton.catalogue.mano.record.VNFRecordDependency;
import org.project.openbaton.catalogue.mano.record.VirtualLinkRecord;
import org.project.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.project.openbaton.catalogue.nfvo.Action;
import org.project.openbaton.catalogue.nfvo.ConfigurationParameter;
import org.project.openbaton.catalogue.nfvo.EndpointType;
import org.project.openbaton.catalogue.nfvo.VnfmManagerEndpoint;
import org.project.openbaton.catalogue.nfvo.messages.Interfaces.NFVMessage;
import org.project.openbaton.catalogue.nfvo.messages.OrVnfmErrorMessage;
import org.project.openbaton.catalogue.nfvo.messages.OrVnfmGenericMessage;
import org.project.openbaton.catalogue.nfvo.messages.OrVnfmInstantiateMessage;
import org.project.openbaton.common.vnfm_sdk.exception.BadFormatException;
import org.project.openbaton.common.vnfm_sdk.exception.NotFoundException;
import org.project.openbaton.common.vnfm_sdk.exception.VnfmSdkException;
import org.project.openbaton.common.vnfm_sdk.interfaces.VNFLifecycleChangeNotification;
import org.project.openbaton.common.vnfm_sdk.interfaces.VNFLifecycleManagement;
import org.project.openbaton.common.vnfm_sdk.utils.VNFRUtils;
import org.project.openbaton.common.vnfm_sdk.utils.VnfmUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public abstract class AbstractVnfm implements VNFLifecycleManagement, VNFLifecycleChangeNotification {
protected VnfmHelper vnfmHelper;
protected String type;
protected String endpoint;
protected String endpointType;
protected Properties properties;
protected Logger log = LoggerFactory.getLogger(this.getClass());
protected VnfmManagerEndpoint vnfmManagerEndpoint;
// protected VirtualNetworkFunctionRecord virtualNetworkFunctionRecord;
@PreDestroy
private void shutdown() {
this.unregister();
}
@PostConstruct
private void init() {
setup();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public abstract void query();
@Override
public abstract void scale();
@Override
public abstract void checkInstantiationFeasibility();
@Override
public abstract void heal();
@Override
public abstract void updateSoftware();
@Override
public abstract VirtualNetworkFunctionRecord modify(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFRecordDependency dependency) throws Exception;
@Override
public abstract void upgradeSoftware();
@Override
public abstract VirtualNetworkFunctionRecord terminate(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception;
public abstract void handleError(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord);
protected void loadProperties() {
Resource resource = new ClassPathResource("conf.properties");
properties = new Properties();
try {
properties.load(resource.getInputStream());
} catch (IOException e) {
e.printStackTrace();
log.error(e.getLocalizedMessage());
}
this.endpoint = (String) properties.get("endpoint");
this.type = (String) properties.get("type");
this.endpointType = properties.getProperty("endpoint-type", "JMS");
}
protected void onAction(NFVMessage message) throws NotFoundException, BadFormatException {
VirtualNetworkFunctionRecord virtualNetworkFunctionRecord = null;
try {
log.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + message.getAction() + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
log.trace("VNFM: Received Message: " + message.getAction());
NFVMessage nfvMessage = null;
OrVnfmGenericMessage orVnfmGenericMessage = null;
switch (message.getAction()) {
case SCALE:
this.scale();
break;
case SCALING:
break;
case ERROR:
OrVnfmErrorMessage errorMessage = (OrVnfmErrorMessage) message;
log.error("ERROR Received: " + errorMessage.getMessage());
handleError(errorMessage.getVnfr());
nfvMessage = null;
break;
case MODIFY:
orVnfmGenericMessage = (OrVnfmGenericMessage) message;
nfvMessage = VnfmUtils.getNfvMessage(Action.MODIFY, this.modify(orVnfmGenericMessage.getVnfr(), orVnfmGenericMessage.getVnfrd()));
break;
case RELEASE_RESOURCES:
orVnfmGenericMessage = (OrVnfmGenericMessage) message;
nfvMessage = VnfmUtils.getNfvMessage(Action.RELEASE_RESOURCES, this.terminate(orVnfmGenericMessage.getVnfr()));
break;
case INSTANTIATE:
OrVnfmInstantiateMessage orVnfmInstantiateMessage = (OrVnfmInstantiateMessage) message;
virtualNetworkFunctionRecord = createVirtualNetworkFunctionRecord(orVnfmInstantiateMessage.getVnfd(), orVnfmInstantiateMessage.getVnfdf().getFlavour_key(), orVnfmInstantiateMessage.getVnfd().getName(), orVnfmInstantiateMessage.getVlrs(), orVnfmInstantiateMessage.getExtention());
virtualNetworkFunctionRecord = vnfmHelper.grantLifecycleOperation(virtualNetworkFunctionRecord).get();
if (properties.getProperty("allocate", "false").equalsIgnoreCase("true"))
virtualNetworkFunctionRecord = vnfmHelper.allocateResources(virtualNetworkFunctionRecord).get();
setupProvides(virtualNetworkFunctionRecord);
for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu())
for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance())
checkEMS(vnfcInstance.getHostname());
if (orVnfmInstantiateMessage.getScriptsLink() != null)
virtualNetworkFunctionRecord = instantiate(virtualNetworkFunctionRecord, orVnfmInstantiateMessage.getScriptsLink());
else
virtualNetworkFunctionRecord = instantiate(virtualNetworkFunctionRecord, orVnfmInstantiateMessage.getScripts());
nfvMessage = VnfmUtils.getNfvMessage(Action.INSTANTIATE, virtualNetworkFunctionRecord);
break;
case RELEASE_RESOURCES_FINISH:
break;
case INSTANTIATE_FINISH:
break;
case CONFIGURE:
orVnfmGenericMessage = (OrVnfmGenericMessage) message;
nfvMessage = VnfmUtils.getNfvMessage(Action.CONFIGURE, configure(orVnfmGenericMessage.getVnfr()));
break;
case START:
orVnfmGenericMessage = (OrVnfmGenericMessage) message;
nfvMessage = VnfmUtils.getNfvMessage(Action.START, start(orVnfmGenericMessage.getVnfr()));
break;
}
log.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
if (nfvMessage != null) {
log.debug("send to NFVO");
vnfmHelper.sendToNfvo(nfvMessage);
}
} catch (Exception e) {
log.error("ERROR: ", e);
if (e instanceof VnfmSdkException){
VnfmSdkException vnfmSdkException = (VnfmSdkException) e;
if (vnfmSdkException.getVnfr() != null){
log.debug("sending vnfr with version: " + vnfmSdkException.getVnfr().getHb_version());
vnfmHelper.sendToNfvo(VnfmUtils.getNfvMessage(Action.ERROR, vnfmSdkException.getVnfr()));
return;
}
}
vnfmHelper.sendToNfvo(VnfmUtils.getNfvMessage(Action.ERROR, virtualNetworkFunctionRecord));
}
}
private void checkEMS(String vduHostname) {
int i = 0;
while (true) {
log.debug("Waiting for ems to be started... (" + i * 5 + " secs)");
i++;
try {
checkEmsStarted(vduHostname);
break;
} catch (RuntimeException e) {
if (i == 100) {
throw e;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
protected abstract void checkEmsStarted(String vduHostname);
private void setupProvides(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) {
fillSpecificProvides(virtualNetworkFunctionRecord);
for (VirtualDeploymentUnit virtualDeploymentUnit : virtualNetworkFunctionRecord.getVdu()) {
for (VNFCInstance vnfcInstance : virtualDeploymentUnit.getVnfc_instance()) {
int i = 1;
for (Ip ip : vnfcInstance.getIps()) {
ConfigurationParameter cp = new ConfigurationParameter();
cp.setConfKey(ip.getNetName() + i);
cp.setValue(ip.getIp());
virtualNetworkFunctionRecord.getProvides().getConfigurationParameters().add(cp);
i++;
}
}
}
log.debug("Provides is: " + virtualNetworkFunctionRecord.getProvides());
}
/**
* This method needs to set all the parameter specified in the VNFDependency.parameters
*
* @param virtualNetworkFunctionRecord
*/
protected void fillSpecificProvides(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) {
}
/**
* This method can be overwritten in case you want a specific initialization of the VirtualNetworkFunctionRecord from the VirtualNetworkFunctionDescriptor
*
* @param virtualNetworkFunctionDescriptor
* @param extension
* @return The new VirtualNetworkFunctionRecord
* @throws BadFormatException
* @throws NotFoundException
*/
protected VirtualNetworkFunctionRecord createVirtualNetworkFunctionRecord(VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor, String flavourId, String vnfInstanceName, Set<VirtualLinkRecord> virtualLinkRecords, Map<String, String> extension) throws BadFormatException, NotFoundException {
try {
VirtualNetworkFunctionRecord virtualNetworkFunctionRecord = VNFRUtils.createVirtualNetworkFunctionRecord(virtualNetworkFunctionDescriptor, flavourId, extension.get("nsr-id"), virtualLinkRecords);
for (InternalVirtualLink internalVirtualLink : virtualNetworkFunctionRecord.getVirtual_link()) {
for (VirtualLinkRecord virtualLinkRecord : virtualLinkRecords) {
if (internalVirtualLink.getName().equals(virtualLinkRecord.getName())) {
internalVirtualLink.setExtId(virtualLinkRecord.getExtId());
internalVirtualLink.setConnectivity_type(virtualLinkRecord.getConnectivity_type());
}
}
}
log.debug("Created VirtualNetworkFunctionRecord: " + virtualNetworkFunctionRecord);
return virtualNetworkFunctionRecord;
} catch (NotFoundException e) {
e.printStackTrace();
vnfmHelper.sendToNfvo(VnfmUtils.getNfvMessage(Action.ERROR, null));
throw e;
} catch (BadFormatException e) {
e.printStackTrace();
vnfmHelper.sendToNfvo(VnfmUtils.getNfvMessage(Action.ERROR, null));
throw e;
}
}
public abstract VirtualNetworkFunctionRecord start(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception;
public abstract VirtualNetworkFunctionRecord configure(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) throws Exception;
/**
* This method unregister the VNFM in the NFVO
*/
protected abstract void unregister();
/**
* This method register the VNFM to the NFVO sending the right endpoint
*/
protected abstract void register();
/**
* This method setups the VNFM and then register it to the NFVO. We recommend to not change this method or at least
* to override calling super()
*/
protected void setup() {
loadProperties();
vnfmManagerEndpoint = new VnfmManagerEndpoint();
vnfmManagerEndpoint.setType(this.type);
vnfmManagerEndpoint.setEndpoint(this.endpoint);
log.debug("creating VnfmManagerEndpoint for vnfm endpointType: " + this.endpointType);
vnfmManagerEndpoint.setEndpointType(EndpointType.valueOf(this.endpointType));
register();
}
protected Map<String, String> getMap(VirtualNetworkFunctionRecord virtualNetworkFunctionRecord) {
Map<String, String> res = new HashMap<>();
for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getProvides().getConfigurationParameters())
res.put(configurationParameter.getConfKey(),configurationParameter.getValue());
for (ConfigurationParameter configurationParameter : virtualNetworkFunctionRecord.getConfigurations().getConfigurationParameters()){
res.put(configurationParameter.getConfKey(),configurationParameter.getValue());
}
return res;
}
}
|
package pl.pronux.sokker.model;
import java.util.ArrayList;
import java.util.List;
import pl.pronux.sokker.bean.TrainingSummary;
public class Training {
final public static int FORMATION_GK = 0;
final public static int FORMATION_DEF = 1;
final public static int FORMATION_MID = 2;
final public static int FORMATION_ATT = 3;
final public static int FORMATION_ALL = 4;
final public static int TYPE_UNKNOWN = 0;
final public static int TYPE_STAMINA = 1;
final public static int TYPE_KEEPER = 2;
final public static int TYPE_PLAYMAKING = 3;
final public static int TYPE_PASSING = 4;
final public static int TYPE_TECHNIQUE = 5;
final public static int TYPE_DEFENDING = 6;
final public static int TYPE_STRIKER = 7;
final public static int TYPE_PACE = 8;
final public static int NO_TRAINING = 1 << 1;
final public static int NEW_TRAINING = 1 << 2;
final public static int UPDATE_TRAINING = 1 << 3;
final public static int UPDATE_PLAYERS = 1 << 4;
private Date date;
private int formation;
private int id;
private String note;
private int type;
private Coach headCoach;
private Coach juniorCoach;
private List<Coach> assistants = new ArrayList<Coach>();
private List<Player> players;
private List<Junior> juniors;
private boolean reported;
private int status;
public List<Coach> getAssistants() {
return assistants;
}
public void setAssistants(List<Coach> assistants) {
this.assistants = assistants;
}
public Coach getHeadCoach() {
return headCoach;
}
public void setHeadCoach(Coach headCoach) {
this.headCoach = headCoach;
}
public Coach getJuniorCoach() {
return juniorCoach;
}
public void setJuniorCoach(Coach juniorCoach) {
this.juniorCoach = juniorCoach;
}
public Date getDate() {
return date;
}
public int getFormation() {
return formation;
}
public int getId() {
return id;
}
public String getNote() {
return note;
}
public int getType() {
return type;
}
public void setDate(Date date) {
this.date = date;
}
public void setFormation(int formation) {
this.formation = formation;
}
public void setId(int id) {
this.id = id;
}
public void setNote(String note) {
this.note = note;
}
public void setType(int type) {
this.type = type;
}
public boolean isReported() {
return reported;
}
public void setReported(boolean reported) {
this.reported = reported;
}
public List<Junior> getJuniors() {
return juniors;
}
public void setJuniors(List<Junior> juniors) {
this.juniors = juniors;
}
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
// public Object clone() {
// Object o = null;
// try {
// o = super.clone();
// } catch (CloneNotSupportedException e) {
// System.err.println("There is no posibillity to clone training object");
// return o;
public void copy(Training training) {
this.setAssistants(training.getAssistants());
this.setJuniors(training.getJuniors());
this.setPlayers(training.getPlayers());
this.setDate(training.getDate());
this.setFormation(training.getFormation());
this.setHeadCoach(training.getHeadCoach());
this.setId(training.getId());
this.setJuniorCoach(training.getJuniorCoach());
this.setNote(training.getNote());
this.setReported(training.isReported());
this.setType(training.getType());
}
public Training clone() {
Training training = new Training();
training.setAssistants(this.getAssistants());
training.setAssistants(new ArrayList<Coach>());
for (Coach assistant : this.assistants) {
training.getAssistants().add(assistant);
}
training.setJuniors(this.getJuniors());
training.setPlayers(this.getPlayers());
training.setDate(this.getDate());
training.setFormation(this.getFormation());
training.setHeadCoach(this.getHeadCoach());
training.setId(this.getId());
training.setJuniorCoach(this.getJuniorCoach());
training.setNote(this.getNote());
training.setReported(this.isReported());
training.setType(this.getType());
return training;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public TrainingSummary getTrainingSummary() {
TrainingSummary trainingSummary = new TrainingSummary();
trainingSummary = getJuniorsTrainingSummary(trainingSummary);
trainingSummary = getPlayersTrainingSummary(trainingSummary);
return trainingSummary;
}
private TrainingSummary getJuniorsTrainingSummary(TrainingSummary trainingSummary) {
int max = 0;
if (this.getJuniors().size() > 0) {
for (Junior junior : this.getJuniors()) {
JuniorSkills[] skills = junior.getSkills();
max = skills.length;
if (max > 1) {
for (int i = max - 1; i > 0; i
if (this.equals(skills[i].getTraining())) {
if (skills[i].getSkill() - skills[i - 1].getSkill() > 0) {
trainingSummary.setJuniorsPops(trainingSummary.getJuniorsPops() + 1);
} else if (skills[i].getSkill() - skills[i - 1].getSkill() < 0) {
trainingSummary.setJuniorsFalls(trainingSummary.getJuniorsFalls() + 1);
}
break;
}
}
}
}
}
return trainingSummary;
}
private TrainingSummary getPlayersTrainingSummary(TrainingSummary trainingSummary) {
int max = 0;
if (this.getPlayers().size() > 0) {
for (Player player : this.getPlayers()) {
PlayerSkills[] skills = player.getSkills();
max = skills.length;
if (max > 1) {
for (int i = max - 1; i > 0; i
if (this.equals(skills[i].getTraining())) {
if (skills[i].getStamina() - skills[i - 1].getStamina() > 0) {
trainingSummary.setStaminaPops(trainingSummary.getStaminaPops() + 1);
if (this.getType() == Training.TYPE_STAMINA) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getStamina() - skills[i - 1].getStamina() < 0) {
trainingSummary.setStaminaFalls(trainingSummary.getStaminaFalls() + 1);
if (this.getType() == Training.TYPE_STAMINA) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getPace() - skills[i - 1].getPace() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_PACE) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getPace() - skills[i - 1].getPace() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_PACE) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getTechnique() - skills[i - 1].getTechnique() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_TECHNIQUE) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getTechnique() - skills[i - 1].getTechnique() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_TECHNIQUE) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getPassing() - skills[i - 1].getPassing() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_PASSING) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getPassing() - skills[i - 1].getPassing() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_PASSING) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getKeeper() - skills[i - 1].getKeeper() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_KEEPER) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getKeeper() - skills[i - 1].getKeeper() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_KEEPER) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getDefender() - skills[i - 1].getDefender() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_DEFENDING) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getDefender() - skills[i - 1].getDefender() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_DEFENDING) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getPlaymaker() - skills[i - 1].getPlaymaker() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_PLAYMAKING) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getPlaymaker() - skills[i - 1].getPlaymaker() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_PLAYMAKING) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
if (skills[i].getScorer() - skills[i - 1].getScorer() > 0) {
trainingSummary.setAllSkillsPops(trainingSummary.getAllSkillsPops() + 1);
if (this.getType() == Training.TYPE_STRIKER) {
trainingSummary.setTrainedSkillsPops(trainingSummary.getTrainedSkillsPops() + 1);
}
} else if (skills[i].getScorer() - skills[i - 1].getScorer() < 0) {
trainingSummary.setAllSkillsFalls(trainingSummary.getAllSkillsFalls() + 1);
if (this.getType() == Training.TYPE_STRIKER) {
trainingSummary.setTrainedSkillsFalls(trainingSummary.getTrainedSkillsFalls() + 1);
}
}
break;
}
}
}
}
}
return trainingSummary;
}
public int getHeadCoachTrainedSkill() {
if (this.getHeadCoach() != null) {
switch (this.getType()) {
case Training.TYPE_DEFENDING:
return getHeadCoach().getDefenders();
case Training.TYPE_KEEPER:
return getHeadCoach().getKeepers();
case Training.TYPE_PACE:
return getHeadCoach().getPace();
case Training.TYPE_PASSING:
return getHeadCoach().getPassing();
case Training.TYPE_PLAYMAKING:
return getHeadCoach().getPlaymakers();
case Training.TYPE_STAMINA:
return getHeadCoach().getStamina();
case Training.TYPE_STRIKER:
return getHeadCoach().getScorers();
case Training.TYPE_TECHNIQUE:
return getHeadCoach().getTechnique();
}
}
return 0;
}
}
|
package ptrman.Showcases;
import ptrman.Datastructures.Dag;
import ptrman.Datastructures.IMap2d;
import ptrman.Datastructures.Map2d;
import ptrman.Datastructures.Vector2d;
import ptrman.Gui.*;
import ptrman.bpsolver.BpSolver;
import ptrman.bpsolver.Parameters;
import ptrman.levels.visual.ColorRgb;
import ptrman.levels.visual.VisualProcessor;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class TestClustering {
final static int RETINA_WIDTH = 120;
final static int RETINA_HEIGHT = 120;
static File currentFile = null;
static BufferedImage currentFileImage = null;
private class InputDrawer implements IImageDrawer {
BufferedImage off_Image;
@Override
public BufferedImage drawToJavaImage(BpSolver bpSolver) {
if (off_Image == null || off_Image.getWidth() != RETINA_WIDTH || off_Image.getHeight() != RETINA_HEIGHT) {
off_Image = new BufferedImage(RETINA_WIDTH, RETINA_HEIGHT, BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2 = off_Image.createGraphics();
if (currentFile == null) {
g2.setColor(Color.WHITE);
g2.drawRect(0, 0, off_Image.getWidth(), off_Image.getHeight());
g2.setColor(Color.BLACK);
g2.drawLine(10, 10, 20, 40);
g2.drawLine(20, 40, 30, 10);
///drawTestTriangle(g2, new Vector2d<>(20.0f, 60.0f), 10.0f, time, (3.0f / (float)Math.sqrt(3)));
//drawTestTriangle(g2, new Vector2d<>(60.0f, 60.0f), 10.0f, time * 0.114f, 0.5f*(3.0f / (float)Math.sqrt(3)));
} else {
if (currentFileImage == null) {
try {
currentFileImage = ImageIO.read(currentFile);
g2.drawImage(currentFileImage, 0, 0, RETINA_WIDTH, RETINA_HEIGHT, null);
System.out.println("painted: "+ currentFile);
} catch (IOException e) {
e.printStackTrace();
currentFile = null;
}
}
}
return off_Image;
}
}
static class ImageFileFilter implements FileFilter {
public boolean accept(File file) {
String extension = file.getName().toLowerCase();
return extension.endsWith(".jpg") || extension.endsWith(".png") || extension.endsWith(".gif");
}
}
/**
*
* gets called when the next frame should be drawn
*
* delegates to all parts
*
*/
private static class TimerActionListener implements ActionListener {
public TimerActionListener(BpSolver bpSolver, IImageDrawer imageDrawer, IntrospectControlPanel introspectControlPanel, NodeGraph nodeGraph, DualConvas dualCanvas, VisualProcessor.ProcessingChain processingChain) {
this.bpSolver = bpSolver;
this.imageDrawer = imageDrawer;
this.introspectControlPanel = introspectControlPanel;
this.nodeGraph = nodeGraph;
this.dualCanvas = dualCanvas;
this.processingChain = processingChain;
}
@Override
public void actionPerformed(ActionEvent e) {
BufferedImage image;
IMap2d<Boolean> mapBoolean;
IMap2d<ColorRgb> mapColor;
// TODO< pull image from source >
// for now imageDrawer does this
image = imageDrawer.drawToJavaImage(bpSolver);
mapColor = TestClustering.translateFromImageToMap(image);
processingChain.filterChain(mapColor);
mapBoolean = ((VisualProcessor.ProcessingChain.ApplyChainElement)processingChain.filterChainDag.elements.get(1).content).result;
bpSolver.recalculate(mapBoolean);
if( introspectControlPanel.getIntrospectionState() )
{
nodeGraph.repopulateAfterNodes(bpSolver.lastFrameObjectNodes, bpSolver.networkHandles);
}
dualCanvas.leftCanvas.setImage(translateFromMapToImage(mapBoolean));
BufferedImage detectorImage;
detectorImage = new BufferedImage(bpSolver.getImageSize().x, bpSolver.getImageSize().y, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = (Graphics2D)detectorImage.getGraphics();
// TODO create graphics and draw it to a created image and put the image into the canvas
DebugDrawingHelper.drawDetectors(graphics, bpSolver.lastFrameRetinaPrimitives, bpSolver.lastFrameIntersections, bpSolver.lastFrameSamples);
dualCanvas.rightCanvas.setImage(detectorImage);
}
private BpSolver bpSolver;
private final IImageDrawer imageDrawer;
private IntrospectControlPanel introspectControlPanel;
private NodeGraph nodeGraph;
private DualConvas dualCanvas;
private final VisualProcessor.ProcessingChain processingChain;
}
public TestClustering() {
JFrame j = new JFrame("TestClustering");
BpSolver bpSolver = new BpSolver();
bpSolver.setImageSize(new Vector2d<>(RETINA_WIDTH, RETINA_HEIGHT));
bpSolver.setup();
Parameters.init();
VisualProcessor.ProcessingChain processingChain;
// setup the processing chain
processingChain = new VisualProcessor.ProcessingChain();
Dag.Element newDagElement;
newDagElement = new Dag.Element(
new VisualProcessor.ProcessingChain.ChainElementColorFloat(
new VisualProcessor.ProcessingChain.ConvertColorRgbToGrayscaleFilter(new ColorRgb(1.0f, 1.0f, 1.0f)),
"convertRgbToGrayscale",
bpSolver.getImageSize()
)
);
newDagElement.childIndices.add(1);
processingChain.filterChainDag.elements.add(newDagElement);
newDagElement = new Dag.Element(
new VisualProcessor.ProcessingChain.ChainElementFloatBoolean(
new VisualProcessor.ProcessingChain.DitheringFilter(),
"dither",
bpSolver.getImageSize()
)
);
processingChain.filterChainDag.elements.add(newDagElement);
/*
new VisualProcessor.ProcessingChain.ChainElementColorFloat(
new VisualProcessor.ProcessingChain.ConvertColorRgbToGrayscaleFilter(
new ColorRgb(1.0f, 1.0f, 1.0f)),
"convertRgbToGrayscale",
bpSolver.getImageSize()
)
)
*/
GraphWindow graphWindow = new GraphWindow();
IntrospectControlPanel introspectControlPanel;
introspectControlPanel = new IntrospectControlPanel();
DualConvas dualCanvas = new DualConvas();
Timer timer = new Timer(1000, new TimerActionListener(bpSolver, new InputDrawer(), introspectControlPanel, graphWindow.getNodeGraph(), dualCanvas, processingChain));
timer.setInitialDelay(0);
timer.start();
Container panel = j.getContentPane();
panel.setLayout(new BorderLayout());
{
GridLayout experimentLayout = new GridLayout(3,1);
final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(experimentLayout);
compsToExperiment.add(introspectControlPanel.getPanel());
compsToExperiment.add(dualCanvas);
compsToExperiment.add(graphWindow.getComponent());
panel.add(compsToExperiment, BorderLayout.CENTER);
}
panel.add(new TuningWindow(), BorderLayout.SOUTH);
{
Component fc = FileChooser.newComponent(new File("/tmp"), new ImageFileFilter(), true, f -> {
currentFileImage = null;
currentFile = f;
});
fc.setPreferredSize(new Dimension(RETINA_WIDTH, RETINA_HEIGHT));
panel.add(fc, BorderLayout.WEST);
}
j.setSize(1024, 1000);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
}
public static void main(String[] args) {
new TestClustering();
}
// TODO< move this into the functionality of the visual processor >
private static IMap2d<ColorRgb> translateFromImageToMap(BufferedImage javaImage) {
DataBuffer imageBuffer = javaImage.getData().getDataBuffer();
int bufferI;
IMap2d<ColorRgb> convertedToMap;
convertedToMap = new Map2d<>(javaImage.getWidth(), javaImage.getHeight());
for( bufferI = 0; bufferI < imageBuffer.getSize(); bufferI++ )
{
int pixelValue;
pixelValue = javaImage.getRGB(bufferI%convertedToMap.getWidth(), bufferI/convertedToMap.getWidth());
Color c = new Color(pixelValue);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
convertedToMap.setAt(bufferI%convertedToMap.getWidth(), bufferI/convertedToMap.getWidth(), new ColorRgb((float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f));
}
return convertedToMap;
}
private static BufferedImage translateFromMapToImage(IMap2d<Boolean> map) {
BufferedImage result;
int x, y;
result = new BufferedImage(map.getWidth(), map.getLength(), BufferedImage.TYPE_INT_ARGB);
for( y = 0; y < map.getLength(); y++ ) {
for( x = 0; x < map.getLength(); x++ ) {
boolean booleanValue;
booleanValue = map.readAt(x, y);
if( booleanValue ) {
result.setRGB(x, y, 0xffffffff);
}
else {
result.setRGB(x, y, 0xff000000);
}
}
}
return result;
}
}
|
package engine;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.ArrayList;
/**
*
* @author bjodet982
*/
public class CollisionChecker {
public static final double CorrectionPercentage = 0.2, Slop = 0.01;
public static boolean intersect(double px, double py, double qx, double qy, double ex, double ey, double fx, double fy) { // CALCULATE INTERSECTIONS
/*double cp = (fx-ex)*(py-fy)-(fy-ey)*(px-fx);
double cq = (fx-ex)*(qy-fy)-(fy-ey)*(qx-fx);
double ce = (px-qx)*(ey-py)-(py-qy)*(ex-px);
double cf = (px-qx)*(fy-py)-(py-qy)*(fx-px);
return (isn(cp) != isn(cq)) && (isn(ce) != isn(cf));*/
return (isNegative((fx - ex) * (py - fy) - (fy - ey) * (px - fx)) != isNegative((fx - ex) * (qy - fy) - (fy - ey) * (qx - fx))) && (isNegative((px - qx) * (ey - py) - (py - qy) * (ex - px)) != isNegative((px - qx) * (fy - py) - (py - qy) * (fx - px)));
}
public static boolean intersect(Line line1, Line line2) { // CALCULATE INTERSECTIONS
line1.vector.readyPoint();
line2.vector.readyPoint();
/*double cp = (line2.vector.point.x)*(line1.origin.y-line2.end.y)-(line2.vector.point.y)*(line1.origin.x-line2.end.x);
double cq = (line2.vector.point.x)*(line1.end.y-line2.end.y)-(line2.vector.point.y)*(line1.end.x-line2.end.x);
double ce = (-line1.vector.point.x)*(line2.origin.y-line1.origin.y)-(-line1.vector.point.y)*(line2.origin.x-line1.origin.x);
double cf = (-line1.vector.point.x)*(line2.end.y-line1.origin.y)-(-line1.vector.point.y)*(line2.end.x-line1.origin.x);
double cp = (line2.vector.point.x)*(line1.origin.y-line2.end.y)-(line2.vector.point.y)*(line1.origin.x-line2.end.x);
double cq = (line2.vector.point.x)*(line1.end.y-line2.end.y)-(line2.vector.point.y)*(line1.end.x-line2.end.x);
double ce = (line1.vector.point.y)*(line2.origin.x-line1.origin.x)-(line1.vector.point.x)*(line2.origin.y-line1.origin.y);
double cf = (line1.vector.point.y)*(line2.end.x-line1.origin.x)-(line1.vector.point.x)*(line2.end.y-line1.origin.y);
return (isn(cp) != isn(cq)) && (isn(ce) != isn(cf));*/
return (isNegative((line2.vector.point.x) * (line1.origin.y - line2.end.y) - (line2.vector.point.y) * (line1.origin.x - line2.end.x)) != isNegative((line2.vector.point.x) * (line1.end.y - line2.end.y) - (line2.vector.point.y) * (line1.end.x - line2.end.x))) && (isNegative((line1.vector.point.y) * (line2.origin.x - line1.origin.x) - (line1.vector.point.x) * (line2.origin.y - line1.origin.y)) != isNegative((line1.vector.point.y) * (line2.end.x - line1.origin.x) - (line1.vector.point.x) * (line2.end.y - line1.origin.y)));
}
public static boolean parallel(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) {
double firstSlope = ((by - ay) / (bx - ax));
double secondSlope = ((dy - cy) / (dx - cx));
return firstSlope == secondSlope;
}
public static boolean parallel(Line a, Line b) {
double firstSlope = (a.vector.getPoint().y) / (a.vector.getPoint().x);
double secondSlope = (b.vector.getPoint().y) / (b.vector.getPoint().x);
return firstSlope == secondSlope;
}
public static boolean pointInRectangleShape(RectangleShape rs, Point.Double p) {
Vector2D vector = new Vector2D(new Point.Double(p.x - rs.x, p.y - rs.y));
System.out.println("vector.x : " + vector.point.x + " - vector.y : " + vector.point.y);
vector.rotate(-rs.rotation);
vector.readyPoint();
System.out.println("vector.x : " + vector.point.x + " - vector.y : " + vector.point.y + " - Width:Height " + rs.width + ":" + rs.height);
System.out.println(!(vector.point.x < 0 || vector.point.x > rs.width || vector.point.y < 0 || vector.point.y > rs.height));
return !(vector.point.x < 0 || vector.point.x > rs.width || vector.point.y < 0 || vector.point.y > rs.height);
}
public static boolean areLinesAlmostTouching(Line line1, Line line2, double distance, double angleLimit) {
double firstAngle = line1.vector.getAngle() % Math.PI;
double secondAngle = line2.vector.getAngle() % Math.PI;
//System.out.println("distance: " + Math.abs(new Vector2D(new Point.Double(line1.origin.x - line2.origin.x, line1.origin.y - line2.origin.y)).rotate(-line1.vector.getAngle()).getPoint().y));
//System.out.println("angle differance: "+Math.abs(firstAngle - secondAngle));
return (Math.abs(firstAngle - secondAngle)) <= angleLimit && Math.abs(new Vector2D(new Point.Double(line1.origin.x - line2.origin.x, line1.origin.y - line2.origin.y)).rotate(-line1.vector.getAngle()).getPoint().y) <= distance;
}
public static boolean areLineAndPointAlmostTouching(Line line, Point.Double point, double distance) {
return new Vector2D(line.origin.x - point.x, line.origin.y - point.y).rotate(line.vector.getAngle()).getPoint().y <= distance;
}
public static boolean isNegative(double num) {
return num == Math.abs(num);
}
private static boolean planeAndRectangleIntersect(RectangleShape rectangle, Plane plane) {
rectangle.calcLines();
for (Line line : rectangle.lines) {
if (intersect(line, plane.surface)) {
return true;
}
}
return false;
}
private static Point.Double planeAndRectangleIntersectCorner(RectangleShape rectangle, Plane plane) {
rectangle.calcLines();
Point.Double point = null;
int line1 = 10000;
int line2 = 10000;
for (int i = 0; i < 4; i++) {
if (intersect(rectangle.lines[i], plane.surface)) {
if (line1 == 10000) {
line1 = i;
} else {
line2 = i;
break;
}
}
}
switch ((line1 * 10 + line2)) {
case 1:
point = rectangle.lines[0].origin;
case 3:
point = rectangle.lines[0].end;
case 12:
point = rectangle.lines[1].end;
case 23:
point = rectangle.lines[2].end;
}
return point;
}
private static boolean planeAndCircleIntersect(CircleShape shape, Plane plane) {
return DistanceBetweenPointAndPlane(new Point.Double(shape.x, shape.y), plane) < shape.radius;
}
private static boolean planeAndShapeIntersect(Shape shape, Plane plane) {
boolean collision = false;
if (shape instanceof RectangleShape) {
collision = planeAndRectangleIntersect((RectangleShape) shape, plane);
} else if (shape instanceof CircleShape) {
collision = planeAndCircleIntersect((CircleShape) shape, plane);
}
return collision;
}
private static boolean planeAndRectangleTouch(RectangleShape rectangle, Plane plane) {
for (Line line : rectangle.lines) {
if (areLinesAlmostTouching(line, plane.surface, 0.1, 0.1)) {
return true;
}
}
return false;
}
private static boolean planeAndCircleTouch(CircleShape circleShape, Plane plane) {
return planeAndCircleIntersect(circleShape, plane);
}
public static boolean planeAndShapeTouch(Shape shape, Plane plane) {
boolean collision = false;
if (shape instanceof RectangleShape) {
collision = planeAndRectangleTouch((RectangleShape) shape, plane);
} else if (shape instanceof CircleShape) {
collision = planeAndCircleTouch((CircleShape) shape, plane);
}
return collision;
}
public static void findNewCollisions(ArrayList<Object> objects, ArrayList<Plane> planes, double dt, Vector2D g) {
for (Object object : objects) {
for (Plane plane : planes) {
if (planeAndShapeIntersect(object.shapes.get(0), plane)) {
System.out.println("COLLISIONS");
//NORMALS
double ImpLength = ObjectAndPlaneCollisionImpulseLengthCalculator(object, plane);
Vector2D impulse = new Vector2D(new Vector2D(plane.getNormalizedNormal()).multiply(ImpLength));
object.nextVelocity = object.velocity.subtract(impulse.multiply(1 / object.getMass()));
System.out.println("Impulse big thingy stuff " + ImpLength);
//FRICTION
ObjectAndPlaneCollisionFrictionCalculator(object,plane,ImpLength);
if (object.shapes.get(0) instanceof RectangleShape) {
RectanglePlanePositionCorrection(object, plane);
} else if (object.shapes.get(0) instanceof CircleShape) {
CirclePlanePositionCorrection(object, plane);
}
// Point.Double balancePoint = planeAndRectangleIntersectCorner((RectangleShape) object.shapes.get(0), plane);
// if (balancePoint != null) {
// Vector2D momentAxis = new Vector2D(object.massCenter.getPoint(), balancePoint);
// Vector2D normalComponent = Vector2D.getNormalComponent(Vector2D.multiply(new Vector2D(g), object.getMass()), momentAxis);
// object.nextAngularVelocity = normalComponent.getLength() * object.getI() * object.velocity.distance(0, 0);
// System.out.println("AV:" + (normalComponent.getLength() * object.getI()));
// //System.out.println("NCL: "+ normalComponent.getLength());
// //System.out.println("it is happening");
// /*double k = 0.5;
// double change = 0.25;
// for (int i = 0; i < 8; i++) {
// object.preUpdate(dt * k, g);
// if (planeAndShapeIntersect(object.shapes.get(0), plane)) {
// k -= change;
// } else {
// k += change;
// }
// change /= 2;
// }
// object.preUpdate(dt * (k + change * 2), g);*/
// Vector2D parVel = Vector2D.OrthogonalProjection(new Vector2D(object.velocity), plane.surface.vector);
// parVel.readyPoint();
// object.nextVelocity = new Point.Double(parVel.point.x, parVel.point.y);
// Vector2D accVec = Vector2D.multiply(plane.getNormal().normalize(), g.getLength() * Math.cos(plane.surface.vector.getAngle()));
// accVec.readyPoint();
// object.acceleration = new Point.Double(accVec.point.x, accVec.point.y);
{
}
}
}
}
for (Object object : objects) {
for (Plane plane : planes) {
if (planeAndShapeTouch(object.shapes.get(0), plane)) {
System.out.println("touching :>");
/*double k = 0.5;
double change = 0.25;
for (int i = 0; i < 8; i++) {
object.preUpdate(dt * k, g);
if (planeAndShapeTouch(object.shapes.get(0), plane)) {
k -= change;
} else {
k += change;
}
change /= 2;
}
object.preUpdate(dt * (k - change * 2), g);*/
//object.velocity = new Point.Double(0, 0);
}
}
}
}
public static void ObjectsCollisionImpulseLengthCalculator(Object obj1, Object obj2) {
// Vector2D relativeVelocityAlongNormal = new Vector2D(obj2.velocity).subtract(obj1.velocity).multiply(obj2.normal);
double e = Math.floor(obj1.restitution - obj2.restitution);
// double Impulse = -(1+e)*(Vector2D.scalarProductCoordinates(rv, plane.)
}
public static double ObjectAndPlaneCollisionImpulseLengthCalculator(Object object, Plane plane) {
//object.velocity.readyPoint();
//plane.surface.vector.readyPoint();
double relativeVelocityAlongNormal = Vector2D.scalarProductCoordinates(object.nextVelocity, plane.getNormalizedNormal());
System.out.println("relVelNorm " + relativeVelocityAlongNormal);
//if (relativeVelocityAlongNormal > 0) {
// return 0;
//} else {
return ((1.0 + Math.min(object.restitution, plane.restitution)) * relativeVelocityAlongNormal) / (1.0 / object.mass);
}
public static void ObjectAndPlaneCollisionFrictionCalculator(Object object, Plane plane, double collisionMagnitude) {
Vector2D tangent = new Vector2D(object.nextVelocity).subtract(new Vector2D(plane.normal).multiply(Vector2D.scalarProductCoordinates(object.nextVelocity, plane.normal)));
tangent.normalize();
double jt = - Vector2D.scalarProductCoordinates(object.nextVelocity, tangent);
double mu = Friction.getStatic(object.material,plane.material);
Vector2D frictionImpulse;
if (Math.abs(jt) < collisionMagnitude*mu) {
frictionImpulse = tangent.multiply(jt);
} else {
frictionImpulse = tangent.multiply(getDynamic(object.material,plane.material)*-collisionMagnitude);
}
object.nextVelocity.subtract(frictionImpulse);
}
public static double RectanglePlanePenetrationDepth(Object object, Plane plane) {
RectangleShape rectangle = (RectangleShape) object.shapes.get(0);
System.out.println("PENETRATION DEPTH: "+Math.min(Math.min(Math.min(Math.min(0.0, Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[2].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[1].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[0].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[0].origin), plane.normal)));
return Math.min(Math.min(Math.min(Math.min(0.0, Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[2].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[1].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[0].end), plane.normal)), Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, rectangle.lines[0].origin), plane.normal));
}
public static double CirclePlanePenetrationDepth(Object object, Plane plane) {
CircleShape circle = (CircleShape) object.shapes.get(0);
return circle.radius-DistanceBetweenPointAndPlane(new Point.Double(circle.x, circle.y), plane);
}
public static void CirclePlanePositionCorrection(Object object, Plane plane) {
Vector2D correction = new Vector2D(plane.normal).multiply(Math.max(-CirclePlanePenetrationDepth(object, plane) - Slop, 0.0f) * object.mass * CorrectionPercentage);
correction.multiply(1.0 / object.mass);
object.nextPosition.x -= correction.point.x;
object.nextPosition.y -= correction.point.y;
}
public static void RectanglePlanePositionCorrection(Object object, Plane plane) {
Vector2D correction = new Vector2D(plane.normal).multiply(Math.max(-RectanglePlanePenetrationDepth(object, plane) - Slop, 0.0f) * object.mass * CorrectionPercentage);
correction.multiply(1.0/object.mass);
object.nextPosition.x += correction.point.x;
object.nextPosition.y += correction.point.y;
}
public static double DistanceBetweenPointAndPlane(Point.Double point, Plane plane) {
return Vector2D.scalarProductCoordinates(new Vector2D(plane.surface.origin, point), plane.normal);
}
}
|
package refinedstorage.tile;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import refinedstorage.RefinedStorageUtils;
import refinedstorage.network.MessageMachineConnectedUpdate;
import refinedstorage.tile.config.IRedstoneModeConfig;
import refinedstorage.tile.config.RedstoneMode;
import java.util.HashSet;
import java.util.Set;
public abstract class TileMachine extends TileBase implements ISynchronizedContainer, IRedstoneModeConfig {
protected boolean connected = false;
protected RedstoneMode redstoneMode = RedstoneMode.IGNORE;
protected TileController controller;
private Block block;
private Set<String> visited = new HashSet<String>();
public TileController getController() {
return controller;
}
// We use a world parameter here and not worldObj because in BlockMachine.onNeighborBlockChange
// this method is called and at that point in time worldObj is not set yet.
public void searchController(World world) {
visited.clear();
TileController newController = ControllerSearcher.search(worldObj, pos, visited);
if (controller == null) {
if (newController != null && newController.canRun() && redstoneMode.isEnabled(worldObj, pos)) {
onConnected(world, newController);
}
} else {
if (newController == null) {
onDisconnected(world);
}
}
}
@Override
public void update() {
super.update();
if (!worldObj.isRemote) {
if (ticks == 1) {
block = worldObj.getBlockState(pos).getBlock();
searchController(worldObj);
}
if (connected && !redstoneMode.isEnabled(worldObj, pos)) {
onDisconnected(worldObj);
}
RefinedStorageUtils.sendToAllAround(worldObj, pos, new MessageMachineConnectedUpdate(this));
}
}
public void onConnected(World world, TileController controller) {
this.controller = controller;
this.connected = true;
world.notifyNeighborsOfStateChange(pos, block);
controller.addMachine(this);
}
public void onDisconnected(World world) {
this.connected = false;
if (this.controller != null) {
this.controller.removeMachine(this);
this.controller = null;
}
world.notifyNeighborsOfStateChange(pos, block);
}
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
@Override
public RedstoneMode getRedstoneMode() {
return redstoneMode;
}
@Override
public void setRedstoneMode(RedstoneMode mode) {
markDirty();
this.redstoneMode = mode;
}
@Override
public BlockPos getMachinePos() {
return pos;
}
@Override
public void receiveContainerData(ByteBuf buf) {
redstoneMode = RedstoneMode.getById(buf.readInt());
}
@Override
public void sendContainerData(ByteBuf buf) {
buf.writeInt(redstoneMode.id);
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
if (nbt.hasKey(RedstoneMode.NBT)) {
redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT));
}
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setInteger(RedstoneMode.NBT, redstoneMode.id);
}
public abstract int getEnergyUsage();
public abstract void updateMachine();
}
|
package engine;
import engine.Main.MyJPanel;
import engine.OptionFrame.MyOptionPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;
/**
*
* @author Letfik
*/
public class CustomOptionMenu extends JMenuBar {
static final ScriptEngineManager manager = new ScriptEngineManager();
static final ScriptEngine engine = manager.getEngineByName("js");
MyOptionPanel optionPanel;
MyJPanel panel;
JMenuItem setupOne = makeSetupOne();
JMenuItem setupTwo = makeSetupTwo();
JMenuItem setupThree = makeSetupThree();
JMenuItem setupFour = makeSetupFour();
JMenuItem setupFive = makeSetupFive();
JMenuItem setupSix = makeSetupSix();
JMenuItem setupSeven = makeSetupSeven();
JMenuItem setupEight = makeSetupEight();
JMenuItem setupNine = makeSetupNine();
JMenuItem setupTen = makeSetupTen();
JMenuItem setupEleven = makeSetupEleven();
JMenuItem setupTwelve = makeSetupTwelve();
JMenuItem setupThirteen = makeSetupThirteen();
public CustomOptionMenu(MyOptionPanel panel) {
this.optionPanel = panel;
this.panel = panel.mainPanel;
JMenu add = new JMenu("Add");
add.add(makeAddObjectAt());
add.add(makeAddPlane());
add.add(makeAddObject());
JMenu remove = new JMenu("Remove");
remove.add(makeRemoveObject());
remove.add(makeResetPlanes());
remove.add(makeResetObjects());
JMenu setup = new JMenu("Setup");
setup.add(setupOne);
setup.add(setupTwo);
setup.add(setupThree);
setup.add(setupFour);
setup.add(setupFive);
setup.add(setupSix);
setup.add(setupSeven);
setup.add(setupEight);
setup.add(setupNine);
setup.add(setupTen);
setup.add(setupEleven);
setup.add(setupTwelve);
setup.add(setupThirteen);
JMenu playback = playbackMenu();
playback.setText("Playback Speed");
add(add);
add(remove);
add(setup);
add(playback);
}
String temp = "Rectangle";
String shape = null;
private JMenuItem makeAddObject() {
JMenuItem addObject = new JMenuItem("Add Object");
addObject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.SHIFT_DOWN_MASK));
addObject.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooseShape(null);
}
});
return addObject;
}
private JMenuItem makeAddPlane() {
JMenuItem addPlane = new JMenuItem("Add Plane");
addPlane.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.SHIFT_DOWN_MASK));
addPlane.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double x1 = Double.parseDouble(inputOptionPane("Enter x1."));
double y1 = Double.parseDouble(inputOptionPane("Enter y1."));
double x2 = Double.parseDouble(inputOptionPane("Enter x2."));
double y2 = Double.parseDouble(inputOptionPane("Enter y2."));
panel.world.addPlane(new Plane(x1, y1, x2, y2));
if (!Main.playing) {
panel.repaint();
}
}
});
return addPlane;
}
private JMenuItem makeAddObjectAt() {
JMenuItem addObjectAt = new JMenuItem("Add Object at Click");
addObjectAt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.SHIFT_DOWN_MASK));
addObjectAt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.adding = true;
}
});
return addObjectAt;
}
private JMenuItem makeResetObjects() {
JMenuItem resetObjects = new JMenuItem("Reset Objects");
resetObjects.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK));
resetObjects.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int confirmReset = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset?\n This action can't be undone.", "RESET", JOptionPane.YES_NO_OPTION);
if (confirmReset == JOptionPane.YES_OPTION) {
panel.world.objects = new ArrayList();
if (!Main.playing) {
panel.repaint();
}
}
}
});
return resetObjects;
}
private JMenuItem makeResetPlanes() {
JMenuItem resetPlanes = new JMenuItem("Reset Planes");
resetPlanes.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_DOWN_MASK));
resetPlanes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int confirmReset = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset?\n This action can't be undone.", "RESET", JOptionPane.YES_NO_OPTION);
if (confirmReset == JOptionPane.YES_OPTION) {
panel.world.planes = new ArrayList();
if (!Main.playing) {
panel.repaint();
}
}
}
});
return resetPlanes;
}
private JMenuItem makeRemoveObject() {
JMenuItem removeObject = new JMenuItem("Remove Object");
removeObject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
removeObject.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.removing = true;
}
});
return removeObject;
}
public void chooseShape(Point.Double p) {
JRadioButton rectangle = new JRadioButton();
JRadioButton circle = new JRadioButton();
JPanel radiopanel = shapeRadioPanel(rectangle, circle);
rectangle.setSelected(true);
circle.setSelected(false);
int chooseShape = JOptionPane.showConfirmDialog(null, radiopanel, "Choose shape.", JOptionPane.OK_CANCEL_OPTION);
if (chooseShape == JOptionPane.CANCEL_OPTION || chooseShape == JOptionPane.CLOSED_OPTION) {
return;
} else if (chooseShape == JOptionPane.OK_OPTION) {
shape = temp;
}
switch (shape) {
case "Rectangle":
if (p == null) {
rectangleOptions();
} else {
rectangleOptions(p);
}
break;
case "Circle":
if (p == null) {
circleOptions();
} else {
circleOptions(p);
}
break;
}
}
private void rectangleOptions() {
double x = doubleInput("Enter x.");
double y = doubleInput("Enter y.");
rectangleOptions(new Point.Double(x, y));
}
private void rectangleOptions(Point.Double p) {
int w = intInput("Enter width.");
int h = intInput("Enter height.");
double r = doubleInput("Enter rotation.");
double m = doubleInput("Enter mass.");
Color c = stringToColorInput("Enter color.");
panel.world.addObject(new Object(new RectangleShape(w, h, new Vector2D(0, 0), r, m, c), new Point.Double(p.x, p.y)));
if (!Main.playing) {
panel.repaint();
}
}
private void circleOptions() {
double x = doubleInput("Enter x.");
double y = doubleInput("Enter y.");
circleOptions(new Point.Double(x, y));
}
private void circleOptions(Point.Double p) {
int rad = intInput("Enter radius.");
double r = doubleInput("Enter rotation.");
double m = doubleInput("Enter mass.");
Color c = stringToColorInput("Enter color");
panel.world.addObject(new Object(new CircleShape(rad, new Vector2D(0, 0), r, m, c), new Point.Double(p.x, p.y)));
if (!Main.playing) {
panel.repaint();
}
}
public static int intInput(String text) {
try {
return Integer.parseInt(inputOptionPane(text));
} catch (NumberFormatException e) {
if (text.contains("(int)")) {
return intInput(text);
} else {
return intInput(text + " (int)");
}
}
}
public static double doubleInput(String text) {
try {
return stringParser(text);
} catch (NumberFormatException e) {
if (text.contains("(double)")) {
return doubleInput(text);
} else {
return doubleInput(text + " (double)");
}
}
}
public static Color stringToColorInput(String text) {
try {
Field field = Class.forName("java.awt.Color").getField(inputOptionPane(text).toUpperCase());
return (Color) field.get(null);
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
if (text.contains("(jawa.awt.Color)")) {
return stringToColorInput(text);
} else {
return stringToColorInput(text + " (jawa.awt.Color)");
}
}
}
private static String inputOptionPane(String text) {
return JOptionPane.showInputDialog(null, text, "TITLE", JOptionPane.QUESTION_MESSAGE);
}
public static Double stringParser(String text) {
String s = inputOptionPane(text);
try {
if (!s.contains("/") && !s.contains(".")) {
s += ".0";
}
java.lang.Object result = engine.eval((s));
return (double) result;
} catch (ScriptException ex) {
Logger.getLogger(OptionFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException ex) {
}
return 0.0;
}
private JPanel shapeRadioPanel(JRadioButton rectangle, JRadioButton circle) {
final JPanel radioPanel = new JPanel(new GridLayout(2, 1));
ButtonGroup buttonGroup = new ButtonGroup();
rectangle = rectangleChoice();
circle = circleChoice();
buttonGroup.add(rectangle);
radioPanel.add(rectangle);
buttonGroup.add(circle);
radioPanel.add(circle);
return radioPanel;
}
private JRadioButton rectangleChoice() {
JRadioButton rectangle = new JRadioButton("Rectangle");
rectangle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
temp = "Rectangle";
}
});
rectangle.setSelected(true);
return rectangle;
}
private JRadioButton circleChoice() {
JRadioButton circle = new JRadioButton("Circle");
circle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
temp = "Circle";
}
});
return circle;
}
private JMenu playbackMenu() {
JMenu menu = new JMenu();
ButtonGroup bg = new ButtonGroup();
JRadioButton hhs = new JRadioButton("1/4 speed");
hhs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
optionPanel.playbackSpeed = 4;
}
});
bg.add(hhs);
menu.add(hhs);
JRadioButton hs = new JRadioButton("1/2 speed");
hs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
optionPanel.playbackSpeed = 2;
}
});
bg.add(hs);
menu.add(hs);
JRadioButton ns = new JRadioButton("1 speed");
ns.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
optionPanel.playbackSpeed = 1;
}
});
ns.setSelected(true);
bg.add(ns);
menu.add(ns);
JRadioButton ds = new JRadioButton("2 speed");
ds.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
optionPanel.playbackSpeed = 0.5;
}
});
bg.add(ds);
menu.add(ds);
JRadioButton dds = new JRadioButton("4 speed");
dds.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
optionPanel.playbackSpeed = 0.25;
}
});
bg.add(dds);
menu.add(dds);
return menu;
}
private JMenuItem makeSetupOne() {
JMenuItem setup = new JMenuItem("Setup One");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.follow = false;
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 500, 800, 500, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupTwo() {
JMenuItem setup = new JMenuItem("Setup Two");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 0, 8000, 6000, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupThree() {
JMenuItem setup = new JMenuItem("Setup Three");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.addPlane(new Plane(0, 0, 8000, 6000, Material.Concrete));
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), panel.world.planes.get(0).surface.vector.getAngle(), 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupFour() {
JMenuItem setup = new JMenuItem("Setup Four");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new CircleShape(50, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.RED), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 0, 8000, 6000, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupFive() {
JMenuItem setup = new JMenuItem("Setup Five");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.follow = false;
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(350, 300), Material.Wood));
panel.world.objects.add(new Object(new CircleShape(50, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.RED), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 500, 800, 500, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupSix() {
JMenuItem setup = new JMenuItem("Setup Six");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(100, 100), Material.Wood));
panel.world.objects.get(0).velocity = new Vector2D(100, 0);
panel.world.addPlane(new Plane(0, 500, 800, 500, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupSeven() {
JMenuItem setup = new JMenuItem("Setup Seven");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(155, 140), Material.Wood));
panel.world.objects.get(0).velocity = new Vector2D(0, 5000);
int x = 100, y = 100;
double angle = Math.toRadians(90);
double length = 102;
int segments = 360;
double dAngle = Math.toRadians(-1);
for (int i = 0; i <= segments; i++) {
panel.world.addPlane(new Plane((int) (x - Math.cos(angle) * 10 + .5), (int) (y - Math.sin(angle) * 10 + .5), (int) (x + Math.cos(angle) * (length + 10) + .5), (int) (y + Math.sin(angle) * (length + 10) + .5), Material.Boost));
x = (int) (x + Math.cos(angle) * length + .5);
y = (int) (y + Math.sin(angle) * length + .5);
angle += dAngle;
}
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupEight() {
JMenuItem setup = new JMenuItem("Setup Eight");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(200, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 150, 400, 550, Material.Concrete));
panel.world.addPlane(new Plane(400, 550, 8000, 550, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupNine() {
JMenuItem setup = new JMenuItem("Setup Nine");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.follow = false;
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(100, 100), Material.Boost));
panel.world.objects.get(0).velocity = new Vector2D(700, -100);
panel.world.addPlane(new Plane(-5000, 100, 700, 500, Material.Concrete));
panel.world.addPlane(new Plane(700, 500, 700, 0, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupTen() {
JMenuItem setup = new JMenuItem("Setup Ten");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.objects.add(new Object(new CircleShape(50, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(155, 140), Material.Wood));
panel.world.objects.get(0).velocity = new Vector2D(0, 0000);
int x = 50, y = 100;
double angle = Math.toRadians(90);
double length = 102;
int segments = 360;
double dAngle = Math.toRadians(-1);
for (int i = 0; i <= segments; i++) {
panel.world.addPlane(new Plane((int) (x - Math.cos(angle) * 10 + .5), (int) (y - Math.sin(angle) * 10 + .5), (int) (x + Math.cos(angle) * (length + 10) + .5), (int) (y + Math.sin(angle) * (length + 10) + .5), Material.Boost));
x = (int) (x + Math.cos(angle) * length + .5);
y = (int) (y + Math.sin(angle) * length + .5);
angle += dAngle;
}
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupEleven() {
JMenuItem setup = new JMenuItem("Setup Eleven");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 0));
panel.world.follow = false;
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.world.objects.get(0).angularVelocity = 1;
panel.world.addPlane(new Plane(0, 500, 800, 500, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupTwelve() {
JMenuItem setup = new JMenuItem("Setup Twelve");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.follow = false;
panel.world.objects.add(new Object(new RectangleShape(100, 100, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 550, 800, 550, Material.Concrete));
panel.world.addPlane(new Plane(0, 350, 390, 350, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
private JMenuItem makeSetupThirteen() {
JMenuItem setup = new JMenuItem("Setup Thirteen");
setup.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.world = new World(new Vector2D(0, 982));
panel.world.follow = false;
panel.world.objects.add(new Object(new CircleShape(50, new Vector2D(new Point.Double(0, 0)), 0, 0.5, Color.BLUE), new Point.Double(400, 100), Material.Wood));
panel.world.addPlane(new Plane(0, 350, 400, 350, Material.Concrete));
panel.optionFrame.panel.save.doClick();
if (!Main.playing) {
panel.repaint();
}
}
});
return setup;
}
}
|
package seedu.taskmanager.ui;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import seedu.taskmanager.commons.core.LogsCenter;
import seedu.taskmanager.commons.util.FxViewUtil;
import java.util.logging.Logger;
/**
* Controller for a help page
*/
public class HelpWindow extends UiPart {
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String ICON = "/images/help_icon.png";
private static final String FXML = "HelpWindow.fxml";
private static final String TITLE = "Help";
private static final String USERGUIDE_URL =
"https://github.com/CS2103AUG2016-T14-C3/main/blob/master/docs/UserGuide.md";
private AnchorPane mainPane;
private Stage dialogStage;
public static HelpWindow load(Stage primaryStage) {
logger.fine("Showing help page about the application.");
HelpWindow helpWindow = UiPartLoader.loadUiPart(primaryStage, new HelpWindow());
helpWindow.configure();
return helpWindow;
}
@Override
public void setNode(Node node) {
mainPane = (AnchorPane) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
private void configure(){
Scene scene = new Scene(mainPane);
//Null passed as the parent stage to make it non-modal.
dialogStage = createDialogStage(TITLE, null, scene);
dialogStage.setMaximized(true); //TODO: set a more appropriate initial size
setIcon(dialogStage, ICON);
WebView browser = new WebView();
browser.getEngine().load(USERGUIDE_URL);
FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0);
mainPane.getChildren().add(browser);
}
public void show() {
dialogStage.showAndWait();
}
}
|
package tamaized.aov.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import org.lwjgl.opengl.GL11;
import tamaized.aov.AoV;
import tamaized.aov.client.entity.RenderCombust;
import tamaized.aov.client.entity.RenderGravity;
import tamaized.aov.common.capabilities.CapabilityList;
import tamaized.aov.common.capabilities.astro.AstroCapabilityHandler;
import tamaized.aov.common.capabilities.astro.IAstroCapability;
@Mod.EventBusSubscriber(modid = AoV.modid, value = Side.CLIENT)
public class RenderAstro {
private static final ResourceLocation TEXTURE_CARDS = new ResourceLocation(AoV.modid, "textures/entity/cards.png");
private static final ResourceLocation TEXTURE_RUNE = new ResourceLocation(AoV.modid, "textures/entity/rune.png");
public static float testVarPleaseIgnore = 0F;
@SubscribeEvent
public static void render(RenderPlayerEvent.Post e) {
EntityPlayer player = e.getEntityPlayer();
if (!player.hasCapability(CapabilityList.ASTRO, null))
return;
GlStateManager.pushMatrix();
GlStateManager.translate(e.getX(), e.getY(), e.getZ());
IAstroCapability cap = player.getCapability(CapabilityList.ASTRO, null);
AstroCapabilityHandler handler = cap instanceof AstroCapabilityHandler ? (AstroCapabilityHandler) cap : null;
/*GlStateManager.pushMatrix();
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.disableCull();
GlStateManager.color(0, 0.6F, 1, 1.0F);
GlStateManager.rotate(90F, 1.0F, 0.0F, 0.0F);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.SRC_ALPHA);
e.getRenderer().bindTexture(RenderCombust.RING);
Tessellator tess = Tessellator.getInstance();
BufferBuilder buf = tess.getBuffer();
buf.begin(7, DefaultVertexFormats.POSITION_TEX);
buf.pos(1, 1, 0).tex(1, 1).endVertex();
buf.pos(1, 0, 0).tex(1, 0).endVertex();
buf.pos(0, 0, 0).tex(0, 0).endVertex();
buf.pos(0, 1, 0).tex(0, 1).endVertex();
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
GlStateManager.disableDepth();
tess.draw();
GlStateManager.enableDepth();
GlStateManager.color(1, 1, 1, 1);
GlStateManager.enableCull();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.popMatrix();*/
if (cap != null) {
for (IAstroCapability.IAnimation animation : cap.getAnimations())
if (animation != null)
switch (animation) {
case Draw:
renderDraw(0, e, cap, handler != null ? handler.lastDraw : cap.getDraw());
break;
case Spread:
renderSpread(2, e, cap, handler != null ? handler.lastSpread : cap.getSpread());
break;
case Burn:
renderBurn(1, e, cap);
break;
case Activate:
renderBurn(3, e, cap);
break;
case Redraw:
renderRedraw(4, e, cap);
break;
default:
break;
}
}
GlStateManager.color(1, 1, 1, 1);
GlStateManager.popMatrix();
}
@SubscribeEvent
public static void tick(TickEvent.RenderTickEvent e) { // Lets tick our frame data while in first person
if (e.phase == TickEvent.Phase.START)
return;
Minecraft mc = Minecraft.getMinecraft();
if (mc.gameSettings.thirdPersonView != 0 || mc.player == null || !mc.player.hasCapability(CapabilityList.ASTRO, null))
return;
IAstroCapability cap = mc.player.getCapability(CapabilityList.ASTRO, null);
if (cap == null)
return;
// Burn and Activate
float timer;
for (int index = 1; index <= 3; index += 2) {
timer = cap.getFrameData()[index][3];
cap.getFrameData()[index][1] = Math.max(0, cap.getFrameData()[index][1] - ((240F * (cap.getFrameData()[1][1] / 90F)) / (float) Minecraft.getDebugFPS()));
if (cap.getFrameData()[index][0] > 0 && !Minecraft.getMinecraft().isGamePaused() && timer < 20)
cap.getFrameData()[index][0] = Math.max(0, cap.getFrameData()[index][0] - (240F / (float) Minecraft.getDebugFPS()));
}
// Spread
if (!Minecraft.getMinecraft().isGamePaused()) {
cap.getFrameData()[2][4] += (240F / (float) Minecraft.getDebugFPS()) % 360;
cap.getFrameData()[2][5] += (cap.getFrameData()[2][5] >= 90 && cap.getFrameData()[2][3] > 35 ? 0 : 60F) / (float) Minecraft.getDebugFPS();
}
// Draw
for (int index = 0; index <= 2; index += 2) {
timer = cap.getFrameData()[index][3];
if (timer < 60 && !Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][2] > 0)
cap.getFrameData()[index][2] = Math.max(0, cap.getFrameData()[index][2] - (240F / (float) Minecraft.getDebugFPS()));
if (timer < 90 && !Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][1] > 0)
cap.getFrameData()[index][1] = Math.max(0, cap.getFrameData()[index][1] - (160F / (float) Minecraft.getDebugFPS()));
if (cap.getFrameData()[index][0] > 0 && !Minecraft.getMinecraft().isGamePaused() && timer < 25)
cap.getFrameData()[index][0] = Math.max(0, cap.getFrameData()[index][0] - (240F / (float) Minecraft.getDebugFPS()));
}
// Redraw
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[4][0] > 0)
cap.getFrameData()[4][0] -= (240F / (float) Minecraft.getDebugFPS());
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[4][1] > 0)
cap.getFrameData()[4][1] -= (120F / (float) Minecraft.getDebugFPS());
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[4][0] <= 0)
cap.getFrameData()[4][4] -= (60F / (float) Minecraft.getDebugFPS());
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[4][4] <= 0)
cap.getFrameData()[4][2] -= (300F / (float) Minecraft.getDebugFPS());
}
private static void renderRedraw(int index, RenderPlayerEvent.Post e, IAstroCapability cap) {
float timer = cap.getFrameData()[index][3];
if (timer > 0) {
GlStateManager.pushMatrix();
GlStateManager.disableCull();
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.rotate(-e.getEntityPlayer().renderYawOffset, 0, 1, 0);
GlStateManager.color(1, 1, 1, 1);
GlStateManager.translate(0F, 1.5F, 1F);
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][0] > 0)
cap.getFrameData()[index][0] -= (240F / (float) Minecraft.getDebugFPS());
GlStateManager.rotate(cap.getFrameData()[index][0] % 360, 0, 0, 1);
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][1] > 0)
cap.getFrameData()[index][1] -= (120F / (float) Minecraft.getDebugFPS());
float s = (80F - cap.getFrameData()[index][1]) / 80F;
GlStateManager.scale(s, s, s);
float f = 1.5F;//ftimer > 0 ? ((ftimer / 80f) * 1.5F) : 0F;
float scale = 0.3F;
e.getRenderer().bindTexture(TEXTURE_CARDS);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
GlStateManager.pushMatrix();
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][0] <= 0)
cap.getFrameData()[index][4] -= (60F / (float) Minecraft.getDebugFPS());
if (!Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][4] <= 0)
cap.getFrameData()[index][2] -= (300F / (float) Minecraft.getDebugFPS());
for (int i = 0; i <= 12; i++) {
vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX);
if (i > 0)
GlStateManager.rotate(30, 0, 0, 1);
float xpos = -0.15F;
float ypos = -0.435F;
float uScale = 125F / 12F;
float u = cap.getFrameData()[index][2] > (i - 1) * uScale ? (Math.max(0, ((i) * uScale) - cap.getFrameData()[index][2])) / uScale : 1F;
vertexbuffer.pos(xpos + scale, ypos + 1F, 0).tex(0, 0.5).endVertex();
vertexbuffer.pos(xpos + scale, ypos + 1F + (f * scale), 0).tex(0, 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(xpos + (scale * u), ypos + 1F + (f * scale), 0).tex(0.25 * (1F - u), 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(xpos + (scale * u), ypos + 1F, 0).tex(0.25 * (1F - u), 0.5).endVertex();
tessellator.draw();
}
GlStateManager.popMatrix();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.enableCull();
GlStateManager.popMatrix();
}
}
private static void renderBurn(int index, RenderPlayerEvent.Post e, IAstroCapability cap) {
float timer = cap.getFrameData()[index][3];
if (timer > 0) {
GlStateManager.pushMatrix();
GlStateManager.disableCull();
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.rotate(180F - e.getRenderer().getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F);
GlStateManager.translate(-0.125F, 0.5F + MathHelper.cos((float) Math.toRadians(cap.getFrameData()[index][1])), -0.125F);
cap.getFrameData()[index][1] = Math.max(0, cap.getFrameData()[index][1] - ((240F * (cap.getFrameData()[index][1] / 90F)) / (float) Minecraft.getDebugFPS()));
float ftimer = cap.getFrameData()[index][0];
if (cap.getFrameData()[index][0] > 0 && !Minecraft.getMinecraft().isGamePaused() && timer < 20)
cap.getFrameData()[index][0] = Math.max(0, cap.getFrameData()[index][0] - (240F / (float) Minecraft.getDebugFPS()));
float f = ftimer > 0 ? ((ftimer / 80f) * 1.5F) : 0F;
float scale = 0.25F;
e.getRenderer().bindTexture(TEXTURE_CARDS);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX);
vertexbuffer.pos(1F * scale, 1F, 0.0001).tex(0, 0.5).endVertex();
vertexbuffer.pos(1F * scale, 1F + (f * scale), 0.0001).tex(0, 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(0, 1F + (f * scale), 0.0001).tex(0.25, 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(0, 1F, 0.0001).tex(0.25, 0.5).endVertex();
tessellator.draw();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.enableCull();
GlStateManager.popMatrix();
}
}
private static void renderDraw(int index, RenderPlayerEvent.Post e, IAstroCapability cap, IAstroCapability.ICard card) {
float timer = cap.getFrameData()[index][3];
if (timer > 0) {
GlStateManager.pushMatrix();
GlStateManager.disableCull();
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.rotate((180F + cap.getFrameData()[index][2] - e.getRenderer().getRenderManager().playerViewY), 0.0F, 1.0F, 0.0F);
if (timer < 60 && !Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][2] > 0) {
cap.getFrameData()[index][2] = Math.max(0, cap.getFrameData()[index][2] - (240F / (float) Minecraft.getDebugFPS()));
}
GlStateManager.translate(-0.5F, 1.0F, 0);
if (timer < 90 && !Minecraft.getMinecraft().isGamePaused() && cap.getFrameData()[index][1] > 0) {
cap.getFrameData()[index][1] = Math.max(0, cap.getFrameData()[index][1] - (160F / (float) Minecraft.getDebugFPS()));
}
GlStateManager.color(1.0F, 1.0F, 1.0F, (80F - cap.getFrameData()[index][1]) / 80F);
float ftimer = cap.getFrameData()[index][0];
if (cap.getFrameData()[index][0] > 0 && !Minecraft.getMinecraft().isGamePaused() && timer < 25)
cap.getFrameData()[index][0] = Math.max(0, cap.getFrameData()[index][0] - (240F / (float) Minecraft.getDebugFPS()));
float f = ftimer > 0 ? ((ftimer / 80f) * 1.5F) : 0F;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
e.getRenderer().bindTexture(TEXTURE_CARDS);
vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX);
vertexbuffer.pos(1, 1, -0.0001).tex(0, 0.5).endVertex();
vertexbuffer.pos(1, 1 + f, -0.0001).tex(0, 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(0, 1 + f, -0.0001).tex(0.25, 0.5F - (0.5F * (f / 1.5F))).endVertex();
vertexbuffer.pos(0, 1, -0.0001).tex(0.25, 0.5).endVertex();
int cardID = IAstroCapability.ICard.getCardID(card) + 1;
double uv = 0.5F * Math.floor(cardID / 4);
vertexbuffer.pos(1, 1, 0).tex((0.25 * cardID % 4), 0.5F + uv).endVertex();
vertexbuffer.pos(1, 1 + f, 0).tex((0.25 * cardID % 4), (0.5F - (0.5F * (f / 1.5F))) + uv).endVertex();
vertexbuffer.pos(0, 1 + f, 0).tex(0.25 + (0.25 * cardID % 4), (0.5F - (0.5F * (f / 1.5F))) + uv).endVertex();
vertexbuffer.pos(0, 1, 0).tex(0.25 + (0.25 * cardID % 4), 0.5F + uv).endVertex();
tessellator.draw();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
GlStateManager.enableCull();
GlStateManager.popMatrix();
}
}
private static void renderSpread(int index, RenderPlayerEvent.Post e, IAstroCapability cap, IAstroCapability.ICard card) {
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.disableCull();
GlStateManager.disableLighting();
GlStateManager.rotate((90F - e.getRenderer().getRenderManager().playerViewY), 0.0F, 1.0F, 0.0F);
GlStateManager.translate(-0.2F, 2.2F, 0.05F);
GlStateManager.rotate(25, 0, 0, 1);
GlStateManager.rotate(60, 1, 0, 0);
if (!Minecraft.getMinecraft().isGamePaused())
cap.getFrameData()[index][4] += (240F / (float) Minecraft.getDebugFPS()) % 360;
GlStateManager.rotate(cap.getFrameData()[index][4], 0, 0, 1);
GlStateManager.translate(-1.45F, -1.55F, 0);
if (!Minecraft.getMinecraft().isGamePaused())
cap.getFrameData()[index][5] += (cap.getFrameData()[index][5] >= 90 && cap.getFrameData()[index][3] > 35 ? 0 : 60F) / (float) Minecraft.getDebugFPS();
GlStateManager.color(1, 1, 1, MathHelper.sin((float) Math.toRadians(Math.min(cap.getFrameData()[index][5], 180))));
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
e.getRenderer().bindTexture(TEXTURE_RUNE);
vertexbuffer.begin(7, DefaultVertexFormats.POSITION_TEX);
vertexbuffer.pos(3, 3, 0).tex(0, 0).endVertex();
vertexbuffer.pos(3, 0, 0).tex(0, 1).endVertex();
vertexbuffer.pos(0, 0, 0).tex(1, 1).endVertex();
vertexbuffer.pos(0, 3, 0).tex(1, 0).endVertex();
tessellator.draw();
GlStateManager.enableCull();
GlStateManager.disableBlend();
GlStateManager.popMatrix();
renderDraw(index, e, cap, card);
}
}
|
package org.cytoscape.welcome.internal.panel;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import org.cytoscape.io.util.RecentlyOpenedTracker;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.welcome.internal.WelcomeScreenDialog;
import org.cytoscape.work.swing.DialogTaskManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class OpenPanel extends AbstractWelcomeScreenChildPanel {
private static final long serialVersionUID = 591882944100485039L;
private static final Logger logger = LoggerFactory.getLogger(OpenPanel.class);
private static final String ICON_LOCATION = "/images/Icons/open_session.png";
private BufferedImage openIconImg;
private ImageIcon openIcon;
// Display up to 7 files due to space.
private static final int MAX_FILES = 7;
private JLabel open;
private final RecentlyOpenedTracker fileTracker;
private final DialogTaskManager taskManager;
private final OpenSessionTaskFactory openSessionTaskFactory;
public OpenPanel(final RecentlyOpenedTracker fileTracker, final DialogTaskManager taskManager,
final OpenSessionTaskFactory openSessionTaskFactory) {
this.fileTracker = fileTracker;
this.taskManager = taskManager;
this.openSessionTaskFactory = openSessionTaskFactory;
initComponents();
}
private void initComponents() {
try {
openIconImg = ImageIO.read(WelcomeScreenDialog.class.getClassLoader().getResource(ICON_LOCATION));
} catch (IOException e) {
e.printStackTrace();
}
openIcon = new ImageIcon(openIconImg);
final List<URL> recentFiles = fileTracker.getRecentlyOpenedURLs();
int fileCount = recentFiles.size();
if(fileCount>MAX_FILES)
fileCount = MAX_FILES;
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
final Border padLine = BorderFactory.createEmptyBorder(3, 5, 3, 0);
for (int i = 0; i<fileCount; i++) {
final URL target = recentFiles.get(i);
URI fileURI = null;
try {
fileURI = target.toURI();
} catch (URISyntaxException e2) {
logger.error("Invalid file URL.", e2);
continue;
}
final File targetFile = new File(fileURI);
final JLabel fileLabel = new JLabel(target.toString());
fileLabel.setMaximumSize(new Dimension(300, 18));
fileLabel.setForeground(REGULAR_FONT_COLOR);
fileLabel.setFont(LINK_FONT);
fileLabel.setBorder(padLine);
fileLabel.setHorizontalAlignment(SwingConstants.LEFT);
fileLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
fileLabel.setToolTipText(fileURI.toString());
fileLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
taskManager.execute(openSessionTaskFactory.createTaskIterator(targetFile));
closeParentWindow();
}
});
this.add(fileLabel);
}
open = new JLabel("Open other file...");
open.setFont(REGULAR_FONT);
open.setForeground(REGULAR_FONT_COLOR);
open.setIcon(openIcon);
open.setBorder(padLine);
open.setHorizontalAlignment(SwingConstants.LEFT);
open.setCursor(new Cursor(Cursor.HAND_CURSOR));
open.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
closeParentWindow();
taskManager.execute(openSessionTaskFactory.createTaskIterator());
}
});
this.add(open);
}
}
|
package tars.logic.commands;
/**
* Undo an undoable command.
*
* @@author A0139924W
*/
public class UndoCommand extends Command {
public static final String COMMAND_WORD = "undo";
public static final String MESSAGE_SUCCESS = "Undo successfully.";
public static final String MESSAGE_UNSUCCESS = "Undo unsuccessfully.";
public static final String MESSAGE_EMPTY_UNDO_CMD_HIST = "No more actions that can be undo.";
@Override
public CommandResult execute() {
assert model != null;
if (model.getUndoableCmdHist().size() == 0) {
return new CommandResult(MESSAGE_EMPTY_UNDO_CMD_HIST);
}
UndoableCommand command = (UndoableCommand) model.getUndoableCmdHist().pop();
model.getRedoableCmdHist().push(command);
return command.undo();
}
}
|
package net.ripe.db.whois.api.whois.rdap;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.ripe.db.whois.api.whois.rdap.domain.Autnum;
import net.ripe.db.whois.api.whois.rdap.domain.Domain;
import net.ripe.db.whois.api.whois.rdap.domain.Entity;
import net.ripe.db.whois.api.whois.rdap.domain.Event;
import net.ripe.db.whois.api.whois.rdap.domain.Ip;
import net.ripe.db.whois.api.whois.rdap.domain.Link;
import net.ripe.db.whois.api.whois.rdap.domain.Nameserver;
import net.ripe.db.whois.api.whois.rdap.domain.RdapObject;
import net.ripe.db.whois.api.whois.rdap.domain.Remark;
import net.ripe.db.whois.api.whois.rdap.domain.vcard.VCard;
import net.ripe.db.whois.common.domain.CIString;
import net.ripe.db.whois.common.domain.IpInterval;
import net.ripe.db.whois.common.domain.Ipv4Resource;
import net.ripe.db.whois.common.domain.Ipv6Resource;
import net.ripe.db.whois.common.domain.attrs.DsRdata;
import net.ripe.db.whois.common.domain.attrs.NServer;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Value;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static net.ripe.db.whois.common.rpsl.ObjectType.INET6NUM;
class RdapObjectMapper {
private static final List<String> RDAP_CONFORMANCE_LEVEL = Lists.newArrayList("rdap_level_0");
private static final Set<AttributeType> CONTACT_ATTRIBUTES = Sets.newHashSet(AttributeType.ADMIN_C, AttributeType.TECH_C);
private static final Map<AttributeType, String> CONTACT_ATTRIBUTE_TO_ROLE_NAME = Maps.newHashMap();
static {
CONTACT_ATTRIBUTE_TO_ROLE_NAME.put(AttributeType.ADMIN_C, "administrative");
CONTACT_ATTRIBUTE_TO_ROLE_NAME.put(AttributeType.TECH_C, "technical");
CONTACT_ATTRIBUTE_TO_ROLE_NAME.put(AttributeType.MNT_BY, "registrant");
}
public static Object map(
final String requestUrl,
final String baseUrl,
final RpslObject rpslObject,
final List<RpslObject> relatedObjects,
final LocalDateTime lastChangedTimestamp,
final List<RpslObject> abuseContacts,
@Value("${rdap.public.port43:}") final String port43) {
RdapObject rdapResponse;
final ObjectType rpslObjectType = rpslObject.getType();
switch (rpslObjectType) {
case DOMAIN:
rdapResponse = createDomain(rpslObject, relatedObjects, requestUrl, baseUrl);
break;
case AUT_NUM:
rdapResponse = createAutnumResponse(rpslObject, relatedObjects, requestUrl, baseUrl);
break;
case INETNUM:
case INET6NUM:
rdapResponse = createIp(rpslObject);
break;
case PERSON:
case ROLE:
// TODO: [RL] Configuration (property?) for allowed RPSL object types for entity lookups
// TODO: [ES] Denis to review
case ORGANISATION:
case IRT:
rdapResponse = createEntity(rpslObject, relatedObjects, requestUrl, baseUrl);
break;
default:
throw new IllegalArgumentException("Unhandled object type: " + rpslObject.getType());
}
rdapResponse.getRdapConformance().addAll(RDAP_CONFORMANCE_LEVEL);
rdapResponse.getLinks().add(new Link().setRel("self").setValue(requestUrl).setHref(requestUrl));
rdapResponse.setPort43(port43);
rdapResponse.getNotices().addAll(NoticeFactory.generateNotices(rpslObject, requestUrl));
List<Remark> remarks = createRemarks(rpslObject);
if (!remarks.isEmpty()) {
rdapResponse.getRemarks().addAll(remarks);
}
Event lastChangedEvent = createEvent(lastChangedTimestamp);
if (lastChangedEvent != null) {
rdapResponse.getEvents().add(lastChangedEvent);
}
for (final RpslObject abuseContact : abuseContacts) {
rdapResponse.getEntities().add(createEntity(abuseContact, Lists.<RpslObject>newArrayList(), requestUrl, baseUrl));
}
rdapResponse.getEntities().addAll(contactEntities(rpslObject, relatedObjects, requestUrl, baseUrl));
return rdapResponse;
}
private static Ip createIp(final RpslObject rpslObject) {
final Ip ip = new Ip();
ip.setHandle(rpslObject.getKey().toString());
IpInterval ipInterval;
if (rpslObject.getType() == INET6NUM) {
ipInterval = Ipv6Resource.parse(rpslObject.getKey());
ip.setIpVersion("v6");
} else {
ipInterval = Ipv4Resource.parse(rpslObject.getKey());
ip.setIpVersion("v4");
}
// TODO: find a better way to remove the cidr notation
String startAddr = IpInterval.asIpInterval(ipInterval.beginAsInetAddress()).toString();
String endAddr = IpInterval.asIpInterval(ipInterval.endAsInetAddress()).toString();
ip.setStartAddress(startAddr.split("/")[0]);
ip.setEndAddress(endAddr.split("/")[0]);
ip.setName(rpslObject.getValueForAttribute(AttributeType.NETNAME).toString());
ip.setCountry(rpslObject.getValueForAttribute(AttributeType.COUNTRY).toString());
ip.setLang(Joiner.on(",").join(rpslObject.getValuesForAttribute(AttributeType.LANGUAGE)));
ip.setType(rpslObject.getValueForAttribute(AttributeType.STATUS).toString());
// ip.getLinks().add(new Link().setRel("up")... //TODO parent (first less specific) - do parentHandle at the same time
return ip;
}
private static List<Remark> createRemarks(final RpslObject rpslObject) {
final List<Remark> remarkList = Lists.newArrayList();
final List<String> descriptions = Lists.newArrayList();
for (final CIString description : rpslObject.getValuesForAttribute(AttributeType.DESCR)) {
descriptions.add(description.toString());
}
if (!descriptions.isEmpty()) {
remarkList.add(new Remark(descriptions));
}
final List<String> remarks = Lists.newArrayList();
for (final CIString description : rpslObject.getValuesForAttribute(AttributeType.REMARKS)) {
remarks.add(description.toString());
}
if (!remarks.isEmpty()) {
remarkList.add(new Remark(remarks));
}
return remarkList;
}
private static Event createEvent(final LocalDateTime lastChanged) {
final Event lastChangedEvent = new Event();
lastChangedEvent.setEventAction("last changed");
lastChangedEvent.setEventDate(lastChanged);
return lastChangedEvent;
}
private static List<Entity> contactEntities(final RpslObject rpslObject, List<RpslObject> relatedObjects, final String requestUrl, final String baseUrl) {
final List<Entity> entities = Lists.newArrayList();
final Map<String, Set<AttributeType>> contacts = Maps.newHashMap();
final Map<String, RpslObject> relatedObjectMap = Maps.newHashMap();
for (final RpslObject object : relatedObjects) {
relatedObjectMap.put(object.getKey().toString(), object);
}
for (final RpslAttribute attribute : rpslObject.findAttributes(CONTACT_ATTRIBUTES)) {
final String contactName = attribute.getCleanValue().toString();
if (contacts.containsKey(contactName)) {
contacts.get(contactName).add(attribute.getType());
} else {
final Set<AttributeType> attributeTypes = Sets.newHashSet();
attributeTypes.add(attribute.getType());
contacts.put(contactName, attributeTypes);
}
}
for (Map.Entry<String, Set<AttributeType>> entry : contacts.entrySet()) {
Entity entity;
final RpslObject object = relatedObjectMap.get(entry.getKey());
if (object != null) {
entity = createEntity(object, Lists.<RpslObject>newArrayList(), requestUrl, baseUrl);
} else {
entity = new Entity();
entity.setHandle(entry.getKey());
}
for (AttributeType attributeType : entry.getValue()) {
entity.getRoles().add(CONTACT_ATTRIBUTE_TO_ROLE_NAME.get(attributeType));
}
entities.add(entity);
}
return entities;
}
private static Entity createEntity(final RpslObject rpslObject, List<RpslObject> relatedObjects, final String requestUrl, final String baseUrl) {
final Entity entity = new Entity();
entity.setHandle(rpslObject.getKey().toString());
entity.setVCardArray(createVCard(rpslObject));
final String selfUrl = baseUrl + "/entity/" + entity.getHandle();
if (!selfUrl.equals(requestUrl)) {
List<Remark> remarks = createRemarks(rpslObject);
if (!remarks.isEmpty()) {
entity.getRemarks().addAll(remarks);
}
entity.getLinks().add(new Link()
.setRel("self")
.setValue(requestUrl)
.setHref(baseUrl + "/entity/" + entity.getHandle()));
List<Entity> contactEntities = contactEntities(rpslObject, relatedObjects, requestUrl, baseUrl);
if (!contactEntities.isEmpty()) {
entity.getEntities().addAll(contactEntities);
}
// TODO: [RL] Add abuse contact here?
}
return entity;
}
private static Autnum createAutnumResponse(final RpslObject rpslObject, List<RpslObject> relatedObjects, final String requestUrl, final String baseUrl) {
final Autnum autnum = new Autnum();
autnum.setHandle(rpslObject.getKey().toString());
final CIString autnumAttributeValue = rpslObject.getValueForAttribute(AttributeType.AUT_NUM);
final long startAndEnd = Long.valueOf(autnumAttributeValue.toString().replace("AS", "").replace(" ", ""));
autnum.setStartAutnum(startAndEnd);
autnum.setEndAutnum(startAndEnd);
if (rpslObject.containsAttribute(AttributeType.COUNTRY)) {
// TODO: no country attribute in autnum? remove?
autnum.setCountry(rpslObject.findAttribute(AttributeType.COUNTRY).getValue().replace(" ", ""));
}
autnum.setName(rpslObject.getValueForAttribute(AttributeType.AS_NAME).toString().replace(" ", ""));
autnum.setType("DIRECT ALLOCATION");
return autnum;
}
private static Domain createDomain(final RpslObject rpslObject, List<RpslObject> relatedObjects, final String requestUrl, final String baseUrl) {
Domain domain = new Domain();
domain.setHandle(rpslObject.getKey().toString());
domain.setLdhName(rpslObject.getKey().toString());
final HashMap<CIString, Set<IpInterval>> hostnameMap = new HashMap<>();
for (final RpslAttribute rpslAttribute : rpslObject.findAttributes(AttributeType.NSERVER)) {
final NServer nserver = NServer.parse(rpslAttribute.getCleanValue().toString());
final CIString hostname = nserver.getHostname();
final Set<IpInterval> ipIntervalSet;
if (hostnameMap.containsKey(hostname)) {
ipIntervalSet = hostnameMap.get(hostname);
} else {
ipIntervalSet = Sets.newHashSet();
hostnameMap.put(hostname, ipIntervalSet);
}
final IpInterval ipInterval = nserver.getIpInterval();
if (ipInterval != null) {
ipIntervalSet.add(ipInterval);
}
}
for (final CIString hostname : hostnameMap.keySet()) {
final Nameserver nameserver = new Nameserver();
nameserver.setLdhName(hostname.toString());
final Set<IpInterval> ipIntervals = hostnameMap.get(hostname);
if (!ipIntervals.isEmpty()) {
final Nameserver.IpAddresses ipAddresses = new Nameserver.IpAddresses();
for (IpInterval ipInterval : ipIntervals) {
if (ipInterval instanceof Ipv4Resource) {
ipAddresses.getIpv4().add(IpInterval.asIpInterval(ipInterval.beginAsInetAddress()).toString());
} else if (ipInterval instanceof Ipv6Resource) {
ipAddresses.getIpv6().add(IpInterval.asIpInterval(ipInterval.beginAsInetAddress()).toString());
}
}
nameserver.setIpAddresses(ipAddresses);
}
domain.getNameservers().add(nameserver);
}
final Domain.SecureDNS secureDNS = new Domain.SecureDNS();
secureDNS.setDelegationSigned(false);
for (final CIString rdata : rpslObject.getValuesForAttribute(AttributeType.DS_RDATA)) {
final DsRdata dsRdata = DsRdata.parse(rdata);
secureDNS.setDelegationSigned(true);
final Domain.SecureDNS.DsData dsData = new Domain.SecureDNS.DsData();
dsData.setKeyTag(dsRdata.getKeytag());
dsData.setAlgorithm(dsRdata.getAlgorithm());
dsData.setDigestType(dsRdata.getDigestType());
dsData.setDigest(dsRdata.getDigestHexString());
secureDNS.getDsData().add(dsData);
}
if (secureDNS.isDelegationSigned()) {
domain.setSecureDNS(secureDNS);
}
return domain;
}
private static VCard createVCard(final RpslObject rpslObject) {
final VCardBuilder builder = new VCardBuilder();
builder.addVersion();
switch (rpslObject.getType()) {
case PERSON:
for (final RpslAttribute attribute : rpslObject.findAttributes(AttributeType.PERSON)) {
builder.addFn(attribute.getCleanValue().toString());
}
builder.addKind("individual");
break;
case ORGANISATION:
for (final RpslAttribute attribute : rpslObject.findAttributes(AttributeType.ORG_NAME)) {
builder.addFn(attribute.getCleanValue().toString());
}
builder.addKind("org");
break;
case ROLE:
for (final RpslAttribute attribute : rpslObject.findAttributes(AttributeType.ROLE)) {
builder.addFn(attribute.getCleanValue().toString());
}
builder.addKind("group");
break;
case IRT:
for (final RpslAttribute attribute : rpslObject.findAttributes(AttributeType.IRT)) {
builder.addFn(attribute.getCleanValue().toString());
}
builder.addKind("group");
break;
default:
break;
}
List<CIString> addrList = new ArrayList<CIString>();
for (final CIString address : rpslObject.getValuesForAttribute(AttributeType.ADDRESS)) {
addrList.add(address);
}
if (!addrList.isEmpty()) {
builder.addAdr(VCardHelper.createMap(Maps.immutableEntry("type", "work")), addrList);
}
for (final CIString phone : rpslObject.getValuesForAttribute(AttributeType.PHONE)) {
builder.addTel(VCardHelper.createMap(Maps.immutableEntry("type", Lists.newArrayList("work", "voice"))),phone.toString());
}
for (final CIString fax : rpslObject.getValuesForAttribute(AttributeType.FAX_NO)) {
builder.addTel(VCardHelper.createMap(Maps.immutableEntry("type", "work")),fax.toString());
}
for (final CIString email : rpslObject.getValuesForAttribute(AttributeType.E_MAIL)) {
// TODO ?? Is it valid to have more than 1 email
builder.addEmail(VCardHelper.createMap(Maps.immutableEntry("type", "work")),email.toString());
}
for (final CIString org : rpslObject.getValuesForAttribute(AttributeType.ORG)) {
builder.addOrg(org.toString());
}
for (final CIString geoloc : rpslObject.getValuesForAttribute(AttributeType.GEOLOC)) {
builder.addGeo(VCardHelper.createMap(Maps.immutableEntry("type", "work")), geoloc.toString());
}
return builder.build();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.data;
/**
*
* @author Sergio Flores
*/
public abstract class SDataConstants {
public static final int UNDEFINED = 0;
public static final int MOD_CFG = 101000;
public static final int MOD_FIN = 102000;
public static final int MOD_PUR = 103000;
public static final int MOD_SAL = 104000;
public static final int MOD_INV = 105000;
public static final int MOD_MKT = 106000;
public static final int MOD_LOG = 107000;
public static final int MOD_MFG = 108000;
public static final int MOD_HRS = 109000;
public static final int MOD_XXX = 109999;
public static final int GLOBAL_CAT_CFG = 201000;
public static final int GLOBAL_CAT_USR = 202000;
public static final int GLOBAL_CAT_LOC = 203000;
public static final int GLOBAL_CAT_BPS = 204000;
public static final int GLOBAL_CAT_ITM = 205000;
public static final int GLOBAL_CAT_FIN = 206000;
public static final int GLOBAL_CAT_TRN = 207000;
public static final int GLOBAL_CAT_MKT = 208000;
public static final int GLOBAL_CAT_LOG = 209000;
public static final int GLOBAL_CAT_MFG = 210000;
public static final int GLOBAL_CAT_HRS = 211000;
public static final int GLOBAL_CAT_XXX = 211999;
public static final int CFGS_CT_ENT = 201001;
public static final int CFGS_TP_ENT = 201002;
public static final int CFGS_TP_SORT = 201003;
public static final int CFGS_TP_BAL = 201004;
public static final int CFGS_TP_REL = 201005;
public static final int CFGS_TP_FMT_D = 201006;
public static final int CFGS_TP_FMT_DT = 201007;
public static final int CFGS_TP_FMT_T = 201008;
public static final int CFGS_TP_DBMS = 201009;
public static final int CFGS_TP_MOD = 201010;
public static final int CFGU_CUR = 201011;
public static final int CFGU_CO = 201012;
public static final int CFGU_COB_ENT = 201013;
public static final int CFGU_LAN = 201014;
public static final int CFGU_PARAM_ERP = 201015;
public static final int CFGU_PARAM_CO = 201016;
public static final int CFGU_CERT = 201017;
public static final int CFGX_COB_ENT_CASH = 201501;
public static final int CFGX_COB_ENT_WH = 201502;
public static final int CFGX_COB_ENT_POS = 201503;
public static final int CFGX_COB_ENT_PLANT = 201504;
public static final int CFGX_CT_ENT_CFG = 201505;
public static final int USRS_TP_LEV = 202001;
public static final int USRS_TP_PRV = 202002;
public static final int USRS_TP_ROL = 202003;
public static final int USRS_PRV = 202004;
public static final int USRS_ROL = 202005;
public static final int USRS_ROL_PRV = 202006;
public static final int USRU_ACCESS_CO = 202007;
public static final int USRU_ACCESS_COB = 202008;
public static final int USRU_ACCESS_COB_ENT = 202009;
public static final int USRU_ACCESS_COB_ENT_UNIV = 202010;
public static final int USRU_PRV_USR = 202011;
public static final int USRU_PRV_CO = 202012;
public static final int USRU_PRV_COB = 202013;
public static final int USRU_ROL_USR = 202014;
public static final int USRU_ROL_CO = 202015;
public static final int USRU_ROL_COB = 202016;
public static final int USRU_PREF = 202017;
public static final int USRU_USR = 202018;
public static final int USRX_RIGHT = 202501;
public static final int USRX_RIGHT_PRV = 202502;
public static final int USRX_RIGHT_ROL = 202503;
public static final int USRX_TP_ROL_ALL = 202504;
public static final int LOCU_CTY = 203001;
public static final int BPSS_CT_BP = 204001;
public static final int BPSS_TP_BP_IDY = 204002;
public static final int BPSS_TP_BP_ATT = 204003;
public static final int BPSS_TP_BPB = 204004;
public static final int BPSS_TP_ADD = 204005;
public static final int BPSS_TP_ADD_FMT = 204006;
public static final int BPSS_TP_CON = 204007;
public static final int BPSS_TP_TEL = 204008;
public static final int BPSS_TP_CRED = 204009;
public static final int BPSS_TP_CFD_ADD = 204010;
public static final int BPSS_TP_RISK = 204011;
public static final int BPSU_BP = 204012;
public static final int BPSU_BP_CT = 204013;
public static final int BPSU_BP_ATT = 204014;
public static final int BPSU_BP_BA = 204015;
public static final int BPSU_BP_NTS = 204016;
public static final int BPSU_BPB = 204017;
public static final int BPSU_BPB_NTS = 204018;
public static final int BPSU_BPB_ADD = 204019;
public static final int BPSU_BPB_ADD_NTS = 204020;
public static final int BPSU_BPB_CON = 204021;
public static final int BPSU_BANK_ACC = 204022;
public static final int BPSU_BANK_ACC_CARD = 204023;
public static final int BPSU_BANK_ACC_NTS = 204024;
public static final int BPSU_BANK_ACC_LAY_BANK = 204025;
public static final int BPSU_TP_BP = 204026;
public static final int BPSU_BA = 204027;
public static final int BPSS_LINK = 204028;
public static final int BPSX_TP_BP_CO = 204501;
public static final int BPSX_TP_BP_SUP = 204502;
public static final int BPSX_TP_BP_CUS = 204503;
public static final int BPSX_TP_BP_CDR = 204504;
public static final int BPSX_TP_BP_DBR = 204505;
public static final int BPSX_TP_BP_EMP = 204506;
public static final int BPSX_BP_CO = 204507;
public static final int BPSX_BP_SUP = 204508;
public static final int BPSX_BP_CUS = 204509;
public static final int BPSX_BP_CDR = 204510;
public static final int BPSX_BP_DBR = 204511;
public static final int BPSX_BP_EMP = 204512;
public static final int BPSX_BP_X_SUP_CUS = 204514;
public static final int BPSX_BP_X_CDR_DBR = 204515;
public static final int BPSX_BP_CT = 204518;
public static final int BPSX_BPB_CON_SUP = 204521;
public static final int BPSX_BPB_CON_CUS = 204522;
public static final int BPSX_BPB_CON_CDR = 204523;
public static final int BPSX_BPB_CON_DBR = 204524;
public static final int BPSX_BPB_CON_EMP = 204525;
public static final int BPSX_BPB_EMP = 204526;
public static final int BPSX_BP_ITEM_DESC = 204527;
public static final int BPSX_BPB_SUP = 204528;
public static final int BPSX_BPB_CUS = 204529;
public static final int BPSX_BPB_CDR = 204530;
public static final int BPSX_BPB_DBR = 204531;
public static final int BPSX_BANK_ACC_SUP = 204532;
public static final int BPSX_BANK_ACC_CUS = 204533;
public static final int BPSX_BANK_ACC_CDR = 204534;
public static final int BPSX_BANK_ACC_DBR = 204535;
public static final int BPSX_BANK_ACC_EMP = 204536;
public static final int BPSX_BPB_ADD_SUP = 204537;
public static final int BPSX_BPB_ADD_CUS = 204538;
public static final int BPSX_BPB_ADD_CDR = 204539;
public static final int BPSX_BPB_ADD_DBR = 204540;
public static final int BPSX_BPB_ADD_EMP = 204541;
public static final int BPSX_BANK_ACC_CHECK = 204544;
public static final int BPSX_BANK_ACC = 204545;
public static final int BPSX_BP_ATT_BANK = 204551;
public static final int BPSX_BP_ATT_CARR = 204552;
public static final int BPSX_BP_ATT_EMP = 204553;
public static final int BPSX_BP_ATT_EMP_MFG = 204517;
public static final int BPSX_BP_ATT_SAL_AGT = 204555;
public static final int ITMS_CT_ITEM = 205001;
public static final int ITMS_CL_ITEM = 205002;
public static final int ITMS_TP_ITEM = 205003;
public static final int ITMS_TP_SNR = 205004;
public static final int ITMU_IFAM = 205005;
public static final int ITMU_IGRP = 205006;
public static final int ITMU_IGEN = 205007;
public static final int ITMU_IGEN_BA = 205008;
public static final int ITMU_LINE = 205009;
public static final int ITMU_ITEM = 205010;
public static final int ITMU_ITEM_BARC = 205011;
public static final int ITMU_CFG_ITEM_LAN = 205012;
public static final int ITMU_CFG_ITEM_BP = 205013;
public static final int ITMU_TP_UNIT = 205014;
public static final int ITMU_TP_LEV = 205015;
public static final int ITMU_UNIT = 205016;
public static final int ITMU_TP_VAR = 205017;
public static final int ITMU_VAR = 205018;
public static final int ITMU_BRD = 205019;
public static final int ITMU_MFR = 205020;
public static final int ITMU_EMT = 205021;
public static final int ITMU_TP_BRD = 205022;
public static final int ITMU_TP_EMT = 205023;
public static final int ITMU_TP_MFR = 205024;
public static final int ITMS_TP_LOT_REQ = 205025;
public static final int ITMX_ITEM_BY_KEY = 205501;
public static final int ITMX_ITEM_BY_NAME = 205502;
public static final int ITMX_ITEM_BY_BRAND = 205503;
public static final int ITMX_ITEM_BY_MANUFACTURER = 205504;
public static final int ITMX_ITEM_PACK = 205507;
public static final int ITMX_ITEM_IOG = 205508;
public static final int ITMX_IGEN_LINE = 205509;
public static final int ITMX_ITEM_BOM_ITEM = 205510;
public static final int ITMX_ITEM_BOM_LEVEL = 205511;
public static final int ITMX_ITEM_SIMPLE = 205512;
public static final int ITMX_ITEM_IDX_SAL_PRO = 205521;
public static final int ITMX_ITEM_IDX_SAL_SRV = 205522;
public static final int ITMX_ITEM_IDX_ASS_ASS = 205523;
public static final int ITMX_ITEM_IDX_PUR_CON = 205524;
public static final int ITMX_ITEM_IDX_PUR_EXP = 205525;
public static final int ITMX_ITEM_IDX_EXP_MFG = 205526;
public static final int ITMX_ITEM_IDX_EXP_OPE = 205527;
public static final int FINS_TP_TAX = 206001;
public static final int FINS_TP_TAX_CAL = 206002;
public static final int FINS_TP_TAX_APP = 206003;
public static final int FINS_TP_BKR = 206004;
public static final int FINS_TP_ACC_MOV = 206005;
public static final int FINS_CL_ACC_MOV = 206006;
public static final int FINS_CLS_ACC_MOV = 206007;
public static final int FINS_TP_ACC = 206008;
public static final int FINS_CL_ACC = 206009;
public static final int FINS_CLS_ACC = 206010;
public static final int FINS_TP_ACC_SPE= 206011;
public static final int FINS_TP_ACC_SYS = 206012;
public static final int FINS_CT_SYS_MOV = 206013;
public static final int FINS_TP_SYS_MOV = 206014;
public static final int FINS_CT_ACC_CASH = 206015;
public static final int FINS_TP_ACC_CASH = 206016;
public static final int FINS_TP_ACC_BP = 206017;
public static final int FINS_TP_ACC_ITEM = 206018;
public static final int FINS_TP_CARD = 206019;
public static final int FINS_TP_PAY_BANK = 206020;
public static final int FINS_ST_FIN_MOV = 206021;
public static final int FINU_TAX_REG = 206022;
public static final int FINU_TAX_IDY = 206023;
public static final int FINU_TAX_BAS = 206024;
public static final int FINU_TAX = 206025;
public static final int FINU_CARD_ISS = 206026;
public static final int FINU_CHECK_FMT = 206027;
public static final int FINU_CHECK_FMT_GP = 206028;
public static final int FINU_TP_REC = 206029;
public static final int FINU_TP_ACC_USR = 206030;
public static final int FINU_CL_ACC_USR = 206031;
public static final int FINU_CLS_ACC_USR = 206032;
public static final int FINU_TP_ACC_LEDGER = 206033;
public static final int FINU_TP_ACC_EBITDA = 206034;
public static final int FINU_TP_ASSET_FIX = 206035;
public static final int FINU_TP_ASSET_DIF = 206036;
public static final int FINU_TP_LIABTY_DIF = 206037;
public static final int FINU_TP_EXPEN_OP = 206038;
public static final int FINU_TP_ADM_CPT = 206039;
public static final int FINU_TP_TAX_CPT = 206040;
public static final int FINU_TP_LAY_BANK = 206041;
public static final int FINU_COST_GIC = 206042;
public static final int FIN_YEAR = 206043;
public static final int FIN_YEAR_PER = 206044;
public static final int FIN_EXC_RATE = 206045;
public static final int FIN_ACC = 206046;
public static final int FIN_CC = 206047;
public static final int FIN_ACC_CASH = 206048;
public static final int FIN_CHECK_WAL = 206049;
public static final int FIN_CHECK = 206050;
public static final int FIN_TAX_GRP = 206051;
public static final int FIN_TAX_GRP_ETY = 206052;
public static final int FIN_TAX_GRP_IGEN = 206053;
public static final int FIN_TAX_GRP_ITEM = 206054;
public static final int FIN_BKK_NUM = 206055;
public static final int FIN_REC = 206056;
public static final int FIN_REC_ETY = 206057;
public static final int FIN_ACC_BP = 206058;
public static final int FIN_ACC_BP_ETY = 206059;
public static final int FIN_ACC_BP_TP_BP = 206060;
public static final int FIN_ACC_BP_BP = 206061;
public static final int FIN_ACC_ITEM = 206062;
public static final int FIN_ACC_ITEM_ETY = 206063;
public static final int FIN_ACC_ITEM_ITEM = 206064;
public static final int FIN_ACC_TAX = 206065;
public static final int FIN_ACC_COB_ENT = 206066;
public static final int FIN_CC_ITEM = 206067;
public static final int FIN_COB_BKC = 206068;
public static final int FIN_BKC = 206069;
public static final int FINS_FISCAL_ACC = 206071;
public static final int FINS_FISCAL_CUR = 206072;
public static final int FINS_FISCAL_BANK = 206073;
public static final int FINS_FISCAL_PAY_MET = 206074;
public static final int FIN_LAY_BANK = 206075;
public static final int FINX_REC_CASH = 206101;
public static final int FINX_MOVES_ACC = 206501;
public static final int FINX_ACC_MAJOR = 206502;
public static final int FINX_CC_MAJOR = 206503;
public static final int FINX_REC_HEADER = 206504;
public static final int FINX_TP_REC_ALL = 206505;
public static final int FINX_TP_REC_USER = 206506;
public static final int FINX_TP_ACC_CASH = 206507;
public static final int FINX_TP_ACC_CASH_BANK = 206508;
public static final int FINX_ACC_CASH_CASH = 206509;
public static final int FINX_ACC_CASH_BANK = 206510;
public static final int FINX_ACC_CASH_BANK_CHECK = 206511;
public static final int FINX_TAX_GRP_ALL_ITEM = 206512;
public static final int FINX_TAX_GRP_ALL_IGEN = 206513;
public static final int FINX_TAX_BAS_TAX = 206514;
public static final int FINX_ACCOUNTING = 206515;
public static final int FINX_ACC_BP_QRY = 206516;
public static final int FINX_ACC_ITEM_QRY = 206517;
public static final int FINX_REC_USER = 206518;
public static final int FINX_REC_RO = 206519;
public static final int FINX_REC_DPS = 206520;
public static final int TRNS_CT_DPS = 207001;
public static final int TRNS_CL_DPS = 207002;
public static final int TRNS_TP_DPS_ADJ = 207003;
public static final int TRNS_STP_DPS_ADJ = 207004;
public static final int TRNS_CT_IOG = 207005;
public static final int TRNS_CL_IOG = 207006;
public static final int TRNS_TP_IOG = 207007;
public static final int TRNS_TP_PAY = 207011;
public static final int TRNS_TP_PAY_WAY = 207012;
public static final int TRNS_TP_LINK = 207013;
public static final int TRNS_TP_DPS_EVT = 207014;
public static final int TRNS_TP_DPS_PRT = 207015;
public static final int TRNS_TP_DPS_ETY = 207016;
public static final int TRNS_ST_DPS = 207017;
public static final int TRNS_ST_DPS_VAL = 207018;
public static final int TRNS_ST_DPS_AUTHORN = 207019;
public static final int TRNS_CT_SIGN = 207020;
public static final int TRNS_TP_SIGN = 207021;
public static final int TRNS_TP_XML = 207022;
//public static final int TRNS_ST_XML = 207023; XXX (obsolete from 2014-02-26, sflores)
public static final int TRNU_DPS_NAT = 207024;
public static final int TRNU_TP_DPS = 207025;
public static final int TRNU_TP_PAY_SYS = 207026;
public static final int TRNU_TP_IOG_ADJ = 207027;
public static final int TRN_DNS_DPS = 207028;
public static final int TRN_DNS_DIOG = 207029;
public static final int TRN_DNC_DPS_COB = 207031;
public static final int TRN_DNC_DPS_COB_ENT = 207032;
public static final int TRN_DNC_DIOG_COB = 207033;
public static final int TRN_DNC_DIOG_COB_ENT = 207034;
public static final int TRN_BP_BLOCK = 207037;
public static final int TRN_SUP_LT_CO = 207038;
public static final int TRN_SUP_LT_COB = 207039;
public static final int TRN_SYS_NTS = 207040;
public static final int TRN_DPS = 207041;
public static final int TRN_DPS_SND_LOG = 207042;
public static final int TRN_DPS_ADD = 207043;
public static final int TRN_DPS_ADD_ETY = 207044;
public static final int TRN_DPS_EVT = 207046;
public static final int TRN_DPS_NTS = 207047;
public static final int TRN_DPS_ETY = 207048;
public static final int TRN_DPS_ETY_NTS = 207049;
public static final int TRN_DPS_ETY_PRC = 207063; // out of place, because of number! (sflores, 2015-03-18)
public static final int TRN_DPS_ETY_TAX = 207050;
public static final int TRN_DPS_ETY_COMMS = 207051;
public static final int TRN_DPS_RISS = 207052;
public static final int TRN_DPS_REPL = 207053;
public static final int TRN_DPS_DPS_SUPPLY = 207054;
public static final int TRN_DPS_DPS_ADJ = 207055;
public static final int TRN_DPS_IOG_CHG = 207056;
public static final int TRN_DPS_IOG_WAR = 207057;
public static final int TRN_DPS_REC = 207058;
public static final int TRN_DIOG = 207059;
public static final int TRN_DIOG_NTS = 207060;
public static final int TRN_DIOG_ETY = 207061;
public static final int TRN_DIOG_REC = 207062;
public static final int TRN_CTR = 207070;
public static final int TRN_CTR_ETY = 207071;
public static final int TRN_DSM = 207072;
public static final int TRN_DSM_NTS = 207073;
public static final int TRN_DSM_ETY = 207074;
public static final int TRN_DSM_ETY_NTS = 207075;
public static final int TRN_DSM_REC = 207076;
public static final int TRN_USR_CFG = 207077; // XXX Review if is still needed
public static final int TRN_USR_CFG_IFAM = 207078; // XXX Review if is still needed
public static final int TRN_USR_CFG_BA = 207079; // XXX Review if is still needed
public static final int TRN_LOT = 207080;
public static final int TRN_STK_CFG = 207081;
public static final int TRN_STK_CFG_ITEM = 207082;
public static final int TRN_STK_CFG_DNS = 207083;
public static final int TRN_STK = 207084;
public static final int TRN_SIGN = 207085;
public static final int TRN_DNC_DPS = 207086;
public static final int TRN_DNC_DPS_DNS = 207087;
public static final int TRN_DNC_DIOG = 207088;
public static final int TRN_DNC_DIOG_DNS = 207089;
public static final int TRNS_TP_XML_DVY = 207090; // out of place! (sflores, 2014-01-06)
public static final int TRNS_ST_XML_DVY = 207091; // out of place! (sflores, 2014-01-06)
public static final int TRNS_TP_CFD = 207092; // out of place! (sflores, 2014-01-28)
public static final int TRN_STK_VAL = 207093; // out of place! (sflores, 2014-01-28)
public static final int TRN_DPS_XML_DVY = 207094; // XXX eliminate! (sflores, 2014-01-28)
public static final int TRN_CFD = 207095; // out of place! (sflores, 2014-01-28)
public static final int TRN_CFD_SND_LOG = 207096; // out of place! (sflores, 2014-05-12)
public static final int TRN_PAC = 207097; // out of place! (sflores, 2014-02-17)
public static final int TRN_TP_CFD_PAC = 207098; // out of place! (sflores, 2014-02-17)
public static final int TRN_MMS_LOG = 207099; // out of place! (sflores, 2014-01-28)
public static final int TRN_CFD_SIGN_LOG = 207100; // out of place! (sflores, 2014-09-01)
public static final int TRNX_DPS_RO = 207505;
public static final int TRNX_DPS_QRY = 207506;
public static final int TRNX_DPS_BAL = 207511;
public static final int TRNX_DPS_FILL = 207512;
public static final int TRNX_DPS_PEND_LINK = 207513;
public static final int TRNX_DPS_PEND_ADJ = 207514;
public static final int TRNX_DPS_BACKORDER = 207516;
public static final int TRNX_DPS_BAL_AGING = 207519;
public static final int TRNX_PRICE_HIST = 207520;
public static final int TRNX_DPS_COMMS_PEND = 207521;
public static final int TRNX_STAMP_AVL = 207522;
public static final int TRNX_STAMP_MOV = 207523;
public static final int TRNX_STAMP_SIGN = 207524;
public static final int TRNX_STAMP_SIGN_PEND = 207525;
public static final int TRNX_DPS_PAY_PEND = 207525;
public static final int TRNX_DPS_PAYED = 207526;
public static final int TRNX_DPS_PAYS = 207527;
public static final int TRNX_DPS_SHIP_PEND_LINK = 207528;
public static final int TRNX_DPS_LINK_PEND = 207531;
public static final int TRNX_DPS_LINK_PEND_ETY = 207532;
public static final int TRNX_DPS_LINKED = 207533;
public static final int TRNX_DPS_LINKED_ETY = 207534;
public static final int TRNX_DPS_LINKS = 207536;
public static final int TRNX_DPS_LINKS_TRACE = 207537;
public static final int TRNX_DPS_SUPPLY_PEND = 207541;
public static final int TRNX_DPS_SUPPLY_PEND_ETY = 207542;
public static final int TRNX_DPS_SUPPLIED = 207543;
public static final int TRNX_DPS_SUPPLIED_ETY = 207544;
public static final int TRNX_DPS_RETURN_PEND = 207551;
public static final int TRNX_DPS_RETURN_PEND_ETY = 207552;
public static final int TRNX_DPS_RETURNED = 207553;
public static final int TRNX_DPS_RETURNED_ETY = 207554;
public static final int TRNX_DPS_AUTHORIZE_PEND = 207561;
public static final int TRNX_DPS_AUTHORIZED = 207562;
public static final int TRNX_DPS_AUDIT_PEND = 207571;
public static final int TRNX_DPS_AUDITED = 207572;
public static final int TRNX_DPS_SEND_PEND = 207573;
public static final int TRNX_DPS_SENT = 207574;
public static final int TRNX_STK_STK = 207581;
public static final int TRNX_STK_STK_WH = 207582;
public static final int TRNX_STK_LOT = 207583;
public static final int TRNX_STK_LOT_WH = 207584;
public static final int TRNX_STK_MOVES = 207585;
public static final int TRNX_STK_MOVES_ETY = 207586;
public static final int TRNX_STK_ROTATION = 207587;
public static final int TRNX_STK_COMSUME = 207588;
public static final int TRNX_DIOG_MFG = 207589;
public static final int TRNX_DIOG_MFG_RM = 207590;
public static final int TRNX_DIOG_MFG_WP = 207591;
public static final int TRNX_DIOG_MFG_FG = 207592;
public static final int TRNX_DIOG_MFG_CON = 207593;
public static final int TRNX_DIOG_MFG_MOVE_IN = 207594;
public static final int TRNX_DIOG_MFG_MOVE_OUT = 207595;
public static final int TRNX_DIOG_MFG_MOVE_ASG = 207596;
public static final int TRNX_DIOG_MFG_MOVE_RET = 207597;
public static final int TRNX_DIOG_AUDIT_PEND = 207599;
public static final int TRNX_DIOG_AUDITED = 207600;
// XXX
public static final int TRNX_DSM_ETY_SOURCE = 207601;
public static final int TRNX_DSM_ETY_DESTINY = 207602;
public static final int TRNX_DPS_SRC = 207603;
public static final int TRNX_DPS_DES = 207604;
public static final int TRNX_DPS_ADJ = 207605;
public static final int TRNX_TP_DPS = 207606;
public static final int TRNX_SAL_PUR_TOT = 207607;
public static final int TRNX_SAL_PUR_GLB = 207608;
public static final int TRNX_DPS_ACT_ANNUL = 207611;
public static final int TRNX_DPS_ACT_RISS = 207612;
public static final int TRNX_DPS_ACT_REPL = 207613;
public static final int TRNX_DPS_ACT_VIEW_LINKS = 207614;
// XXX
public static final int TRNX_MFG_ORD = 207620;
public static final int TRNX_MFG_ORD_ASSIGN_PEND = 207621;
public static final int TRNX_MFG_ORD_ASSIGN_PEND_ETY = 207622;
public static final int TRNX_MFG_ORD_ASSIGNED = 207623;
public static final int TRNX_MFG_ORD_ASSIGNED_ETY = 207624;
public static final int TRNX_MFG_ORD_CONSUME_PEND = 207626;
public static final int TRNX_MFG_ORD_CONSUME_PEND_ETY = 207627;
public static final int TRNX_MFG_ORD_CONSUMED = 207628;
public static final int TRNX_MFG_ORD_CONSUMED_ETY = 207629;
public static final int TRNX_MFG_ORD_CONSUME_PEND_MASS = 207630;
public static final int TRNX_MFG_ORD_CONSUME_PEND_ETY_MASS = 207631;
public static final int TRNX_MFG_ORD_CONSUMED_MASS = 207632;
public static final int TRNX_MFG_ORD_CONSUMED_ETY_MASS = 207633;
public static final int TRNX_MFG_ORD_FINISH_PEND = 207634;
public static final int TRNX_MFG_ORD_FINISH_PEND_ETY = 207635;
public static final int TRNX_MFG_ORD_FINISHED = 207636;
public static final int TRNX_MFG_ORD_FINISHED_ETY = 207637;
public static final int TRNR_ACCOUNT_CASH_PDAY = 207640;
public static final int TRNR_ACCOUNT_BANK_PDAY = 207641;
public static final int TRNR_ACCOUNT_CASH_CON = 207642;
public static final int TRNR_ACCOUNT_BANK_CON = 207643;
public static final int MKTS_TP_DISC_APP = 208001;
public static final int MKTU_TP_CUS = 208002;
public static final int MKTU_TP_SAL_AGT = 208003;
public static final int MKTU_MKT_SEGM = 208004;
public static final int MKTU_MKT_SEGM_SUB = 208005;
public static final int MKTU_DIST_CHAN = 208006;
public static final int MKTU_SAL_ROUTE = 208007;
public static final int MKTU_SAL_AGT = 208008;
public static final int MKT_CFG_CUS = 208009;
public static final int MKT_CFG_CUSB = 208010;
public static final int MKT_CFG_SAL_AGT = 208011;
public static final int MKT_PLIST_GRP = 208012;
public static final int MKT_PLIST = 208013;
public static final int MKT_PLIST_ITEM = 208014;
public static final int MKT_PLIST_PRICE = 208015;
public static final int MKT_PLIST_BP_LINK = 208016;
public static final int MKT_PLIST_CUS = 208017; // XXX eliminate! (sflores, 2014-02-26)
public static final int MKT_PLIST_CUS_TP = 208018; // XXX eliminate! (sflores, 2014-02-26)
public static final int MKT_COMMS_SAL_AGT = 208019;
public static final int MKT_COMMS_SAL_AGT_TP = 208020;
public static final int MKT_COMMS_DPS = 208021; // XXX eliminate, no loger useful! (sflores, 2014-09-01)
public static final int MKT_COMMS_LOG = 208021;
public static final int MKT_COMMS = 208022;
public static final int MKT_COMMS_PAY = 208023;
public static final int MKT_COMMS_PAY_ETY = 208024;
public static final int MKTX_COMMS_ITEM_SAL_AGT = 208030;
public static final int MKTX_COMMS_SAL_AGT_CONS = 208031;
public static final int MKTX_COMMS_SAL_AGT_TP_CONS = 208032;
public static final int MKTX_COMMS_SAL_AGT_TPS = 208033;
public static final int MKTX_COMMS_SAL_AGTS = 208034;
public static final int MKTX_COMMS_RES = 208035;
public static final int MKTX_COMMS_DET = 208036;
public static final int MKTX_COMMS_NOT_PAY = 208037;
public static final int MKTX_COMMS_WITH_PAY = 208038;
public static final int MKTX_COMMS_ALL = 208039;
public static final int MKTX_COMMS_DPS_SAL_AGT = 208040;
public static final int MFGS_ST_ORD = 210001;
public static final int MFGS_PTY_ORD = 210002;
public static final int MFGS_TP_REQ = 210003;
public static final int MFGS_TP_COST_OBJ = 210004;
public static final int MFGU_TP_ORD = 210005;
public static final int MFGU_TURN = 210006;
public static final int MFGU_GANG = 210007;
public static final int MFGU_GANG_ETY = 210008;
public static final int MFG_BOM = 210009;
public static final int MFG_BOM_NTS = 210010;
public static final int MFG_BOM_SUB = 210011;
public static final int MFG_SGDS = 210012;
public static final int MFG_LINE = 210013;
public static final int MFG_ORD = 210014;
public static final int MFG_ORD_PER = 210015;
public static final int MFG_ORD_NTS = 210016;
public static final int MFG_ORD_CHG = 210017;
public static final int MFG_ORD_CHG_ETY = 210018;
public static final int MFG_ORD_CHG_ETY_LOT = 210019;
public static final int MFG_ORD_SGDS = 210020;
public static final int MFG_EXP = 210021;
public static final int MFG_EXP_ORD = 210022;
public static final int MFG_EXP_ETY_ITEM = 210023;
public static final int MFG_EXP_ETY = 210024;
public static final int MFG_REQ = 210025;
public static final int MFG_EXP_REQ = 210026;
public static final int MFG_REQ_ETY = 210027;
public static final int MFG_REQ_PUR = 210028;
public static final int MFG_DRC = 210029;
public static final int MFG_DRC_ETY = 210030;
public static final int MFG_DRC_ETY_HR = 210031;
public static final int MFG_COST = 210032;
public static final int MFG_LT_CO = 210033;
public static final int MFG_LT_COB = 210034;
public static final int MFGU_LINE = 210035;
public static final int MFGU_LINE_CFG_ITEM = 210036;
public static final int MFG_REP_MON = 210100;
public static final int MFGX_BOM_ITEMS = 210200;
public static final int MFGX_BOM_LEV = 210201;
public static final int MFGX_COST_CLS_PER = 210202;
public static final int MFGX_COST_DIR = 210203;
public static final int MFGX_COST_EMP = 210204;
public static final int MFGX_COST_IND = 210205;
public static final int MFGX_EXP_ETY_LOT_VIEW = 210206;
public static final int MFGX_EXP_FOR = 210207;
public static final int MFGX_GANG_EMP = 210208;
public static final int MFGX_LT = 210209;
public static final int MFGX_ORD = 210210;
public static final int MFGX_ORD_ALL = 210211;
public static final int MFGX_ORD_FAT_SON = 210212;
public static final int MFGX_ORD_FOR = 210213;
public static final int MFGX_ORD_LOT_FG = 210214;
public static final int MFGX_ORD_LOT_RM = 210215;
public static final int MFGX_ORD_MAIN_NA = 210216;
public static final int MFGX_ORD_MAIN_FA = 210217;
public static final int MFGX_ORD_MAIN_CH = 210218;
public static final int MFGX_ORD_PERF = 210219;
public static final int MFGX_PROD = 210220;
public static final int MFGX_PROD_BY_ITM = 210221;
public static final int MFGX_PROD_BY_IGEN = 210222;
public static final int MFGX_PROD_BY_ITM_BIZ = 210223;
public static final int MFGX_PROD_BY_BIZ_ITM = 210224;
public static final int HRS_FORMER_PAYR = 220001;
public static final int HRS_FORMER_PAYR_EMP = 220002;
public static final int HRS_FORMER_PAYR_MOV = 220003;
public static final java.lang.String MSG_ERR_DATA_NOT_FOUND = "El tipo de registro no existe.";
}
|
package net.wigle.wigleandroid;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import net.wigle.wigleandroid.background.ApiDownloader;
import net.wigle.wigleandroid.background.DownloadHandler;
import static net.wigle.wigleandroid.UserStatsFragment.MSG_USER_DONE;
/**
* configure settings
*/
public final class SettingsFragment extends Fragment implements DialogListener {
private static final int MENU_RETURN = 12;
private static final int MENU_ERROR_REPORT = 13;
private static final int DONATE_DIALOG=112;
private static final int ANONYMOUS_DIALOG=113;
private static final int DEAUTHORIZE_DIALOG=114;
public boolean allowRefresh = false;
/** convenience, just get the darn new string */
public static abstract class SetWatcher implements TextWatcher {
@Override
public void afterTextChanged( final Editable s ) {}
@Override
public void beforeTextChanged( final CharSequence s, final int start, final int count, final int after ) {}
@Override
public void onTextChanged( final CharSequence s, final int start, final int before, final int count ) {
onTextChanged( s.toString() );
}
public abstract void onTextChanged( String s );
}
/** Called when the activity is first created. */
@Override
public void onCreate( final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set language
MainActivity.setLocale(getActivity());
}
@SuppressLint("SetTextI18n")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.settings, container, false);
// force media volume controls
getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
// don't let the textbox have focus to start with, so we don't see a keyboard right away
final LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linearlayout);
linearLayout.setFocusableInTouchMode(true);
linearLayout.requestFocus();
updateView(view);
return view;
}
@SuppressLint("SetTextI18n")
@Override
public void handleDialog(final int dialogId) {
final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
final View view = getView();
switch (dialogId) {
case DONATE_DIALOG: {
editor.putBoolean(ListFragment.PREF_DONATE, true);
editor.apply();
if (view != null) {
final CheckBox donate = (CheckBox) view.findViewById(R.id.donate);
donate.setChecked(true);
}
// poof
eraseDonate();
break;
}
case ANONYMOUS_DIALOG: {
// turn anonymous
if (view != null) {
final EditText user = (EditText) view.findViewById(R.id.edit_username);
final EditText pass = (EditText) view.findViewById(R.id.edit_password);
user.setEnabled(false);
pass.setEnabled(false);
}
editor.putBoolean( ListFragment.PREF_BE_ANONYMOUS, true );
editor.apply();
if (view != null) {
final CheckBox be_anonymous = (CheckBox) view.findViewById(R.id.be_anonymous);
be_anonymous.setChecked(true);
// might have to remove or show register link
updateRegister(view);
}
break;
}
case DEAUTHORIZE_DIALOG: {
editor.remove(ListFragment.PREF_AUTHNAME);
editor.remove(ListFragment.PREF_TOKEN);
editor.apply();
this.updateView(view);
break;
}
default:
MainActivity.warn("Settings unhandled dialogId: " + dialogId);
}
}
@Override
public void onResume() {
MainActivity.info("resume settings.");
final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
// donate
final boolean isDonate = prefs.getBoolean(ListFragment.PREF_DONATE, false);
if ( isDonate ) {
eraseDonate();
}
super.onResume();
MainActivity.info("Resume with allow: "+allowRefresh);
if (allowRefresh) {
allowRefresh = false;
final View view = getView();
updateView(view);
//ALIBI: what doesn't work here:
//does not successfully reload
//getFragmentManager().beginTransaction().replace(this.container.getId(),this).commit();
// WTF: actually re-pauses and resumes.
//getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
getActivity().setTitle(R.string.settings_app_name);
}
@Override
public void onPause() {
super.onPause();
MainActivity.info("Pause; setting allowRefresh");
allowRefresh = true;
}
private void updateView(final View view) {
final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
// donate
final CheckBox donate = (CheckBox) view.findViewById(R.id.donate);
final boolean isDonate = prefs.getBoolean( ListFragment.PREF_DONATE, false);
donate.setChecked( isDonate );
if ( isDonate ) {
eraseDonate();
}
donate.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked == prefs.getBoolean( ListFragment.PREF_DONATE, false) ) {
// this would cause no change, bail
return;
}
if ( isChecked ) {
// turn off until confirmed
buttonView.setChecked( false );
// confirm
MainActivity.createConfirmation( getActivity(),
getString(R.string.donate_question) + "\n\n"
+ getString(R.string.donate_explain),
MainActivity.SETTINGS_TAB_POS, DONATE_DIALOG);
}
else {
editor.putBoolean( ListFragment.PREF_DONATE, false);
editor.apply();
}
}
});
final String authUser = prefs.getString(ListFragment.PREF_AUTHNAME,"");
final TextView authUserDisplay = (TextView) view.findViewById(R.id.show_authuser);
final TextView authUserLabel = (TextView) view.findViewById(R.id.show_authuser_label);
final EditText passEdit = (EditText) view.findViewById(R.id.edit_password);
final TextView passEditLabel = (TextView) view.findViewById(R.id.edit_password_label);
final CheckBox showPass = (CheckBox) view.findViewById(R.id.showpassword);
final String authToken = prefs.getString(ListFragment.PREF_TOKEN, "");
final Button deauthButton = (Button) view.findViewById(R.id.deauthorize_client);
final Button authButton = (Button) view.findViewById(R.id.authorize_client);
if (!authUser.isEmpty()) {
authUserDisplay.setText(authUser);
authUserDisplay.setVisibility(View.VISIBLE);
authUserLabel.setVisibility(View.VISIBLE);
if (!authToken.isEmpty()) {
deauthButton.setVisibility(View.VISIBLE);
deauthButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.createConfirmation( getActivity(),
getString(R.string.deauthorize_confirm),
MainActivity.SETTINGS_TAB_POS, DEAUTHORIZE_DIALOG );
}
});
authButton.setVisibility(View.GONE);
passEdit.setVisibility(View.GONE);
passEditLabel.setVisibility(View.GONE);
showPass.setVisibility(View.GONE);
}
} else {
authUserDisplay.setVisibility(View.GONE);
authUserLabel.setVisibility(View.GONE);
deauthButton.setVisibility(View.GONE);
passEdit.setVisibility(View.VISIBLE);
passEditLabel.setVisibility(View.VISIBLE);
showPass.setVisibility(View.VISIBLE);
authButton.setVisibility(View.VISIBLE);
final Handler handler = new UserDownloadHandler(view, getActivity().getPackageName(),
getResources(), this);
final UserStatsFragment.UserDownloadApiListener apiListener =
new UserStatsFragment.UserDownloadApiListener(handler);
authButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
final ApiDownloader task = new ApiDownloader(getActivity(), ListFragment.lameStatic.dbHelper,
"user-stats-cache.json", MainActivity.USER_STATS_URL, false, true, true,
ApiDownloader.REQUEST_GET,
apiListener);
try {
task.startDownload(SettingsFragment.this);
} catch (WiGLEAuthException waex) {
MainActivity.info("User Stats Download Failed due to failed auth");
}
//TODO either authorize and update or show error
}
});
}
// anonymous
final CheckBox beAnonymous = (CheckBox) view.findViewById(R.id.be_anonymous);
final EditText user = (EditText) view.findViewById(R.id.edit_username);
final EditText pass = (EditText) view.findViewById(R.id.edit_password);
final boolean isAnonymous = prefs.getBoolean( ListFragment.PREF_BE_ANONYMOUS, false);
if ( isAnonymous ) {
user.setEnabled( false );
pass.setEnabled( false );
}
beAnonymous.setChecked( isAnonymous );
beAnonymous.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked == prefs.getBoolean(ListFragment.PREF_BE_ANONYMOUS, false) ) {
// this would cause no change, bail
return;
}
if ( isChecked ) {
// turn off until confirmed
buttonView.setChecked( false );
// confirm
MainActivity.createConfirmation( getActivity(), "Upload anonymously?",
MainActivity.SETTINGS_TAB_POS, ANONYMOUS_DIALOG );
}
else {
// unset anonymous
user.setEnabled( true );
pass.setEnabled( true );
editor.putBoolean( ListFragment.PREF_BE_ANONYMOUS, false );
editor.apply();
// might have to remove or show register link
updateRegister(view);
}
}
});
// register link
final TextView register = (TextView) view.findViewById(R.id.register);
final String registerString = getString(R.string.register);
final String activateString = getString(R.string.activate);
String registerBlurb = "<a href='https://wigle.net/register'>" + registerString +
"</a> @WiGLE.net";
// ALIBI: vision APIs started in 4.2.2; JB2 4.3 = 18 is safe. 17 might work...
if (Build.VERSION.SDK_INT >= 23) {
registerBlurb += " or <a href='net.wigle.wigleandroid://activate'>" + activateString +
"</a>";
}
try {
if (Build.VERSION.SDK_INT >= 24) {
register.setText(Html.fromHtml(registerBlurb,
Html.FROM_HTML_MODE_LEGACY));
} else {
register.setText(Html.fromHtml(registerBlurb));
}
} catch (Exception ex) {
register.setText(registerString + " @WiGLE.net");
}
register.setMovementMethod(LinkMovementMethod.getInstance());
updateRegister(view);
user.setText( prefs.getString( ListFragment.PREF_USERNAME, "" ) );
user.addTextChangedListener( new SetWatcher() {
@Override
public void onTextChanged( final String s ) {
credentialsUpdate(ListFragment.PREF_USERNAME, editor, prefs, s);
// might have to remove or show register link
updateRegister(view);
}
});
final CheckBox showPassword = (CheckBox) view.findViewById(R.id.showpassword);
showPassword.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged( final CompoundButton buttonView, final boolean isChecked ) {
if ( isChecked ) {
pass.setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
else {
pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
pass.setText( prefs.getString( ListFragment.PREF_PASSWORD, "" ) );
pass.addTextChangedListener( new SetWatcher() {
@Override
public void onTextChanged( final String s ) {
credentialsUpdate(ListFragment.PREF_PASSWORD, editor, prefs, s);
}
});
final Button button = (Button) view.findViewById(R.id.speech_button);
button.setOnClickListener( new OnClickListener() {
@Override
public void onClick( final View view ) {
final Intent errorReportIntent = new Intent( getActivity(), SpeechActivity.class );
SettingsFragment.this.startActivity( errorReportIntent );
}
});
// period spinners
doScanSpinner( R.id.periodstill_spinner, ListFragment.PREF_SCAN_PERIOD_STILL,
MainActivity.SCAN_STILL_DEFAULT, getString(R.string.nonstop), view );
doScanSpinner( R.id.period_spinner, ListFragment.PREF_SCAN_PERIOD,
MainActivity.SCAN_DEFAULT, getString(R.string.nonstop), view );
doScanSpinner( R.id.periodfast_spinner, ListFragment.PREF_SCAN_PERIOD_FAST,
MainActivity.SCAN_FAST_DEFAULT, getString(R.string.nonstop), view );
doScanSpinner( R.id.gps_spinner, ListFragment.GPS_SCAN_PERIOD,
MainActivity.LOCATION_UPDATE_INTERVAL, getString(R.string.setting_tie_wifi), view );
MainActivity.prefBackedCheckBox(this, view, R.id.edit_showcurrent, ListFragment.PREF_SHOW_CURRENT, true);
MainActivity.prefBackedCheckBox(this, view, R.id.use_metric, ListFragment.PREF_METRIC, false);
MainActivity.prefBackedCheckBox(this, view, R.id.found_sound, ListFragment.PREF_FOUND_SOUND, true);
MainActivity.prefBackedCheckBox(this, view, R.id.found_new_sound, ListFragment.PREF_FOUND_NEW_SOUND, true);
MainActivity.prefBackedCheckBox(this, view, R.id.circle_size_map, ListFragment.PREF_CIRCLE_SIZE_MAP, false);
MainActivity.prefBackedCheckBox(this, view, R.id.use_network_location, ListFragment.PREF_USE_NETWORK_LOC, false);
MainActivity.prefBackedCheckBox(this, view, R.id.disable_toast, ListFragment.PREF_DISABLE_TOAST, false);
final String[] languages = new String[]{ "", "en", "ar", "cs", "da", "de", "es", "fi", "fr", "fy",
"he", "hi", "hu", "it", "ja", "ko", "nl", "no", "pl", "pt", "pt-rBR", "ru", "sv", "tr", "zh" };
final String[] languageName = new String[]{ getString(R.string.auto), getString(R.string.language_en),
getString(R.string.language_ar), getString(R.string.language_cs), getString(R.string.language_da),
getString(R.string.language_de), getString(R.string.language_es), getString(R.string.language_fi),
getString(R.string.language_fr), getString(R.string.language_fy), getString(R.string.language_he),
getString(R.string.language_hi), getString(R.string.language_hu), getString(R.string.language_it),
getString(R.string.language_ja), getString(R.string.language_ko), getString(R.string.language_nl),
getString(R.string.language_no), getString(R.string.language_pl), getString(R.string.language_pt),
getString(R.string.language_pt_rBR), getString(R.string.language_ru), getString(R.string.language_sv),
getString(R.string.language_tr), getString(R.string.language_zh),
};
doSpinner( R.id.language_spinner, view, ListFragment.PREF_LANGUAGE, "", languages, languageName );
final String off = getString(R.string.off);
final String sec = " " + getString(R.string.sec);
final String min = " " + getString(R.string.min);
// battery kill spinner
final Long[] batteryPeriods = new Long[]{ 1L,2L,3L,4L,5L,10L,15L,20L,0L };
final String[] batteryName = new String[]{ "1 %","2 %","3 %","4 %","5 %","10 %","15 %","20 %",off };
doSpinner( R.id.battery_kill_spinner, view, ListFragment.PREF_BATTERY_KILL_PERCENT,
MainActivity.DEFAULT_BATTERY_KILL_PERCENT, batteryPeriods, batteryName );
// reset wifi spinner
final Long[] resetPeriods = new Long[]{ 15000L,30000L,60000L,90000L,120000L,300000L,600000L,0L };
final String[] resetName = new String[]{ "15" + sec, "30" + sec,"1" + min,"1.5" + min,
"2" + min,"5" + min,"10" + min,off };
doSpinner( R.id.reset_wifi_spinner, view, ListFragment.PREF_RESET_WIFI_PERIOD,
MainActivity.DEFAULT_RESET_WIFI_PERIOD, resetPeriods, resetName );
}
private void updateRegister(final View view) {
final SharedPreferences prefs = getActivity().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final String username = prefs.getString(ListFragment.PREF_USERNAME, "");
final boolean isAnonymous = prefs.getBoolean(ListFragment.PREF_BE_ANONYMOUS, false);
if (view != null) {
final TextView register = (TextView) view.findViewById(R.id.register);
if ("".equals(username) || isAnonymous) {
register.setEnabled(true);
register.setVisibility(View.VISIBLE);
} else {
// poof
register.setEnabled(false);
register.setVisibility(View.GONE);
}
}
}
/**
* The little dance we do when we update username or password, removing old creds/cache
* @param key the ListFragment key (u or p)
* @param editor prefs editor reference
* @param prefs preferences for checks
* @param newValue the new value for the username or pass
*/
public void credentialsUpdate(String key, Editor editor, SharedPreferences prefs, String newValue) {
//DEBUG: MainActivity.info(key + ": " + newValue.trim());
String currentValue = prefs.getString(key, "");
if (currentValue.equals(newValue.trim())) {
return;
}
if (newValue.trim().isEmpty()) {
//ALIBI: empty values should unset
editor.remove(key);
} else {
editor.putString(key, newValue.trim());
}
// ALIBI: if the u|p changes, force refetch token
editor.remove(ListFragment.PREF_AUTHNAME);
editor.remove(ListFragment.PREF_TOKEN);
editor.apply();
this.clearCachefiles();
}
/**
* clear cache files (i.e. on creds change)
*/
private void clearCachefiles() {
final File cacheDir = new File(MainActivity.getSDPath());
final File[] cacheFiles = cacheDir.listFiles(new FilenameFilter() {
@Override
public boolean accept( final File dir,
final String name ) {
return name.matches( ".*-cache\\.json" );
}
} );
if (null != cacheFiles) {
for (File cache: cacheFiles) {
//DEBUG: MainActivity.info("deleting: " + cache.getAbsolutePath());
boolean deleted = cache.delete();
if (!deleted) {
MainActivity.warn("failed to delete cache file: "+cache.getAbsolutePath());
}
}
}
}
private void eraseDonate() {
final View view = getView();
if (view != null) {
final CheckBox donate = (CheckBox) view.findViewById(R.id.donate);
donate.setEnabled(false);
donate.setVisibility(View.GONE);
}
}
private void doScanSpinner( final int id, final String pref, final long spinDefault,
final String zeroName, final View view ) {
final String ms = " " + getString(R.string.ms_short);
final String sec = " " + getString(R.string.sec);
final String min = " " + getString(R.string.min);
final Long[] periods = new Long[]{ 0L,50L,250L,500L,750L,1000L,1500L,2000L,3000L,4000L,5000L,10000L,30000L,60000L };
final String[] periodName = new String[]{ zeroName,"50" + ms,"250" + ms,"500" + ms,"750" + ms,
"1" + sec,"1.5" + sec,"2" + sec,
"3" + sec,"4" + sec,"5" + sec,"10" + sec,"30" + sec,"1" + min };
doSpinner(id, view, pref, spinDefault, periods, periodName);
}
private <V> void doSpinner(final int id, final View view, final String pref, final V spinDefault,
final V[] periods, final String[] periodName) {
doSpinner((Spinner)view.findViewById(id), pref, spinDefault, periods, periodName, getContext());
}
public static <V> void doSpinner( final Spinner spinner, final String pref, final V spinDefault, final V[] periods,
final String[] periodName, final Context context ) {
if ( periods.length != periodName.length ) {
throw new IllegalArgumentException("lengths don't match, periods: " + Arrays.toString(periods)
+ " periodName: " + Arrays.toString(periodName));
}
final SharedPreferences prefs = context.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
ArrayAdapter<String> adapter = new ArrayAdapter<>(
context, android.R.layout.simple_spinner_item);
Object period = null;
if ( periods instanceof Long[] ) {
period = prefs.getLong( pref, (Long) spinDefault );
}
else if ( periods instanceof String[] ) {
period = prefs.getString( pref, (String) spinDefault );
}
else {
MainActivity.error("unhandled object type array: " + Arrays.toString(periods) + " class: " + periods.getClass());
}
if (period == null) {
period = periods[0];
}
int periodIndex = 0;
for ( int i = 0; i < periods.length; i++ ) {
adapter.add( periodName[i] );
if ( period.equals(periods[i]) ) {
periodIndex = i;
}
}
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner.setAdapter( adapter );
spinner.setSelection( periodIndex );
spinner.setOnItemSelectedListener( new OnItemSelectedListener() {
@Override
public void onItemSelected( final AdapterView<?> parent, final View v, final int position, final long id ) {
// set pref
final V period = periods[position];
MainActivity.info( pref + " setting scan period: " + period );
if ( period instanceof Long ) {
editor.putLong( pref, (Long) period );
}
else if ( period instanceof String ) {
editor.putString( pref, (String) period );
}
else {
MainActivity.error("unhandled object type: " + period + " class: " + period.getClass());
}
editor.apply();
if ( period instanceof String ) {
MainActivity.setLocale( context, context.getResources().getConfiguration() );
}
}
@Override
public void onNothingSelected( final AdapterView<?> arg0 ) {}
});
}
/* Creates the menu items */
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
MenuItem item = menu.add( 0, MENU_ERROR_REPORT, 0, getString(R.string.menu_error_report) );
item.setIcon( android.R.drawable.ic_menu_report_image );
item = menu.add(0, MENU_RETURN, 0, getString(R.string.menu_return));
item.setIcon( android.R.drawable.ic_media_previous );
}
/* Handles item selections */
@Override
public boolean onOptionsItemSelected( final MenuItem item ) {
switch ( item.getItemId() ) {
case MENU_RETURN:
final MainActivity mainActivity = MainActivity.getMainActivity(this);
if (mainActivity != null) mainActivity.selectFragment(MainActivity.LIST_TAB_POS);
return true;
case MENU_ERROR_REPORT:
final Intent errorReportIntent = new Intent( getActivity(), ErrorReportActivity.class );
this.startActivity( errorReportIntent );
break;
}
return false;
}
/**
* used for authentication - this seems really heavy
*/
private final static class UserDownloadHandler extends DownloadHandler {
private SettingsFragment fragment;
private UserDownloadHandler(final View view, final String packageName,
final Resources resources, SettingsFragment settingsFragment) {
super(view, null, packageName, resources);
fragment = settingsFragment;
}
@SuppressLint("SetTextI18n")
@Override
public void handleMessage(final Message msg) {
final Bundle bundle = msg.getData();
if (msg.what == MSG_USER_DONE) {
if (bundle.containsKey("error")) {
//ALIBI: not doing anything more here, since the toast will alert.
MainActivity.info("Settings auth unsuccessful");
} else {
MainActivity.info("Settings auth successful");
final SharedPreferences prefs = MainActivity.getMainActivity()
.getApplicationContext().getSharedPreferences(ListFragment.SHARED_PREFS, 0);
final Editor editor = prefs.edit();
editor.remove(ListFragment.PREF_PASSWORD);
editor.apply();
fragment.updateView(view);
}
}
}
}
}
|
package tigase.cluster;
import tigase.conf.Configurable;
import tigase.disco.ServiceEntity;
import tigase.disco.ServiceIdentity;
import tigase.disco.XMPPService;
import tigase.server.DisableDisco;
import tigase.server.Packet;
import tigase.server.ServerComponent;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class VirtualComponent
implements ServerComponent, XMPPService, Configurable, DisableDisco {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger("tigase.cluster.VirtualComponent");
/**
* Virtual component parameter setting packet redirect destination address.
*/
public static final String REDIRECT_TO_PROP_KEY = "redirect-to";
/**
* Parameter to set service discovery item name for the virtual component
* instance. You should refer to service discovery documentation for a proper
* name for your component.
*/
public static final String DISCO_NAME_PROP_KEY = "disco-name";
/** Field description */
public static final String DISCO_NAME_PROP_VAL = "Multi User Chat";
/**
* Parameter to set service discovery node name. In most cases you should leave
* it empty unless you really know what you are doing.
*/
public static final String DISCO_NODE_PROP_KEY = "disco-node";
/** Field description */
public static final String DISCO_NODE_PROP_VAL = "";
/**
* Parameter to set service discovery item type for the virtual component.
* You should refer to a service discovery documentation for a correct type
* for your component. Or, alternatively you can have a look what returns
* your real component.
*/
public static final String DISCO_TYPE_PROP_KEY = "disco-type";
/** Field description */
public static final String DISCO_TYPE_PROP_VAL = "text";
/**
* Parameter to set service discovery item category name for the virtual
* component. Please refer to service discovery documentation for a correct
* category or check what is returned by your real component instance.
*/
public static final String DISCO_CATEGORY_PROP_KEY = "disco-category";
/** Field description */
public static final String DISCO_CATEGORY_PROP_VAL = "conference";
/**
* Comma separated list of features for the service discovery item
* reprezented by this virtual component. Please check with the real component
* to obtain a correct list of features.
*/
public static final String DISCO_FEATURES_PROP_KEY = "disco-features";
/** Field description */
public static final String DISCO_FEATURES_PROP_VAL = "http://jabber.org/protocol/muc";
private JID componentId = null;
private String discoCategory = null;
private String[] discoFeatures = null;
private String discoName = null;
private String discoNode = null;
private String discoType = null;
private String name = null;
private JID redirectTo = null;
private ServiceEntity serviceEntity = null;
/**
* Method description
*
*
* @return
*/
@Override
public JID getComponentId() {
return componentId;
}
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = new LinkedHashMap<String, Object>();
defs.put(REDIRECT_TO_PROP_KEY, "");
if (params.get(CLUSTER_NODES) != null) {
String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(",");
for (String node : cl_nodes) {
if ( !node.equals(DNSResolver.getDefaultHostname())) {
defs.put(REDIRECT_TO_PROP_KEY, BareJID.toString(getName(), node));
break;
}
}
}
defs.put(DISCO_NAME_PROP_KEY, DISCO_NAME_PROP_VAL);
defs.put(DISCO_NODE_PROP_KEY, DISCO_NODE_PROP_VAL);
defs.put(DISCO_TYPE_PROP_KEY, DISCO_TYPE_PROP_VAL);
defs.put(DISCO_CATEGORY_PROP_KEY, DISCO_CATEGORY_PROP_VAL);
defs.put(DISCO_FEATURES_PROP_KEY, DISCO_FEATURES_PROP_VAL);
return defs;
}
/**
* Method description
*
*
* @param from
*
* @return
*/
@Override
public List<Element> getDiscoFeatures(JID from) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
* @return
*/
@Override
public Element getDiscoInfo(String node, JID jid, JID from) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
* @return
*/
@Override
public List<Element> getDiscoItems(String node, JID jid, JID from) {
Element result = serviceEntity.getDiscoItem(null, getName() + "." + jid);
return Arrays.asList(result);
}
/**
* Method description
*
*
* @return
*/
@Override
public String getName() {
return name;
}
/**
* Method description
*
*/
@Override
public void initializationCompleted() {}
/**
* Method description
*
*
* @param packet
* @param results
*/
@Override
public void processPacket(Packet packet, Queue<Packet> results) {
if (redirectTo != null) {
packet.setPacketTo(redirectTo);
results.add(packet);
} else {
log.info("No redirectTo address, dropping packet: " + packet.toString());
}
}
/**
* Method description
*
*/
@Override
public void release() {}
/**
* Method description
*
*
* @param name
*/
@Override
public void setName(String name) {
this.name = name;
this.componentId = JID.jidInstanceNS(name, DNSResolver.getDefaultHostname(), null);
}
/**
* Method description
*
*
* @param properties
*/
@Override
public void setProperties(Map<String, Object> properties) {
String redirect = (String) properties.get(REDIRECT_TO_PROP_KEY);
if ((redirect == null) || redirect.isEmpty()) {
redirectTo = null;
} else {
try {
redirectTo = JID.jidInstance(redirect);
} catch (TigaseStringprepException ex) {
redirectTo = null;
log.warning("stringprep processing failed for given redirect address: " + redirect);
}
}
discoName = (String) properties.get(DISCO_NAME_PROP_KEY);
discoNode = (String) properties.get(DISCO_NODE_PROP_KEY);
if (discoNode.isEmpty()) {
discoNode = null;
}
discoCategory = (String) properties.get(DISCO_CATEGORY_PROP_KEY);
discoType = (String) properties.get(DISCO_TYPE_PROP_KEY);
discoFeatures = ((String) properties.get(DISCO_TYPE_PROP_KEY)).split(",");
serviceEntity = new ServiceEntity(getName(), null, discoName);
serviceEntity.addIdentities(new ServiceIdentity(discoCategory, discoType, discoName));
for (String feature : discoFeatures) {
serviceEntity.addFeatures(feature);
}
}
}
//~ Formatted in Sun Code Convention
|
/* vim: set et ts=4 sts=4 sw=4 tw=72 : */
package uk.ac.cam.cl.git;
import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.mongodb.BasicDBObject;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoException;
import uk.ac.cam.cl.git.configuration.ConfigurationLoader;
import uk.ac.cam.cl.git.database.Mongo;
/**
* @author Isaac Dunn <ird28@cam.ac.uk>
* @author Kovacsics Robert <rmk35@cam.ac.uk>
* @version 0.1
*/
public class ConfigDatabase {
/* For logging */
private static final Logger log = LoggerFactory.getLogger(ConfigDatabase.class);
/*
* For Guice to inject dependencies, the following line must be run:
* Guice.createInjector(new DatabaseModule());
*/
private static JacksonDBCollection<Repository, String>
reposCollection =
JacksonDBCollection.wrap
( Mongo.getDB().getCollection("repos")
, Repository.class
, String.class);
/**
* For unit testing only, to allow a mock collection to be used.
* Replaces the mongo collection with the argument.
* @param reposCollection The collection to be used.
*/
@Inject
static void setReposCollection(JacksonDBCollection<Repository, String> rCollection) {
reposCollection = rCollection;
}
/**
* Returns a list of all the repository objects in the database
*
* @return List of repository objects in the database
*/
public static List<Repository> getRepos()
{ /* TODO: Test ordered-ness or repositories. */
List<Repository> rtn = new LinkedList<Repository>();
DBCursor<Repository> allRepos = reposCollection.find();
while (allRepos.hasNext())
rtn.add(allRepos.next());
allRepos.close();
return rtn;
}
/**
* Returns the repository object with the given name in the
* database.
*
* @param name The name of the repository
* @return The requested repository object
*/
public static Repository getRepoByName(String name) {
return reposCollection.findOne(new BasicDBObject("name", name));
}
/**
* Removes the repository object with the given name from the
* database.
*
* @param name The name of the repository to remove
*/
public static void delRepoByName(String name) throws IOException {
reposCollection.remove(new BasicDBObject("name", name));
generateConfigFile();
}
/**
* Generates config file for gitolite and writes it to gitoliteGeneratedConfigFile (see ConfigurationLoader).
* <p>
* Accesses the database to find repositories and assumes the
* Repository.toString() method returns the appropriate representation. The
* main conf file should have an include statement so that
* when the hook is called, the updates are made. The hook is
* called at the end of this method.
*
* @throws IOException Typically an unrecoverable problem.
*/
public static void generateConfigFile() throws IOException {
log.info("Generating config file \"" +
ConfigurationLoader.getConfig()
.getGitoliteGeneratedConfigFile()
+ "\"");
StringBuilder output = new StringBuilder();
for (Repository r : getRepos())
output.append(r.toString() + "\n");
/* Write out file */
File configFile = new File(ConfigurationLoader.getConfig()
.getGitoliteGeneratedConfigFile());
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(configFile, false));
buffWriter.write(output.toString());
buffWriter.close();
runGitoliteUpdate(new String[] {"compile",
"trigger POST_COMPILE"});
log.info("Generated config file \"" +
ConfigurationLoader.getConfig()
.getGitoliteGeneratedConfigFile()
+ "\"");
}
/**
* Adds a new repository to the mongo database for inclusion in the
* conf file when generated.
*
* @param repo The repository to be added
* @throws DuplicateKeyException A repository with this name already
* exists.
*/
public static void addRepo(Repository repo) throws DuplicateKeyException, IOException {
reposCollection.ensureIndex(new BasicDBObject("name", 1), null, true); // each repo name must be unique
reposCollection.insert(repo);
generateConfigFile();
}
/**
* Takes public key and username as strings, writes the key to
* getGitoliteSSHKeyLocation (see ConfigurationLoader), and calls the hook.
*
* @param key The SSH key to be added
* @param username The name of the user to be added
* @throws IOException
*/
public static void addSSHKey(String key, String userName) throws IOException {
log.info("Adding key for \"" + userName + "\" to \""
+ ConfigurationLoader.getConfig()
.getGitoliteSSHKeyLocation() + "\"");
File keyFile = new File(ConfigurationLoader.getConfig()
.getGitoliteSSHKeyLocation() + userName + ".pub");
if (!keyFile.exists()) {
if (keyFile.getParentFile() != null)
keyFile.getParentFile().mkdirs(); /* Make parent directories if necessary */
keyFile.createNewFile();
}
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(keyFile));
buffWriter.write(key);
buffWriter.close();
runGitoliteUpdate(new String[] {"trigger SSH_AUTHKEYS"});
log.info("Finished adding key for \"" + userName + "\"");
}
/**
* Updates the given repository.
*
* This selects the repository uniquely using the ID (not
* technically the name of the repository, but is equivalent).
*
* @param repo The updated repository (there must also be a
* repository by this name).
* @throws MongoException If the update operation fails (for some
* unknown reason).
*/
public static void updateRepo(Repository repo) throws MongoException, IOException
{
reposCollection.updateById(repo.get_id(), repo);
generateConfigFile();
}
private static void runGitoliteUpdate(String[] updates) throws IOException
{
log.info("Starting gitolite recompilation");
for (String command : updates)
{
Process p = Runtime.getRuntime().exec(
"env gitolite " + command
, new String[]
{"HOME=" + ConfigurationLoader.getConfig().getGitoliteHome()
, "PATH=" + ConfigurationLoader.getConfig().getGitolitePath()
, "GL_LIBDIR=" + ConfigurationLoader.getConfig().getGitoliteLibdir()});
BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader outputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = outputReader.readLine()) != null) {
System.out.println(line);
}
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
}
log.info("Finished gitolite recompilation");
}
private static void rebuildDatabaseFromGitolite() throws MongoException, IOException {
reposCollection.remove(new BasicDBObject()); // Empty database collection
BufferedReader reader = new BufferedReader(new FileReader(new File(
ConfigurationLoader.getConfig().getGitoliteGeneratedConfigFile())));
String firstLine;
while ((firstLine = reader.readLine()) != null) { // While not end of file
String repoName = firstLine.split("\\s\\+")[1]; // Repo name is second word of first line
String[] readWriteLine = reader.readLine().split("=")[1].trim().split("\\s\\+");
// We want the words to the right of the "RW ="
String nextLine = reader.readLine();
String[] readOnlyLine;
String[] auxiliaryLine;
if (nextLine.startsWith("#")) { // No users with read only access
readOnlyLine = new String[0];
auxiliaryLine = nextLine.split(" ");
}
else { // At least one user with read only access
readOnlyLine = nextLine.split("=")[1].trim().split("\\s\\+");
auxiliaryLine = reader.readLine().split("\\s\\+");
}
String owner = readWriteLine[0]; // Owner is always first RW entry - see Repository.toString()
List<String> readWrites = new LinkedList<String>(Arrays.asList(readWriteLine));
readWrites.remove(0); // remove owner from RW list as owner is automatically added
List<String> readOnlys = Arrays.asList(readOnlyLine);
String parent = auxiliaryLine[1]; // see Repository.toString()
String parent_hidden = auxiliaryLine[2];
Repository toInsert = new Repository(repoName, owner, readWrites,
readOnlys, parent, parent_hidden, null);
reposCollection.insert(toInsert);
reader.readLine(); // extra line between repos
}
reader.close();
}
}
|
/*
* $Id: TestAuConfig.java,v 1.10 2008-07-11 08:21:38 tlipkis Exp $
*/
package org.lockss.servlet;
import junit.framework.TestCase;
import java.io.*;
import java.util.*;
import org.lockss.util.*;
import org.lockss.test.*;
import org.lockss.state.*;
import org.lockss.plugin.*;
import org.lockss.servlet.*;
import org.lockss.repository.*;
import com.meterware.servletunit.*;
import com.meterware.httpunit.*;
/**
* This is the test class for org.lockss.servlet.AuConfig
*/
public class TestAuConfig extends LockssServletTestCase {
static Logger log = Logger.getLogger("TestAuConfig");
private MockArchivalUnit mau = null;
private PluginManager pluginMgr = null;
public void setUp() throws Exception {
super.setUp();
pluginMgr = new PluginManager();
theDaemon.setPluginManager(pluginMgr);
theDaemon.setIdentityManager(new org.lockss.protocol.MockIdentityManager());
theDaemon.getServletManager();
theDaemon.setDaemonInited(true);
theDaemon.getRemoteApi().startService();
pluginMgr.initService(theDaemon);
pluginMgr.startService();
String tempDirPath = getTempDir().getAbsolutePath() + File.separator;
Properties props = new Properties();
props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath);
props.setProperty(HistoryRepositoryImpl.PARAM_HISTORY_LOCATION,
tempDirPath);
props.setProperty(AdminServletManager.PARAM_START, "false");
ConfigurationUtil.setCurrentConfigFromProps(props);
mau = new MockArchivalUnit();
}
protected void initServletRunner() {
super.initServletRunner();
sRunner.registerServlet("/AuConfig", AuConfig.class.getName() );
}
public void testBeforeAusLoaded() throws Exception {
initServletRunner();
WebRequest request =
new GetMethodWebRequest("http://null/AuConfig" );
WebResponse resp1 = sClient.getResponse(request);
log.debug2("Response 1: " + resp1.getText());
assertResponseOk(resp1);
assertEquals("Content type", "text/html", resp1.getContentType());
WebForm auForm = resp1.getFormWithID("AuSummaryForm");
WebTable auTable = resp1.getTableWithID("AuSummaryTable");
assertNull("Form named AuSummaryForm should not appear " +
"until PluginManager has started all AUs", auForm);
assertNull("Table named AuSummaryTable should not appear " +
"until PluginManager has started all AUs", auTable);
}
public void testAfterAusLoaded() throws Exception {
// Force PluginManager to think all AUs have started.
theDaemon.setAusStarted(true);
initServletRunner();
WebRequest request =
new GetMethodWebRequest("http://null/AuConfig" );
// request.setParameter( "color", "red" );
WebResponse resp1 = sClient.getResponse(request);
log.debug2("Response 1: " + resp1.getText());
assertResponseOk(resp1);
assertEquals("Content type", "text/html", resp1.getContentType());
WebForm auForm = resp1.getFormWithID("AuSummaryForm");
WebTable auTable = resp1.getTableWithID("AuSummaryTable");
assertNotNull("No form named AuSummaryForm", auForm);
assertNotNull("No table named AuSummaryTable", auTable);
assertEquals(1, auTable.getRowCount());
assertEquals(2, auTable.getColumnCount());
assertEquals("", auTable.getCellAsText(0,0));
assertEquals("Add new Archival Unit", auTable.getCellAsText(0,1));
TableCell cell = auTable.getTableCell(0,0);
HTMLElement elem = cell.getElementWithID("lsb.1");
Button btn = (Button)elem;
assertEquals("Add", btn.getValue());
// This form must be submitted via the javascript invoked by this button,
btn.click();
WebResponse resp2 = sClient.getCurrentPage();
log.debug2("Response 2: " + resp2.getText());
assertResponseOk(resp2);
}
}
|
package org.resteasy;
import org.resteasy.spi.ResourceFactory;
import org.resteasy.util.IsHttpMethod;
import org.resteasy.util.PathHelper;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ProviderFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Registry {
public class Node {
private List<ResourceMethod> invokers = new ArrayList<ResourceMethod>();
private List<Node> wildChildren = new ArrayList<Node>();
private Map<String, Node> children = new HashMap<String, Node>();
public Node() {
}
public void addChild(String[] path, int pathIndex, ResourceMethod invoker) {
Matcher matcher = PathHelper.URI_TEMPLATE_PATTERN.matcher(path[pathIndex]);
if (matcher.matches()) {
String uriParamName = matcher.group(2);
Node child = new Node();
wildChildren.add(child);
if (path.length == pathIndex + 1) {
child.invokers.add(invoker);
} else {
child.addChild(path, ++pathIndex, invoker);
}
} else {
Node child = children.get(path[pathIndex]);
if (child == null) {
child = new Node();
children.put(path[pathIndex], child);
}
if (path.length == pathIndex + 1) {
child.invokers.add(invoker);
} else {
child.addChild(path, ++pathIndex, invoker);
}
}
}
public ResourceMethod findResourceInvoker(String httpMethod, String[] path, int pathIndex, MediaType contentType, List<MediaType> accepts) {
if (pathIndex >= path.length) return match(httpMethod, contentType, accepts);
else return findChild(httpMethod, path, pathIndex, contentType, accepts);
}
private ResourceMethod findChild(String httpMethod, String[] path, int pathIndex, MediaType contentType, List<MediaType> accepts) {
Node next = children.get(path[pathIndex]);
if (next != null) return next.findResourceInvoker(httpMethod, path, ++pathIndex, contentType, accepts);
else if (wildChildren != null) {
for (Node wildcard : wildChildren) {
ResourceMethod wildcardReturn = wildcard.findResourceInvoker(httpMethod, path, ++pathIndex, contentType, accepts);
if (wildcardReturn != null) return wildcardReturn;
}
return null;
} else {
return null;
}
}
private ResourceMethod match(String httpMethod, MediaType contentType, List<MediaType> accepts) {
for (ResourceMethod invoker : invokers) {
if (invoker.matchByType(contentType, accepts) && invoker.getHttpMethods().contains(httpMethod))
return invoker;
}
return null;
}
}
private Node root = new Node();
private ProviderFactory providerFactory;
public Registry(ProviderFactory providerFactory) {
this.providerFactory = providerFactory;
}
public void addResourceFactory(ResourceFactory factory) {
addResourceFactory(factory, null);
}
public void addResourceFactory(ResourceFactory factory, String base) {
Class<?> clazz = factory.getScannableClass();
Path classBasePath = clazz.getAnnotation(Path.class);
String classBase = (classBasePath == null) ? null : classBasePath.value();
if (base == null) base = classBase;
else if (classBase != null) base = base + "/" + classBase;
for (Method method : clazz.getMethods()) {
Path path = method.getAnnotation(Path.class);
Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
if (path == null && httpMethods == null) continue;
String pathExpression = null;
if (base != null) pathExpression = base;
if (path != null)
pathExpression = (pathExpression == null) ? path.value() : pathExpression + "/" + path.value();
if (pathExpression == null) pathExpression = "";
if (httpMethods == null) {
ResourceLocator locator = new ResourceLocator(pathExpression, factory, method, providerFactory);
addResourceFactory(locator, pathExpression);
} else {
ResourceMethod invoker = new ResourceMethod(pathExpression, clazz, method, factory, providerFactory, httpMethods);
String[] paths = pathExpression.split("/");
root.addChild(paths, 0, invoker);
}
}
}
public ResourceMethod getResourceInvoker(String httpMethod, String path, MediaType contentType, List<MediaType> accepts) {
if (path.startsWith("/")) path = path.substring(1);
return root.findResourceInvoker(httpMethod, path.split("/"), 0, contentType, accepts);
}
}
|
package skylight1.sevenwonders;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
public class MenuActivity extends Activity {
public static final String PREFS_NAME = "SevenWondersPrefs";
private static final String TAG = MenuActivity.class.getName();
private boolean SOUNDENABLED;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SOUNDENABLED = settings.getBoolean("SOUNDENABLED", false);
Log.i(TAG, "started");
setContentView(R.layout.menu);
final CheckBox soundCB = (CheckBox)findViewById(R.id.soundCheckBox);
soundCB.setChecked(SOUNDENABLED);
soundCB.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View aV) {
SOUNDENABLED = soundCB.isChecked();
//save preference
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("SOUNDENABLED", SOUNDENABLED);
editor.commit();
}
});
final View view = findViewById(R.id.EnterEgypt);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View aV) {
final Intent gameActivity = new Intent(MenuActivity.this, PlayActivity.class);
gameActivity.putExtra("ENABLESOUND", SOUNDENABLED);
startActivity(gameActivity);
}
});
}
}
|
package me.lucko.helper.menu;
import com.google.common.base.Preconditions;
import me.lucko.helper.Events;
import me.lucko.helper.Schedulers;
import me.lucko.helper.metadata.Metadata;
import me.lucko.helper.metadata.MetadataKey;
import me.lucko.helper.metadata.MetadataMap;
import me.lucko.helper.terminable.TerminableConsumer;
import me.lucko.helper.terminable.composite.CompositeTerminable;
import me.lucko.helper.text.Text;
import me.lucko.helper.utils.annotation.NonnullByDefault;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.inventory.Inventory;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A simple GUI abstraction
*/
@NonnullByDefault
public abstract class Gui implements TerminableConsumer {
public static final MetadataKey<Gui> OPEN_GUI_KEY = MetadataKey.create("open-gui", Gui.class);
/**
* Utility method to get the number of lines needed for x items
*
* @param count the number of items
* @return the number of lines needed
*/
public static int getMenuSize(int count) {
Preconditions.checkArgument(count >= 0, "count < 0");
return getMenuSize(count, 9);
}
/**
* Utility method to get the number of lines needed for x items
*
* @param count the number of items
* @param itemsPerLine the number of items per line
* @return the number of lines needed
*/
public static int getMenuSize(int count, int itemsPerLine) {
Preconditions.checkArgument(itemsPerLine >= 1, "itemsPerLine < 1");
return (count / itemsPerLine + ((count % itemsPerLine != 0) ? 1 : 0));
}
// The player holding the GUI
private final Player player;
// The backing inventory instance
private final Inventory inventory;
// The initial title set when the inventory was made.
private final String initialTitle;
// The slots in the gui, lazily loaded
private final Map<Integer, SimpleSlot> slots;
// This remains true until after #redraw is called for the first time
private boolean firstDraw = true;
// A function used to build a fallback page when this page is closed.
@Nullable
private Function<Player, Gui> fallbackGui = null;
// Callbacks to be ran when the GUI is invalidated (closed). useful for cancelling tick tasks
// Also contains the event handlers bound to this GUI, currently listening to events
private final CompositeTerminable compositeTerminable = CompositeTerminable.create();
private boolean valid = false;
public Gui(Player player, int lines, String title) {
this.player = Objects.requireNonNull(player, "player");
this.initialTitle = Text.colorize(Objects.requireNonNull(title, "title"));
this.inventory = Bukkit.createInventory(player, lines * 9, this.initialTitle);
this.slots = new HashMap<>();
}
/**
* Places items on the GUI. Called when the GUI is opened.
* Use {@link #isFirstDraw()} to determine if this is the first time redraw has been called.
*/
public abstract void redraw();
/**
* Gets the player viewing this Gui
*
* @return the player viewing this gui
*/
public Player getPlayer() {
return this.player;
}
/**
* Gets the delegate Bukkit inventory
*
* @return the bukkit inventory being wrapped by this instance
*/
public Inventory getHandle() {
return this.inventory;
}
/**
* Gets the initial title which was set when this GUI was made
*
* @return the initial title used when this GUI was made
*/
public String getInitialTitle() {
return this.initialTitle;
}
@Nullable
public Function<Player, Gui> getFallbackGui() {
return this.fallbackGui;
}
public void setFallbackGui(@Nullable Function<Player, Gui> fallbackGui) {
this.fallbackGui = fallbackGui;
}
@Nonnull
@Override
public <T extends AutoCloseable> T bind(@Nonnull T terminable) {
return this.compositeTerminable.bind(terminable);
}
public boolean isFirstDraw() {
return this.firstDraw;
}
public Slot getSlot(int slot) {
if (slot < 0 || slot >= this.inventory.getSize()) {
throw new IllegalArgumentException("Invalid slot id: " + slot);
}
return this.slots.computeIfAbsent(slot, i -> new SimpleSlot(this, i));
}
public void setItem(int slot, Item item) {
getSlot(slot).applyFromItem(item);
}
public void setItems(Item item, int... slots) {
Objects.requireNonNull(item, "item");
for (int slot : slots) {
setItem(slot, item);
}
}
public void setItems(Iterable<Integer> slots, Item item) {
Objects.requireNonNull(item, "item");
Objects.requireNonNull(slots, "slots");
for (int slot : slots) {
setItem(slot, item);
}
}
public int getFirstEmpty() {
int ret = this.inventory.firstEmpty();
if (ret < 0) {
throw new IndexOutOfBoundsException("no empty slots");
}
return ret;
}
public Optional<Slot> getFirstEmptySlot() {
int ret = this.inventory.firstEmpty();
if (ret < 0) {
return Optional.empty();
}
return Optional.of(getSlot(ret));
}
public void addItem(Item item) {
Objects.requireNonNull(item, "item");
getFirstEmptySlot().ifPresent(s -> s.applyFromItem(item));
}
public void addItems(Iterable<Item> items) {
Objects.requireNonNull(items, "items");
for (Item item : items) {
addItem(item);
}
}
public void fillWith(Item item) {
Objects.requireNonNull(item, "item");
for (int i = 0; i < this.inventory.getSize(); ++i) {
setItem(i, item);
}
}
public void removeItem(int slot) {
getSlot(slot).clear();
}
public void removeItems(int... slots) {
for (int slot : slots) {
removeItem(slot);
}
}
public void removeItems(Iterable<Integer> slots) {
Objects.requireNonNull(slots, "slots");
for (int slot : slots) {
removeItem(slot);
}
}
public void clearItems() {
this.inventory.clear();
this.slots.values().forEach(Slot::clearBindings);
}
public void open() {
if (this.valid) {
throw new IllegalStateException("Gui is already opened.");
}
this.firstDraw = true;
try {
redraw();
} catch (Exception e) {
e.printStackTrace();
invalidate();
return;
}
this.firstDraw = false;
startListening();
this.player.openInventory(this.inventory);
Metadata.provideForPlayer(this.player).put(OPEN_GUI_KEY, this);
this.valid = true;
}
public void close() {
this.player.closeInventory();
}
private void invalidate() {
this.valid = false;
MetadataMap metadataMap = Metadata.provideForPlayer(this.player);
Gui existing = metadataMap.getOrNull(OPEN_GUI_KEY);
if (existing == this) {
metadataMap.remove(OPEN_GUI_KEY);
}
// stop listening
this.compositeTerminable.closeAndReportException();
// clear all items from the GUI, just in case the menu didn't close properly.
clearItems();
}
/**
* Returns true unless this GUI has been invalidated, through being closed, or the player leaving.
* @return true unless this GUI has been invalidated.
*/
public boolean isValid() {
return this.valid;
}
/**
* Registers the event handlers for this GUI
*/
private void startListening() {
Events.merge(Player.class)
.bindEvent(PlayerDeathEvent.class, PlayerDeathEvent::getEntity)
.bindEvent(PlayerQuitEvent.class, PlayerEvent::getPlayer)
.bindEvent(PlayerChangedWorldEvent.class, PlayerEvent::getPlayer)
.bindEvent(PlayerTeleportEvent.class, PlayerEvent::getPlayer)
.filter(p -> p.equals(this.player))
.filter(p -> isValid())
.handler(p -> invalidate())
.bindWith(this);
Events.subscribe(InventoryDragEvent.class)
.filter(e -> e.getInventory().getHolder() != null)
.filter(e -> e.getInventory().getHolder().equals(this.player))
.handler(e -> {
e.setCancelled(true);
if (!isValid()) {
close();
}
}).bindWith(this);
Events.subscribe(InventoryClickEvent.class)
.filter(e -> e.getInventory().getHolder() != null)
.filter(e -> e.getInventory().getHolder().equals(this.player))
.handler(e -> {
e.setCancelled(true);
if (!isValid()) {
close();
return;
}
if (!e.getInventory().equals(this.inventory)) {
return;
}
int slotId = e.getRawSlot();
// check if the click was in the top inventory
if (slotId != e.getSlot()) {
return;
}
SimpleSlot slot = this.slots.get(slotId);
if (slot != null) {
slot.handle(e);
}
})
.bindWith(this);
Events.subscribe(InventoryCloseEvent.class)
.filter(e -> e.getPlayer().equals(this.player))
.filter(e -> e.getInventory().equals(this.inventory))
.filter(e -> isValid())
.handler(e -> {
invalidate();
// Check for a fallback GUI
Function<Player, Gui> fallback = this.fallbackGui;
if (fallback == null) {
return;
}
// Open at a delay
Schedulers.sync().runLater(() -> {
if (!this.player.isOnline()) {
return;
}
Gui fallbackGui = fallback.apply(this.player);
if (fallbackGui == null) {
throw new IllegalStateException("Fallback function " + fallback + " returned null");
}
if (fallbackGui.valid) {
throw new IllegalStateException("Fallback function " + fallback + " produced a GUI " + fallbackGui + " which is already open");
}
fallbackGui.open();
}, 1L);
})
.bindWith(this);
}
}
|
package yuku.alkitabconverter.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DesktopVerseParserTest {
@Test
public void testVerseStringToAri() throws Exception {
test("John 3:16", "0x2a0310 .");
test("John 3.16", "0x2a0310 .");
test("John 3:16-18", "0x2a0310 0x2a0312");
test("John 3.16-18", "0x2a0310 0x2a0312");
test("John 3:16-3:18", "0x2a0310 0x2a0312");
test("John 3:16-4:18", "0x2a0310 0x2a0412");
test("Kejadian 1:1", "0x000101 0x000101");
test("Kej 1:1 dan 2", "0x000101 . 0x000102 .");
test("Gen 1:1,3,5", "0x000101 . 0x000103 . 0x000105 .");
// one chapter books
test("jud 9", "0x400109 .");
test("jud 9-12", "0x400109 0x40010c");
test("jud 1:9", "0x400109 .");
test("jud 1:9-12", "0x400109 0x40010c");
// not one chapter books
test("ps 9", "0x120900 .");
test("ps 9-12", "0x120900 0x120c00");
test("ps 1:9", "0x120109 .");
test("ps 1:9-12", "0x120109 0x12010c");
// multiple
test("gn 2:2, 5, 8-32", "0x000202 . 0x000205 . 0x000208 0x000220");
// new abbr
test("wah 9:9", "0x410909 .");
test("zak 9:9", "0x250909 .");
// single chapter book whole book
test("oba 0", "0x1E0100 .");
test("philemon 0", "0x380100 .");
test("2 john 0", "0x3E0100 .");
test("3 john 0", "0x3F0100 .");
test("jud 0", "0x400100 .");
}
private void test(final String ref, final String s) {
final IntArrayList parsed = DesktopVerseParser.verseStringToAri(ref);
final String[] aris2 = s.split(" ");
final IntArrayList expected = new IntArrayList();
for (final String aris : aris2) {
if (aris.equals(".")) { // repeat last
expected.add(expected.get(expected.size() - 1));
} else {
expected.add(Integer.decode(aris));
}
}
assertEquals(expected, parsed);
}
}
|
package ru.job4j.max;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* MaxTest.
* @author mklimentiev
* @version 2.0
* @since 01.04.2017
*/
public class MaxTest {
/**
* Test maxFromTwo.
*/
@Test
public void whenPassFirstAndSecondThenReturnMaxOfThem() {
Max max1 = new Max();
int result1 = max1.maxFromTwo(1, 2);
assertThat(result1, is(2));
Max max2 = new Max();
int result2 = max2.maxFromTwo(0, 1);
assertThat(result2, is(1));
}
/**
* Test maxFromThree.
*/
@Test
public void whenPassFirstSecondThirdParametresThenReturnMaxOfThem() {
Max max3 = new Max();
int result3 = max3.maxFromThree(1, 2, 6);
assertThat(result3, is(6));
Max max4 = new Max();
int result4 = max4.maxFromThree(0, 1, 0);
assertThat(result4, is(1));
}
}
|
package ru.job4j.bank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Final task collection.
*/
public class Manage {
/**
* Private filed.
*/
private Map<User, List<Account>> dep = new HashMap<User, List<Account>>();
/**
* Getter.
*
* @return Map.
*/
public Map<User, List<Account>> getDep() {
return dep;
}
/**
* Method add user.
*
* @param user user.
*/
public void addUser(User user) {
if (user != null) {
dep.put(user, new ArrayList<Account>());
}
}
/**
* Method delete user.
*
* @param user user.
*/
public void deleteUser(User user) {
if (user != null) {
dep.remove(user);
}
}
/**
* Method add account to user.
*
* @param user user.
* @param account account.
*/
public void addAccountToUser(User user, Account account) {
if (user != null && dep.containsKey(user)) {
dep.get(user).add(account);
}
}
/**
* Method delete account from user.
*
* @param user user.
* @param account account.
*/
public void deleteAccountFromUser(User user, Account account) {
if (user != null && dep.containsKey(user)) {
dep.get(user).remove(account);
}
}
/**
* Method return all user accounts.
*
* @param user user.
* @return List accounts.
*/
public List<Account> getUserAccounts(User user) {
List<Account> acc = new ArrayList<>();
if (user != null && dep.containsKey(user)) {
acc = dep.get(user);
}
return acc;
}
/**
* Method transfer money from one account to another.
*
* @param srcUser source user.
* @param srcAccount source account.
* @param dstUser destination user.
* @param dstAccount destination account.
* @param amount amount for transfer.
* @return boolean.
*/
public boolean transferMoney(User srcUser, Account srcAccount, User dstUser, Account dstAccount, double amount) {
List<Account> tmp = new ArrayList<>();
if (srcUser != null && srcAccount != null && dstUser != null && dstAccount != null) {
tmp = dep.get(srcUser);
} else {
return false;
}
for (Account account : tmp) {
if (account.equals(srcAccount) && account.getValue() >= amount) {
account.setValue(account.getValue() - amount);
break;
} else if (account.equals(srcAccount) && account.getValue() < amount) {
return false;
}
}
tmp = dep.get(dstUser);
for (Account account : tmp) {
if (account.equals(dstAccount)) {
account.setValue(account.getValue() + amount);
break;
}
}
return true;
}
}
|
package org.smoothbuild.cli;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.smoothbuild.util.Strings.unlines;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import org.junit.Test;
import org.smoothbuild.lang.object.base.SObject;
import org.smoothbuild.testing.TestingContext;
import com.google.common.base.Throwables;
public class ConsoleTest extends TestingContext {
private final String name = "GROUP NAME";
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private final PrintStream printStream = new PrintStream(outputStream);
private final Console console = new Console(printStream);
@Test
public void printing_messages_containing_error_message() {
console.print(name, array(errorMessage("message string")));
assertThat(outputStream.toString()).isEqualTo(unlines(
" + GROUP NAME",
" + ERROR: message string",
""));
}
@Test
public void printing_messages_without_error_message() {
console.print(name, array(warningMessage("message string\nsecond line")));
assertThat(outputStream.toString()).isEqualTo(unlines(
" + GROUP NAME",
" + WARNING: message string",
" second line",
""));
}
// isProblemReported()
@Test
public void isProblemReported_returns_false_when_nothing_was_logged() {
console.print(name, array(infoMessage("message string")));
assertFalse(console.isProblemReported());
}
@Test
public void isProblemReported_returns_false_when_only_info_was_logged() {
console.print(name, array(infoMessage("message string")));
assertFalse(console.isProblemReported());
}
@Test
public void isProblemReported_returns_false_when_only_warning_was_logged() {
console.print(name, array(warningMessage("message string")));
assertFalse(console.isProblemReported());
}
@Test
public void isProblemReported_returns_true_when_error_was_logged() {
console.print(name, array(errorMessage("message string")));
assertTrue(console.isProblemReported());
}
@Test
public void isProblemReported_returns_true_when_failure_was_logged() {
console.print(name, new RuntimeException("message string"));
assertTrue(console.isProblemReported());
}
// printFinalSummary()
@Test
public void final_summary_is_failed_when_error_was_logged() {
console.print(name, array(errorMessage("message string")));
console.printFinalSummary();
assertThat(outputStream.toString()).isEqualTo(unlines(
" + GROUP NAME",
" + ERROR: message string",
" + 1 error(s)",
""));
}
@Test
public void final_summary_contains_all_stats() {
ArrayList<SObject> messages = new ArrayList<>();
RuntimeException exception = new RuntimeException("failure message");
console.print(name, exception);
for (int i = 0; i < 2; i++) {
messages.add(errorMessage("error string"));
}
for (int i = 0; i < 3; i++) {
messages.add(warningMessage("warning string"));
}
for (int i = 0; i < 4; i++) {
messages.add(infoMessage("info string"));
}
console.print(name, array(messages.toArray(SObject[]::new)));
console.printFinalSummary();
StringBuilder builder = new StringBuilder();
builder.append(" + GROUP NAME\n");
builder.append(Throwables.getStackTraceAsString(exception));
builder.append(" + GROUP NAME\n");
builder.append(" + ERROR: error string\n".repeat(2));
builder.append(" + WARNING: warning string\n".repeat(3));
builder.append(" + INFO: info string\n".repeat(4));
builder.append(" + 1 failure(s)\n");
builder.append(" + 2 error(s)\n");
builder.append(" + 3 warning(s)\n");
builder.append(" + 4 info(s)\n");
assertEquals(builder.toString(), outputStream.toString());
}
}
|
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Gen {
private static final String DIGITS = "0123456789abcdef";
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
Provider bc = Security.getProvider("BC");
String algorithm = "RSA";
int keysize = 1024;
KeyPairGenerator kg = null;
try {
kg = KeyPairGenerator.getInstance(algorithm, bc);
kg.initialize(keysize);
} catch (NoSuchAlgorithmException e) {
System.out.println("Can't find algorithm " + algorithm);
System.exit(-1);
}
KeyPair keyPair = kg.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
String privateKeyFileName = "private";
String publicKeyFileName = "public";
try {
FileOutputStream privateKeyOutput = new FileOutputStream(privateKeyFileName);
FileOutputStream publicKeyOutput = new FileOutputStream(publicKeyFileName);
X509EncodedKeySpec X509 = new X509EncodedKeySpec(publicKey.getEncoded());
privateKeyOutput.write(X509.getEncoded());
PKCS8EncodedKeySpec PKCS8 = new PKCS8EncodedKeySpec(privateKey.getEncoded());
publicKeyOutput.write(PKCS8.getEncoded());
} catch (IOException e) {
System.out.println("Can't write key to disk");
}
}
public static String toHex(byte[] data) {
return toHex(data, data.length);
}
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++)
{
int v = data[i] & 0xff;
buf.append(DIGITS.charAt(v >> 4));
buf.append(DIGITS.charAt(v & 0xf));
}
return buf.toString();
}
}
|
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class GoL extends JFrame{
JPanel p1 = new JPanel(new BorderLayout());
JPanel p2 = new JPanel(new GridLayout(32,32));//Table Panel
//JPanel p3 = new JPanel();//Tool Panel
JPanel p4 = new JPanel();//Signiture
JPanel p5 = new JPanel(new GridLayout(4,1));//PreMade Set
JPanel p6 = new JPanel(new GridLayout(2,1));
JPanel p7 = new JPanel();//front
JPanel p8 = new JPanel();//back
JPanel p9 = new JPanel(new BorderLayout());//Padding
JLabel l1 = new JLabel((char)169 +"Lucas Rivera & Hans Kiessler 2014 for Rutgers University-HACK RU");
JLabel l2 = new JLabel("PreMade Sets");
JLabel l3 = new JLabel("Stop At N=:");
JLabel l4 = new JLabel("\tTime Delay:");
JLabel l5 = new JLabel("ms");
JButton b1 = new JButton("Play");
JButton b2 = new JButton("Stop");
JButton b3 = new JButton("About");
JButton b4 = new JButton("Expand Set");
JButton b5 = new JButton("Save");
JButton b6 = new JButton("Clear");
JButton b7 = new JButton("Reset");
JButton b8 = new JButton("Load");
JTextField t1 = new JTextField("N=0000");
JTextField t2 = new JTextField("-1");
JTextField t3 = new JTextField("200");
JTextField ti2;
JTextField ti1;
JRadioButton rb1;
JRadioButton rb2;
JRadioButton rb3;
JRadioButton rb4;
JDialog di;
Cell[][] ppl = new Cell[32][32];
//Point[] compress = new Point[1024]; <-- will eventually use for optimization at some point(pun was not inteded)
String s[] = {"--Select
JComboBox c1 = new JComboBox(s);
JScrollBar sb = new JScrollBar();
JSplitPane p3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,p5,p6);
int count = 0;
byte[] ini = new byte[128];
boolean isOn = false;
boolean begin = true;
long sleep = 200;
String[] manyS;
File dir = new File("design");
public GoL(){
try {
DataInputStream in = new DataInputStream(new FileInputStream("design/log.gol"));
in.close();
findFiles();
} catch (FileNotFoundException e1) {
try{
//File dir = new File("design");
dir.mkdir();
DataOutputStream out = new DataOutputStream(new FileOutputStream("design/log.gol"));
out.writeUTF("Hay");
out.close();
}
catch(FileNotFoundException e2) {
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
b1.addActionListener(new playButton());
b2.addActionListener(new stopButton());
b3.addActionListener(new aboutButton());
b6.addActionListener(new clearButton());
b5.addActionListener(new saveButton());
b7.addActionListener(new resetButton());
t3.addActionListener(new timeDelay());
b8.addActionListener(new loadButton());
p9.add(p3,BorderLayout.CENTER);
p9.add(p4, BorderLayout.SOUTH);
p2.setMaximumSize(new Dimension(800,200));
p2.setSize(800, 200);
t1.setEditable(false);
p3.setMinimumSize(new Dimension(100,50));
p7.add(t1);
p7.add(b1);
p7.add(b2);
p7.add(b6);
p7.add(b5);
p7.add(b7);
p7.add(b3);
p8.add(l3);
p8.add(t2);
p8.add(l4);
p8.add(t3);
p8.add(l5);
p6.add(p7);
p6.add(p8);
p5.add(l2);
p5.add(c1);
p5.add(b8);
p5.add(b4);
//p3.add(p5);
TitledBorder title = BorderFactory.createTitledBorder("CUSTOM");
p6.setBorder(title);
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
ppl[i][j] = new Cell();
ppl[i][j].addActionListener(new userClick());
p2.add(ppl[i][j]);
}
}
p4.add(l1);
p1.add(p2, BorderLayout.CENTER);
p1.add(p9, BorderLayout.SOUTH);//used to be p3
//p1.add(p4, BorderLayout.SOUTH);
add(p1);
(new saveButton()).actionPerformed(new ActionEvent(new Object(),0,""));
}
public static void main(String[] args) {
GoL r1 = new GoL();
r1.setSize(800, 780);
r1.setMinimumSize(new Dimension(600, 400));
r1.setVisible(true);
r1.setTitle("Conway's - The Game of Life");
r1.setLocationRelativeTo(null);
r1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void reloadList(){
c1 = new JComboBox(s);
//c1.validate();
//this.validate();
}
public class Cell extends JButton{
//JButton b;
boolean alive;
boolean after;
Cell(){
//b = new JButton();
}
}
public class userClick implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(isOn==false){
Cell p = (Cell)e.getSource();
if(p.alive==false){
p.setBackground(Color.BLACK);
p.setOpaque(true);
p.setText("X");
p.revalidate();
p.alive = true;
}
else{
p.setBackground(b1.getBackground());
p.setText("");
p.alive = false;
}
}
}
}
public class aboutButton implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Conway's Game of Life\n\n"
+ "It is a 'game' solely determined by its initial state\n"
+ "It follow some basic rules.\n"
+ "A cell has eight neighbors.\n"
+ "A cell is either alive or dead.\n"
+ "Any live cell with either 2 or 3 neighbors lives on.\n"
+ "Any live cell with < 2 neighbors dies.\n"
+ "Any live cell with > 3 neighbors dies.\n"
+ "Any dead cell with exactly 3 neighbors comes to life.\n"
+ "\nImagine a System in which"
+ "\nThe Play button starts the clycle and the algoritm and the stop button"
+ "\npauses the algoritm at which point the play button"
+ "Stop at N: Option allows the user to specify a specific "
+ "\nGeneration(N) at which the program will stop"
);/*"Conway's Game of Life:\n"
+ "\nImageine a System in which\nThe Play button starts the clycle and the algoritm and the stop button"
+ "\npauses the algoritm at which point the play button"
+ "Stop at N: Option allows the user to specify a specific "
+ "\nGeneration(N) at which the program will stop"
+ "\n");*/
}
}
public class AlgoPlay implements Runnable{
public void run() {
while(isOn){
algoritm();
if((Long.parseLong(t1.getText().substring(2)))==(Long.parseLong(t2.getText()))){
isOn = false;
break;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class playButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
sleep = Long.parseLong(t3.getText());
if(!isOn){
p2.setEnabled(false);
isOn = true;
if(begin){
begin = false;
downloadBored();
}
(new Thread(new AlgoPlay())).start();
//algoritm();
}
}
}
public void downloadBored(){
/*
for(int i=0;i<ini.length;i++){
System.out.println(manyS[i]);
}*/
//need to spit out to file
}
public void findFiles(){
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".gol");
}
});
if(matches.length>0){
s = new String[matches.length+1];
}
else{
s = new String[1];
}
s[0] = "--Select
for(int i=1;i<s.length;i++){
s[i] = matches[i-1].getName().replaceAll(".gol","");
}
for(int k=0;k<s.length;k++){
System.out.println(s[k]);
}
c1 = new JComboBox(s);
}
public void algoritm(){
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
if((i>0&&j>0)&&(i<(ppl.length-1)&&j<(ppl[0].length-1))){
if(ppl[i-1][j-1].alive==true){
count = count + 1;
}
if(ppl[i][j-1].alive==true){
count = count + 1;
}
if(ppl[i+1][j-1].alive==true){
count = count + 1;
}
if(ppl[i-1][j].alive==true){
count = count + 1;
}
if(ppl[i+1][j].alive==true){
count = count + 1;
}
if(ppl[i-1][j+1].alive==true){
count = count + 1;
}
if(ppl[i][j+1].alive==true){
count = count + 1;
}
if(ppl[i+1][j+1].alive==true){
count = count + 1;
}
}//first case - Without Wrapping
else if(i==0 && j==0){//Top-Right
if(ppl[ppl.length-1][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[0][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[1][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][0].alive==true){
count = count + 1;
}
if(ppl[1][0].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][1].alive==true){
count = count + 1;
}
if(ppl[0][1].alive==true){
count = count + 1;
}
if(ppl[1][1].alive==true){
count = count + 1;
}
}
else if(i>0 && j==0 && i<ppl.length-1){//Top-Mid
if(ppl[i-1][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[i][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[i+1][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[i-1][j].alive==true){
count = count + 1;
}
if(ppl[i+1][j].alive==true){
count = count + 1;
}
if(ppl[i-1][j+1].alive==true){
count = count + 1;
}
if(ppl[i][j+1].alive==true){
count = count + 1;
}
if(ppl[i+1][j+1].alive==true){
count = count + 1;
}
}
else if(i==ppl.length-1 && j==0){//Top-Left
if(ppl[i-1][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[i][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[0][ppl[0].length-1].alive==true){
count = count + 1;
}
if(ppl[i-1][0].alive==true){
count = count + 1;
}
if(ppl[0][0].alive==true){
count = count + 1;
}
if(ppl[i-1][1].alive==true){
count = count + 1;
}
if(ppl[i][1].alive==true){
count = count + 1;
}
if(ppl[0][1].alive==true){
count = count + 1;
}
}
else if(i==0&& j>0 && j < ppl[0].length-1){//Middle-Left
if(ppl[ppl.length-1][j-1].alive==true){
count = count + 1;
}
if(ppl[i][j-1].alive==true){
count = count + 1;
}
if(ppl[i+1][j-1].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][j].alive==true){
count = count + 1;
}
if(ppl[i+1][j].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][j+1].alive==true){
count = count + 1;
}
if(ppl[i][j+1].alive==true){
count = count + 1;
}
if(ppl[i+1][j+1].alive==true){
count = count + 1;
}
}
else if(i==(ppl.length-1)&& j>0 && j<ppl.length-1){//Middle-Right
if(ppl[i-1][j-1].alive==true){
count = count + 1;
}
if(ppl[i][j-1].alive==true){
count = count + 1;
}
if(ppl[0][j-1].alive==true){
count = count + 1;
}
if(ppl[i-1][j].alive==true){
count = count + 1;
}
if(ppl[0][j].alive==true){
count = count + 1;
}
if(ppl[i-1][j+1].alive==true){
count = count + 1;
}
if(ppl[i][j+1].alive==true){
count = count + 1;
}
if(ppl[0][j+1].alive==true){
count = count + 1;
}
}
else if(i==0 && j==(ppl[0].length-1)){//Bottom-Left
if(ppl[ppl.length-1][j-1].alive==true){
count = count + 1;
}
if(ppl[0][j-1].alive==true){
count = count + 1;
}
if(ppl[1][j-1].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][j].alive==true){
count = count + 1;
}
if(ppl[1][j].alive==true){
count = count + 1;
}
if(ppl[ppl.length-1][0].alive==true){
count = count + 1;
}
if(ppl[0][0].alive==true){
count = count + 1;
}
if(ppl[1][0].alive==true){
count = count + 1;
}
}
else if(j==(ppl[0].length-1) && i>0 && i<ppl.length-1){//Bottom-Mid
if(ppl[i-1][j-1].alive==true){
count = count + 1;
}
if(ppl[i][j-1].alive==true){
count = count + 1;
}
if(ppl[i+1][j-1].alive==true){
count = count + 1;
}
if(ppl[i-1][j].alive==true){
count = count + 1;
}
if(ppl[i+1][j].alive==true){
count = count + 1;
}
if(ppl[i-1][0].alive==true){
count = count + 1;
}
if(ppl[i][0].alive==true){
count = count + 1;
}
if(ppl[i+1][0].alive==true){
count = count + 1;
}
}
else if(i==(ppl.length-1)&&j==(ppl[0].length-1)){//Bottom-Right
if(ppl[i-1][j-1].alive==true){
count = count + 1;
}
if(ppl[i][j-1].alive==true){
count = count + 1;
}
if(ppl[0][j-1].alive==true){
count = count + 1;
}
if(ppl[i-1][j].alive==true){
count = count + 1;
}
if(ppl[0][j].alive==true){
count = count + 1;
}
if(ppl[i-1][0].alive==true){
count = count + 1;
}
if(ppl[i][0].alive==true){
count = count + 1;
}
if(ppl[0][0].alive==true){
count = count + 1;
}
}
if(ppl[i][j].alive==true){
if(count<2 || count>3){
ppl[i][j].setText("");
ppl[i][j].after = false;
}
else{
ppl[i][j].after = true;
}
}
else{
if(count==3){
ppl[i][j].after= true;
ppl[i][j].setText("X");
}
}
count = 0;
}//end of inner for-loop
}//end of nested for-loop
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
if(ppl[i][j].after){
ppl[i][j].alive=true;
ppl[i][j].after = false;
}
else{
ppl[i][j].alive=false;
ppl[i][j].after = false;
}
}
}
t1.setText("N="+((Long.parseLong(t1.getText().substring(2)))+1));
}
public class stopButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
isOn = false;
}
}
public class clearButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
isOn = false;
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
ppl[i][j].setText("");//TODO
ppl[i][j].alive = false;
ppl[i][j].after = false;
}
}
}
}
public class resetButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
(new clearButton()).actionPerformed(e);
t1.setText("N=0000");
begin = true;
}
}
public class saveButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(begin){
downloadBored();
}
else{
di = new JDialog ();
di.setModal (true);
di.setAlwaysOnTop (true);
di.setModalityType (ModalityType.APPLICATION_MODAL);
JPanel pi = new JPanel(new BorderLayout());
JPanel pi2 = new JPanel(new GridLayout(2,1));
JPanel pi3 = new JPanel(new GridLayout(5,1));
JPanel pi4 = new JPanel();
JPanel pi5 = new JPanel(new GridLayout(1,1));
JPanel pi6 = new JPanel(new GridLayout(1,1));
JLabel li1 = new JLabel("File Name:");
JLabel li2 = new JLabel("Broswer Path:");
JTextArea li3 = new JTextArea(""
+ "Chose to save the current state that your bored is in,\n"
+ " or save the intial state that, that yeild such wonderful\n"
+ "results!\n"
+ "\n"
+ "It is recamended to use the default path locations,\n"
+ " which is the realitive path to where the program\n"
+ "(Game of Life) is located\n"
+ "However, If you wish you can save files else where\n"
+ "You just have to import them using the import\n"
+ "feture\n"
+ "\n"
+ "Enjoy.");
ti1 = new JTextField("Example.gol");
ti2 = new JTextField("C:/PC/Example.gol");
JButton bi1 = new JButton("Browse");
JButton bi2 = new JButton("Save");
rb1 = new JRadioButton("Initial Bored",true);
rb2 = new JRadioButton("Current Bored");
rb3 = new JRadioButton("Realitive Path",true);
rb4 = new JRadioButton("Absolute Path");
radioChoice ActionList = new radioChoice();
rb3.addActionListener(ActionList);
rb4.addActionListener(ActionList);
bi1.addActionListener(new browserButton());
bi2.addActionListener(new saveWriter());
ButtonGroup g1 = new ButtonGroup();
ButtonGroup g2 = new ButtonGroup();
g1.add(rb1);
g1.add(rb2);
g2.add(rb3);
g2.add(rb4);
pi5.add(rb1);
pi5.add(rb2);
pi6.add(rb3);
pi6.add(rb4);
pi2.add(pi5);
pi2.add(pi6);
TitledBorder tit = BorderFactory.createTitledBorder("Save Options");
pi2.setBorder(tit);
TitledBorder tit2 = BorderFactory.createTitledBorder("Discription");
pi2.setBorder(tit2);
li3.setEditable(false);
li3.setBorder(tit2);
ti2.setEnabled(false);
li3.setBackground(b1.getBackground());
pi3.add(li1);
pi3.add(ti1);
pi3.add(li2);
pi3.add(ti2);
pi4.add(bi1);
pi4.add(bi2);
pi3.add(pi4);
pi.add(pi2,BorderLayout.NORTH);
pi.add(pi3,BorderLayout.CENTER);
pi.add(li3, BorderLayout.SOUTH);
di.add(pi);
di.setEnabled(true);
di.setLocationRelativeTo(null);
di.setSize(352,476);//340
di.setMinimumSize(new Dimension(352,476));
di.setVisible(true);
}
}
}
public void writeBored(){
try {
if(rb1.isSelected() || rb2.isSelected()){
FileOutputStream s = new FileOutputStream("design/"+ti1.getText());
s.write(ini);
s.close();
}
else{
FileOutputStream s = new FileOutputStream(ti2.getText());
s.write(ini);
s.close();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public class radioChoice implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(rb3.isSelected()){
ti2.setEnabled(false);
}
else if(rb4.isSelected()){
ti2.setEnabled(true);
}
}
}
public class browserButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(ti2.isEnabled()){
di.setAlwaysOnTop (false);
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
j.setDialogTitle("Select target directory");
int returnVal = j.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = j.getSelectedFile();
ti2.setText(file.getAbsolutePath()+"/"+ti1.getText());
} else {
System.out.print("Open command cancelled by user.");
}
di.setAlwaysOnTop (true);
}
}
}
public class saveWriter implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(rb1.isSelected()&&!ti2.isEnabled()){//Ini, rel
writeBored();
}
else if(rb1.isSelected()&&rb4.isSelected()){//Ini,abso
writeBored();
}
else if(rb2.isSelected()&&rb3.isSelected()){//Cur, rel
downloadBored();
writeBored();
}
else if(rb2.isSelected()&&rb4.isSelected()){//cur,absol
downloadBored();
writeBored();
}
findFiles();
reloadList();
di.dispose();
}
}
public class timeDelay implements ActionListener{
public void actionPerformed(ActionEvent e) {
sleep = Long.parseLong(t3.getText());
}
}
public class loadButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(c1.getSelectedIndex()!=0){
isOn = false;
System.out.println(c1.getSelectedItem().toString());
try {
FileInputStream in = new FileInputStream("design/"+c1.getSelectedItem().toString()+".gol");
in.read(ini);
in.close();
//convert byte->string binary
for(int i=0;i<ini.length;i++){
manyS[i] = String.format("%8s", Integer.toBinaryString(ini[i] & 0xFF)).replace(' ', '0');
//System.out.println(manyS[i]);
}
int m = 0, p=0, q=0;
for(int i=0;i<manyS.length;i++){
for(int j=0;j<manyS[i].length();j++){
m= i*8+j;
p = m/32;
q = m%32;
ppl[p][q].alive=true;
ppl[p][q].setText("X");
if(Integer.parseInt(""+manyS[i].charAt(j))==1){
ppl[p][q].alive=true;
ppl[p][q].setText("X");
}
else{
ppl[p][q].alive=false;
ppl[p][q].setText("");
}
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
//You deleated a file you BAD BOY!
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
|
package kryptografia;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Kryptografia extends JFrame {
private static JTextField kluczWejscie;
private static JTextArea textWyjscie, textWejscie, textStat, textKrypto, textWzorcowa;
private JScrollPane scrollText, scrollText2, scrollTextStat, scrollTextKrypto, scrollTextWzorcowa;
private JButton szyfrujPrzycisk, deszyfrujPrzycisk, kryptoanalizaPrzycisk, archiwumKluczyPrzycisk,
wczytajPrzycisk, autorzyPrzycisk, zapiszSzyfrPrzycisk, wczytajSzyfrPrzycisk, zamianaMiejscPrzycisk,
uzupelnijPrzycisk, wczytajWzorcowaPrzycisk, wygenerujWzorcowaPrzycisk, zapiszWzorcowaPrzycisk;
private PrzyciskSzyfruj obslugaSzyfruj;
private PrzyciskDeszyfruj obslugaDeszyfruj;
private PrzyciskKryptoanaliza obslugaKryptoanaliza;
private PrzyciskArchiwumKluczy obslugaArchiwumKluczy;
private PrzyciskWczytaj obslugaWczytaj;
private PrzyciskAutorzy obslugaAutorzy;
private PrzyciskZapiszSzyfr obslugaZapiszSzyfr;
private PrzyciskWczytajSzyfr obslugaWczytajSzyfr;
private PrzyciskZamianaMiejsc obslugaZamianaMiejsc;
private PrzyciskUzupelnij obslugaUzupelnij;
private PrzyciskWczytajWzorcowa obslugaWczytajWzorcowa;
private PrzyciskWygenerujWzorcowa obslugaWygenerujWzorcowa;
private PrzyciskZapiszWzorcowa obslugaZapiszWzorcowa;
private String kluczKryptoanaliza;
public Kryptografia() {
Container okno = getContentPane();
okno.setLayout(null);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Bład podczas ładowania wyglądu okna.");
}
this.setResizable(false);
textWejscie = new JTextArea("", 50, 895);
scrollText2 = new JScrollPane(textWejscie);
scrollText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWejscie.setLineWrap(true);
textWejscie.setWrapStyleWord(true);
scrollText2.setLocation(5, 52);
scrollText2.setSize(400, 180);
okno.add(scrollText2);
textStat = new JTextArea("", 800, 50);
scrollTextStat = new JScrollPane(textStat);
scrollTextStat.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textStat.setLineWrap(true);
textStat.setWrapStyleWord(true);
textStat.setEditable(false);
scrollTextStat.setLocation(410, 52);
scrollTextStat.setSize(180, 447);
okno.add(scrollTextStat);
textKrypto = new JTextArea("", 800, 50);
scrollTextKrypto = new JScrollPane(textKrypto);
scrollTextKrypto.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textKrypto.setLineWrap(true);
textKrypto.setWrapStyleWord(true);
scrollTextKrypto.setLocation(780, 52);
scrollTextKrypto.setSize(180, 447);
okno.add(scrollTextKrypto);
textWzorcowa = new JTextArea("", 800, 50);
scrollTextWzorcowa = new JScrollPane(textWzorcowa);
scrollTextWzorcowa.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWzorcowa.setLineWrap(true);
textWzorcowa.setWrapStyleWord(true);
textWzorcowa.setEditable(false);
scrollTextWzorcowa.setLocation(595, 52);
scrollTextWzorcowa.setSize(180, 447);
okno.add(scrollTextWzorcowa);
textWyjscie = new JTextArea("", 50, 895);
scrollText = new JScrollPane(textWyjscie);
scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWyjscie.setLineWrap(true);
textWyjscie.setWrapStyleWord(false);
//textWyjscie.setEditable(false);
scrollText.setLocation(5, 320);
scrollText.setSize(400, 180);
okno.add(scrollText);
kluczWejscie = new JTextField(3);
kluczWejscie.setLocation(115, 243);
kluczWejscie.setSize(200, 40);
okno.add(kluczWejscie);
szyfrujPrzycisk = new JButton("Szyfruj");
obslugaSzyfruj = new PrzyciskSzyfruj();
szyfrujPrzycisk.addActionListener(obslugaSzyfruj);
szyfrujPrzycisk.setLocation(5, 502);
szyfrujPrzycisk.setSize(150, 20);
okno.add(szyfrujPrzycisk);
deszyfrujPrzycisk = new JButton("Deszyfruj");
obslugaDeszyfruj = new PrzyciskDeszyfruj();
deszyfrujPrzycisk.addActionListener(obslugaDeszyfruj);
deszyfrujPrzycisk.setLocation(165, 502);
deszyfrujPrzycisk.setSize(150, 20);
okno.add(deszyfrujPrzycisk);
kryptoanalizaPrzycisk = new JButton("Start Kryptoanaliza");
obslugaKryptoanaliza = new PrzyciskKryptoanaliza();
kryptoanalizaPrzycisk.addActionListener(obslugaKryptoanaliza);
kryptoanalizaPrzycisk.setLocation(485, 502);
kryptoanalizaPrzycisk.setSize(150, 20);
okno.add(kryptoanalizaPrzycisk);
archiwumKluczyPrzycisk = new JButton("Archiwum kluczy");
obslugaArchiwumKluczy = new PrzyciskArchiwumKluczy();
archiwumKluczyPrzycisk.addActionListener(obslugaArchiwumKluczy);
archiwumKluczyPrzycisk.setLocation(325, 502);
archiwumKluczyPrzycisk.setSize(150, 20);
okno.add(archiwumKluczyPrzycisk);
zapiszSzyfrPrzycisk = new JButton("Zapisz szyfrogram");
obslugaZapiszSzyfr = new PrzyciskZapiszSzyfr();
zapiszSzyfrPrzycisk.addActionListener(obslugaZapiszSzyfr);
zapiszSzyfrPrzycisk.setLocation(165, 522);
zapiszSzyfrPrzycisk.setSize(150, 20);
okno.add(zapiszSzyfrPrzycisk);
wczytajSzyfrPrzycisk = new JButton("Wczytaj szyfrogram");
obslugaWczytajSzyfr = new PrzyciskWczytajSzyfr();
wczytajSzyfrPrzycisk.addActionListener(obslugaWczytajSzyfr);
wczytajSzyfrPrzycisk.setLocation(5, 522);
wczytajSzyfrPrzycisk.setSize(150, 20);
okno.add(wczytajSzyfrPrzycisk);
wczytajWzorcowaPrzycisk = new JButton("Wczytaj stat.wzorcową");
obslugaWczytajWzorcowa = new PrzyciskWczytajWzorcowa();
wczytajWzorcowaPrzycisk.addActionListener(obslugaWczytajWzorcowa);
wczytajWzorcowaPrzycisk.setLocation(325, 522);
wczytajWzorcowaPrzycisk.setSize(150, 20);
okno.add(wczytajWzorcowaPrzycisk);
wygenerujWzorcowaPrzycisk = new JButton("Wygeneruj stat.wzorcową");
obslugaWygenerujWzorcowa = new PrzyciskWygenerujWzorcowa();
wygenerujWzorcowaPrzycisk.addActionListener(obslugaWygenerujWzorcowa);
wygenerujWzorcowaPrzycisk.setLocation(645, 522);
wygenerujWzorcowaPrzycisk.setSize(150, 20);
okno.add(wygenerujWzorcowaPrzycisk);
zapiszWzorcowaPrzycisk = new JButton("Zapisz stat.wzorcową");
obslugaZapiszWzorcowa = new PrzyciskZapiszWzorcowa();
zapiszWzorcowaPrzycisk.addActionListener(obslugaZapiszWzorcowa);
zapiszWzorcowaPrzycisk.setLocation(485, 522);
zapiszWzorcowaPrzycisk.setSize(150, 20);
okno.add(zapiszWzorcowaPrzycisk);
wczytajPrzycisk = new JButton("Wczytaj");
obslugaWczytaj = new PrzyciskWczytaj();
wczytajPrzycisk.addActionListener(obslugaWczytaj);
wczytajPrzycisk.setLocation(320, 243);
wczytajPrzycisk.setSize(82, 20);
okno.add(wczytajPrzycisk);
uzupelnijPrzycisk = new JButton("Uzupełnij");
obslugaUzupelnij = new PrzyciskUzupelnij();
uzupelnijPrzycisk.addActionListener(obslugaUzupelnij);
uzupelnijPrzycisk.setLocation(320, 263);
uzupelnijPrzycisk.setSize(82, 20);
okno.add(uzupelnijPrzycisk);
autorzyPrzycisk = new JButton("Autorzy");
obslugaAutorzy = new PrzyciskAutorzy();
autorzyPrzycisk.addActionListener(obslugaAutorzy);
autorzyPrzycisk.setLocation(885, 0);
autorzyPrzycisk.setSize(80, 20);
okno.add(autorzyPrzycisk);
zamianaMiejscPrzycisk = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/resources/strzalki.png"));
zamianaMiejscPrzycisk.setIcon(new ImageIcon(img));
} catch (IOException ex) {
System.out.println("Problem z załadowaniem obrazka strzalki.png");
}
obslugaZamianaMiejsc = new PrzyciskZamianaMiejsc();
zamianaMiejscPrzycisk.addActionListener(obslugaZamianaMiejsc);
zamianaMiejscPrzycisk.setLocation(10, 250);
zamianaMiejscPrzycisk.setSize(20, 27);
okno.add(zamianaMiejscPrzycisk);
setTitle("Kryptografia");
Font czcionka = new Font("Courier New", Font.BOLD, 17);
JLabel tekst1 = new JLabel("Tekst jawny:", SwingConstants.LEFT);
tekst1.setSize(300, 20);
tekst1.setLocation(5, 30);
tekst1.setFont(czcionka);
okno.add(tekst1);
JLabel tekst2 = new JLabel("Klucz:", SwingConstants.LEFT);
tekst2.setSize(300, 20);
tekst2.setLocation(50, 255);
tekst2.setFont(czcionka);
okno.add(tekst2);
JLabel tekst3 = new JLabel("Charakt.szyfrogr.", SwingConstants.LEFT);
tekst3.setSize(300, 20);
tekst3.setLocation(410, 30);
tekst3.setFont(czcionka);
okno.add(tekst3);
JLabel tekst4 = new JLabel("Kryptoanaliza", SwingConstants.LEFT);
tekst4.setSize(300, 20);
tekst4.setLocation(780, 30);
tekst4.setFont(czcionka);
okno.add(tekst4);
JLabel tekst5 = new JLabel("Szyfrogram:", SwingConstants.LEFT);
tekst5.setSize(300, 20);
tekst5.setLocation(5, 298);
tekst5.setFont(czcionka);
okno.add(tekst5);
JLabel tekst6 = new JLabel("Stat.wzorcowa", SwingConstants.LEFT);
tekst6.setSize(300, 20);
tekst6.setLocation(595, 30);
tekst6.setFont(czcionka);
okno.add(tekst6);
setSize(980, 585);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public Kryptografia(String wybor) {
kluczWejscie.setText(wybor);
}
private class PrzyciskSzyfruj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText();
String klucz = kluczWejscie.getText();
klucz = dodajAlfabet(klucz.toUpperCase());
textWyjscie.setText("");
kluczWejscie.setText(klucz);
char[] tab_tresc = tresc.toUpperCase().toCharArray();
char[] tab_klucz = klucz.toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeAlfabet(tab_tresc[i]);
char szyfruj;
if (pozycja == -1) {
szyfruj = tab_tresc[i];
} else {
szyfruj = tab_klucz[pozycja];
}
textWyjscie.append(Character.toString(szyfruj));
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
if (!kluczWejscie.getText().isEmpty()) {
if (sprawdzCzyKluczSiePowtarza(kluczWejscie.getText()) == 1) {
zapiszDoPliku(kluczWejscie.getText().toUpperCase(), "klucze.txt", true);
}
}
}
}
private class PrzyciskDeszyfruj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText().trim();
String klucz = kluczWejscie.getText().replace("\r", "");
textWyjscie.setText("");
if (klucz.length() != 26) {
JOptionPane.showMessageDialog(null, "Podany klucz nie ma 26 znaków!\n"
+ "Wczytaj klucz z archiwum bądź popraw już wpisany.");
} else {
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
char[] tab_tresc = tresc.toUpperCase().toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeKlucz(tab_tresc[i], klucz);
char deszyfruj;
if (pozycja == -1) {
deszyfruj = tab_tresc[i];
} else {
deszyfruj = tab_alfabet[pozycja];
}
textWyjscie.append(Character.toString(deszyfruj));
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
}
}
}
private class PrzyciskKryptoanaliza implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String text = textKrypto.getText();
if (text.isEmpty()) {
String szablon = wygenerujSzablonKryptoanalizy();
textKrypto.setText(szablon);
} else {
pobierzZmianyKryptoanalizy(textKrypto.getText());
String wejscie = textWejscie.getText().toUpperCase();
if (!"".equals(wejscie)) {
String kryptoanaliza = kryptoanalizuj(wejscie);
char[] tab_wejscie = wejscie.toCharArray();
char[] tab_kryptoanaliza = kryptoanaliza.toCharArray();
kryptoanaliza = "";
for (int i = 0; i < tab_kryptoanaliza.length; i++) {
if (tab_wejscie[i] != tab_kryptoanaliza[i]) {
String pomoc = "";
pomoc += tab_kryptoanaliza[i];
kryptoanaliza += pomoc.toLowerCase();
} else {
kryptoanaliza += tab_kryptoanaliza[i];
}
}
textWyjscie.setText(kryptoanaliza);
}
}
}
}
private class PrzyciskArchiwumKluczy implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucze = wczytajZpliku("klucze.txt");
new Archiwum(klucze);
}
}
private class PrzyciskAutorzy implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Autorzy:"
+ "\n- Goniprowski Mateusz"
+ "\n- Niesłuchowski Kamil"
+ "\n- Załuska Paweł");
}
}
private class PrzyciskWczytaj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucze = wczytajZpliku("klucze.txt");
String[] tab_klucze = klucze.split("\n");
String ostatniKlucz = tab_klucze[tab_klucze.length - 1];
kluczWejscie.setText(ostatniKlucz);
}
}
private class PrzyciskZapiszSzyfr implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("zapisz");
if (plik != null) {
zapiszDoPliku(textWyjscie.getText(), plik, false);
}
}
}
private class PrzyciskWczytajSzyfr implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
String text = "";
if (plik != null) {
text = wczytajZpliku(plik);
textWejscie.setText(text);
}
}
}
private class PrzyciskZamianaMiejsc implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String pomoc = textWejscie.getText();
textWejscie.setText(textWyjscie.getText());
textWyjscie.setText(pomoc);
}
}
private class PrzyciskUzupelnij implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucz = kluczWejscie.getText();
klucz = dodajAlfabet(klucz.toUpperCase());
kluczWejscie.setText(klucz);
}
}
private class PrzyciskWczytajWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
if (plik != null) {
String text = wczytajZpliku(plik);
textWzorcowa.setText(text);
}
}
}
private class PrzyciskWygenerujWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
if (plik != null) {
String text = wczytajZpliku(plik);
String charakterystyka = wyznaczCharakterystyke(text.toUpperCase());
textWzorcowa.setText(charakterystyka);
}
}
}
private class PrzyciskZapiszWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("zapisz");
if (plik != null) {
zapiszDoPliku(textWzorcowa.getText(), plik, false);
}
}
}
public String dodajAlfabet(String klucz) {
String wymieszanyAlfabet = wymieszajAlfabet(pobierzAlfabet());
char[] tab_wymieszanyAlfabet = wymieszanyAlfabet.toCharArray();
char[] znaki = klucz.toCharArray();
for (int i = 0; i < tab_wymieszanyAlfabet.length; i++) {
boolean poprawnosc = false;
for (int j = 0; j < znaki.length; j++) {
if (znaki[j] == tab_wymieszanyAlfabet[i]) {
poprawnosc = true;
break;
}
}
if (!poprawnosc) {
klucz += tab_wymieszanyAlfabet[i];
}
}
return klucz;
}
/**
* Miesza litery w alfabecie
*
* @param text
* @return
*/
static String wymieszajAlfabet(String text) {
if (text.length() <= 1) {
return text;
}
int split = text.length() / 2;
String temp1 = wymieszajAlfabet(text.substring(0, split));
String temp2 = wymieszajAlfabet(text.substring(split));
if (Math.random() > 0.5) {
return temp1 + temp2;
} else {
return temp2 + temp1;
}
}
public int sprawdzPozycjeAlfabet(char znak) {
int pozycja = 0;
boolean czyZnaleziono = false;
for (char ch = 'A'; ch <= 'Z'; ++ch) {
if (ch == znak) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if (czyZnaleziono) {
return pozycja;
} else {
return -1;
}
}
public int sprawdzPozycjeKlucz(char znak, String klucz) {
char[] tab_klucz = klucz.toCharArray();
int pozycja = 0;
boolean czyZnaleziono = false;
for (int i = 0; i < klucz.length(); i++) {
if (znak == tab_klucz[i]) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if (czyZnaleziono) {
return pozycja;
} else {
return -1;
}
}
/**
* Pobiera alfabet i zapisuje do stringa
*
* @return
*/
public String pobierzAlfabet() {
String alfabet = "";
for (char ch = 'A'; ch <= 'Z'; ++ch) {
alfabet += ch;
}
return alfabet;
}
public String wyznaczCharakterystyke(String text) {
String charakterystyka = "";
for (char ch = 'A'; ch <= 'Z'; ++ch) {
charakterystyka += ch;
charakterystyka += " = ";
int ilosc = policzWystapienia(text, ch);
float srednia = (float) ilosc / (float) text.length();
charakterystyka += Integer.toString(ilosc);
charakterystyka += " (";
charakterystyka += Float.toString(srednia);
charakterystyka += ")";
charakterystyka += '\n';
}
int[] tab_pozycji = sortujCharakterystyke(charakterystyka);
String[] tab_charakterystyka = charakterystyka.split("\n");
charakterystyka = "";
for (int i = 0; i < tab_charakterystyka.length; i++) {
charakterystyka += tab_charakterystyka[tab_pozycji[i]];
charakterystyka += '\n';
}
return charakterystyka;
}
public int policzWystapienia(String text, char znak) {
int wystapienia = 0;
char[] tab_text = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
if (tab_text[i] == znak) {
wystapienia++;
}
}
return wystapienia;
}
/**
* Generuje szablon kryptoanalizy
*
* @return
*/
public String wygenerujSzablonKryptoanalizy() {
String szablon = "";
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
kluczKryptoanaliza = pobierzAlfabet();
char[] tab_kluczKryptoanaliza = kluczKryptoanaliza.toCharArray();
for (int i = 0; i < kluczKryptoanaliza.length(); i++) {
szablon += tab_alfabet[i];
szablon += " => ";
szablon += tab_kluczKryptoanaliza[i];
szablon += "\n";
}
return szablon;
}
/**
* Pobiera zmiany z szablonu kryptoanalizy do klucza
*
* @param szablon
*/
public void pobierzZmianyKryptoanalizy(String szablon) {
String[] tab_szablon = szablon.split(" => ");
kluczKryptoanaliza = "";
for (int i = 1; i < tab_szablon.length; i++) {
kluczKryptoanaliza += tab_szablon[i].substring(0, 1);
}
}
public String kryptoanalizuj(String text) {
char[] tab_kluczKryptografia = kluczKryptoanaliza.toCharArray();
char[] tab_text = text.toCharArray();
String krypto = "";
for (int i = 0; i < text.length(); i++) {
int pozycja = sprawdzPozycjeAlfabet(tab_text[i]);
if (pozycja == -1) {
krypto += tab_text[i];
} else {
krypto += tab_kluczKryptografia[pozycja];
}
}
return krypto;
}
/**
* Wczytuje z pliku
*
* @param nazwaPliku
* @return
*/
public String wczytajZpliku(String nazwaPliku) {
File plik = new File(nazwaPliku);
StringBuilder zawartosc = new StringBuilder();
BufferedReader czytnik = null;
try {
czytnik = new BufferedReader(new FileReader(plik));
String text = null;
while ((text = czytnik.readLine()) != null) {
zawartosc.append(text).append(System.getProperty("line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (czytnik != null) {
czytnik.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return zawartosc.toString();
}
/**
* Zapisuje do pliku
*
* @param text
* @param nazwaPliku
* @param CzyDopisacDoPliku
*/
public void zapiszDoPliku(String text, String nazwaPliku, Boolean CzyDopisacDoPliku) {
try {
PrintWriter zapis = new PrintWriter(new FileOutputStream(
new File(nazwaPliku),
CzyDopisacDoPliku));
zapis.println(text);
zapis.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
/**
* Sprawdza przed zapisem do pliku czy dany klucz istnieje w archiwum
*
* @param klucz
* @return
*/
public int sprawdzCzyKluczSiePowtarza(String klucz) {
String archiwum = wczytajZpliku("klucze.txt");
String[] tab_archiwum = archiwum.split("\\r?\\n");
klucz = klucz.replace("\r", "");
for (String tab_archiwum1 : tab_archiwum) {
if (tab_archiwum1.equals(klucz.toUpperCase())) {
return 0;
}
}
return 1;
}
private String wczytajSciezkePlikuZdysku(String opcja) {
JFileChooser fc = new JFileChooser();
int dialog = 0;
if ("wczytaj".equals(opcja)) {
dialog = fc.showOpenDialog(this);
} else {
dialog = fc.showSaveDialog(this);
}
if (dialog == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile().getAbsolutePath();
} else {
return null;
}
}
private int[] sortujCharakterystyke(String charakterystyka) {
String[] tab = charakterystyka.split(" = ");
String[] inty = new String[26];
int[] tab_inty = new int[26];
int[] tab_inty2 = new int[26];
int[] tab_pozycje = new int[26];
for (int i = 1; i < tab.length; i++) {
for (int j = 1; true; j++) {
if (tab[i].toString().substring(j, j + 1).indexOf(" ") == 0) {
inty[i - 1] = tab[i].toString().substring(0, j);
break;
}
}
tab_inty[i - 1] = Integer.parseInt(inty[i - 1]);
tab_inty2[i - 1] = Integer.parseInt(inty[i - 1]);
}
for (int i = 0; i < tab_inty.length; i++) {
for (int j = 0; j < tab_inty.length - 1; j++) {
if (tab_inty[j] > tab_inty[j + 1]) {
int temp = tab_inty[j + 1];
tab_inty[j + 1] = tab_inty[j];
tab_inty[j] = temp;
}
}
}
// wyznaczanie pozycji
int k = 0;
for (int i = tab_inty.length - 1; i >= 0; i
for (int j = 0; j < tab_inty2.length; j++) {
if (tab_inty[i] == tab_inty2[j]) {
tab_pozycje[k++] = j;
tab_inty2[j] = -1;
break;
}
}
}
return tab_pozycje;
}
/**
* Main
*
* @param args
*/
public static void main(String[] args) {
Kryptografia obiekt = new Kryptografia();
obiekt.setLocationRelativeTo(null);
}
}
|
package outbackcdx;
import org.junit.*;
import org.junit.rules.TemporaryFolder;
import outbackcdx.auth.Permit;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static outbackcdx.NanoHTTPD.Method.*;
import static outbackcdx.NanoHTTPD.Response.Status.OK;
import static outbackcdx.NanoHTTPD.Response.Status.UNAUTHORIZED;
public class ReplicationFeaturesTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private Webapp webapp;
private DataStore manager;
@Before
public void setUp() throws IOException {
File root = folder.newFolder();
manager = new DataStore(root, 0);
webapp = new Webapp(manager, false, Collections.emptyMap());
}
@After
public void tearDown() {
}
// tests for replication features:
// ensure that write urls are disabled on secondary
// ensure that we can retrieve a sequenceNumber on secondary
// ensure that we can delete WALs on primary
@Test
public void testReadOnly() throws Exception {
FeatureFlags.setSecondaryMode(true);
// make a request to a write-able url
// it should 401.
POST("/test", "- 20050614070159 http:
FeatureFlags.setSecondaryMode(false);
}
@Test
public void testSequenceNumber() throws Exception {
FeatureFlags.setSecondaryMode(false);
// post some CDX
POST("/testa", "- 20050614070159 http:
// get the sequenceNumber, should be 1
String output = GET("/testa/sequence", OK);
assertEquals("2", output);
FeatureFlags.setSecondaryMode(false);
}
private String GET(String url, NanoHTTPD.Response.Status expectedStatus) throws Exception {
ReplicationFeaturesTest.DummySession session = new ReplicationFeaturesTest.DummySession(GET, url);
NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full()));
assertEquals(expectedStatus, response.getStatus());
return slurp(response);
}
private String GET(String url, NanoHTTPD.Response.Status expectedStatus, String... parmKeysAndValues) throws Exception {
ReplicationFeaturesTest.DummySession session = new ReplicationFeaturesTest.DummySession(GET, url);
for (int i = 0; i < parmKeysAndValues.length; i += 2) {
session.parm(parmKeysAndValues[i], parmKeysAndValues[i + 1]);
}
NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full()));
assertEquals(expectedStatus, response.getStatus());
return slurp(response);
}
private String DELETE(String url, NanoHTTPD.Response.Status expectedStatus) throws Exception {
ReplicationFeaturesTest.DummySession session = new ReplicationFeaturesTest.DummySession(DELETE, url);
NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full()));
assertEquals(expectedStatus, response.getStatus());
return slurp(response);
}
private String POST(String url, String data, NanoHTTPD.Response.Status expectedStatus) throws Exception {
ReplicationFeaturesTest.DummySession session = new ReplicationFeaturesTest.DummySession(POST, url);
session.data(data);
NanoHTTPD.Response response = webapp.handle(new Web.NRequest(session, Permit.full()));
assertEquals(expectedStatus, response.getStatus());
return slurp(response);
}
private String slurp(NanoHTTPD.Response response) throws IOException {
NanoHTTPD.IStreamer streamer = response.getStreamer();
if (streamer != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
streamer.stream(out);
return out.toString("UTF-8");
}
InputStream data = response.getData();
if (data != null) {
Scanner scanner = new Scanner(response.getData(), "UTF-8").useDelimiter("\\Z");
if (scanner.hasNext()) {
return scanner.next();
}
}
return "";
}
private static class DummySession implements NanoHTTPD.IHTTPSession {
private final NanoHTTPD.Method method;
InputStream stream = new ByteArrayInputStream(new byte[0]);
Map<String, String> parms = new HashMap<String, String>();
String url;
public DummySession(NanoHTTPD.Method method, String url) {
this.url = url;
this.method = method;
}
public ReplicationFeaturesTest.DummySession data(String data) {
stream = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
return this;
}
public ReplicationFeaturesTest.DummySession parm(String key, String value) {
parms.put(key, value);
return this;
}
@Override
public void execute() throws IOException {
// nothing
}
@Override
public Map<String, String> getParms() {
return parms;
}
@Override
public Map<String, String> getHeaders() {
return Collections.emptyMap();
}
@Override
public String getUri() {
return url;
}
@Override
public String getQueryParameterString() {
return "";
}
@Override
public NanoHTTPD.Method getMethod() {
return method;
}
@Override
public InputStream getInputStream() {
return stream;
}
}
}
|
package kryptografia;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class Kryptografia extends JFrame {
private static JTextField kluczWejscie;
private static JTextArea textWejscie, textStat, textKrypto, textWzorcowa;
private static JTextPane textWyjscie;
private JScrollPane scrollText, scrollText2, scrollTextStat, scrollTextKrypto, scrollTextWzorcowa;
private JButton szyfrujPrzycisk, deszyfrujPrzycisk, kryptoanalizaPrzycisk, archiwumKluczyPrzycisk,
wczytajPrzycisk, autorzyPrzycisk, zapiszSzyfrPrzycisk, wczytajSzyfrPrzycisk, zamianaMiejscPrzycisk,
uzupelnijPrzycisk, wczytajWzorcowaPrzycisk, wygenerujWzorcowaPrzycisk, zapiszWzorcowaPrzycisk, zakonczPrzycisk;
private PrzyciskSzyfruj obslugaSzyfruj;
private PrzyciskDeszyfruj obslugaDeszyfruj;
private PrzyciskKryptoanaliza obslugaKryptoanaliza;
private PrzyciskArchiwumKluczy obslugaArchiwumKluczy;
private PrzyciskWczytaj obslugaWczytaj;
private PrzyciskAutorzy obslugaAutorzy;
private PrzyciskZapiszSzyfr obslugaZapiszSzyfr;
private PrzyciskWczytajSzyfr obslugaWczytajSzyfr;
private PrzyciskZamianaMiejsc obslugaZamianaMiejsc;
private PrzyciskUzupelnij obslugaUzupelnij;
private PrzyciskWczytajWzorcowa obslugaWczytajWzorcowa;
private PrzyciskWygenerujWzorcowa obslugaWygenerujWzorcowa;
private PrzyciskZapiszWzorcowa obslugaZapiszWzorcowa;
private PrzyciskZakoncz oblugaZakoncz;
private String kluczKryptoanaliza;
public Kryptografia() {
Container okno = getContentPane();
okno.setLayout(null);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Bład podczas ładowania wyglądu okna.");
}
this.setResizable(false);
textWejscie = new JTextArea("", 50, 895);
scrollText2 = new JScrollPane(textWejscie);
scrollText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWejscie.setLineWrap(true);
textWejscie.setWrapStyleWord(true);
scrollText2.setLocation(5, 52);
scrollText2.setSize(400, 180);
okno.add(scrollText2);
textStat = new JTextArea("", 800, 50);
scrollTextStat = new JScrollPane(textStat);
scrollTextStat.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textStat.setLineWrap(true);
textStat.setWrapStyleWord(true);
textStat.setEditable(false);
scrollTextStat.setLocation(410, 52);
scrollTextStat.setSize(180, 447);
okno.add(scrollTextStat);
textKrypto = new JTextArea("", 800, 50);
scrollTextKrypto = new JScrollPane(textKrypto);
scrollTextKrypto.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textKrypto.setLineWrap(true);
textKrypto.setWrapStyleWord(true);
scrollTextKrypto.setLocation(780, 52);
scrollTextKrypto.setSize(180, 447);
okno.add(scrollTextKrypto);
textWzorcowa = new JTextArea("", 800, 50);
scrollTextWzorcowa = new JScrollPane(textWzorcowa);
scrollTextWzorcowa.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWzorcowa.setLineWrap(true);
textWzorcowa.setWrapStyleWord(true);
textWzorcowa.setEditable(false);
scrollTextWzorcowa.setLocation(595, 52);
scrollTextWzorcowa.setSize(180, 447);
okno.add(scrollTextWzorcowa);
//textWyjscie = new JTextPane(50, 895);
textWyjscie = new JTextPane();
textWyjscie.setLocation(50, 895);
scrollText = new JScrollPane(textWyjscie);
scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// textWyjscie.setLineWrap(true);
// textWyjscie.setWrapStyleWord(false);
//textWyjscie.setEditable(false);
scrollText.setLocation(5, 320);
scrollText.setSize(400, 180);
okno.add(scrollText);
kluczWejscie = new JTextField(3);
kluczWejscie.setLocation(115, 243);
kluczWejscie.setSize(200, 40);
okno.add(kluczWejscie);
szyfrujPrzycisk = new JButton("Szyfruj");
obslugaSzyfruj = new PrzyciskSzyfruj();
szyfrujPrzycisk.addActionListener(obslugaSzyfruj);
szyfrujPrzycisk.setLocation(5, 502);
szyfrujPrzycisk.setSize(150, 20);
okno.add(szyfrujPrzycisk);
deszyfrujPrzycisk = new JButton("Deszyfruj");
obslugaDeszyfruj = new PrzyciskDeszyfruj();
deszyfrujPrzycisk.addActionListener(obslugaDeszyfruj);
deszyfrujPrzycisk.setLocation(165, 502);
deszyfrujPrzycisk.setSize(150, 20);
okno.add(deszyfrujPrzycisk);
kryptoanalizaPrzycisk = new JButton("Start Kryptoanaliza");
obslugaKryptoanaliza = new PrzyciskKryptoanaliza();
kryptoanalizaPrzycisk.addActionListener(obslugaKryptoanaliza);
kryptoanalizaPrzycisk.setLocation(485, 502);
kryptoanalizaPrzycisk.setSize(150, 20);
okno.add(kryptoanalizaPrzycisk);
archiwumKluczyPrzycisk = new JButton("Archiwum kluczy");
obslugaArchiwumKluczy = new PrzyciskArchiwumKluczy();
archiwumKluczyPrzycisk.addActionListener(obslugaArchiwumKluczy);
archiwumKluczyPrzycisk.setLocation(325, 502);
archiwumKluczyPrzycisk.setSize(150, 20);
okno.add(archiwumKluczyPrzycisk);
zapiszSzyfrPrzycisk = new JButton("Zapisz szyfrogram");
obslugaZapiszSzyfr = new PrzyciskZapiszSzyfr();
zapiszSzyfrPrzycisk.addActionListener(obslugaZapiszSzyfr);
zapiszSzyfrPrzycisk.setLocation(165, 522);
zapiszSzyfrPrzycisk.setSize(150, 20);
okno.add(zapiszSzyfrPrzycisk);
wczytajSzyfrPrzycisk = new JButton("Wczytaj szyfrogram");
obslugaWczytajSzyfr = new PrzyciskWczytajSzyfr();
wczytajSzyfrPrzycisk.addActionListener(obslugaWczytajSzyfr);
wczytajSzyfrPrzycisk.setLocation(5, 522);
wczytajSzyfrPrzycisk.setSize(150, 20);
okno.add(wczytajSzyfrPrzycisk);
wczytajWzorcowaPrzycisk = new JButton("Wczytaj stat.wzorcową");
wczytajWzorcowaPrzycisk.setToolTipText("Wczytaj statystykę wzorcową");
obslugaWczytajWzorcowa = new PrzyciskWczytajWzorcowa();
wczytajWzorcowaPrzycisk.addActionListener(obslugaWczytajWzorcowa);
wczytajWzorcowaPrzycisk.setLocation(325, 522);
wczytajWzorcowaPrzycisk.setSize(150, 20);
okno.add(wczytajWzorcowaPrzycisk);
wygenerujWzorcowaPrzycisk = new JButton("Wygeneruj stat.wzorcową");
wygenerujWzorcowaPrzycisk.setToolTipText("Wygeneruj statystykę wzorcową");
obslugaWygenerujWzorcowa = new PrzyciskWygenerujWzorcowa();
wygenerujWzorcowaPrzycisk.addActionListener(obslugaWygenerujWzorcowa);
wygenerujWzorcowaPrzycisk.setLocation(645, 522);
wygenerujWzorcowaPrzycisk.setSize(200, 20);
okno.add(wygenerujWzorcowaPrzycisk);
zapiszWzorcowaPrzycisk = new JButton("Zapisz stat.wzorcową");
zapiszWzorcowaPrzycisk.setToolTipText("Zapisz statystykę wzorcową");
obslugaZapiszWzorcowa = new PrzyciskZapiszWzorcowa();
zapiszWzorcowaPrzycisk.addActionListener(obslugaZapiszWzorcowa);
zapiszWzorcowaPrzycisk.setLocation(485, 522);
zapiszWzorcowaPrzycisk.setSize(150, 20);
okno.add(zapiszWzorcowaPrzycisk);
wczytajPrzycisk = new JButton("Wczytaj");
obslugaWczytaj = new PrzyciskWczytaj();
wczytajPrzycisk.addActionListener(obslugaWczytaj);
wczytajPrzycisk.setLocation(320, 243);
wczytajPrzycisk.setSize(82, 20);
okno.add(wczytajPrzycisk);
uzupelnijPrzycisk = new JButton("Uzupełnij");
obslugaUzupelnij = new PrzyciskUzupelnij();
uzupelnijPrzycisk.addActionListener(obslugaUzupelnij);
uzupelnijPrzycisk.setLocation(320, 263);
uzupelnijPrzycisk.setSize(82, 20);
okno.add(uzupelnijPrzycisk);
autorzyPrzycisk = new JButton("Autorzy");
obslugaAutorzy = new PrzyciskAutorzy();
autorzyPrzycisk.addActionListener(obslugaAutorzy);
autorzyPrzycisk.setLocation(880, 5);
autorzyPrzycisk.setSize(80, 20);
okno.add(autorzyPrzycisk);
zakonczPrzycisk = new JButton("Zakończ");
zakonczPrzycisk.setToolTipText("Wyjdź z programu");
oblugaZakoncz = new PrzyciskZakoncz();
zakonczPrzycisk.addActionListener(oblugaZakoncz);
zakonczPrzycisk.setLocation(880, 500);
zakonczPrzycisk.setSize(80, 40);
zakonczPrzycisk.setForeground(Color.RED);
okno.add(zakonczPrzycisk);
zamianaMiejscPrzycisk = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/resources/strzalki.png"));
zamianaMiejscPrzycisk.setIcon(new ImageIcon(img));
} catch (IOException ex) {
System.out.println("Problem z załadowaniem obrazka strzalki.png");
}
obslugaZamianaMiejsc = new PrzyciskZamianaMiejsc();
zamianaMiejscPrzycisk.addActionListener(obslugaZamianaMiejsc);
zamianaMiejscPrzycisk.setLocation(10, 250);
zamianaMiejscPrzycisk.setSize(20, 27);
okno.add(zamianaMiejscPrzycisk);
setTitle("Kryptografia");
Font czcionka = new Font("Courier New", Font.BOLD, 17);
JLabel tekst1 = new JLabel("Tekst jawny:", SwingConstants.LEFT);
tekst1.setSize(300, 20);
tekst1.setLocation(5, 30);
tekst1.setFont(czcionka);
okno.add(tekst1);
JLabel tekst2 = new JLabel("Klucz:", SwingConstants.LEFT);
tekst2.setSize(300, 20);
tekst2.setLocation(50, 255);
tekst2.setFont(czcionka);
okno.add(tekst2);
JLabel tekst3 = new JLabel("Charakt.szyfrogr.", SwingConstants.LEFT);
tekst3.setSize(300, 20);
tekst3.setLocation(410, 30);
tekst3.setFont(czcionka);
okno.add(tekst3);
JLabel tekst4 = new JLabel("Kryptoanaliza", SwingConstants.LEFT);
tekst4.setSize(300, 20);
tekst4.setLocation(780, 30);
tekst4.setFont(czcionka);
okno.add(tekst4);
JLabel tekst5 = new JLabel("Szyfrogram:", SwingConstants.LEFT);
tekst5.setSize(300, 20);
tekst5.setLocation(5, 298);
tekst5.setFont(czcionka);
okno.add(tekst5);
JLabel tekst6 = new JLabel("Stat.wzorcowa", SwingConstants.LEFT);
tekst6.setSize(300, 20);
tekst6.setLocation(595, 30);
tekst6.setFont(czcionka);
okno.add(tekst6);
setSize(980, 585);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public Kryptografia(String wybor) {
kluczWejscie.setText(wybor);
}
private void appendToPane(JTextPane tp, String msg, Color c)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
tp.replaceSelection(msg);
}
private class PrzyciskSzyfruj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText();
String klucz = kluczWejscie.getText();
if(textWejscie.getText().length() == 0){
JOptionPane.showMessageDialog(null, "Brak wpisanego tekstu jawnego !!!", "Brak tekstu jawnego" , JOptionPane.ERROR_MESSAGE);
return ;
}
if(kluczWejscie.getText().length() == 0){
JOptionPane.showMessageDialog(null, "Brak wpisanego klucza !!!", "Brak klucza" , JOptionPane.ERROR_MESSAGE);
return ;
}
klucz = dodajAlfabet(klucz.toUpperCase());
textWyjscie.setText("");
kluczWejscie.setText(klucz);
char[] tab_tresc = tresc.toCharArray();
char[] tab_klucz = klucz.toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeAlfabet(tab_tresc[i]);
char szyfruj;
if (pozycja == -1) {
szyfruj = tab_tresc[i];
} else {
szyfruj = tab_klucz[pozycja];
}
// textWyjscie.append(Character.toString(szyfruj));
appendToPane(textWyjscie, (Character.toString(szyfruj)), Color.black);
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
if (!kluczWejscie.getText().isEmpty()) {
if (sprawdzCzyKluczSiePowtarza(kluczWejscie.getText()) == 1) {
zapiszDoPliku(kluczWejscie.getText().toUpperCase(), "klucze.txt", true);
}
}
}
}
private class PrzyciskDeszyfruj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText().trim();
String klucz = kluczWejscie.getText().replace("\r", "");
textWyjscie.setText("");
if (klucz.length() != 26) {
JOptionPane.showMessageDialog(null, "Podany klucz nie ma 26 znaków!\n"
+ "Wczytaj klucz z archiwum bądź popraw już wpisany.", "Błąd klucza", JOptionPane.ERROR_MESSAGE);
} else {
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
char[] tab_tresc = tresc.toUpperCase().toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeKlucz(tab_tresc[i], klucz);
char deszyfruj;
if (pozycja == -1) {
deszyfruj = tab_tresc[i];
} else {
deszyfruj = tab_alfabet[pozycja];
}
// textWyjscie.append(Character.toString(deszyfruj));
appendToPane(textWyjscie, (Character.toString(deszyfruj)), Color.black);
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
}
}
}
private class PrzyciskKryptoanaliza implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
textWyjscie.setText("");
String text = textKrypto.getText();
if (text.isEmpty()) {
String szablon = wygenerujSzablonKryptoanalizy();
textKrypto.setText(szablon);
} else {
pobierzZmianyKryptoanalizy(textKrypto.getText());
String wejscie = textWejscie.getText().toUpperCase();
if (!"".equals(wejscie)) {
String kryptoanaliza = kryptoanalizuj(wejscie);
char[] tab_wejscie = wejscie.toCharArray();
char[] tab_kryptoanaliza = kryptoanaliza.toCharArray();
kryptoanaliza = "";
for (int i = 0; i < tab_kryptoanaliza.length; i++) {
if (tab_wejscie[i] != tab_kryptoanaliza[i]) {
appendToPane(textWyjscie, "" + tab_kryptoanaliza[i], Color.red);
} else {
appendToPane(textWyjscie, "" + tab_kryptoanaliza[i], Color.black);
}
}
// textWyjscie.setText(kryptoanaliza);
}
}
}
}
private class PrzyciskArchiwumKluczy implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucze = wczytajZpliku("klucze.txt");
new Archiwum(klucze);
}
}
private class PrzyciskAutorzy implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"- Goniprowski Mateusz"
+ "\n- Niesłuchowski Kamil"
+ "\n- Załuska Paweł", "Autorzy",JOptionPane.INFORMATION_MESSAGE);
}
}
private class PrzyciskZakoncz implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private class PrzyciskWczytaj implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucze = wczytajZpliku("klucze.txt");
String[] tab_klucze = klucze.split("\n");
String ostatniKlucz = tab_klucze[tab_klucze.length - 1];
kluczWejscie.setText(ostatniKlucz);
}
}
private class PrzyciskZapiszSzyfr implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("zapisz");
if (plik != null) {
zapiszDoPliku(textWyjscie.getText(), plik, false);
}
}
}
private class PrzyciskWczytajSzyfr implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
String text = "";
if (plik != null) {
text = wczytajZpliku(plik);
textWejscie.setText(text);
}
}
}
private class PrzyciskZamianaMiejsc implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String pomoc = textWejscie.getText();
textWejscie.setText(textWyjscie.getText());
textWyjscie.setText(pomoc);
}
}
private class PrzyciskUzupelnij implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String klucz = kluczWejscie.getText();
klucz = dodajAlfabet(klucz.toUpperCase());
kluczWejscie.setText(klucz);
}
}
private class PrzyciskWczytajWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
if (plik != null) {
String text = wczytajZpliku(plik);
textWzorcowa.setText(text);
}
}
}
private class PrzyciskWygenerujWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("wczytaj");
if (plik != null) {
String text = wczytajZpliku(plik);
String charakterystyka = wyznaczCharakterystyke(text.toUpperCase());
textWzorcowa.setText(charakterystyka);
}
}
}
private class PrzyciskZapiszWzorcowa implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String plik = wczytajSciezkePlikuZdysku("zapisz");
if (plik != null) {
zapiszDoPliku(textWzorcowa.getText(), plik, false);
}
}
}
public String dodajAlfabet(String klucz) {
String wymieszanyAlfabet = wymieszajAlfabet(pobierzAlfabet());
char[] tab_wymieszanyAlfabet = wymieszanyAlfabet.toCharArray();
char[] znaki = klucz.toCharArray();
for (int i = 0; i < tab_wymieszanyAlfabet.length; i++) {
boolean poprawnosc = false;
for (int j = 0; j < znaki.length; j++) {
if (znaki[j] == tab_wymieszanyAlfabet[i]) {
poprawnosc = true;
break;
}
}
if (!poprawnosc) {
klucz += tab_wymieszanyAlfabet[i];
}
}
return klucz;
}
/**
* Miesza litery w alfabecie
*
* @param text
* @return
*/
static String wymieszajAlfabet(String text) {
if (text.length() <= 1) {
return text;
}
int split = text.length() / 2;
String temp1 = wymieszajAlfabet(text.substring(0, split));
String temp2 = wymieszajAlfabet(text.substring(split));
if (Math.random() > 0.5) {
return temp1 + temp2;
} else {
return temp2 + temp1;
}
}
public int sprawdzPozycjeAlfabet(char znak) {
int pozycja = 0;
boolean czyZnaleziono = false;
for (char ch = 'A'; ch <= 'Z'; ++ch) {
if (ch == znak) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if (czyZnaleziono) {
return pozycja;
} else {
return -1;
}
}
public int sprawdzPozycjeKlucz(char znak, String klucz) {
char[] tab_klucz = klucz.toCharArray();
int pozycja = 0;
boolean czyZnaleziono = false;
for (int i = 0; i < klucz.length(); i++) {
if (znak == tab_klucz[i]) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if (czyZnaleziono) {
return pozycja;
} else {
return -1;
}
}
/**
* Pobiera alfabet i zapisuje do stringa
*
* @return
*/
public String pobierzAlfabet() {
String alfabet = "";
for (char ch = 'A'; ch <= 'Z'; ++ch) {
alfabet += ch;
}
return alfabet;
}
public String wyznaczCharakterystyke(String text) {
String charakterystyka = "";
for (char ch = 'A'; ch <= 'Z'; ++ch) {
charakterystyka += ch;
charakterystyka += " = ";
int ilosc = policzWystapienia(text, ch);
float srednia = (float) ilosc / (float) text.length();
charakterystyka += Integer.toString(ilosc);
charakterystyka += " (";
charakterystyka += Float.toString(srednia);
charakterystyka += ")";
charakterystyka += '\n';
}
int[] tab_pozycji = sortujCharakterystyke(charakterystyka);
String[] tab_charakterystyka = charakterystyka.split("\n");
charakterystyka = "";
for (int i = 0; i < tab_charakterystyka.length; i++) {
charakterystyka += tab_charakterystyka[tab_pozycji[i]];
charakterystyka += '\n';
}
return charakterystyka;
}
public int policzWystapienia(String text, char znak) {
int wystapienia = 0;
char[] tab_text = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
if (tab_text[i] == znak) {
wystapienia++;
}
}
return wystapienia;
}
/**
* Generuje szablon kryptoanalizy
*
* @return
*/
public String wygenerujSzablonKryptoanalizy() {
String szablon = "";
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
kluczKryptoanaliza = pobierzAlfabet();
char[] tab_kluczKryptoanaliza = kluczKryptoanaliza.toCharArray();
for (int i = 0; i < kluczKryptoanaliza.length(); i++) {
szablon += tab_alfabet[i];
szablon += " => ";
szablon += tab_kluczKryptoanaliza[i];
szablon += "\n";
}
return szablon;
}
/**
* Pobiera zmiany z szablonu kryptoanalizy do klucza
*
* @param szablon
*/
public void pobierzZmianyKryptoanalizy(String szablon) {
String[] tab_szablon = szablon.split(" => ");
kluczKryptoanaliza = "";
for (int i = 1; i < tab_szablon.length; i++) {
kluczKryptoanaliza += tab_szablon[i].substring(0, 1);
}
}
public String kryptoanalizuj(String text) {
char[] tab_kluczKryptografia = kluczKryptoanaliza.toCharArray();
char[] tab_text = text.toCharArray();
String krypto = "";
for (int i = 0; i < text.length(); i++) {
int pozycja = sprawdzPozycjeAlfabet(tab_text[i]);
if (pozycja == -1) {
krypto += tab_text[i];
} else {
krypto += tab_kluczKryptografia[pozycja];
}
}
return krypto;
}
/**
* Wczytuje z pliku
*
* @param nazwaPliku
* @return
*/
public String wczytajZpliku(String nazwaPliku) {
File plik = new File(nazwaPliku);
StringBuilder zawartosc = new StringBuilder();
BufferedReader czytnik = null;
try {
czytnik = new BufferedReader(new FileReader(plik));
String text = null;
while ((text = czytnik.readLine()) != null) {
zawartosc.append(text).append(System.getProperty("line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (czytnik != null) {
czytnik.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return zawartosc.toString();
}
/**
* Zapisuje do pliku
*
* @param text
* @param nazwaPliku
* @param CzyDopisacDoPliku
*/
public void zapiszDoPliku(String text, String nazwaPliku, Boolean CzyDopisacDoPliku) {
try {
PrintWriter zapis = new PrintWriter(new FileOutputStream(
new File(nazwaPliku),
CzyDopisacDoPliku));
zapis.println(text);
zapis.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
/**
* Sprawdza przed zapisem do pliku czy dany klucz istnieje w archiwum
*
* @param klucz
* @return
*/
public int sprawdzCzyKluczSiePowtarza(String klucz) {
String archiwum = wczytajZpliku("klucze.txt");
String[] tab_archiwum = archiwum.split("\\r?\\n");
klucz = klucz.replace("\r", "");
for (String tab_archiwum1 : tab_archiwum) {
if (tab_archiwum1.equals(klucz.toUpperCase())) {
return 0;
}
}
return 1;
}
private String wczytajSciezkePlikuZdysku(String opcja) {
JFileChooser fc = new JFileChooser();
int dialog = 0;
if ("wczytaj".equals(opcja)) {
dialog = fc.showOpenDialog(this);
} else {
dialog = fc.showSaveDialog(this);
}
if (dialog == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile().getAbsolutePath();
} else {
return null;
}
}
private int[] sortujCharakterystyke(String charakterystyka) {
String[] tab = charakterystyka.split(" = ");
String[] inty = new String[26];
int[] tab_inty = new int[26];
int[] tab_inty2 = new int[26];
int[] tab_pozycje = new int[26];
for (int i = 1; i < tab.length; i++) {
for (int j = 1; true; j++) {
if (tab[i].toString().substring(j, j + 1).indexOf(" ") == 0) {
inty[i - 1] = tab[i].toString().substring(0, j);
break;
}
}
tab_inty[i - 1] = Integer.parseInt(inty[i - 1]);
tab_inty2[i - 1] = Integer.parseInt(inty[i - 1]);
}
for (int i = 0; i < tab_inty.length; i++) {
for (int j = 0; j < tab_inty.length - 1; j++) {
if (tab_inty[j] > tab_inty[j + 1]) {
int temp = tab_inty[j + 1];
tab_inty[j + 1] = tab_inty[j];
tab_inty[j] = temp;
}
}
}
// wyznaczanie pozycji
int k = 0;
for (int i = tab_inty.length - 1; i >= 0; i
for (int j = 0; j < tab_inty2.length; j++) {
if (tab_inty[i] == tab_inty2[j]) {
tab_pozycje[k++] = j;
tab_inty2[j] = -1;
break;
}
}
}
return tab_pozycje;
}
/**
* Main
*
* @param args
*/
public static void main(String[] args) {
Kryptografia obiekt = new Kryptografia();
obiekt.setLocationRelativeTo(null);
}
}
|
package com.ayvytr.easyandroid.tools.withcontext;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.annotation.ArrayRes;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import com.ayvytr.easyandroid.Easy;
import com.ayvytr.easyandroid.exception.UnsupportedInitializationException;
public class ResTool
{
ResTool()
{
throw new UnsupportedInitializationException();
}
/**
* Drawable
*
* @param id Drawableid
* @return Drawable
*/
public static Drawable getDrawable(@DrawableRes int id)
{
//ContextCompat
return ContextCompat.getDrawable(Easy.getContext(), id);
}
/**
* String
*
* @param id Stringid
* @return String
*/
public static String getString(@StringRes int id)
{
return Easy.getContext().getString(id);
}
/**
* String
*
* @param id String id
* @param args
* @return String
*/
public static String getString(@StringRes int id, Object... args)
{
return Easy.getContext().getString(id, args);
}
/**
* Dimension
*
* @param id id
* @return
*/
public static int getDimen(@DimenRes int id)
{
return (int) getDimenFloat(id);
}
/**
* Dimensionfloat
*
* @param id id
* @return
*/
public static float getDimenFloat(@DimenRes int id)
{
return getResources().getDimension(id);
}
/**
* Dimension
*
* @param id id
* @return dp
*/
public static int getDimenToDp(@DimenRes int id)
{
return (int) getDimenFloat(id);
}
/**
* Dimensionfloat
*
* @param id id
* @return dp
*/
public static float getDimenFloatToDp(@DimenRes int id)
{
return DensityTool.px2dp(Easy.getContext().getResources().getDimension(id));
}
/**
* Color
*
* @param id id
* @return
*/
public static int getColor(@ColorRes int id)
{
return ContextCompat.getColor(Easy.getContext(), id);
}
/**
* Configuration
*
* @return Configuration
*/
public static Configuration getConfiguration()
{
return getResources().getConfiguration();
}
/**
* Resources
*
* @return Resources
*/
public static Resources getResources()
{
return Easy.getContext().getResources();
}
/**
* String array.
*
* @param id resource id
* @return String array
*/
public static String[] getStringArray(@ArrayRes int id)
{
return getResources().getStringArray(id);
}
/**
* int array.
*
* @param id resource id
* @return int array
*/
public static int[] getIntArray(@ArrayRes int id)
{
return getResources().getIntArray(id);
}
/**
* text id.
*
* @param id resource id
* @return text array
*/
public static CharSequence[] getTextArray(@ArrayRes int id)
{
return getResources().getTextArray(id);
}
}
|
package org.exist.dom;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.collections.IndexInfo;
import org.exist.collections.CollectionConfigurationManager;
import org.exist.security.SecurityManager;
import org.exist.security.xacml.AccessContext;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.ElementValue;
import org.exist.storage.serializers.Serializer;
import org.exist.storage.txn.TransactionManager;
import org.exist.storage.txn.Txn;
import org.exist.util.Configuration;
import org.exist.util.DatabaseConfigurationException;
import org.exist.util.XMLFilenameFilter;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.AncestorSelector;
import org.exist.xquery.ChildSelector;
import org.exist.xquery.Constants;
import org.exist.xquery.DescendantOrSelfSelector;
import org.exist.xquery.DescendantSelector;
import org.exist.xquery.NameTest;
import org.exist.xquery.NodeSelector;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQuery;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.NodeValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test basic {@link org.exist.dom.NodeSet} operations to ensure that
* the used algorithms are correct.
*
* @author wolf
*
*/
public class BasicNodeSetTest {
private final static String NESTED_XML =
"<section n='1'>" +
"<section n='1.1'>" +
"<section n='1.1.1'>" +
"<para n='1.1.1.1'/>" +
"<para n='1.1.1.2'/>" +
"<para n='1.1.1.3'/>" +
"</section>" +
"<section n='1.1.2'>" +
"<para n='1.1.2.1'/>" +
"</section>" +
"</section>" +
"<section n='1.2'>" +
"<para n='1.2.1'/>" +
"</section>" +
"</section>";
private static String COLLECTION_CONFIG1 =
"<collection xmlns=\"http://exist-db.org/collection-config/1.0\">" +
" <index>" +
" <fulltext default=\"none\">" +
" <create qname=\"LINE\"/>" +
" <create qname=\"SPEAKER\"/>" +
" <create qname=\"TITLE\"/>" +
" </fulltext>" +
" </index>" +
"</collection>";
private static String directory = "samples/shakespeare";
//private static File dir = new File(directory);
private static File dir = null;
static {
String existHome = System.getProperty("exist.home");
File existDir = existHome==null ? new File(".") : new File(existHome);
dir = new File(existDir,directory);
}
private static BrokerPool pool = null;
private static Collection root = null;
private static DBBroker broker = null;
private static Sequence seqSpeech = null;
@Test
public void childSelector() throws XPathException {
NodeSelector selector = new ChildSelector(seqSpeech.toNodeSet(), -1);
NameTest test = new NameTest(Type.ELEMENT, new QName("LINE", ""));
NodeSet set = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);
assertEquals(9492, set.getLength());
}
@Test
public void descendantOrSelfSelector() throws XPathException {
NodeSelector selector = new DescendantOrSelfSelector(seqSpeech.toNodeSet(), -1);
NameTest test = new NameTest(Type.ELEMENT, new QName("SPEECH", ""));
NodeSet set = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);
assertEquals(2628, set.getLength());
}
@Test
public void ancestorSelector() throws XPathException {
NodeSelector selector = new AncestorSelector(seqSpeech.toNodeSet(), -1, false, true);
NameTest test = new NameTest(Type.ELEMENT, new QName("ACT", ""));
NodeSet set = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);
assertEquals(15, set.getLength());
}
@Test
public void ancestorSelector_self() throws XPathException {
NodeSet ns = seqSpeech.toNodeSet();
NodeSelector selector = new AncestorSelector(ns, -1, true, true);
NameTest test = new NameTest(Type.ELEMENT, new QName("SPEECH", ""));
NodeSet set = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT, seqSpeech.getDocumentSet(), test.getName(), selector);
assertEquals(2628, set.getLength());
}
@Test
public void descendantSelector() throws XPathException, SAXException {
Sequence seq = executeQuery(broker, "//SCENE", 72, null);
NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
NodeSelector selector = new DescendantSelector(seq.toNodeSet(), -1);
NodeSet set = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT, seq.getDocumentSet(), test.getName(), selector);
assertEquals(2639, set.getLength());
}
@Test
public void testAxes() throws XPathException, SAXException {
Serializer serializer = broker.getSerializer();
serializer.reset();
DocumentSet docs = root.allDocs(broker, new DefaultDocumentSet(), true, false);
Sequence smallSet = executeQuery(broker, "//SPEECH[LINE &= 'perturbed spirit']", 1, null);
Sequence largeSet = executeQuery(broker, "//SPEECH[LINE &= 'love']", 160, null);
Sequence outerSet = executeQuery(broker, "//SCENE[TITLE &= 'closet']", 1, null);
NameTest test = new NameTest(Type.ELEMENT, new QName("SPEAKER", ""));
NodeSet speakers = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
System.out.println("Testing NodeSetHelper.selectParentChild ...");
NodeSet result = NodeSetHelper.selectParentChild(speakers, smallSet.toNodeSet(), NodeSet.DESCENDANT, -1);
assertEquals(1, result.getLength());
String value = serialize(broker, result.itemAt(0));
System.out.println("NodeSetHelper.selectParentChild: " + value);
assertEquals(value, "<SPEAKER>HAMLET</SPEAKER>");
result = NodeSetHelper.selectParentChild(speakers, largeSet.toNodeSet(), NodeSet.DESCENDANT, -1);
assertEquals(160, result.getLength());
System.out.println("NodeSetHelper.selectParentChild: PASS");
System.out.println("Testing AbstractNodeSet.selectAncestorDescendant ...");
result = speakers.selectAncestorDescendant(outerSet.toNodeSet(), NodeSet.DESCENDANT, false, -1, true);
assertEquals(56, result.getLength());
System.out.println("AbstractNodeSet.selectAncestorDescendant: PASS");
System.out.println("Testing AbstractNodeSet.selectAncestorDescendant2 ...");
result = ((AbstractNodeSet)outerSet).selectAncestorDescendant(outerSet.toNodeSet(), NodeSet.DESCENDANT,
true, -1, true);
assertEquals(1, result.getLength());
System.out.println("AbstractNodeSet.selectAncestorDescendant2: PASS");
System.out.println("Testing AbstractNodeSet.getParents ...");
result = ((AbstractNodeSet)largeSet).getParents(-1);
assertEquals(49, result.getLength());
System.out.println("AbstractNodeSet.getParents: PASS");
test = new NameTest(Type.ELEMENT, new QName("SCENE", ""));
NodeSet scenes = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
scenes.getLength();
System.out.println("Testing AbstractNodeSet.selectAncestors ...");
result = ((AbstractNodeSet)scenes).selectAncestors(largeSet.toNodeSet(), false, -1);
assertEquals(47, result.getLength());
System.out.println("AbstractNodeSet.selectAncestors: PASS");
NodeProxy proxy = (NodeProxy) smallSet.itemAt(0);
System.out.println("Testing NodeProxy.getParents ...");
result = proxy.getParents(-1);
assertEquals(1, result.getLength());
System.out.println("NodeProxy.getParents: PASS");
result = speakers.selectParentChild(proxy, NodeSet.DESCENDANT, -1);
assertEquals(1, result.getLength());
largeSet = executeQuery(broker, "//SPEECH[LINE &= 'love']/SPEAKER", 160, null);
test = new NameTest(Type.ELEMENT, new QName("LINE", ""));
NodeSet lines = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
System.out.println("LINE: " + lines.getLength());
System.out.println("SPEAKER: " + largeSet.getItemCount());
result = ((AbstractNodeSet) lines).selectFollowingSiblings(largeSet.toNodeSet(), -1);
assertEquals(1451, result.getLength());
largeSet = executeQuery(broker, "//SPEECH[LINE &= 'love']/LINE[1]", 160, null);
result = ((AbstractNodeSet) speakers).selectPrecedingSiblings(largeSet.toNodeSet(), -1);
assertEquals(160, result.getLength());
System.out.println("Testing ExtArrayNodeSet.selectParentChild ...");
Sequence nestedSet = executeQuery(broker, "//section[@n = ('1.1', '1.1.1')]", 2, null);
test = new NameTest(Type.ELEMENT, new QName("para", ""));
NodeSet children = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
result = children.selectParentChild(nestedSet.toNodeSet(), NodeSet.DESCENDANT);
assertEquals(3, result.getLength());
nestedSet = executeQuery(broker, "//section[@n = ('1.1', '1.1.2', '1.2')]", 3, null);
result = children.selectParentChild(nestedSet.toNodeSet(), NodeSet.DESCENDANT);
assertEquals(2, result.getLength());
nestedSet = executeQuery(broker, "//section[@n = ('1.1', '1.1.1', '1.2')]", 3, null);
result = children.selectParentChild(nestedSet.toNodeSet(), NodeSet.DESCENDANT);
assertEquals(4, result.getLength());
nestedSet = executeQuery(broker, "//para[@n = ('1.1.2.1')]", 1, null);
test = new NameTest(Type.ELEMENT, new QName("section", ""));
NodeSet sections = broker.getElementIndex().findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
result = ((NodeSet) nestedSet).selectParentChild(sections.toNodeSet(), NodeSet.DESCENDANT);
assertEquals(1, result.getLength());
}
@Test
public void testOptimizations() throws XPathException, SAXException {
Serializer serializer = broker.getSerializer();
serializer.reset();
DocumentSet docs = root.allDocs(broker, new DefaultDocumentSet(), true, false);
System.out.println("
// parent set: 1.1.1; child set: 1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.2.1, 1.2.1
ExtNodeSet nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1.1']", 1, null);
NodeSet children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT,
new QName("para", ""), Constants.CHILD_AXIS, docs, nestedSet, -1);
assertEquals(3, children.getLength());
// parent set: 1.1; child set: 1.1.1, 1.1.2
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT,
new QName("section", ""), Constants.CHILD_AXIS, docs, nestedSet, -1);
assertEquals(2, children.getLength());
// parent set: 1, 1.1, 1.1.1, 1.1.2 ; child set: 1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.2.1, 1.2.1
// problem: ancestor set contains nested nodes
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = ('1.1', '1.1.1', '1.1.2')]", 3, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT,
new QName("para", ""), Constants.CHILD_AXIS, docs, nestedSet, -1);
assertEquals(4, children.getLength());
// parent set: 1.1, 1.1.2, 1.2 ; child set: 1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.2.1, 1.2.1
// problem: ancestor set contains nested nodes
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = ('1.1', '1.1.2', '1.2')]", 3, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT, new QName("para", ""),
Constants.CHILD_AXIS, docs, nestedSet, -1);
assertEquals(2, children.getLength());
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT, new QName("para", ""),
Constants.DESCENDANT_AXIS, docs, nestedSet, -1);
assertEquals(4, children.getLength());
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT, new QName("para", ""),
Constants.DESCENDANT_AXIS, docs, nestedSet, -1);
assertEquals(5, children.getLength());
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1.2']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ELEMENT, new QName("section", ""),
Constants.DESCENDANT_SELF_AXIS, docs, nestedSet, -1);
assertEquals(1, children.getLength());
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1.2']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ATTRIBUTE, new QName("n", ""),
Constants.ATTRIBUTE_AXIS, docs, nestedSet, -1);
assertEquals(1, children.getLength());
nestedSet = (ExtNodeSet) executeQuery(broker, "//section[@n = '1.1']", 1, null);
children =
broker.getElementIndex().findDescendantsByTagName(ElementValue.ATTRIBUTE, new QName("n", ""),
Constants.DESCENDANT_ATTRIBUTE_AXIS, docs, nestedSet, -1);
assertEquals(7, children.getLength());
System.out.println("
}
@Test
public void virtualNodeSet() throws XPathException, SAXException {
Serializer serializer = broker.getSerializer();
serializer.reset();
executeQuery(broker, "//*/LINE", 9492, null);
executeQuery(broker, "//*/LINE/*", 61, null);
executeQuery(broker, "//*/LINE/text()", 9485, null);
executeQuery(broker, "//SCENE/*/LINE", 9464, null);
executeQuery(broker, "//SCENE/*/LINE[. &= 'the']", 2167, null);
|
package fi.harism.curl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.opengl.GLUtils;
/**
* Class implementing actual curl.
*
* @author harism
*/
public class CurlMesh {
private static final boolean DRAW_HELPERS = false;
private static final boolean DRAW_POLYGON_OUTLINES = false;
private static final float[] SHADOW_INNER_COLOR = { 0f, 0f, 0f, .7f };
private static final float[] SHADOW_OUTER_COLOR = { 0f, 0f, 0f, 0f };
private static final double BACKFACE_ALPHA = .4f;
private static final double FRONTFACE_ALPHA = 1f;
private boolean mSwapAlpha = false;
// For testing purposes.
private int mHelperLinesCount;
private FloatBuffer mHelperLines;
// Buffers for feeding rasterizer.
private FloatBuffer mVertices;
private FloatBuffer mTexCoords;
private FloatBuffer mColors;
private int mVerticesCountFront;
private int mVerticesCountBack;
private FloatBuffer mShadowColors;
private FloatBuffer mShadowVertices;
private int mDropShadowCount;
private int mSelfShadowCount;
private int mMaxCurlSplits;
private Vertex[] mRectangle = new Vertex[4];
private int[] mTextureIds;
private Bitmap mBitmap;
/**
* Constructor for mesh object.
*
* @param rect
* Rect for the surface.
* @param texRect
* Texture coordinates.
* @param maxCurlSplits
* Maximum number curl can be divided into.
*/
public CurlMesh(int maxCurlSplits) {
mMaxCurlSplits = maxCurlSplits;
for (int i = 0; i < 4; ++i) {
mRectangle[i] = new Vertex();
}
if (DRAW_HELPERS) {
mHelperLinesCount = 3;
ByteBuffer hvbb = ByteBuffer
.allocateDirect(mHelperLinesCount * 2 * 2 * 4);
hvbb.order(ByteOrder.nativeOrder());
mHelperLines = hvbb.asFloatBuffer();
mHelperLines.position(0);
}
int maxVerticesCount = 4 + 2 * mMaxCurlSplits;
ByteBuffer vbb = ByteBuffer.allocateDirect(maxVerticesCount * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mVertices = vbb.asFloatBuffer();
mVertices.position(0);
ByteBuffer tbb = ByteBuffer.allocateDirect(maxVerticesCount * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexCoords = tbb.asFloatBuffer();
mTexCoords.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(maxVerticesCount * 4 * 4);
cbb.order(ByteOrder.nativeOrder());
mColors = cbb.asFloatBuffer();
mColors.position(0);
int maxShadowVerticesCount = (mMaxCurlSplits + 1) * 2 * 2;
ByteBuffer scbb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 4 * 4);
scbb.order(ByteOrder.nativeOrder());
mShadowColors = scbb.asFloatBuffer();
mShadowColors.position(0);
ByteBuffer sibb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 2 * 4);
sibb.order(ByteOrder.nativeOrder());
mShadowVertices = sibb.asFloatBuffer();
mShadowVertices.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Curl calculation.
*
* @param curlPos
* Position for curl center.
* @param directionVec
* Curl direction.
* @param radius
* Radius of curl.
*/
public synchronized void curl(PointF curlPos, PointF directionVec,
double radius) {
// First add some 'helper' lines used for development.
if (DRAW_HELPERS) {
mHelperLines.position(0);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y - 1.0f);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y + 1.0f);
mHelperLines.put(curlPos.x - 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + directionVec.x * 2);
mHelperLines.put(curlPos.y + directionVec.y * 2);
mHelperLines.position(0);
}
// Actual 'curl' implementation starts here.
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Calculate curl direction.
double curlAngle = Math.acos(directionVec.x);
curlAngle = directionVec.y > 0 ? -curlAngle : curlAngle;
// Initiate rotated 'rectangle' which's is translated to curlPos and
// rotated so that curl direction heads to (1,0).
Vector<Vertex> rotatedVertices = new Vector<Vertex>();
for (int i = 0; i < 4; ++i) {
Vertex v = new Vertex(mRectangle[i]);
v.translate(-curlPos.x, -curlPos.y);
v.rotateZ(-curlAngle);
int j = 0;
for (; j < rotatedVertices.size(); ++j) {
Vertex v2 = rotatedVertices.elementAt(j);
// We want to test for equality but rotating messes this unless
// we check against certain error margin instead.
double errormargin = 0.001f;
if (Math.abs(v.mPosX - v2.mPosX) <= errormargin
&& v.mPosY < v2.mPosY) {
break;
}
if (Math.abs(v.mPosX - v2.mPosX) > errormargin
&& v.mPosX > v2.mPosX) {
break;
}
}
rotatedVertices.add(j, v);
}
mVerticesCountFront = mVerticesCountBack = 0;
Vector<ShadowVertex> dropShadowVertices = new Vector<ShadowVertex>();
Vector<ShadowVertex> selfShadowVertices = new Vector<ShadowVertex>();
// Our rectangle lines/vertex indices.
int lines[] = { 0, 1, 2, 0, 3, 1, 3, 2 };
// Length of 'curl' curve.
double curlLength = Math.PI * radius;
// Calculate scan lines.
Vector<Double> scanLines = new Vector<Double>();
if (mMaxCurlSplits > 0) {
scanLines.add((double) 0);
}
for (int i = 1; i < mMaxCurlSplits; ++i) {
scanLines.add((-curlLength * i) / (mMaxCurlSplits - 1));
}
scanLines.add(rotatedVertices.elementAt(3).mPosX - 1);
// Start from right most vertex.
double scanXmax = rotatedVertices.elementAt(0).mPosX + 1;
Vector<Vertex> out = new Vector<Vertex>();
for (int i = 0; i < scanLines.size(); ++i) {
double scanXmin = scanLines.elementAt(i);
// First iterate vertices within scan area.
for (int j = 0; j < rotatedVertices.size(); ++j) {
Vertex v = rotatedVertices.elementAt(j);
if (v.mPosX >= scanXmin && v.mPosX < scanXmax) {
Vertex n = new Vertex(v);
out.add(n);
}
}
// Search for line intersections.
for (int j = 0; j < lines.length; j += 2) {
Vertex v1 = rotatedVertices.elementAt(lines[j]);
Vertex v2 = rotatedVertices.elementAt(lines[j + 1]);
if ((v1.mPosX > scanXmin && v2.mPosX < scanXmin)
|| (v2.mPosX > scanXmin && v1.mPosX < scanXmin)) {
Vertex n = new Vertex(v2);
n.mPosX = scanXmin;
double c = (scanXmin - v2.mPosX) / (v1.mPosX - v2.mPosX);
n.mPosY += (v1.mPosY - v2.mPosY) * c;
n.mTexX += (v1.mTexX - v2.mTexX) * c;
n.mTexY += (v1.mTexY - v2.mTexY) * c;
out.add(n);
}
}
// Add vertices to out buffers.
while (out.size() > 0) {
Vertex v = out.remove(0);
// Untouched vertices.
if (i == 0) {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA : FRONTFACE_ALPHA;
mVerticesCountFront++;
}
// 'Completely' rotated vertices.
else if (i == scanLines.size() - 1 || radius == 0) {
v.mPosX = -(curlLength + v.mPosX);
v.mPosZ = 2 * radius;
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA : BACKFACE_ALPHA;
mVerticesCountBack++;
}
// Vertex lies within 'curl'.
else {
double rotY = Math.PI / 2;
rotY -= Math.PI * (v.mPosX / curlLength);
// rotY = -rotY;
v.mPosX = radius * Math.cos(rotY);
v.mPosZ = radius + (radius * -Math.sin(rotY));
v.mColor = Math.sqrt(Math.cos(rotY) + 1);
if (v.mPosZ >= radius) {
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA
: BACKFACE_ALPHA;
mVerticesCountBack++;
} else {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
mVerticesCountFront++;
}
}
// Rotate vertex back to 'world' coordinates.
v.rotateZ(curlAngle);
v.translate(curlPos.x, curlPos.y);
addVertex(v);
// Drop shadow is cast 'behind' the curl.
if (v.mPosZ > 0 && v.mPosZ <= radius) {
// TODO: There is some overlapping in some cases, not all
// vertices should be added to shadow.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = (v.mPosZ / 4) * -directionVec.x;
sv.mPenumbraY = (v.mPosZ / 4) * -directionVec.y;
int idx = (dropShadowVertices.size() + 1) / 2;
dropShadowVertices.add(idx, sv);
}
// Self shadow is cast partly over mesh.
if (v.mPosZ > radius) {
// TODO: Shadow penumbra direction is not good, shouldn't be
// calculated using only directionVec.
ShadowVertex sv = new ShadowVertex();
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = ((v.mPosZ - radius) / 4) * directionVec.x;
sv.mPenumbraY = ((v.mPosZ - radius) / 4) * directionVec.y;
int idx = (selfShadowVertices.size() + 1) / 2;
selfShadowVertices.add(idx, sv);
}
}
scanXmax = scanXmin;
}
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
// Add shadow Vertices.
mShadowColors.position(0);
mShadowVertices.position(0);
mDropShadowCount = 0;
for (int i = 0; i < dropShadowVertices.size(); ++i) {
ShadowVertex sv = dropShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mDropShadowCount += 2;
}
mSelfShadowCount = 0;
for (int i = 0; i < selfShadowVertices.size(); ++i) {
ShadowVertex sv = selfShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mSelfShadowCount += 2;
}
mShadowColors.position(0);
mShadowVertices.position(0);
}
/**
* Draw our mesh.
*/
public synchronized void draw(GL10 gl) {
// First allocate texture if there is not one yet.
if (mTextureIds == null) {
// Generate texture.
mTextureIds = new int[1];
gl.glGenTextures(1, mTextureIds, 0);
// Set texture attributes.
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
}
// If mBitmap != null we have new texture.
if (mBitmap != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, Bitmap
.createScaledBitmap(mBitmap,
getNextHighestPO2(mBitmap.getWidth()),
getNextHighestPO2(mBitmap.getHeight()), true), 0);
mBitmap = null;
}
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
// Some 'global' settings.
gl.glEnable(GL10.GL_BLEND);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
// Enable texture coordinates.
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoords);
// Enable color array.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColors);
// Draw blank / 'white' front facing vertices.
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw front facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw blank / 'white' back facing vertices.
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
// Draw back facing texture.
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
gl.glDisable(GL10.GL_TEXTURE_2D);
// Disable textures and color array.
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (DRAW_POLYGON_OUTLINES || DRAW_HELPERS) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL10.GL_LINE_SMOOTH);
gl.glLineWidth(1.0f);
}
if (DRAW_POLYGON_OUTLINES) {
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, mVerticesCountFront);
}
if (DRAW_HELPERS) {
gl.glColor4f(1.0f, 0.5f, 0.5f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mHelperLines);
gl.glDrawArrays(GL10.GL_LINES, 0, mHelperLinesCount * 2);
}
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mShadowVertices);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mDropShadowCount);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mDropShadowCount,
mSelfShadowCount);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
/**
* Resets mesh to 'initial' state.
*/
public synchronized void reset() {
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
for (int i = 0; i < 4; ++i) {
addVertex(mRectangle[i]);
}
mVerticesCountFront = 4;
mVerticesCountBack = 0;
mVertices.position(0);
mTexCoords.position(0);
mColors.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Sets new texture for this mesh.
*/
public void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}
/**
* Update mesh bounds.
*/
public synchronized void setRect(RectF r) {
mRectangle[0].mPosX = r.left;
mRectangle[0].mPosY = r.top;
mRectangle[1].mPosX = r.left;
mRectangle[1].mPosY = r.bottom;
mRectangle[2].mPosX = r.right;
mRectangle[2].mPosY = r.top;
mRectangle[3].mPosX = r.right;
mRectangle[3].mPosY = r.bottom;
}
/**
* Update texture bounds.
*/
public synchronized void setTexRect(RectF r) {
mRectangle[0].mTexX = r.left;
mRectangle[0].mTexY = r.top;
mRectangle[1].mTexX = r.left;
mRectangle[1].mTexY = r.bottom;
mRectangle[2].mTexX = r.right;
mRectangle[2].mTexY = r.top;
mRectangle[3].mTexX = r.right;
mRectangle[3].mTexY = r.bottom;
mSwapAlpha = r.left > r.right;
for (int i = 0; i < 4; ++i) {
mRectangle[i].mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
}
}
/**
* Adds vertex to buffers.
*/
private void addVertex(Vertex vertex) {
mVertices.put((float) vertex.mPosX);
mVertices.put((float) vertex.mPosY);
mVertices.put((float) vertex.mPosZ);
mTexCoords.put((float) vertex.mTexX);
mTexCoords.put((float) vertex.mTexY);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mAlpha);
}
/**
* Calculates the next highest power of two for a given integer.
*
* @param n
* the number
* @return a power of two equal to or higher than n
*/
private int getNextHighestPO2(int n) {
n -= 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
n = n | (n >> 32);
return n + 1;
}
/**
* Holder for shadow vertex information.
*/
private class ShadowVertex {
public double mPosX;
public double mPosY;
public double mPenumbraX;
public double mPenumbraY;
}
/**
* Holder for vertex information.
*/
private class Vertex {
public double mPosX;
public double mPosY;
public double mPosZ;
public double mTexX;
public double mTexY;
public double mColor;
public double mAlpha;
public Vertex() {
mPosX = mPosY = mPosZ = mTexX = mTexY = 0;
mColor = mAlpha = 1;
}
public Vertex(Vertex vertex) {
mPosX = vertex.mPosX;
mPosY = vertex.mPosY;
mPosZ = vertex.mPosZ;
mTexX = vertex.mTexX;
mTexY = vertex.mTexY;
mColor = vertex.mColor;
mAlpha = vertex.mAlpha;
}
public void rotateZ(double theta) {
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double x = mPosX * cos + mPosY * sin;
double y = mPosX * -sin + mPosY * cos;
mPosX = x;
mPosY = y;
}
public void translate(double dx, double dy) {
mPosX += dx;
mPosY += dy;
}
}
}
|
package fi.harism.curl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.opengl.GLUtils;
import android.util.Log;
/**
* Class implementing actual curl.
*
* @author harism
*/
public class CurlMesh {
// Flag for additional lines.
private static final boolean DRAW_HELPERS = false;
// Flag for drawing polygon outlines.
private static final boolean DRAW_POLYGON_OUTLINES = false;
// Flag for enabling texture rendering.
private static final boolean DRAW_TEXTURE = true;
// Flag for enabling shadow rendering.
private static final boolean DRAW_SHADOW = true;
// Colors for shadow.
private static final float[] SHADOW_INNER_COLOR = { 0f, 0f, 0f, .5f };
private static final float[] SHADOW_OUTER_COLOR = { 0f, 0f, 0f, .0f };
// Alpha values for front and back facing texture.
private static final double BACKFACE_ALPHA = .2f;
private static final double FRONTFACE_ALPHA = 1f;
private boolean mSwapAlpha = false;
// For testing purposes.
private int mHelperLinesCount;
private FloatBuffer mHelperLines;
// Buffers for feeding rasterizer.
private FloatBuffer mVertices;
private FloatBuffer mTexCoords;
private FloatBuffer mColors;
private int mVerticesCountFront;
private int mVerticesCountBack;
private FloatBuffer mShadowColors;
private FloatBuffer mShadowVertices;
private int mDropShadowCount;
private int mSelfShadowCount;
private int mMaxCurlSplits;
private Vertex[] mRectangle = new Vertex[4];
private int[] mTextureIds;
private Bitmap mBitmap;
// Let's avoid using 'new' as much as possible.
private Array<Vertex> mTempVertices;
private Array<Vertex> mIntersections;
private Array<Vertex> mOutputVertices;
private Array<Vertex> mRotatedVertices;
private Array<Double> mScanLines;
private Array<ShadowVertex> mTempShadowVertices;
private Array<ShadowVertex> mSelfShadowVertices;
private Array<ShadowVertex> mDropShadowVertices;
/**
* Constructor for mesh object.
*
* @param maxCurlSplits
* Maximum number curl can be divided into.
*/
public CurlMesh(int maxCurlSplits) {
// There really is no use for 0 splits.
mMaxCurlSplits = maxCurlSplits < 1 ? 1 : maxCurlSplits;
mScanLines = new Array<Double>(maxCurlSplits + 2);
mOutputVertices = new Array<Vertex>(7);
mRotatedVertices = new Array<Vertex>(4);
mIntersections = new Array<Vertex>(2);
mTempVertices = new Array<Vertex>(7 + 4);
for (int i = 0; i < 7 + 4; ++i) {
mTempVertices.add(new Vertex());
}
if (DRAW_SHADOW) {
mSelfShadowVertices = new Array<ShadowVertex>(
(mMaxCurlSplits + 2) * 2);
mDropShadowVertices = new Array<ShadowVertex>(
(mMaxCurlSplits + 2) * 2);
mTempShadowVertices = new Array<ShadowVertex>(
(mMaxCurlSplits + 2) * 2);
for (int i = 0; i < (mMaxCurlSplits + 2) * 2; ++i) {
mTempShadowVertices.add(new ShadowVertex());
}
}
for (int i = 0; i < 4; ++i) {
mRectangle[i] = new Vertex();
}
if (DRAW_HELPERS) {
mHelperLinesCount = 3;
ByteBuffer hvbb = ByteBuffer
.allocateDirect(mHelperLinesCount * 2 * 2 * 4);
hvbb.order(ByteOrder.nativeOrder());
mHelperLines = hvbb.asFloatBuffer();
mHelperLines.position(0);
}
int maxVerticesCount = 4 + 2 + 2 * mMaxCurlSplits;
ByteBuffer vbb = ByteBuffer.allocateDirect(maxVerticesCount * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mVertices = vbb.asFloatBuffer();
mVertices.position(0);
if (DRAW_TEXTURE) {
ByteBuffer tbb = ByteBuffer
.allocateDirect(maxVerticesCount * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexCoords = tbb.asFloatBuffer();
mTexCoords.position(0);
}
ByteBuffer cbb = ByteBuffer.allocateDirect(maxVerticesCount * 4 * 4);
cbb.order(ByteOrder.nativeOrder());
mColors = cbb.asFloatBuffer();
mColors.position(0);
if (DRAW_SHADOW) {
int maxShadowVerticesCount = (mMaxCurlSplits + 2) * 2 * 2;
ByteBuffer scbb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 4 * 4);
scbb.order(ByteOrder.nativeOrder());
mShadowColors = scbb.asFloatBuffer();
mShadowColors.position(0);
ByteBuffer sibb = ByteBuffer
.allocateDirect(maxShadowVerticesCount * 2 * 4);
sibb.order(ByteOrder.nativeOrder());
mShadowVertices = sibb.asFloatBuffer();
mShadowVertices.position(0);
mDropShadowCount = mSelfShadowCount = 0;
}
}
/**
* Curl calculation.
*
* @param curlPos
* Position for curl center.
* @param directionVec
* Curl direction.
* @param radius
* Radius of curl.
*/
public synchronized void curl(PointF curlPos, PointF directionVec,
double radius) {
// First add some 'helper' lines used for development.
if (DRAW_HELPERS) {
mHelperLines.position(0);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y - 1.0f);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y + 1.0f);
mHelperLines.put(curlPos.x - 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + 1.0f);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x);
mHelperLines.put(curlPos.y);
mHelperLines.put(curlPos.x + directionVec.x * 2);
mHelperLines.put(curlPos.y + directionVec.y * 2);
mHelperLines.position(0);
}
// Actual 'curl' implementation starts here.
mVertices.position(0);
mColors.position(0);
if (DRAW_TEXTURE) {
mTexCoords.position(0);
}
// Calculate curl direction.
double curlAngle = Math.acos(directionVec.x);
curlAngle = directionVec.y > 0 ? -curlAngle : curlAngle;
// Initiate rotated 'rectangle' which's is translated to curlPos and
// rotated so that curl direction heads to (1,0).
mTempVertices.addAll(mRotatedVertices);
mRotatedVertices.clear();
for (int i = 0; i < 4; ++i) {
Vertex v = mTempVertices.remove(0);
v.set(mRectangle[i]);
v.translate(-curlPos.x, -curlPos.y);
v.rotateZ(-curlAngle);
int j = 0;
for (; j < mRotatedVertices.size(); ++j) {
Vertex v2 = mRotatedVertices.get(j);
if (v.mPosX > v2.mPosX) {
break;
}
if (v.mPosX == v2.mPosX && v.mPosY > v2.mPosY) {
break;
}
}
mRotatedVertices.add(j, v);
}
mVerticesCountFront = mVerticesCountBack = 0;
if (DRAW_SHADOW) {
mTempShadowVertices.addAll(mDropShadowVertices);
mTempShadowVertices.addAll(mSelfShadowVertices);
mDropShadowVertices.clear();
mSelfShadowVertices.clear();
}
// Our rectangle lines/vertex indices.
final int lines[] = { 0, 1, 0, 2, 3, 1, 3, 2 };
// Length of 'curl' curve.
double curlLength = Math.PI * radius;
// Calculate scan lines.
mScanLines.clear();
if (mMaxCurlSplits > 0) {
mScanLines.add((double) 0);
}
for (int i = 1; i < mMaxCurlSplits; ++i) {
mScanLines.add((-curlLength * i) / (mMaxCurlSplits - 1));
}
mScanLines.add(mRotatedVertices.get(3).mPosX - 1);
// Start from right most vertex.
double scanXmax = mRotatedVertices.get(0).mPosX + 1;
for (int i = 0; i < mScanLines.size(); ++i) {
double scanXmin = mScanLines.get(i);
// First iterate vertices within scan area.
for (int j = 0; j < mRotatedVertices.size(); ++j) {
Vertex v = mRotatedVertices.get(j);
if (v.mPosX >= scanXmin && v.mPosX <= scanXmax) {
Vertex n = mTempVertices.remove(0);
n.set(v);
Array<Vertex> intersections = getIntersections(
mRotatedVertices, lines, n.mPosX);
if (intersections.size() == 1
&& intersections.get(0).mPosY > v.mPosY) {
mOutputVertices.addAll(intersections);
mOutputVertices.add(n);
} else if (intersections.size() <= 1) {
mOutputVertices.add(n);
mOutputVertices.addAll(intersections);
} else {
Log.d("CurlMesh", "Intersections size > 1");
mTempVertices.add(n);
mTempVertices.addAll(intersections);
}
}
}
// Search for line intersections.
Array<Vertex> intersections = getIntersections(mRotatedVertices,
lines, scanXmin);
if (intersections.size() == 2) {
Vertex v1 = intersections.get(0);
Vertex v2 = intersections.get(1);
if (v1.mPosY < v2.mPosY) {
mOutputVertices.add(v2);
mOutputVertices.add(v1);
} else {
mOutputVertices.addAll(intersections);
}
} else if (intersections.size() != 0) {
Log.d("CurlMesh", "Intersections size != 0 or 2");
mTempVertices.addAll(intersections);
}
// Add vertices to out buffers.
while (mOutputVertices.size() > 0) {
Vertex v = mOutputVertices.remove(0);
mTempVertices.add(v);
// Untouched vertices.
if (i == 0) {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA : FRONTFACE_ALPHA;
mVerticesCountFront++;
}
// 'Completely' rotated vertices.
else if (i == mScanLines.size() - 1 || curlLength == 0) {
v.mPosX = -(curlLength + v.mPosX);
v.mPosZ = 2 * radius;
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA : BACKFACE_ALPHA;
mVerticesCountBack++;
}
// Vertex lies within 'curl'.
else {
// Even though it's not obvious from the if-else clause, here
// v.mPosX is between [-curlLength, 0]. And we can do
// calculations around a half cylinder.
double rotY = Math.PI * (v.mPosX / curlLength);
v.mPosX = radius * Math.sin(rotY);
v.mPosZ = radius - (radius * Math.cos(rotY));
// Map color multiplier to [.1f, 1f] range.
v.mColor = .1f + .9f * Math.sqrt(Math.sin(rotY) + 1);
if (v.mPosZ >= radius) {
v.mAlpha = mSwapAlpha ? FRONTFACE_ALPHA
: BACKFACE_ALPHA;
mVerticesCountBack++;
} else {
v.mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
mVerticesCountFront++;
}
}
// Rotate vertex back to 'world' coordinates.
v.rotateZ(curlAngle);
v.translate(curlPos.x, curlPos.y);
addVertex(v);
// Drop shadow is cast 'behind' the curl.
if (DRAW_SHADOW && v.mPosZ > 0 && v.mPosZ <= radius) {
// TODO: There is some overlapping in some cases, not all
// vertices should be added to shadow.
ShadowVertex sv = mTempShadowVertices.remove(0);
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = (v.mPosZ / 2) * -directionVec.x;
sv.mPenumbraY = (v.mPosZ / 2) * -directionVec.y;
int idx = (mDropShadowVertices.size() + 1) / 2;
mDropShadowVertices.add(idx, sv);
}
// Self shadow is cast partly over mesh.
if (DRAW_SHADOW && v.mPosZ > radius) {
// TODO: Shadow penumbra direction is not good, shouldn't be
// calculated using only directionVec.
ShadowVertex sv = mTempShadowVertices.remove(0);
sv.mPosX = v.mPosX;
sv.mPosY = v.mPosY;
sv.mPenumbraX = ((v.mPosZ - radius) / 2) * directionVec.x;
sv.mPenumbraY = ((v.mPosZ - radius) / 2) * directionVec.y;
int idx = (mSelfShadowVertices.size() + 1) / 2;
mSelfShadowVertices.add(idx, sv);
}
}
scanXmax = scanXmin;
}
mVertices.position(0);
mColors.position(0);
if (DRAW_TEXTURE) {
mTexCoords.position(0);
}
// Add shadow Vertices.
if (DRAW_SHADOW) {
mShadowColors.position(0);
mShadowVertices.position(0);
mDropShadowCount = 0;
for (int i = 0; i < mDropShadowVertices.size(); ++i) {
ShadowVertex sv = mDropShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mDropShadowCount += 2;
}
mSelfShadowCount = 0;
for (int i = 0; i < mSelfShadowVertices.size(); ++i) {
ShadowVertex sv = mSelfShadowVertices.get(i);
mShadowVertices.put((float) sv.mPosX);
mShadowVertices.put((float) sv.mPosY);
mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX));
mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY));
mShadowColors.put(SHADOW_INNER_COLOR);
mShadowColors.put(SHADOW_OUTER_COLOR);
mSelfShadowCount += 2;
}
mShadowColors.position(0);
mShadowVertices.position(0);
}
}
/**
* Draw our mesh.
*/
public synchronized void draw(GL10 gl) {
// First allocate texture if there is not one yet.
if (DRAW_TEXTURE && mTextureIds == null) {
// Generate texture.
mTextureIds = new int[1];
gl.glGenTextures(1, mTextureIds, 0);
// Set texture attributes.
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
}
// If mBitmap != null we have new texture.
if (DRAW_TEXTURE && mBitmap != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
mBitmap = null;
}
if (DRAW_TEXTURE) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]);
}
// Some 'global' settings.
gl.glEnable(GL10.GL_BLEND);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// TODO: Drop shadow drawing is done temporarily here to hide some
// problems with its calculation.
if (DRAW_SHADOW) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mShadowVertices);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mDropShadowCount);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
// Enable texture coordinates.
if (DRAW_TEXTURE) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoords);
}
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
// Enable color array.
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColors);
// Draw blank / 'white' front facing vertices.
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDisable(GL10.GL_TEXTURE_2D);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
// Draw front facing texture.
if (DRAW_TEXTURE) {
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
// Draw blank / 'white' back facing vertices.
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ZERO);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
// Draw back facing texture.
if (DRAW_TEXTURE) {
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mVerticesCountFront,
mVerticesCountBack);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
// Disable textures and color array.
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (DRAW_POLYGON_OUTLINES || DRAW_HELPERS) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL10.GL_LINE_SMOOTH);
gl.glLineWidth(1.0f);
}
if (DRAW_POLYGON_OUTLINES) {
gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices);
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, mVerticesCountFront);
}
if (DRAW_HELPERS) {
gl.glColor4f(1.0f, 0.5f, 0.5f, 1.0f);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mHelperLines);
gl.glDrawArrays(GL10.GL_LINES, 0, mHelperLinesCount * 2);
}
if (DRAW_SHADOW) {
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mShadowVertices);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mDropShadowCount,
mSelfShadowCount);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
/**
* Resets mesh to 'initial' state.
*/
public synchronized void reset() {
mVertices.position(0);
mColors.position(0);
if (DRAW_TEXTURE) {
mTexCoords.position(0);
}
for (int i = 0; i < 4; ++i) {
addVertex(mRectangle[i]);
}
mVerticesCountFront = 4;
mVerticesCountBack = 0;
mVertices.position(0);
mColors.position(0);
if (DRAW_TEXTURE) {
mTexCoords.position(0);
}
mDropShadowCount = mSelfShadowCount = 0;
}
/**
* Sets new texture for this mesh.
*/
public void setBitmap(Bitmap bitmap) {
if (DRAW_TEXTURE) {
mBitmap = Bitmap.createScaledBitmap(bitmap,
getNextHighestPO2(bitmap.getWidth()),
getNextHighestPO2(bitmap.getHeight()), true);
}
}
/**
* Update mesh bounds.
*/
public synchronized void setRect(RectF r) {
mRectangle[0].mPosX = r.left;
mRectangle[0].mPosY = r.top;
mRectangle[1].mPosX = r.left;
mRectangle[1].mPosY = r.bottom;
mRectangle[2].mPosX = r.right;
mRectangle[2].mPosY = r.top;
mRectangle[3].mPosX = r.right;
mRectangle[3].mPosY = r.bottom;
}
/**
* Update texture bounds.
*/
public synchronized void setTexRect(RectF r) {
mRectangle[0].mTexX = r.left;
mRectangle[0].mTexY = r.top;
mRectangle[1].mTexX = r.left;
mRectangle[1].mTexY = r.bottom;
mRectangle[2].mTexX = r.right;
mRectangle[2].mTexY = r.top;
mRectangle[3].mTexX = r.right;
mRectangle[3].mTexY = r.bottom;
mSwapAlpha = r.left > r.right;
for (int i = 0; i < 4; ++i) {
mRectangle[i].mAlpha = mSwapAlpha ? BACKFACE_ALPHA
: FRONTFACE_ALPHA;
}
}
/**
* Adds vertex to buffers.
*/
private void addVertex(Vertex vertex) {
mVertices.put((float) vertex.mPosX);
mVertices.put((float) vertex.mPosY);
mVertices.put((float) vertex.mPosZ);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mColor);
mColors.put((float) vertex.mAlpha);
if (DRAW_TEXTURE) {
mTexCoords.put((float) vertex.mTexX);
mTexCoords.put((float) vertex.mTexY);
}
}
/**
* Calculates intersections for given scan line.
*/
private Array<Vertex> getIntersections(Array<Vertex> vertices,
int[] lineIndices, double scanX) {
mIntersections.clear();
for (int j = 0; j < lineIndices.length; j += 2) {
Vertex v1 = vertices.get(lineIndices[j]);
Vertex v2 = vertices.get(lineIndices[j + 1]);
if ((v1.mPosX > scanX && v2.mPosX < scanX)
|| (v2.mPosX > scanX && v1.mPosX < scanX)) {
double c = (scanX - v2.mPosX) / (v1.mPosX - v2.mPosX);
Vertex n = mTempVertices.remove(0);
n.set(v2);
n.mPosX = scanX;
n.mPosY += (v1.mPosY - v2.mPosY) * c;
if (DRAW_TEXTURE) {
n.mTexX += (v1.mTexX - v2.mTexX) * c;
n.mTexY += (v1.mTexY - v2.mTexY) * c;
}
mIntersections.add(n);
}
}
return mIntersections;
}
/**
* Calculates the next highest power of two for a given integer.
*/
private int getNextHighestPO2(int n) {
n -= 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
n = n | (n >> 32);
return n + 1;
}
/**
* Simple fixed size array implementation.
*/
private class Array<T> {
private Object[] mArray;
private int mSize;
private int mCapacity;
public Array(int capacity) {
mCapacity = capacity;
mArray = new Object[capacity];
}
public void add(int index, T item) {
if (index < 0 || index > mSize || mSize >= mCapacity) {
throw new IndexOutOfBoundsException();
}
for (int i = mSize; i > index; --i) {
mArray[i] = mArray[i - 1];
}
mArray[index] = item;
++mSize;
}
public void add(T item) {
if (mSize >= mCapacity) {
throw new IndexOutOfBoundsException();
}
mArray[mSize++] = item;
}
public void addAll(Array<T> array) {
if (mSize + array.size() > mCapacity) {
throw new IndexOutOfBoundsException();
}
for (int i = 0; i < array.size(); ++i) {
mArray[mSize++] = array.get(i);
}
}
public void clear() {
mSize = 0;
}
@SuppressWarnings("unchecked")
public T get(int index) {
if (index < 0 || index >= mSize) {
throw new IndexOutOfBoundsException();
}
return (T) mArray[index];
}
@SuppressWarnings("unchecked")
public T remove(int index) {
if (index < 0 || index >= mSize) {
throw new IndexOutOfBoundsException();
}
T item = (T) mArray[index];
for (int i = index; i < mSize - 1; ++i) {
mArray[i] = mArray[i + 1];
}
--mSize;
return item;
}
public void set(int index, T item) {
if (index < 0 || index >= mSize) {
throw new IndexOutOfBoundsException();
}
mArray[index] = item;
}
public int size() {
return mSize;
}
}
/**
* Holder for shadow vertex information.
*/
private class ShadowVertex {
public double mPosX;
public double mPosY;
public double mPenumbraX;
public double mPenumbraY;
}
/**
* Holder for vertex information.
*/
private class Vertex {
public double mPosX;
public double mPosY;
public double mPosZ;
public double mTexX;
public double mTexY;
public double mColor;
public double mAlpha;
public Vertex() {
mPosX = mPosY = mPosZ = mTexX = mTexY = 0;
mColor = mAlpha = 1;
}
public void rotateZ(double theta) {
double cos = Math.cos(theta);
double sin = Math.sin(theta);
double x = mPosX * cos + mPosY * sin;
double y = mPosX * -sin + mPosY * cos;
mPosX = x;
mPosY = y;
}
public void set(Vertex vertex) {
mPosX = vertex.mPosX;
mPosY = vertex.mPosY;
mPosZ = vertex.mPosZ;
mTexX = vertex.mTexX;
mTexY = vertex.mTexY;
mColor = vertex.mColor;
mAlpha = vertex.mAlpha;
}
public void translate(double dx, double dy) {
mPosX += dx;
mPosY += dy;
}
}
}
|
package foam.dao.pg;
import foam.core.ClassInfo;
import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.core.X;
import foam.dao.AbstractDAO;
import foam.dao.ListSink;
import foam.dao.Sink;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;
import java.sql.*;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
public class PostgresDAO
extends AbstractDAO
{
protected ConnectionPool connectionPool = new ConnectionPool();
protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
@Override
public StringBuilder get() {
StringBuilder b = super.get();
b.setLength(0);
return b;
}
};
protected final String table;
protected final List<PropertyInfo> props;
public PostgresDAO(X x, ClassInfo of) throws SQLException {
setX(x);
setOf(of);
// fetch connection pool from context
connectionPool = (ConnectionPool) getX().get("connectionPool");
// load columns and sql types
table = of.getObjClass().getSimpleName().toLowerCase();
if ( ! createTable(of) ) {
throw new SQLException("Error creating table");
}
props = ((List<PropertyInfo>) of.getAxiomsByClass(PropertyInfo.class))
.stream().filter(e -> ! e.getStorageTransient())
.collect(Collectors.toList());
}
public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
if ( sink == null ) {
sink = new ListSink();
}
Connection c = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("select * from ")
.append(table);
if ( predicate != null ) {
builder.append(" where ")
.append(predicate.createStatement(table));
}
stmt = c.prepareStatement(builder.toString());
resultSet = stmt.executeQuery();
while ( resultSet.next() ) {
sink.put(createFObject(resultSet), null);
}
return sink;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
@Override
public FObject remove_(X x, FObject o) {
Connection c = null;
PreparedStatement stmt = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("delete from ")
.append(table)
.append(" where id = ?");
stmt = c.prepareStatement(builder.toString());
// TODO: add support for non-numbers
stmt.setLong(1, ((Number) o.getProperty("id")).longValue());
int removed = stmt.executeUpdate();
if ( removed == 0 ) {
throw new SQLException("Error while removing.");
}
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(null, stmt, c);
}
}
@Override
public FObject find_(X x, Object o) {
Connection c = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("select * from ")
.append(table)
.append(" where id = ?");
stmt = c.prepareStatement(builder.toString());
// TODO: add support for non-numbers
stmt.setLong(1, ((Number) o).longValue());
resultSet = stmt.executeQuery();
if ( ! resultSet.next() ) {
// no rows
return null;
}
return createFObject(resultSet);
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
@Override
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
throw new UnsupportedOperationException("Unsupported operation: removeAll_");
}
@Override
public FObject put_(X x, FObject obj) {
Connection c = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("insert into ")
.append(table);
buildFormattedColumnNames(obj, builder);
builder.append(" values");
buildFormattedColumnPlaceholders(obj, builder);
builder.append(" on conflict (id) do update set");
buildFormattedColumnNames(obj, builder);
builder.append(" = ");
buildFormattedColumnPlaceholders(obj, builder);
int index = 1;
stmt = c.prepareStatement(builder.toString(),
Statement.RETURN_GENERATED_KEYS);
// set statement values twice: once for the insert and once for the update on conflict
index = setStatementValues(index, stmt, obj);
index = setStatementValues(index, stmt, obj);
int inserted = stmt.executeUpdate();
if ( inserted == 0 ) {
throw new SQLException("Error performing put_ command");
}
// get auto-generated postgres keys
resultSet = stmt.getGeneratedKeys();
if ( resultSet.next() ) {
obj.setProperty("id", resultSet.getLong(1));
}
return obj;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
/**
* Creates a table if one does not exist already
* @throws SQLException
*/
public boolean createTable(ClassInfo classInfo) {
Connection c = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
DatabaseMetaData meta = c.getMetaData();
resultSet = meta.getTables(null, null, table, new String[]{"TABLE"});
if ( resultSet.isBeforeFirst() ) {
// found a table, don't create
return false;
}
String columns = props.stream()
.filter(e -> !"id".equals(e.getName()))
.map(e -> e.getName() + " " + e.getSQLType())
.collect(Collectors.joining(","));
StringBuilder builder = sb.get()
.append("CREATE TABLE ")
.append(table)
.append("(id bigserial primary key,")
.append(columns)
.append(")");
// execute statement
stmt = c.prepareStatement(builder.toString());
stmt.executeUpdate();
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
/**
* maps a database result row to an FObject
*
* @param resultSet
* @return FObject
* @throws SQLException
*/
private FObject createFObject(ResultSet resultSet) throws Exception {
if ( getOf() == null ) {
throw new Exception("`Of` is not set");
}
FObject obj = (FObject) getOf().getObjClass().newInstance();
ResultSetMetaData metaData = resultSet.getMetaData();
int index = 1;
Iterator i = props.iterator();
while ( i.hasNext() ) {
// prevent reading out of bounds of result set
if ( index > metaData.getColumnCount() )
break;
// get the property and set the value
PropertyInfo prop = (PropertyInfo) i.next();
prop.set(obj, resultSet.getObject(index++));
}
return obj;
}
/**
* Prepare the formatted column names. Appends column names like: (c1,c2,c3)
* @param builder builder to append to
*/
public void buildFormattedColumnNames(FObject obj, StringBuilder builder) {
// collect columns list into comma delimited string
String columns = props.stream()
.filter(e -> ! "id".equals(e.getName()))
.map(e -> e.getName().toLowerCase())
.collect(Collectors.joining(","));
builder.append("(")
.append(columns)
.append(")");
}
/**
* Prepare the formatted value placeholders. Appends value placeholders like: (?,?,?)
* @param builder builder to append to
*/
public void buildFormattedColumnPlaceholders(FObject obj, StringBuilder builder) {
// map columns into ? and collect into comma delimited string
String placeholders = props.stream()
.filter(e -> ! "id".equals(e.getName()))
.map(String -> "?")
.collect(Collectors.joining(","));
builder.append("(")
.append(placeholders)
.append(")");
}
/**
* Sets the value of the PrepareStatement
* @param index index to start from
* @param stmt statement to set values
* @param obj object to get values from
* @return the updated index
* @throws SQLException
*/
public int setStatementValues(int index, PreparedStatement stmt, FObject obj) throws SQLException {
Iterator i = props.iterator();
while ( i.hasNext() ) {
PropertyInfo prop = (PropertyInfo) i.next();
if ( prop.getName().equals("id") )
continue;
stmt.setObject(index++, prop.get(obj));
}
return index;
}
/**
* Closes resources without throwing exceptions
* @param resultSet ResultSet
* @param stmt PreparedStatement
* @param c Connection
*/
public void closeAllQuietly(ResultSet resultSet, PreparedStatement stmt, Connection c) {
if ( resultSet != null )
try { resultSet.close(); } catch (Throwable ignored) {}
if ( stmt != null )
try { stmt.close(); } catch (Throwable ignored) {}
if ( c != null )
try { c.close(); } catch (Throwable ignored) {}
}
}
|
package foam.dao.pg;
import foam.core.ClassInfo;
import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.core.X;
import foam.dao.AbstractDAO;
import foam.dao.ListSink;
import foam.dao.Sink;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PostgresDAO
extends AbstractDAO
{
protected ConnectionPool connectionPool = new ConnectionPool();
protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
@Override
public StringBuilder get() {
StringBuilder b = super.get();
b.setLength(0);
return b;
}
};
protected String table_;
protected List<PropertyInfo> props_ = new ArrayList<>();
public PostgresDAO(X x, ClassInfo of) throws SQLException {
setX(x);
setOf(of);
// fetch connection pool from context
connectionPool = (ConnectionPool) getX().get("connectionPool");
// load columns and sql types
List<PropertyInfo> props = of.getAxiomsByClass(PropertyInfo.class);
for ( PropertyInfo prop : props ) {
if ( prop.getStorageTransient() )
continue;
if ( "".equals(prop.getSQLType()) )
continue;
props_.add(prop);
}
table_ = of.getObjClass().getSimpleName().toLowerCase();
if ( ! createTable() ) {
//throw new SQLException("Error creating table");
}
}
public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
if ( sink == null ) {
sink = new ListSink();
}
Connection c = null;
IndexedPreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("select * from ")
.append(table_);
if ( predicate != null ) {
builder.append(" where ")
.append(predicate.createStatement());
}
if ( order != null ) {
builder.append(" order by ")
.append(order.createStatement());
}
if ( limit > 0 && limit < this.MAX_SAFE_INTEGER ) {
builder.append(" limit ").append(limit);
}
if ( skip > 0 && skip < this.MAX_SAFE_INTEGER ) {
builder.append(" offset ").append(skip);
}
stmt = new IndexedPreparedStatement(c.prepareStatement(builder.toString()));
if ( predicate != null ) {
predicate.prepareStatement(stmt);
}
resultSet = stmt.executeQuery();
while ( resultSet.next() ) {
sink.put(createFObject(resultSet), null);
}
return sink;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
@Override
public FObject remove_(X x, FObject o) {
Connection c = null;
IndexedPreparedStatement stmt = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("delete from ")
.append(table_)
.append(" where ")
.append(getPrimaryKey().createStatement())
.append(" = ?");
stmt = new IndexedPreparedStatement(c.prepareStatement(builder.toString()));
// TODO: add support for non-numbers
//stmt.setLong(((Number) o.getProperty("id")).longValue());
stmt.setObject(o.getProperty(getPrimaryKey().getName()));
int removed = stmt.executeUpdate();
if ( removed == 0 ) {
throw new SQLException("Error while removing.");
}
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(null, stmt, c);
}
}
@Override
public FObject find_(X x, Object o) {
Connection c = null;
IndexedPreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("select * from ")
.append(table_)
.append(" where id = ?");
stmt = new IndexedPreparedStatement(c.prepareStatement(builder.toString()));
// TODO: add support for non-numbers
stmt.setLong(((Number) o).longValue());
resultSet = stmt.executeQuery();
if ( ! resultSet.next() ) {
// no rows
return null;
}
return createFObject(resultSet);
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
@Override
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
throw new UnsupportedOperationException("Unsupported operation: removeAll_");
}
@Override
public FObject put_(X x, FObject obj) {
Connection c = null;
IndexedPreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
StringBuilder builder = sb.get()
.append("insert into ")
.append(table_);
buildFormattedColumnNames(obj, builder);
builder.append(" values");
buildFormattedColumnPlaceholders(obj, builder);
builder.append(" on conflict (id) do update set");
buildFormattedColumnNames(obj, builder);
builder.append(" = ");
buildFormattedColumnPlaceholders(obj, builder);
stmt = new IndexedPreparedStatement(c.prepareStatement(builder.toString(),
Statement.RETURN_GENERATED_KEYS));
// set statement values twice: once for the insert and once for the update on conflict
setStatementValues(stmt, obj);
setStatementValues(stmt, obj);
int inserted = stmt.executeUpdate();
if ( inserted == 0 ) {
throw new SQLException("Error performing put_ command");
}
// get auto-generated postgres keys
resultSet = stmt.getGeneratedKeys();
if ( resultSet.next() ) {
obj.setProperty("id", resultSet.getLong(1));
}
return obj;
} catch (Throwable e) {
e.printStackTrace();
return null;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
/**
* Creates a table if one does not exist already
* @throws SQLException
*/
public boolean createTable() {
Connection c = null;
IndexedPreparedStatement stmt = null;
ResultSet resultSet = null;
try {
c = connectionPool.getConnection();
DatabaseMetaData meta = c.getMetaData();
resultSet = meta.getTables(null, null, table_, new String[]{"TABLE"});
if ( resultSet.isBeforeFirst() ) {
// found a table, don't create
return false;
}
StringBuilder builder = sb.get()
.append("CREATE TABLE ")
.append(table_)
.append("(id bigserial primary key,");
Iterator i = props_.iterator();
while ( i.hasNext() ) {
PropertyInfo prop = (PropertyInfo) i.next();
if ( "id".equals(prop.getName()) )
continue;
builder.append(prop.getName())
.append(" ")
.append(prop.getSQLType());
if ( i.hasNext() ) {
builder.append(",");
}
}
builder.append(")");
// execute statement
stmt = new IndexedPreparedStatement(c.prepareStatement(builder.toString()));
stmt.executeUpdate();
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
} finally {
closeAllQuietly(resultSet, stmt, c);
}
}
/**
* maps a database result row to an FObject
*
* @param resultSet
* @return FObject
* @throws SQLException
*/
private FObject createFObject(ResultSet resultSet) throws Exception {
if ( getOf() == null ) {
throw new Exception("`Of` is not set");
}
FObject obj = (FObject) getOf().getObjClass().newInstance();
ResultSetMetaData metaData = resultSet.getMetaData();
int index = 1;
Iterator i = props_.iterator();
while ( i.hasNext() ) {
// prevent reading out of bounds of result set
if ( index > metaData.getColumnCount() )
break;
// get the property and set the value
PropertyInfo prop = (PropertyInfo) i.next();
prop.set(obj, resultSet.getObject(index++));
}
return obj;
}
/**
* Prepare the formatted column names. Appends column names like: (c1,c2,c3)
* @param builder builder to append to
*/
public void buildFormattedColumnNames(FObject obj, StringBuilder builder) {
// collect columns list into comma delimited string
builder.append("(");
Iterator i = props_.iterator();
while ( i.hasNext() ) {
PropertyInfo prop = (PropertyInfo) i.next();
if ( "id".equals(prop.getName()) )
continue;
builder.append(prop.getName().toLowerCase());
if ( i.hasNext() ) {
builder.append(",");
}
}
builder.append(")");
}
/**
* Prepare the formatted value placeholders. Appends value placeholders like: (?,?,?)
* @param builder builder to append to
*/
public void buildFormattedColumnPlaceholders(FObject obj, StringBuilder builder) {
// map columns into ? and collect into comma delimited string
builder.append("(");
Iterator i = props_.iterator();
while ( i.hasNext() ) {
PropertyInfo prop = (PropertyInfo) i.next();
if ( "id".equals(prop.getName()) )
continue;
builder.append("?");
if ( i.hasNext() ) {
builder.append(",");
}
}
builder.append(")");
}
/**
* Sets the value of the PrepareStatement
* @param stmt statement to set values
* @param obj object to get values from
* @return the updated index
* @throws SQLException
*/
public void setStatementValues(IndexedPreparedStatement stmt, FObject obj) throws SQLException {
Iterator i = props_.iterator();
while ( i.hasNext() ) {
PropertyInfo prop = (PropertyInfo) i.next();
if ( prop.getName().equals("id") )
continue;
stmt.setObject(prop.get(obj));
}
}
/**
* Closes resources without throwing exceptions
* @param resultSet ResultSet
* @param stmt IndexedPreparedStatement
* @param c Connection
*/
public void closeAllQuietly(ResultSet resultSet, IndexedPreparedStatement stmt, Connection c) {
if ( resultSet != null )
try { resultSet.close(); } catch (Throwable ignored) {}
if ( stmt != null )
try { stmt.close(); } catch (Throwable ignored) {}
if ( c != null )
try { c.close(); } catch (Throwable ignored) {}
}
}
|
package rogel.io.fopl.formulas;
import rogel.io.fopl.Symbol;
/**
* A NegatedFormula is a Formula whose value is the opposite of the
* value of another Formula it describes.
* @author recardona
*/
public class NegatedFormula extends Formula {
/** The Formula this class negates. */
private Formula formula;
/**
* Constructs a NegatedFormula with the given name, over the given Formula.
* If the name is a String that did not already exist within the domain of
* discourse (i.e. was already defined as a Symbol), then a new Symbol is
* created and added to the domain of discourse. The value of this Formula
* is the opposite of the parameter Formula (the Formula it describes).
* @param name the name of the Formula
* @param formula the Formula this NegatedFormula describes
*/
public NegatedFormula(String name, Formula formula) {
super(name);
this.formula = formula; // The Formula this class describes.
this.value = !this.formula.value; // This class' value is the opposite of the Formula it describes.
}
/**
* Constructs a NegatedFormula with the given Symbol, over the given
* Formula. The value of this Formula is the opposite of the parameter
* Formula (the Formula it describes).
* @param symbol the Symbol that represents this NegatedFormula within the
* domain of discourse
* @param formula the Formula this NegatedFormula describes
*/
public NegatedFormula(Symbol symbol, Formula formula) {
super(symbol);
this.formula = formula;
this.value = !this.formula.value;
}
@Override
public String toString() {
return "(not " + formula + ")";
}
}
|
package sample.java.project;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
/**
* The main class of the application. It contains the main() method,
* the first method called.
*/
@NoArgsConstructor
@AllArgsConstructor
public class SampleJavaProject implements Runnable {
/** The delay between printed messages. */
private static final long PRINT_DELAY = 1000L;
/** The name to be printed in the output message. */
@Getter @Setter @NonNull
@Parameter(names = "--name", description = "set the user's name",
required = true)
private String name = "world";
/** Command line parameter for --loop. */
@Parameter(names = "--loop", description = "print endlessly, hotswap demo")
private boolean loop = false;
/** Command line parameter for --help. */
@Parameter(names = { "-h", "--help" }, description = "print help message")
private boolean help = false;
/**
* Print the "Hello, world!" string.
* @param args application input arguments
*/
public static void main(final String[] args) {
/* Parse command line arguments. */
SampleJavaProject sjp = new SampleJavaProject();
try {
JCommander jc = new JCommander(sjp, args);
String nullString = null;
String notNullString = "34";
if (nullString.equals(notNullString)) {
System.err.println("error: " + e.getMessage());
}
if (sjp.help) {
jc.usage();
return;
}
} catch (ParameterException e) {
String testString;
if (testString.equals("null pointer")) {
System.err.println("error: " + e.getMessage());
}
System.err.println("error: " + e.getMessage());
new JCommander(new SampleJavaProject()).usage();
System.exit(-1);
}
sjp.run();
}
/**
* Print the "Hello, world!" string.
*/
public final void sayHello() {
System.out.printf("Hello, %s!%n", name);
}
@Override
public final void run() {
do {
sayHello();
try {
Thread.sleep(PRINT_DELAY);
} catch (InterruptedException e) {
return;
}
} while (loop);
}
}
|
package org.TexasTorque.TexasTorque2013;
import edu.wpi.first.wpilibj.IterativeRobot;
import org.TexasTorque.TexasTorque2013.io.*;
import org.TexasTorque.TexasTorque2013.subsystem.*;
import org.TexasTorque.TorqueLib.util.DashboardManager;
public class RobotBase extends IterativeRobot
{
DashboardManager dashboardManager;
DriverInput driverInput;
SensorInput sensorInput;
RobotOutput robotOutput;
Drivebase drivebase;
public void robotInit()
{
dashboardManager = DashboardManager.getInstance();
driverInput = DriverInput.getInstance();
sensorInput = SensorInput.getInstance();
robotOutput = RobotOutput.getInstance();
drivebase = new Drivebase();
}
public void autonomousInit()
{
sensorInput.resetEncoders();
}
public void autonomousPeriodic()
{
dashboardManager.updateLCD();
}
public void autonomousContinuous()
{
}
public void teleopInit()
{
sensorInput.resetEncoders();
}
public void teleopPeriodic()
{
dashboardManager.updateLCD();
}
public void teleopContinuous()
{
drivebase.run();
}
public void disabledInit()
{
}
public void disabledPeriodic()
{
dashboardManager.updateLCD();
}
public void disabledContinuous()
{
}
}
|
package org.anddev.andengine.opengl.util;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.engine.options.RenderOptions;
import org.anddev.andengine.util.Debug;
import android.graphics.Bitmap;
import android.opengl.GLUtils;
import android.os.Build;
/**
* @author Nicolas Gramlich
* @since 18:00:43 - 08.03.2010
*/
public class GLHelper {
// Constants
public static final int BYTES_PER_FLOAT = 4;
public static final int BYTES_PER_PIXEL_RGBA = 4;
private static final boolean IS_LITTLE_ENDIAN = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN);
private static final int[] HARDWARETEXTUREID_CONTAINER = new int[1];
private static final int[] HARDWAREBUFFERID_CONTAINER = new int[1];
// Fields
private static int sCurrentHardwareBufferID = -1;
private static int sCurrentHardwareTextureID = -1;
private static int sCurrentMatrix = -1;
private static int sCurrentSourceBlendMode = -1;
private static int sCurrentDestionationBlendMode = -1;
private static FastFloatBuffer sCurrentTextureFloatBuffer = null;
private static FastFloatBuffer sCurrentVertexFloatBuffer = null;
private static boolean sEnableDither = true;
private static boolean sEnableLightning = true;
private static boolean sEnableDepthTest = true;
private static boolean sEnableMultisample = true;
private static boolean sEnableBlend = false;
private static boolean sEnableCulling = false;
private static boolean sEnableTextures = false;
private static boolean sEnableTexCoordArray = false;
private static boolean sEnableVertexArray = false;
private static float sLineWidth = 1;
private static float sRed = -1;
private static float sGreen = -1;
private static float sBlue = -1;
private static float sAlpha = -1;
public static boolean EXTENSIONS_VERTEXBUFFEROBJECTS = false;
public static boolean EXTENSIONS_DRAWTEXTURE = false;
// Methods
public static void reset(final GL10 pGL) {
GLHelper.sCurrentHardwareBufferID = -1;
GLHelper.sCurrentHardwareTextureID = -1;
GLHelper.sCurrentMatrix = -1;
GLHelper.sCurrentSourceBlendMode = -1;
GLHelper.sCurrentDestionationBlendMode = -1;
GLHelper.sCurrentTextureFloatBuffer = null;
GLHelper.sCurrentVertexFloatBuffer = null;
GLHelper.enableDither(pGL);
GLHelper.enableLightning(pGL);
GLHelper.enableDepthTest(pGL);
GLHelper.enableMultisample(pGL);
GLHelper.disableBlend(pGL);
GLHelper.disableCulling(pGL);
GLHelper.disableTextures(pGL);
GLHelper.disableTexCoordArray(pGL);
GLHelper.disableVertexArray(pGL);
GLHelper.sLineWidth = 1;
GLHelper.sRed = -1;
GLHelper.sGreen = -1;
GLHelper.sBlue = -1;
GLHelper.sAlpha = -1;
GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false;
GLHelper.EXTENSIONS_DRAWTEXTURE = false;
}
public static void enableExtensions(final GL10 pGL, final RenderOptions pRenderOptions) {
final String version = pGL.glGetString(GL10.GL_VERSION);
final String renderer = pGL.glGetString(GL10.GL_RENDERER);
final String extensions = pGL.glGetString(GL10.GL_EXTENSIONS);
Debug.d("RENDERER: " + renderer);
Debug.d("VERSION: " + version);
Debug.d("EXTENSIONS: " + extensions);
final boolean isOpenGL10 = version.endsWith("1.0");
final boolean isSoftwareRenderer = renderer.contains("PixelFlinger");
final boolean isVBOCapable = extensions.contains("_vertex_buffer_object");
final boolean isDrawTextureCapable = extensions.contains("draw_texture");
GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = !pRenderOptions.isDisableExtensionVertexBufferObjects() && !isSoftwareRenderer && (isVBOCapable || !isOpenGL10);
GLHelper.EXTENSIONS_DRAWTEXTURE = isDrawTextureCapable;
GLHelper.hackBrokenDevices();
Debug.d("EXTENSIONS_VERXTEXBUFFEROBJECTS = " + EXTENSIONS_VERTEXBUFFEROBJECTS);
Debug.d("EXTENSIONS_DRAWTEXTURE = " + EXTENSIONS_DRAWTEXTURE);
}
private static void hackBrokenDevices() {
if (Build.PRODUCT.contains("morrison")) {
// This is the Motorola Cliq. This device LIES and says it supports
// VBOs, which it actually does not (or, more likely, the extensions string
// is correct and the GL JNI glue is broken).
GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS = false;
// TODO: if Motorola fixes this, I should switch to using the fingerprint
// (blur/morrison/morrison/morrison:1.5/CUPCAKE/091007:user/ota-rel-keys,release-keys)
// instead of the product name so that newer versions use VBOs
}
}
public static void setColor(final GL10 pGL, final float pRed, final float pGreen, final float pBlue, final float pAlpha) {
if(pAlpha != GLHelper.sAlpha || pRed != GLHelper.sRed || pGreen != GLHelper.sGreen || pBlue != GLHelper.sBlue) {
GLHelper.sAlpha = pAlpha;
GLHelper.sRed = pRed;
GLHelper.sGreen = pGreen;
GLHelper.sBlue = pBlue;
pGL.glColor4f(pRed, pGreen, pBlue, pAlpha);
}
}
public static void enableVertexArray(final GL10 pGL) {
if(!GLHelper.sEnableVertexArray) {
GLHelper.sEnableVertexArray = true;
pGL.glEnableClientState(GL10.GL_VERTEX_ARRAY);
}
}
public static void disableVertexArray(final GL10 pGL) {
if(GLHelper.sEnableVertexArray) {
GLHelper.sEnableVertexArray = false;
pGL.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}
public static void enableTexCoordArray(final GL10 pGL) {
if(!GLHelper.sEnableTexCoordArray) {
GLHelper.sEnableTexCoordArray = true;
pGL.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
}
public static void disableTexCoordArray(final GL10 pGL) {
if(GLHelper.sEnableTexCoordArray) {
GLHelper.sEnableTexCoordArray = false;
pGL.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
}
public static void enableBlend(final GL10 pGL) {
if(!GLHelper.sEnableBlend) {
GLHelper.sEnableBlend = true;
pGL.glEnable(GL10.GL_BLEND);
}
}
public static void disableBlend(final GL10 pGL) {
if(GLHelper.sEnableBlend) {
GLHelper.sEnableBlend = false;
pGL.glDisable(GL10.GL_BLEND);
}
}
public static void enableCulling(final GL10 pGL) {
if(!GLHelper.sEnableCulling) {
GLHelper.sEnableCulling = true;
pGL.glEnable(GL10.GL_CULL_FACE);
}
}
public static void disableCulling(final GL10 pGL) {
if(GLHelper.sEnableCulling) {
GLHelper.sEnableCulling = false;
pGL.glDisable(GL10.GL_CULL_FACE);
}
}
public static void enableTextures(final GL10 pGL) {
if(!GLHelper.sEnableTextures) {
GLHelper.sEnableTextures = true;
pGL.glEnable(GL10.GL_TEXTURE_2D);
}
}
public static void disableTextures(final GL10 pGL) {
if(GLHelper.sEnableTextures) {
GLHelper.sEnableTextures = false;
pGL.glDisable(GL10.GL_TEXTURE_2D);
}
}
public static void enableLightning(final GL10 pGL) {
if(!GLHelper.sEnableLightning) {
GLHelper.sEnableLightning = true;
pGL.glEnable(GL10.GL_LIGHTING);
}
}
public static void disableLightning(final GL10 pGL) {
if(GLHelper.sEnableLightning) {
GLHelper.sEnableLightning = false;
pGL.glDisable(GL10.GL_LIGHTING);
}
}
public static void enableDither(final GL10 pGL) {
if(!GLHelper.sEnableDither) {
GLHelper.sEnableDither = true;
pGL.glEnable(GL10.GL_DITHER);
}
}
public static void disableDither(final GL10 pGL) {
if(GLHelper.sEnableDither) {
GLHelper.sEnableDither = false;
pGL.glDisable(GL10.GL_DITHER);
}
}
public static void enableDepthTest(final GL10 pGL) {
if(!GLHelper.sEnableDepthTest) {
GLHelper.sEnableDepthTest = true;
pGL.glEnable(GL10.GL_DEPTH_TEST);
}
}
public static void disableDepthTest(final GL10 pGL) {
if(GLHelper.sEnableDepthTest) {
GLHelper.sEnableDepthTest = false;
pGL.glDisable(GL10.GL_DEPTH_TEST);
}
}
public static void enableMultisample(final GL10 pGL) {
if(!GLHelper.sEnableMultisample) {
GLHelper.sEnableMultisample = true;
pGL.glEnable(GL10.GL_MULTISAMPLE);
}
}
public static void disableMultisample(final GL10 pGL) {
if(GLHelper.sEnableMultisample) {
GLHelper.sEnableMultisample = false;
pGL.glDisable(GL10.GL_MULTISAMPLE);
}
}
public static void bindBuffer(final GL11 pGL11, final int pHardwareBufferID) {
/* Reduce unnecessary buffer switching calls. */
if(GLHelper.sCurrentHardwareBufferID != pHardwareBufferID) {
GLHelper.sCurrentHardwareBufferID = pHardwareBufferID;
pGL11.glBindBuffer(GL11.GL_ARRAY_BUFFER, pHardwareBufferID);
}
}
public static void deleteBuffer(final GL11 pGL11, final int pHardwareBufferID) {
GLHelper.HARDWAREBUFFERID_CONTAINER[0] = pHardwareBufferID;
pGL11.glDeleteBuffers(1, GLHelper.HARDWAREBUFFERID_CONTAINER, 0);
}
public static void bindTexture(final GL10 pGL, final int pHardwareTextureID) {
/* Reduce unnecessary texture switching calls. */
if(GLHelper.sCurrentHardwareTextureID != pHardwareTextureID) {
GLHelper.sCurrentHardwareTextureID = pHardwareTextureID;
pGL.glBindTexture(GL10.GL_TEXTURE_2D, pHardwareTextureID);
}
}
public static void deleteTexture(final GL10 pGL, final int pHardwareTextureID) {
GLHelper.HARDWARETEXTUREID_CONTAINER[0] = pHardwareTextureID;
pGL.glDeleteTextures(1, GLHelper.HARDWARETEXTUREID_CONTAINER, 0);
}
public static void texCoordPointer(final GL10 pGL, final FastFloatBuffer pTextureFloatBuffer) {
if(GLHelper.sCurrentTextureFloatBuffer != pTextureFloatBuffer) {
GLHelper.sCurrentTextureFloatBuffer = pTextureFloatBuffer;
pGL.glTexCoordPointer(2, GL10.GL_FLOAT, 0, pTextureFloatBuffer.mByteBuffer);
}
}
public static void texCoordZeroPointer(final GL11 pGL11) {
pGL11.glTexCoordPointer(2, GL10.GL_FLOAT, 0, 0);
}
public static void vertexPointer(final GL10 pGL, final FastFloatBuffer pVertexFloatBuffer) {
if(GLHelper.sCurrentVertexFloatBuffer != pVertexFloatBuffer) {
GLHelper.sCurrentVertexFloatBuffer = pVertexFloatBuffer;
pGL.glVertexPointer(2, GL10.GL_FLOAT, 0, pVertexFloatBuffer.mByteBuffer);
}
}
public static void vertexZeroPointer(final GL11 pGL11) {
pGL11.glVertexPointer(2, GL10.GL_FLOAT, 0, 0);
}
public static void blendFunction(final GL10 pGL, final int pSourceBlendMode, final int pDestinationBlendMode) {
if(GLHelper.sCurrentSourceBlendMode != pSourceBlendMode || GLHelper.sCurrentDestionationBlendMode != pDestinationBlendMode) {
GLHelper.sCurrentSourceBlendMode = pSourceBlendMode;
GLHelper.sCurrentDestionationBlendMode = pDestinationBlendMode;
pGL.glBlendFunc(pSourceBlendMode, pDestinationBlendMode);
}
}
public static void lineWidth(final GL10 pGL, final float pLineWidth) {
if(GLHelper.sLineWidth != pLineWidth) {
GLHelper.sLineWidth = pLineWidth;
pGL.glLineWidth(pLineWidth);
}
}
public static void switchToModelViewMatrix(final GL10 pGL) {
/* Reduce unnecessary matrix switching calls. */
if(GLHelper.sCurrentMatrix != GL10.GL_MODELVIEW) {
GLHelper.sCurrentMatrix = GL10.GL_MODELVIEW;
pGL.glMatrixMode(GL10.GL_MODELVIEW);
}
}
public static void switchToProjectionMatrix(final GL10 pGL) {
/* Reduce unnecessary matrix switching calls. */
if(GLHelper.sCurrentMatrix != GL10.GL_PROJECTION) {
GLHelper.sCurrentMatrix = GL10.GL_PROJECTION;
pGL.glMatrixMode(GL10.GL_PROJECTION);
}
}
public static void setProjectionIdentityMatrix(final GL10 pGL) {
GLHelper.switchToProjectionMatrix(pGL);
pGL.glLoadIdentity();
}
public static void setModelViewIdentityMatrix(final GL10 pGL) {
GLHelper.switchToModelViewMatrix(pGL);
pGL.glLoadIdentity();
}
public static void setShadeModelFlat(final GL10 pGL) {
pGL.glShadeModel(GL10.GL_FLAT);
}
public static void setPerspectiveCorrectionHintFastest(final GL10 pGL) {
pGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
}
public static void bufferData(final GL11 pGL11, final ByteBuffer pByteBuffer, final int pUsage) {
pGL11.glBufferData(GL11.GL_ARRAY_BUFFER, pByteBuffer.capacity(), pByteBuffer, pUsage);
}
public static void glTexSubImage2D(final GL10 pGL, final int target, final int level, final int xoffset, final int yoffset, final Bitmap bitmap, final int format, final int type) {
final int[] pixels = GLHelper.getPixels(bitmap);
final Buffer pixelBuffer = GLHelper.convertARGBtoRGBABuffer(pixels);
pGL.glTexSubImage2D(GL10.GL_TEXTURE_2D, 0, xoffset, yoffset, bitmap.getWidth(), bitmap.getHeight(), GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, pixelBuffer);
}
private static Buffer convertARGBtoRGBABuffer(final int[] pPixels) {
for(int i = pPixels.length - 1; i >= 0; i
final int pixel = pPixels[i];
final int red = ((pixel >> 16) & 0xFF);
final int green = ((pixel >> 8) & 0xFF);
final int blue = ((pixel) & 0xFF);
final int alpha = (pixel >> 24);
// TODO This check could be outside of the loop, so it doesn't get evaluated every iteration.
if(IS_LITTLE_ENDIAN) {
pPixels[i] = alpha << 24 | blue << 16 | green << 8 | red;
} else {
pPixels[i] = red << 24 | green << 16 | blue << 8 | alpha;
}
}
return IntBuffer.wrap(pPixels);
}
public static int[] getPixels(final Bitmap pBitmap) {
final int w = pBitmap.getWidth();
final int h = pBitmap.getHeight();
final int[] pixels = new int[w * h];
pBitmap.getPixels(pixels, 0, w, 0, 0, w, h);
return pixels;
}
// Inner and Anonymous Classes
}
|
package org.apache.fop.fo.pagination;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.fo.flow.Flow;
import org.apache.fop.fo.flow.StaticContent;
import org.apache.fop.layout.PageMaster;
import org.apache.fop.area.AreaTree;
import org.apache.fop.area.PageViewport;
import org.apache.fop.apps.FOPException;
import org.apache.fop.layoutmgr.PageLayoutManager;
// Java
import java.util.*;
import org.xml.sax.Attributes;
/**
* This provides pagination of flows onto pages. Much of the
* logic for paginating flows is contained in this class.
* The main entry point is the format method.
*/
public class PageSequence extends FObj {
// intial-page-number types
private static final int EXPLICIT = 0;
private static final int AUTO = 1;
private static final int AUTO_EVEN = 2;
private static final int AUTO_ODD = 3;
// associations
/**
* The parent root object
*/
private Root root;
/**
* the set of layout masters (provided by the root object)
*/
private LayoutMasterSet layoutMasterSet;
// There doesn't seem to be anything in the spec requiring flows
// to be in the order given, only that they map to the regions
// defined in the page sequence, so all we need is this one hashtable
// the set of flows includes StaticContent flows also
/**
* Map of flows to their flow name (flow-name, Flow)
*/
private Hashtable _flowMap;
/**
* the "master-reference" attribute
*/
private String masterName;
// according to communication from Paul Grosso (XSL-List,
// 001228, Number 406), confusion in spec section 6.4.5 about
// multiplicity of fo:flow in XSL 1.0 is cleared up - one (1)
// fo:flow per fo:page-sequence only.
private boolean isFlowSet = false;
// state attributes used during layout
private PageViewport currentPage;
// page number and related formatting variables
private String ipnValue;
private int currentPageNumber = 0;
private int explicitFirstNumber = 0; // explicitly specified
private int firstPageNumber = 0; // actual
private PageNumberGenerator pageNumberGenerator;
private int forcePageCount = 0;
private int pageCount = 0;
private boolean isForcing = false;
/**
* specifies page numbering type (auto|auto-even|auto-odd|explicit)
*/
private int pageNumberType;
/**
* used to determine whether to calculate auto, auto-even, auto-odd
*/
private boolean thisIsFirstPage;
/**
* the current subsequence while formatting a given page sequence
*/
private SubSequenceSpecifier currentSubsequence;
/**
* the current index in the subsequence list
*/
private int currentSubsequenceNumber =
-1; // starting case is -1 so that first getNext increments to 0
/**
* the name of the current page master
*/
private String currentPageMasterName;
/**
* The main content flow for this page-sequence.
*/
private Flow mainFlow=null;
/**
* The fo:title object for this page-sequence.
*/
private FObj titleFO;
public PageSequence(FONode parent) {
super(parent);
}
public void handleAttrs(Attributes attlist) throws FOPException {
super.handleAttrs(attlist);
if (parent.getName().equals("fo:root")) {
this.root = (Root)parent;
// this.root.addPageSequence(this);
}
else {
throw new FOPException("page-sequence must be child of root, not "
+ parent.getName());
}
layoutMasterSet = root.getLayoutMasterSet();
// best time to run some checks on LayoutMasterSet
layoutMasterSet.checkRegionNames();
_flowMap = new Hashtable();
thisIsFirstPage =
true; // we are now on the first page of the page sequence
ipnValue = this.properties.get("initial-page-number").getString();
if (ipnValue.equals("auto")) {
pageNumberType = AUTO;
} else if (ipnValue.equals("auto-even")) {
pageNumberType = AUTO_EVEN;
} else if (ipnValue.equals("auto-odd")) {
pageNumberType = AUTO_ODD;
} else {
pageNumberType = EXPLICIT;
try {
int pageStart = new Integer(ipnValue).intValue();
this.explicitFirstNumber = (pageStart > 0) ? pageStart - 1 : 0;
} catch (NumberFormatException nfe) {
throw new FOPException("\"" + ipnValue
+ "\" is not a valid value for initial-page-number");
}
}
masterName = this.properties.get("master-reference").getString();
// TODO: Add code here to set a reference to the PageSequenceMaster
// if the masterName names a page-sequence-master, else get a
// reference to the SimplePageMaster. Throw an exception if neither?
// get the 'format' properties
this.pageNumberGenerator =
new PageNumberGenerator(this.properties.get("format").getString(),
this.properties.get("grouping-separator").getCharacter(),
this.properties.get("grouping-size").getNumber().intValue(),
this.properties.get("letter-value").getEnum());
this.forcePageCount =
this.properties.get("force-page-count").getEnum();
// this.properties.get("country");
// this.properties.get("language");
// this.properties.get("id");
}
/**
* Add a flow or static content, mapped by its flow-name.
* The flow-name is used to associate the flow with a region on a page,
* based on the names given to the regions in the page-master used to
* generate that page.
*/
private void addFlow(Flow flow) throws FOPException {
if (_flowMap.containsKey(flow.getFlowName())) {
throw new FOPException("flow-names must be unique within an fo:page-sequence");
}
if (!this.layoutMasterSet.regionNameExists(flow.getFlowName())) {
log.error("region-name '"
+ flow.getFlowName()
+ "' doesn't exist in the layout-master-set.");
}
_flowMap.put(flow.getFlowName(), flow);
//setIsFlowSet(true);
}
/**
* Validate the child being added and initialize internal variables.
* XSL content model for page-sequence:
* <pre>(title?,static-content*,flow)</pre>
* Note: title isn't currently implemented.
* @param child The flow object child to be added to the PageSequence.
*/
public void addChild(FONode child) {
try {
String childName = child.getName();
if (childName.equals("fo:title")) {
if (this._flowMap.size()>0) {
log.warn("fo:title should be first in page-sequence");
}
this.titleFO = (FObj)child;
}
else if (childName.equals("fo:flow")) {
if (this.mainFlow != null) {
throw new FOPException("Only a single fo:flow permitted"
+ " per fo:page-sequence");
}
else {
this.mainFlow = (Flow)child;
addFlow(mainFlow);
}
}
else if (childName.equals("fo:static-content")) {
if (this.mainFlow != null) {
throw new FOPException(childName +
" must precede fo:flow; ignoring");
}
else {
addFlow((Flow)child);
}
}
else {
// Ignore it!
log.warn("FO '" + childName +
"' not a legal page-sequence child.");
return;
}
} catch (FOPException fopex) {
log.error("Error in PageSequence.addChild(): " +
fopex.getMessage());
}
}
public void end() {
try {
format(null);
} catch (FOPException fopex) {
log.error("Error in PageSequence.end(): " +
fopex.getMessage());
}
}
/**
* Return children for layout. Only the main flow is laid out directly.
*/
public Iterator getChildren() {
return new Iterator() {
boolean bFirst=true;
public boolean hasNext() {
return (bFirst==true && mainFlow != null);
}
public Object next() {
if (bFirst==true && mainFlow != null) {
bFirst=false;
return mainFlow;
}
else throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Runs the formatting of this page sequence into the given area tree
*/
public void format(AreaTree areaTree) throws FOPException {
// Make a new PageLayoutManager and a FlowLayoutManager
// Run the PLM in a thread
// Wait for them to finish.
// If no main flow, nothing to layout!
if (this.mainFlow == null) return;
// Initialize if already used?
this.layoutMasterSet.resetPageMasters();
int firstAvailPageNumber = 0;
// This will layout pages and add them to the area tree
PageLayoutManager pageLM = new PageLayoutManager(areaTree, this);
// For now, skip the threading and just call run directly.
pageLM.run();
// Thread layoutThread = new Thread(pageLM);
// layoutThread.start();
// log.debug("Layout thread started");
// // wait on both managers
// try {
// layoutThread.join();
// log.debug("Layout thread done");
// } catch (InterruptedException ie) {
// log.error("PageSequence.format() interrupted waiting on layout");
// Tell the root the last page number we created.
this.root.setRunningPageNumberCounter(this.currentPageNumber);
}
private void initPageNumber() {
this.currentPageNumber = this.root.getRunningPageNumberCounter() + 1;
if (this.pageNumberType == AUTO_ODD) {
// Next page but force odd. May force empty page creation!
// Whose master is used for this??? Assume no.
// Use force-page-count=auto
// on preceding page-sequence to make sure that there is no gap!
if (currentPageNumber % 2 == 0) {
this.currentPageNumber++;
}
} else if (pageNumberType == AUTO_EVEN) {
if (currentPageNumber % 2 == 1) {
this.currentPageNumber++;
}
}
else if (pageNumberType == EXPLICIT) {
this.currentPageNumber = this.explicitFirstNumber;
}
this.firstPageNumber = this.currentPageNumber;
}
/**
* Called by PageLayoutManager when it needs a new page on which to
* place content. The PageSequence manages the page number (odd/even),
* but the PLM tells it if the page is blank or is the last page.
* @param bIsBlank If true, use a master for a blank page.
* @param bIsLast If true, use the master for the last page in the sequence.
*/
public PageViewport createPage(boolean bIsBlank, boolean bIsLast)
throws FOPException
{
// Set even/odd flag and first flag based on current state
// Should do it this way, but fix it later....
/*boolean bEvenPage = ((this.currentPageNumber %2)==0);
currentPage = makePage(bEvenPage, */
currentPage = makePage(this.currentPageNumber,
this.currentPageNumber==this.firstPageNumber,
bIsLast, bIsBlank);
return currentPage;
// The page will have a viewport/reference area pair defined
// for each region in the master.
// Set up the page itself
// currentPage.setNumber(this.currentPageNumber);
// SKIP ALL THIS FOR NOW!!!
// String formattedPageNumber =
// pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
// currentPage.setFormattedNumber(formattedPageNumber);
// this.currentPageNumber++;
// //this.root.setRunningPageNumberCounter(this.currentPageNumber);
// BodyAreaContainer bodyArea = currentPage.getBody();
// bodyArea.setIDReferences(areaTree.getIDReferences());
// // because of markers, do after fo:flow (likely also
// // justifiable because of spec)
// currentPage.setPageSequence(this);
// formatStaticContent(areaTree);
// //log.info("]");
// areaTree.addPage(currentPage);
// this.pageCount++; // used for 'force-page-count' calculations
// handle the 'force-page-count'
//forcePage(areaTree, firstAvailPageNumber);
}
/**
* Creates a new page area for the given parameters
* @param areaTree the area tree the page should be contained in
* @param firstAvailPageNumber the page number for this page
* @param isFirstPage true when this is the first page in the sequence
* @param isEmptyPage true if this page will be empty
* (e.g. forced even or odd break)
* @return a Page layout object based on the page master selected
* from the params
* TODO: modify the other methods to use even/odd flag and bIsLast
*/
private PageViewport makePage(int firstAvailPageNumber,
boolean isFirstPage, boolean bIsLast,
boolean isEmptyPage) throws FOPException {
// layout this page sequence
// while there is still stuff in the flow, ask the
// layoutMasterSet for a new page
// page number is 0-indexed
PageMaster pageMaster = getNextPageMaster(masterName,
firstAvailPageNumber,
isFirstPage, isEmptyPage);
// specification which should be handled in getNextSubsequence.
// That's not done here.
if (pageMaster == null) {
throw new FOPException("page masters exhausted. Cannot recover.");
}
PageViewport p = pageMaster.makePage();
// if (currentPage != null) {
// Vector foots = currentPage.getPendingFootnotes();
// p.setPendingFootnotes(foots);
return p;
}
/**
* Formats the static content of the current page
*/
// private void formatStaticContent(AreaTree areaTree) throws FOPException {
// SimplePageMaster simpleMaster = getCurrentSimplePageMaster();
// if (simpleMaster.getRegion(Region.BODY) != null
// && (currentPage.getBefore() != null)) {
// Flow staticFlow =
// (Flow)_flowMap.get(simpleMaster.getRegion(RegionBefore.REGION_CLASS).getRegionName());
// if (staticFlow != null) {
// AreaContainer beforeArea = currentPage.getBefore();
// beforeArea.setIDReferences(areaTree.getIDReferences());
// layoutStaticContent(staticFlow,
// simpleMaster.getRegion(RegionBefore.REGION_CLASS),
// beforeArea);
// if (simpleMaster.getRegion(RegionAfter.REGION_CLASS) != null
// && (currentPage.getAfter() != null)) {
// Flow staticFlow =
// (Flow)_flowMap.get(simpleMaster.getRegion(RegionAfter.REGION_CLASS).getRegionName());
// if (staticFlow != null) {
// AreaContainer afterArea = currentPage.getAfter();
// afterArea.setIDReferences(areaTree.getIDReferences());
// layoutStaticContent(staticFlow,
// simpleMaster.getRegion(RegionAfter.REGION_CLASS),
// afterArea);
// if (simpleMaster.getRegion(RegionStart.REGION_CLASS) != null
// && (currentPage.getStart() != null)) {
// Flow staticFlow =
// (Flow)_flowMap.get(simpleMaster.getRegion(RegionStart.REGION_CLASS).getRegionName());
// if (staticFlow != null) {
// AreaContainer startArea = currentPage.getStart();
// startArea.setIDReferences(areaTree.getIDReferences());
// layoutStaticContent(staticFlow,
// simpleMaster.getRegion(RegionStart.REGION_CLASS),
// startArea);
// if (simpleMaster.getRegion(RegionEnd.REGION_CLASS) != null
// && (currentPage.getEnd() != null)) {
// Flow staticFlow =
// (Flow)_flowMap.get(simpleMaster.getRegion(RegionEnd.REGION_CLASS).getRegionName());
// if (staticFlow != null) {
// AreaContainer endArea = currentPage.getEnd();
// endArea.setIDReferences(areaTree.getIDReferences());
// layoutStaticContent(staticFlow,
// simpleMaster.getRegion(RegionEnd.REGION_CLASS),
// endArea);
// private void layoutStaticContent(Flow flow, Region region,
// AreaContainer area) throws FOPException {
// if (flow instanceof StaticContent) {
// AreaContainer beforeArea = currentPage.getBefore();
// ((StaticContent)flow).layout(area, region);
// } else {
// log.error("" + region.getName()
// + " only supports static-content flows currently. Cannot use flow named '"
// + flow.getFlowName() + "'");
/**
* Returns the next SubSequenceSpecifier for the given page sequence master. The result
* is bassed on the current state of this page sequence.
*/
// refactored from PageSequenceMaster
private SubSequenceSpecifier getNextSubsequence(PageSequenceMaster master) {
if (master.getSubSequenceSpecifierCount()
> currentSubsequenceNumber + 1) {
currentSubsequence =
master.getSubSequenceSpecifier(currentSubsequenceNumber + 1);
currentSubsequenceNumber++;
return currentSubsequence;
} else {
return null;
}
}
/**
* Returns the next simple page master for the given sequence master, page number and
* other state information
*/
private SimplePageMaster getNextSimplePageMaster(PageSequenceMaster sequenceMaster,
int currentPageNumber, boolean thisIsFirstPage,
boolean isEmptyPage) {
// handle forcing
if (isForcing) {
String nextPageMaster = getNextPageMasterName(sequenceMaster,
currentPageNumber, false, true);
return this.layoutMasterSet.getSimplePageMaster(nextPageMaster);
}
String nextPageMaster = getNextPageMasterName(sequenceMaster,
currentPageNumber, thisIsFirstPage, isEmptyPage);
return this.layoutMasterSet.getSimplePageMaster(nextPageMaster);
}
private String getNextPageMasterName(PageSequenceMaster sequenceMaster,
int currentPageNumber,
boolean thisIsFirstPage,
boolean isEmptyPage) {
if (null == currentSubsequence) {
currentSubsequence = getNextSubsequence(sequenceMaster);
}
String nextPageMaster =
currentSubsequence.getNextPageMaster(currentPageNumber,
thisIsFirstPage,
isEmptyPage);
if (null == nextPageMaster
|| isFlowForMasterNameDone(currentPageMasterName)) {
SubSequenceSpecifier nextSubsequence =
getNextSubsequence(sequenceMaster);
if (nextSubsequence == null) {
log.error("Page subsequences exhausted. Using previous subsequence.");
thisIsFirstPage =
true; // this becomes the first page in the new (old really) page master
currentSubsequence.reset();
// we leave currentSubsequence alone
}
else {
currentSubsequence = nextSubsequence;
}
nextPageMaster =
currentSubsequence.getNextPageMaster(currentPageNumber,
thisIsFirstPage,
isEmptyPage);
}
currentPageMasterName = nextPageMaster;
return nextPageMaster;
}
private SimplePageMaster getCurrentSimplePageMaster() {
return this.layoutMasterSet.getSimplePageMaster(currentPageMasterName);
}
private String getCurrentPageMasterName() {
return currentPageMasterName;
}
// refactored from LayoutMasterSet
private PageMaster getNextPageMaster(String pageSequenceName,
int currentPageNumber,
boolean thisIsFirstPage,
boolean isEmptyPage) throws FOPException {
PageMaster pageMaster = null;
// see if there is a page master sequence for this master name
PageSequenceMaster sequenceMaster =
this.layoutMasterSet.getPageSequenceMaster(pageSequenceName);
if (sequenceMaster != null) {
pageMaster = getNextSimplePageMaster(sequenceMaster,
currentPageNumber,
thisIsFirstPage,
isEmptyPage).getPageMaster();
} else { // otherwise see if there's a simple master by the given name
SimplePageMaster simpleMaster =
this.layoutMasterSet.getSimplePageMaster(pageSequenceName);
if (simpleMaster == null) {
throw new FOPException("'master-reference' for 'fo:page-sequence'"
+ "matches no 'simple-page-master' or 'page-sequence-master'");
}
currentPageMasterName = pageSequenceName;
pageMaster = simpleMaster.getNextPageMaster();
}
return pageMaster;
}
// /**
// * Returns true when there is more flow elements left to lay out.
// */
// private boolean flowsAreIncomplete() {
// boolean isIncomplete = false;
// for (Enumeration e = _flowMap.elements(); e.hasMoreElements(); ) {
// Flow flow = (Flow)e.nextElement();
// if (flow instanceof StaticContent) {
// continue;
// Status status = flow.getStatus();
// isIncomplete |= status.isIncomplete();
// return isIncomplete;
// /**
// * Returns the flow that maps to the given region class for the current
// * page master.
// */
// private Flow getCurrentFlow(String regionClass) {
// Region region = getCurrentSimplePageMaster().getRegion(regionClass);
// if (region != null) {
// Flow flow = (Flow)_flowMap.get(region.getRegionName());
// return flow;
// } else {
// System.out.println("flow is null. regionClass = '" + regionClass
// + "' currentSPM = "
// + getCurrentSimplePageMaster());
// return null;
private boolean isFlowForMasterNameDone(String masterName) {
// parameter is master-name of PMR; we need to locate PM
// referenced by this, and determine whether flow(s) are OK
if (isForcing)
return false;
if (masterName != null) {
SimplePageMaster spm =
this.layoutMasterSet.getSimplePageMaster(masterName);
Region region = spm.getRegion(Region.BODY);
Flow flow = (Flow)_flowMap.get(region.getRegionName());
if ((null == flow) || flow.getStatus().isIncomplete())
return false;
else
return true;
}
return false;
}
public boolean isFlowSet() {
return isFlowSet;
}
public void setIsFlowSet(boolean isFlowSet) {
this.isFlowSet = isFlowSet;
}
public String getIpnValue() {
return ipnValue;
}
public int getCurrentPageNumber() {
return currentPageNumber;
}
// private void forcePage(AreaTree areaTree, int firstAvailPageNumber) {
// boolean makePage = false;
// if (this.forcePageCount == ForcePageCount.AUTO) {
// PageSequence nextSequence =
// this.root.getSucceedingPageSequence(this);
// if (nextSequence != null) {
// if (nextSequence.getIpnValue().equals("auto")) {
// // do nothing special
// else if (nextSequence.getIpnValue().equals("auto-odd")) {
// if (firstAvailPageNumber % 2 == 0) {
// makePage = true;
// } else if (nextSequence.getIpnValue().equals("auto-even")) {
// if (firstAvailPageNumber % 2 != 0) {
// makePage = true;
// } else {
// int nextSequenceStartPageNumber =
// nextSequence.getCurrentPageNumber();
// if ((nextSequenceStartPageNumber % 2 == 0)
// && (firstAvailPageNumber % 2 == 0)) {
// makePage = true;
// } else if ((nextSequenceStartPageNumber % 2 != 0)
// && (firstAvailPageNumber % 2 != 0)) {
// makePage = true;
// } else if ((this.forcePageCount == ForcePageCount.EVEN)
// && (this.pageCount % 2 != 0)) {
// makePage = true;
// } else if ((this.forcePageCount == ForcePageCount.ODD)
// && (this.pageCount % 2 == 0)) {
// makePage = true;
// } else if ((this.forcePageCount == ForcePageCount.END_ON_EVEN)
// && (firstAvailPageNumber % 2 == 0)) {
// makePage = true;
// } else if ((this.forcePageCount == ForcePageCount.END_ON_ODD)
// && (firstAvailPageNumber % 2 != 0)) {
// makePage = true;
// } else if (this.forcePageCount == ForcePageCount.NO_FORCE) {
// // do nothing
// if (makePage) {
// try {
// this.isForcing = true;
// this.currentPageNumber++;
// firstAvailPageNumber = this.currentPageNumber;
// currentPage = makePage(areaTree, firstAvailPageNumber, false,
// true);
// String formattedPageNumber =
// pageNumberGenerator.makeFormattedPageNumber(this.currentPageNumber);
// currentPage.setFormattedNumber(formattedPageNumber);
// currentPage.setPageSequence(this);
// formatStaticContent(areaTree);
// log.debug("[forced-" + firstAvailPageNumber + "]");
// areaTree.addPage(currentPage);
// this.root.setRunningPageNumberCounter(this.currentPageNumber);
// this.isForcing = false;
// } catch (FOPException fopex) {
// log.debug("'force-page-count' failure");
}
|
package org.biojava.bio.seq.io;
import java.io.*;
import java.util.*;
import org.biojava.bio.*;
import org.biojava.utils.*;
import org.biojava.bio.symbol.*;
import org.biojava.bio.seq.*;
/**
* Simple parser for feature tables. This is shared between
* the EMBL and GENBANK format readers.
*
* <p>
* This has been partially re-written for newio, but would probably
* benefit from a few more changes. In particular, it should notify
* startFeature as early as possible, then use addFeatureProperty.
* </p>
*
* @author Thomas Down
* @author Matthew Pocock
*/
class FeatureTableParser {
private final static int WITHOUT=0;
private final static int WITHIN=1;
private final static int LOCATION=2;
private final static int ATTRIBUTE=3;
private int featureStatus = WITHOUT;
private StringBuffer featureBuf;
private String featureType;
private Location featureLocation;
private Map featureAttributes;
private StrandedFeature.Strand featureStrand;
private SeqIOListener listener;
FeatureTableParser(SeqIOListener listener) {
this.listener = listener;
featureBuf = new StringBuffer();
featureAttributes = new HashMap();
}
public void startFeature(String type) throws BioException {
featureType = type;
featureStatus = LOCATION;
featureBuf.setLength(0);
featureAttributes.clear();
}
public void featureData(String line) throws BioException {
// System.out.println(line);
// System.out.println(featureStatus);
switch (featureStatus) {
case LOCATION:
featureBuf.append(line);
if (countChar(featureBuf, '(') == countChar(featureBuf, ')')) {
featureLocation = parseLocation(featureBuf.toString());
featureStatus = WITHIN;
}
break;
case WITHIN:
if (line.charAt(0) == '/') {
// System.out.println("got '/', quotes = " + countChar(line, '"'));
if (countChar(line, '"') % 2 == 0)
processAttribute(line);
else {
featureBuf.setLength(0);
featureBuf.append(line);
featureStatus = ATTRIBUTE;
}
} else {
throw new BioException("Invalid line in feature body: "+line);
}
break;
case ATTRIBUTE:
featureBuf.append(line);
if (countChar(featureBuf, '"') % 2 == 0) {
processAttribute(featureBuf.toString());
featureStatus = WITHIN;
}
break;
}
}
public void endFeature()
throws BioException
{
listener.startFeature(buildFeatureTemplate(featureType,
featureLocation,
featureStrand,
featureAttributes));
listener.endFeature();
featureStatus = WITHOUT;
}
protected Feature.Template buildFeatureTemplate(String type,
Location loc,
StrandedFeature.Strand strandHint,
Map attrs)
{
StrandedFeature.Template t = new StrandedFeature.Template();
t.annotation = new SimpleAnnotation();
for (Iterator i = attrs.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry) i.next();
try {
t.annotation.setProperty(e.getKey(), e.getValue());
} catch (ChangeVetoException cve) {
throw new BioError(
cve,
"Assertion Failure: Couldn't set up the annotation"
);
}
}
t.location = loc;
t.type = type;
t.source = "EMBL";
t.strand = strandHint;
return t;
}
private Location parseLocation(String loc) throws BioException {
boolean joining = false;
boolean complementing = false;
boolean isComplement = false;
boolean ranging = false;
boolean fuzzyMin = false;
boolean fuzzyMax = false;
int start = -1;
Location result = null;
List locationList = null;
StringTokenizer toke = new StringTokenizer(loc, "(),. ><", true);
int level = 0;
while (toke.hasMoreTokens()) {
String t = toke.nextToken();
// System.err.println(t);
if (t.equals("join") || t.equals("order")) {
joining = true;
locationList = new ArrayList();
} else if (t.equals("complement")) {
complementing = true;
isComplement = true;
} else if (t.equals("(")) {
++level;
} else if (t.equals(")")) {
--level;
} else if (t.equals(".")) {
} else if (t.equals(",")) {
} else if (t.equals(">")) {
if (ranging) {
fuzzyMax = true;
} else {
fuzzyMin = true;
}
} else if (t.equals("<")) {
if (ranging) {
fuzzyMax = true;
} else {
fuzzyMin = true;
}
} else if (t.equals(" ")) {
} else {
// System.err.println("Range! " + ranging);
// This ought to be an actual coordinate.
int pos = -1;
try {
pos = Integer.parseInt(t);
} catch (NumberFormatException ex) {
throw new BioException("bad locator: " + t + " " + loc);
}
if (ranging == false) {
start = pos;
ranging = true;
} else {
Location rl = new RangeLocation(start, pos);
if (fuzzyMin || fuzzyMax) {
rl = new FuzzyLocation(rl, fuzzyMin, fuzzyMax);
}
if (joining) {
locationList.add(rl);
} else {
if (result != null) {
throw new BioException(
"Tried to set result to " + rl +
" when it was alredy set to " + result
);
}
result = rl;
}
ranging = false;
complementing = false;
fuzzyMin = fuzzyMax = false;
}
}
}
if (level != 0) {
throw new BioException("Mismatched parentheses: " + loc);
}
if (ranging) {
Location rl = new PointLocation(start);
if (joining) {
locationList.add(rl);
} else {
if (result != null) {
throw new BioException();
}
result = rl;
}
}
if (isComplement) {
featureStrand = StrandedFeature.NEGATIVE;
} else {
featureStrand = StrandedFeature.POSITIVE;
}
if (result == null) {
if(locationList == null) {
throw new BioException("Location null: " + loc);
}
result = new CompoundLocation(locationList);
}
return result;
}
private void processAttribute(String attr) throws BioException {
// System.err.println(attr);
int eqPos = attr.indexOf('=');
if (eqPos == -1) {
featureAttributes.put(attr.substring(1), Boolean.TRUE);
} else {
String tag = attr.substring(1, eqPos);
eqPos++;
if (attr.charAt(eqPos) == '"')
++eqPos;
int max = attr.length();
if (attr.charAt(max - 1) == '"')
--max;
String val = attr.substring(eqPos, max);
if (val.indexOf('"') >= 0) {
StringBuffer sb = new StringBuffer();
boolean escape = false;
for (int i = 0; i < val.length(); ++i) {
char c = val.charAt(i);
if (c == '"') {
if (escape)
sb.append(c);
escape = !escape;
} else {
sb.append(c);
escape = false;
}
}
val = sb.toString();
}
featureAttributes.put(tag, val);
}
}
public boolean inFeature() {
return (featureStatus != WITHOUT);
}
private int countChar(StringBuffer s, char c) {
int cnt = 0;
for (int i = 0; i < s.length(); ++i)
if (s.charAt(i) == c)
++cnt;
return cnt;
}
private int countChar(String s, char c) {
int cnt = 0;
for (int i = 0; i < s.length(); ++i)
if (s.charAt(i) == c)
++cnt;
return cnt;
}
}
|
package org.bouncycastle.crypto.digests;
import org.bouncycastle.crypto.*;
/**
* implementation of MD2
* as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
*/
public class MD2Digest
implements ExtendedDigest
{
private static final int DIGEST_LENGTH = 16;
/* X buffer */
private byte[] X = new byte[48];
private int xOff;
/* M buffer */
private byte[] M = new byte[16];
private int mOff;
/* check sum */
private byte[] C = new byte[16];
private int COff;
public MD2Digest()
{
reset();
}
public MD2Digest(MD2Digest t)
{
System.arraycopy(t.X, 0, X, 0, t.X.length);
xOff = t.xOff;
System.arraycopy(t.M, 0, M, 0, t.M.length);
mOff = t.mOff;
System.arraycopy(t.C, 0, C, 0, t.C.length);
COff = t.COff;
}
/**
* return the algorithm name
*
* @return the algorithm name
*/
public String getAlgorithmName()
{
return "MD2";
}
/**
* return the size, in bytes, of the digest produced by this message digest.
*
* @return the size, in bytes, of the digest produced by this message digest.
*/
public int getDigestSize()
{
return DIGEST_LENGTH;
}
/**
* close the digest, producing the final digest value. The doFinal
* call leaves the digest reset.
*
* @param out the array the digest is to be copied into.
* @param outOff the offset into the out array the digest is to start at.
*/
public int doFinal(byte[] out, int outOff)
{
// add padding
byte paddingByte = (byte)(M.length-mOff);
for (int i=mOff;i<M.length;i++)
{
M[i] = paddingByte;
}
//do final check sum
processCheckSum(M);
// do final block process
processBlock(M);
processBlock(C);
System.arraycopy(X,xOff,out,outOff,16);
reset();
return DIGEST_LENGTH;
}
/**
* reset the digest back to it's initial state.
*/
public void reset()
{
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
mOff = 0;
for (int i = 0; i != M.length; i++)
{
M[i] = 0;
}
COff = 0;
for (int i = 0; i != C.length; i++)
{
C[i] = 0;
}
}
/**
* update the message digest with a single byte.
*
* @param in the input byte to be entered.
*/
public void update(byte in)
{
M[mOff++] = in;
if (mOff == 16)
{
processCheckSum(M);
processBlock(M);
mOff = 0;
}
}
/**
* update the message digest with a block of bytes.
*
* @param in the byte array containing the data.
* @param inOff the offset into the byte array where the data starts.
* @param len the length of the data.
*/
public void update(byte[] in, int inOff, int len)
{
// fill the current word
while ((mOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len
}
// process whole words.
while (len > 16)
{
System.arraycopy(in,inOff,M,0,16);
processCheckSum(M);
processBlock(M);
len -= 16;
inOff += 16;
}
// load in the remainder.
while (len > 0)
{
update(in[inOff]);
inOff++;
len
}
}
protected void processCheckSum(byte[] m)
{
int L = C[15];
for (int i=0;i<16;i++)
{
C[i] ^= S[(m[i] ^ L) & 0xff];
L = C[i];
}
}
protected void processBlock(byte[] m)
{
for (int i=0;i<16;i++)
{
X[i+16] = m[i];
X[i+32] = (byte)(m[i] ^ X[i]);
}
// encrypt block
int t = 0;
for (int j=0;j<18;j++)
{
for (int k=0;k<48;k++)
{
t = X[k] ^= S[t];
t = t & 0xff;
}
t = (t + j)%256;
}
}
// 256-byte random permutation constructed from the digits of PI
private static final byte[] S = {
(byte)41,(byte)46,(byte)67,(byte)201,(byte)162,(byte)216,(byte)124,
(byte)1,(byte)61,(byte)54,(byte)84,(byte)161,(byte)236,(byte)240,
(byte)6,(byte)19,(byte)98,(byte)167,(byte)5,(byte)243,(byte)192,
(byte)199,(byte)115,(byte)140,(byte)152,(byte)147,(byte)43,(byte)217,
(byte)188,(byte)76,(byte)130,(byte)202,(byte)30,(byte)155,(byte)87,
(byte)60,(byte)253,(byte)212,(byte)224,(byte)22,(byte)103,(byte)66,
(byte)111,(byte)24,(byte)138,(byte)23,(byte)229,(byte)18,(byte)190,
(byte)78,(byte)196,(byte)214,(byte)218,(byte)158,(byte)222,(byte)73,
(byte)160,(byte)251,(byte)245,(byte)142,(byte)187,(byte)47,(byte)238,
(byte)122,(byte)169,(byte)104,(byte)121,(byte)145,(byte)21,(byte)178,
(byte)7,(byte)63,(byte)148,(byte)194,(byte)16,(byte)137,(byte)11,
(byte)34,(byte)95,(byte)33,(byte)128,(byte)127,(byte)93,(byte)154,
(byte)90,(byte)144,(byte)50,(byte)39,(byte)53,(byte)62,(byte)204,
(byte)231,(byte)191,(byte)247,(byte)151,(byte)3,(byte)255,(byte)25,
(byte)48,(byte)179,(byte)72,(byte)165,(byte)181,(byte)209,(byte)215,
(byte)94,(byte)146,(byte)42,(byte)172,(byte)86,(byte)170,(byte)198,
(byte)79,(byte)184,(byte)56,(byte)210,(byte)150,(byte)164,(byte)125,
(byte)182,(byte)118,(byte)252,(byte)107,(byte)226,(byte)156,(byte)116,
(byte)4,(byte)241,(byte)69,(byte)157,(byte)112,(byte)89,(byte)100,
(byte)113,(byte)135,(byte)32,(byte)134,(byte)91,(byte)207,(byte)101,
(byte)230,(byte)45,(byte)168,(byte)2,(byte)27,(byte)96,(byte)37,
(byte)173,(byte)174,(byte)176,(byte)185,(byte)246,(byte)28,(byte)70,
(byte)97,(byte)105,(byte)52,(byte)64,(byte)126,(byte)15,(byte)85,
(byte)71,(byte)163,(byte)35,(byte)221,(byte)81,(byte)175,(byte)58,
(byte)195,(byte)92,(byte)249,(byte)206,(byte)186,(byte)197,(byte)234,
(byte)38,(byte)44,(byte)83,(byte)13,(byte)110,(byte)133,(byte)40,
(byte)132, 9,(byte)211,(byte)223,(byte)205,(byte)244,(byte)65,
(byte)129,(byte)77,(byte)82,(byte)106,(byte)220,(byte)55,(byte)200,
(byte)108,(byte)193,(byte)171,(byte)250,(byte)36,(byte)225,(byte)123,
(byte)8,(byte)12,(byte)189,(byte)177,(byte)74,(byte)120,(byte)136,
(byte)149,(byte)139,(byte)227,(byte)99,(byte)232,(byte)109,(byte)233,
(byte)203,(byte)213,(byte)254,(byte)59,(byte)0,(byte)29,(byte)57,
(byte)242,(byte)239,(byte)183,(byte)14,(byte)102,(byte)88,(byte)208,
(byte)228,(byte)166,(byte)119,(byte)114,(byte)248,(byte)235,(byte)117,
(byte)75,(byte)10,(byte)49,(byte)68,(byte)80,(byte)180,(byte)143,
(byte)237,(byte)31,(byte)26,(byte)219,(byte)153,(byte)141,(byte)51,
(byte)159,(byte)17,(byte)131,(byte)20
};
public int getByteLength()
{
return 16;
}
}
|
package org.broad.igv.renderer;
import org.apache.log4j.Logger;
import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.track.FeatureTrack;
import org.broad.igv.track.RenderContext;
import org.broad.igv.track.Track;
import org.broad.igv.track.TrackType;
import org.broad.igv.ui.FontManager;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.util.collections.MultiMap;
import java.awt.*;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.util.*;
import java.util.List;
/**
* Renderer for the full "IGV" feature interface
*/
public class IGVFeatureRenderer extends FeatureRenderer {
private static Logger log = Logger.getLogger(IGVFeatureRenderer.class);
// Constants
static protected final int NORMAL_STRAND_Y_OFFSET = 14;
static protected final int ARROW_SPACING = 30;
static protected final int NO_STRAND_THICKNESS = 2;
static protected final int REGION_STRAND_THICKNESS = 4;
static final int BLOCK_HEIGHT = 14;
static final int THIN_BLOCK_HEIGHT = 6;
static final Color AA_COLOR_1 = new Color(92, 92, 164);
static final Color AA_COLOR_2 = new Color(12, 12, 120);
static final Color DULL_BLUE = new Color(0, 0, 200);
static final Color DULL_RED = new Color(200, 0, 0);
static final int NON_CODING_HEIGHT = 8;
float viewLimitMin = Float.NaN;
float viewLimitMax = Float.NaN;
// Use the max of these values to determine where
// text should be drawn
//protected double lastFeatureLineMaxY = 0;
//protected double lastFeatureBoundsMaxY = 0;
//protected double lastRegionMaxY = 0;
protected boolean drawBoundary = false;
int blockHeight = BLOCK_HEIGHT;
int thinBlockHeight = THIN_BLOCK_HEIGHT;
//Map from Exon to y offset
//Could use more coordinates, but they are all contained in the Exon
private Map<IExon, Integer> exonMap = new HashMap<IExon, Integer>(100);
private AlternativeSpliceGraph<Integer> exonGraph = new AlternativeSpliceGraph<Integer>();
private Set<String> drawnNames = new HashSet<String>(100);
/**
* Note: assumption is that featureList is sorted by start position.
*
* @param featureList
* @param context
* @param trackRectangle
* @param track
*/
public void render(List<IGVFeature> featureList,
RenderContext context,
Rectangle trackRectangle,
Track track) {
double origin = context.getOrigin();
double locScale = context.getScale();
double end = origin + trackRectangle.width * locScale;
final Track.DisplayMode displayMode = track.getDisplayMode();
blockHeight = displayMode == Track.DisplayMode.SQUISHED ? BLOCK_HEIGHT / 2 : BLOCK_HEIGHT;
thinBlockHeight = displayMode == Track.DisplayMode.SQUISHED ? THIN_BLOCK_HEIGHT / 2 : THIN_BLOCK_HEIGHT;
// TODO -- use enum instead of string "Color"
if ((featureList != null) && (featureList.size() > 0)) {
// Create a graphics object to draw font names. Graphics are not cached
// by font, only by color, so its neccessary to create a new one to prevent
// affecting other tracks.
Font font = FontManager.getFont(track.getFontSize());
Graphics2D fontGraphics = (Graphics2D) context.getGraphic2DForColor(Color.BLACK).create();
fontGraphics.setFont(font);
// Track coordinates
int trackRectangleX = trackRectangle.x;
int trackRectangleMaxX = trackRectangleX + trackRectangle.width;
int trackRectangleY = trackRectangle.y;
int trackRectangleMaxY = trackRectangleY + trackRectangle.height;
int lastNamePixelEnd = -9999;
int lastPixelEnd = -1;
int occludedCount = 0;
int maxOcclusions = 2;
boolean alternateExonColor = (track instanceof FeatureTrack && ((FeatureTrack) track).isAlternateExonColor());
for (IGVFeature feature : featureList) {
if (feature.getEnd() < origin) continue;
if (feature.getStart() > end) break;
// Get the pStart and pEnd of the entire feature at extreme zoom levels the
// virtual pixel value can be too large for an int, so the computation is
// done in double precision and cast to an int only when its confirmed its
// within the field of view.
double virtualPixelStart = Math.round((feature.getStart() - origin) / locScale);
double virtualPixelEnd = Math.round((feature.getEnd() - origin) / locScale);
int pixelEnd = (int) Math.min(trackRectangleMaxX, virtualPixelEnd);
int pixelStart = (int) Math.max(trackRectangleX, virtualPixelStart);
// Draw a maximum of "maxOcclusions" features on top of each other.
if (pixelEnd <= lastPixelEnd) {
if (occludedCount >= maxOcclusions) {
continue;
} else {
occludedCount++;
}
} else {
occludedCount = 0;
lastPixelEnd = pixelEnd;
}
Color color = getFeatureColor(feature, track);
Graphics2D g2D = context.getGraphic2DForColor(color);
// Draw block representing entire feature
int pixelThickStart = pixelStart;
int pixelThickEnd = pixelEnd;
boolean hasExons = false;
if (feature instanceof BasicFeature) {
BasicFeature bf = (BasicFeature) feature;
pixelThickStart = (int) Math.max(trackRectangleX, (bf.getThickStart() - origin) / locScale);
pixelThickEnd = (int) Math.min(trackRectangleMaxX, (bf.getThickEnd() - origin) / locScale);
hasExons = bf.hasExons();
}
// Add directional arrows and exons, if there is room.
int pixelYCenter = trackRectangle.y + NORMAL_STRAND_Y_OFFSET / 2;
if (!hasExons) {
drawFeatureBlock(pixelStart, pixelEnd, pixelThickStart, pixelThickEnd, pixelYCenter, g2D);
}
if ((pixelEnd - pixelStart < 3) && hasExons) {
drawFeatureBounds(pixelStart, pixelEnd, pixelYCenter, g2D);
} else {
if (hasExons) {
drawExons(feature, pixelYCenter, context, g2D, trackRectangle, displayMode,
alternateExonColor, track.getColor(), track.getAltColor());
}else{
Graphics2D arrowGraphics = hasExons
? g2D
: context.getGraphic2DForColor(Color.WHITE);
drawStrandArrows(feature.getStrand(), pixelStart, pixelEnd, pixelYCenter, 0,
displayMode, arrowGraphics);
}
}
// Draw name , if there is room
if (displayMode != Track.DisplayMode.SQUISHED) {
String name = feature.getName();
if (name != null) {
LineMetrics lineMetrics = font.getLineMetrics(name, g2D.getFontRenderContext());
int fontHeight = (int) Math.ceil(lineMetrics.getHeight());
// Draw feature name. Center it over the feature extent,
// or if the feature extends beyond the track bounds over
// the track rectangle.
int nameStart = Math.max(0, pixelStart);
int nameEnd = Math.min(pixelEnd, (int) trackRectangle.getWidth());
int textBaselineY = pixelYCenter + blockHeight;
// Calculate the minimum amount of vertical track
// space required be we draw the
// track name without drawing over the features
int verticalSpaceRequiredForText = textBaselineY - trackRectangleY;
if (verticalSpaceRequiredForText <= trackRectangle.height) {
lastNamePixelEnd = drawFeatureName(feature, track.getDisplayMode(), nameStart, nameEnd,
lastNamePixelEnd, fontGraphics, textBaselineY);
}
}
}
// If this is the highlight feature highlight it
if (getHighlightFeature() == feature) {
int yStart = pixelYCenter - blockHeight / 2 - 1;
Graphics2D highlightGraphics = context.getGraphic2DForColor(Color.cyan);
highlightGraphics.drawRect(pixelStart - 1, yStart, (pixelEnd - pixelStart + 2), blockHeight + 2);
}
}
if (drawBoundary) {
Graphics2D g2D = context.getGraphic2DForColor(Color.LIGHT_GRAY);
g2D.drawLine((int) trackRectangleX, (int) trackRectangleMaxY - 1,
(int) trackRectangleMaxX, (int) trackRectangleMaxY - 1);
}
}
}
/**
* @param pixelStart
* @param pixelEnd
* @param pixelThickStart
* @param pixelThickEnd
* @param yOffset
* @param g
*/
final private void drawFeatureBlock(int pixelStart, int pixelEnd, int pixelThickStart, int pixelThickEnd,
int yOffset, Graphics2D g) {
Graphics2D g2D = (Graphics2D) g.create();
if (pixelThickStart > pixelStart) {
g2D.fillRect(pixelStart, yOffset - (thinBlockHeight) / 2,
Math.max(1, pixelThickStart - pixelStart), (thinBlockHeight));
}
if (pixelThickEnd > 0 && pixelThickEnd < pixelEnd) {
g2D.fillRect(pixelThickEnd, yOffset - (thinBlockHeight) / 2,
Math.max(1, pixelEnd - pixelThickEnd), (thinBlockHeight));
}
g2D.fillRect(pixelThickStart, yOffset - (blockHeight - 4) / 2,
Math.max(1, pixelThickEnd - pixelThickStart), (blockHeight - 4));
g2D.dispose();
}
final private void drawConnectingLine(int startX, int startY, int endX, int endY, Strand strand, Graphics2D g) {
Graphics2D g2D = (Graphics2D) g.create();
float lineThickness = ((BasicStroke) g.getStroke()).getLineWidth();
if (strand == null) {
// Double the line thickness
lineThickness *= NO_STRAND_THICKNESS;
Stroke stroke = new BasicStroke(lineThickness);
g2D.setStroke(stroke);
}
g2D.drawLine(startX, startY, endX, endY);
g2D.dispose();
}
// If the width is < 3 there isn't room to draw the
// feature, or orientation. If the feature has any exons
// at all indicate by filling a small rect
private void drawFeatureBounds(int pixelStart, int pixelEnd, int yOffset, Graphics2D g2D) {
if (pixelEnd == pixelStart) {
int yStart = yOffset - blockHeight / 2;
g2D.drawLine(pixelStart, yStart, pixelStart, yStart + blockHeight);
} else {
g2D.fillRect(pixelStart, yOffset - blockHeight / 2, pixelEnd - pixelStart, blockHeight);
}
}
protected void drawExons(IGVFeature gene, int yOffset, RenderContext context,
Graphics2D g2D, Rectangle trackRectangle, Track.DisplayMode mode,
boolean alternateExonColor, Color color1, Color color2) {
Graphics exonNumberGraphics = g2D.create();
exonNumberGraphics.setColor(Color.BLACK);
exonNumberGraphics.setFont(FontManager.getFont(Font.BOLD, 8));
// Now get the individual regions of the
// feature are drawn here
double theOrigin = context.getOrigin();
double locationScale = context.getScale();
Graphics2D fontGraphics = context.getGraphic2DForColor(Color.WHITE);
boolean colorToggle = true;
int lastX = Integer.MIN_VALUE;
int lastY = Integer.MIN_VALUE;
IExon lastExon = null;
exonGraph.startFeature();
for (Exon exon : gene.getExons()) {
// Parse expression from tags, if available
//Credit Michael Poidinger and Solomonraj Wilson, Singapore Immunology Network.
Float exprValue = null;
MultiMap<String, String> attributes = exon.getAttributes();
if (attributes != null && attributes.containsKey("expr")) {
try {
exprValue = Float.parseFloat(attributes.get("expr"));
} catch (NumberFormatException e) {
log.error("Error parsing expression tag " + attributes.get("expr"), e);
}
}
if (exprValue != null) {
ContinuousColorScale colorScale = PreferenceManager.getInstance().getColorScale(TrackType.GENE_EXPRESSION);
Color chartColor = colorScale.getColor(exprValue);
g2D = context.getGraphic2DForColor(chartColor);
}
// Added by Solomon - End
Graphics2D blockGraphics = g2D;
Graphics2D edgeGraphics = context.getGraphic2DForColor(Color.gray);
if (alternateExonColor) {
Color color = colorToggle ? color1 : color2;
blockGraphics = context.getGraphic2DForColor(color);
colorToggle = !colorToggle;
}
int curYOffset = yOffset;
boolean drawConnectingLine = true;
if (mode == Track.DisplayMode.ALTERNATIVE_SPLICE) {
IExon eProx = Exon.getExonProxy(exon);
drawConnectingLine = !exonGraph.containsEdge(lastExon, eProx);
if (exonGraph.hasParameter(eProx)) {
curYOffset = exonGraph.getParameter(eProx);
} else {
exonGraph.put(eProx, curYOffset);
}
lastExon = eProx;
}
int pStart = getPixelFromChromosomeLocation(exon.getChr(), exon.getStart(), theOrigin, locationScale);
int pEnd = getPixelFromChromosomeLocation(exon.getChr(), exon.getEnd(), theOrigin, locationScale);
Graphics2D arrowGraphics = context.getGraphic2DForColor(Color.blue);
if (drawConnectingLine && lastX > Integer.MIN_VALUE && lastY > Integer.MIN_VALUE) {
drawConnectingLine(lastX, lastY, pStart, curYOffset, exon.getStrand(), blockGraphics);
double angle = Math.atan(-(curYOffset - lastY) / ((pStart - lastX) + 1e-12));
drawStrandArrows(gene.getStrand(), lastX, pStart, lastY, angle, mode, arrowGraphics);
}
lastX = pEnd;
lastY = curYOffset;
if ((pEnd >= trackRectangle.getX()) && (pStart <= trackRectangle.getMaxX())) {
int pCdStart =
Math.min(pEnd, Math.max(pStart,
getPixelFromChromosomeLocation(exon.getChr(),
exon.getCdStart(), theOrigin, locationScale)));
int pCdEnd = Math.max(pStart, Math.min(pEnd,
getPixelFromChromosomeLocation(exon.getChr(),
exon.getCdEnd(), theOrigin, locationScale)));
// Entire exon is UTR
if (exon.isUTR()) {
int pClippedStart = (int) Math.max(pStart, trackRectangle.getX());
int pClippedEnd = (int) Math.min(pEnd, trackRectangle.getMaxX());
int pClippedWidth = pClippedEnd - pClippedStart;
blockGraphics.fillRect(pClippedStart, curYOffset - NON_CODING_HEIGHT / 2, pClippedWidth, NON_CODING_HEIGHT);
} else {// Exon contains 5' UTR -- draw non-coding part
if (pCdStart > pStart) {
int pClippedStart = (int) Math.max(pStart, trackRectangle.getX());
int pClippedEnd = (int) Math.min(pCdStart, trackRectangle.getMaxX());
int pClippedWidth = pClippedEnd - pClippedStart;
blockGraphics.fillRect(pClippedStart, curYOffset - NON_CODING_HEIGHT / 2, pClippedWidth, NON_CODING_HEIGHT);
pStart = pCdStart;
}
// Exon contains 3' UTR -- draw non-coding part
if (pCdEnd < pEnd) {
int pClippedStart = (int) Math.max(pCdEnd, trackRectangle.getX());
int pClippedEnd = (int) Math.min(pEnd, trackRectangle.getMaxX());
int pClippedWidth = pClippedEnd - pClippedStart;
blockGraphics.fillRect(pClippedStart, curYOffset - NON_CODING_HEIGHT / 2, pClippedWidth, NON_CODING_HEIGHT);
pEnd = pCdEnd;
}
// At least part of this exon is coding. Draw the coding part.
if ((exon.getCdStart() < exon.getEnd()) && (exon.getCdEnd() > exon.getStart())) {
int pClippedStart = (int) Math.max(pStart, trackRectangle.getX());
int pClippedEnd = (int) Math.min(pEnd, trackRectangle.getMaxX());
int pClippedWidth = Math.max(2, pClippedEnd - pClippedStart);
blockGraphics.fillRect(pClippedStart, curYOffset - blockHeight / 2, pClippedWidth, blockHeight);
}
}
Graphics2D whiteArrowGraphics = context.getGraphic2DForColor(Color.white);
drawStrandArrows(gene.getStrand(), pStart + ARROW_SPACING / 2, pEnd, curYOffset, 0, mode,
whiteArrowGraphics);
if (locationScale < 0.25) {
labelAminoAcids(pStart, fontGraphics, theOrigin, context, gene, locationScale,
curYOffset, exon, trackRectangle);
}
if (FrameManager.isExomeMode()) {
//Draw exon edge bound
int halfHeight = blockHeight / 2;
edgeGraphics.drawLine(pStart, curYOffset - halfHeight, pStart, curYOffset + halfHeight - 1);
edgeGraphics.drawLine(pEnd, curYOffset - halfHeight, pEnd, curYOffset + halfHeight - 1);
}
}
}
}
/**
* @param strand
* @param startX
* @param endX
* @param startY
* @param angle
* @param mode
* @param g2D
*/
protected void drawStrandArrows(Strand strand, int startX, int endX, int startY, double angle, Track.DisplayMode mode,
Graphics2D g2D) {
// Don't draw strand arrows for very small regions
int distance = endX - startX;
if ((distance < 6)) {
return;
}
Graphics2D g = (Graphics2D) g2D.create();
// Limit drawing to visible region, we don't really know the viewport pEnd,
int vStart = 0;
int vEnd = 10000;
// Draw the directional arrows on the feature
int sz = mode == Track.DisplayMode.EXPANDED ? 3 : 2;
sz = strand.equals(Strand.POSITIVE) ? -sz : sz;
final int asz = Math.abs(sz);
/*
We draw arrows in a translated and rotated frame.
This is to deal with alternative splice
*/
g.translate(startX, startY);
g.rotate(-angle);
double endXInFrame = distance / Math.cos(angle);
for (int ii = ARROW_SPACING / 2; ii < endXInFrame; ii += ARROW_SPACING) {
g.drawLine(ii, 0, ii + sz, +asz);
g.drawLine(ii, 0, ii + sz, -asz);
}
}
final private int drawFeatureName(IGVFeature feature, Track.DisplayMode mode, int pixelStart, int pixelEnd,
int lastFeatureEndedAtPixelX, Graphics2D g2D,
int textBaselineY) {
String name = feature.getName();
if (name == null || (drawnNames.contains(name) && mode == Track.DisplayMode.ALTERNATIVE_SPLICE)) {
return lastFeatureEndedAtPixelX;
}
FontMetrics fm = g2D.getFontMetrics();
int fontSize = fm.getFont().getSize();
int nameWidth = fm.stringWidth(name);
int nameStart = (pixelStart + pixelEnd - nameWidth) / 2;
Rectangle2D sb = fm.getStringBounds(name, g2D);
if (nameStart > (lastFeatureEndedAtPixelX + fontSize) && sb.getWidth() < g2D.getClipBounds().getWidth()) {
// g2D.clearRect(xString2, textBaselineY, (int) stringBounds.getWidth(), (int) stringBounds.getHeight());
g2D.drawString(name, nameStart, textBaselineY);
lastFeatureEndedAtPixelX = nameStart + nameWidth;
drawnNames.add(name);
}
return lastFeatureEndedAtPixelX;
}
/**
* Method description
*
* @param pStart
* @param fontGraphics
* @param theOrigin
* @param context
* @param gene
* @param locationScale
* @param yOffset
* @param exon
* @param trackRectangle
*/
public void labelAminoAcids(int pStart, Graphics2D fontGraphics, double theOrigin,
RenderContext context, IGVFeature gene, double locationScale,
int yOffset, Exon exon, Rectangle trackRectangle) {
Genome genome = GenomeManager.getInstance().getCurrentGenome();
AminoAcidSequence aaSequence = exon.getAminoAcidSequence(genome);
if ((aaSequence != null) && aaSequence.hasNonNullSequence()) {
Rectangle aaRect = new Rectangle(pStart, yOffset - blockHeight / 2, 1, blockHeight);
int aaSeqStartPosition = aaSequence.getStartPosition();
int firstFullAcidIndex = (int) Math.floor((aaSeqStartPosition - exon.getReadingShift()) / 3);
//calculated oddness or evenness of first amino acid. This is also done independently in SequenceRenderer
boolean odd = (firstFullAcidIndex % 2) == 1;
if (aaSeqStartPosition > exon.getStart()) {
// The codon for the first amino acid is split between this and the previous exon
// TODO -- get base from previous exon and compute aaSequence. For now skipping drawing
// the AA label
int cdStart = Math.max(exon.getCdStart(), exon.getStart());
aaRect.x = getPixelFromChromosomeLocation(exon.getChr(), cdStart, theOrigin,
locationScale);
aaRect.width = getPixelFromChromosomeLocation(exon.getChr(),
aaSeqStartPosition, theOrigin, locationScale) - aaRect.x;
if (trackRectangle.intersects(aaRect)) {
//use opposite color from first AA color
Graphics2D bgGraphics = context.getGraphic2DForColor(!odd ? AA_COLOR_1 : AA_COLOR_2);
bgGraphics.fill(aaRect);
}
}
for (AminoAcid acid : aaSequence.getSequence()) {
if (acid != null) {
int px = getPixelFromChromosomeLocation(exon.getChr(), aaSeqStartPosition, theOrigin, locationScale);
int px2 = getPixelFromChromosomeLocation(exon.getChr(), aaSeqStartPosition + 3, theOrigin, locationScale);
if ((px <= trackRectangle.getMaxX()) && (px2 >= trackRectangle.getX())) {
aaRect.x = px;
aaRect.width = px2 - px;
Graphics2D bgGraphics = context.getGraphic2DForColor(odd ? AA_COLOR_1 : AA_COLOR_2);
if (((acid.getSymbol() == 'M') && (((gene.getStrand() == Strand.POSITIVE) &&
(aaSeqStartPosition == exon.getCdStart())) || ((gene.getStrand() == Strand.NEGATIVE) &&
(aaSeqStartPosition == exon.getCdEnd() - 3))))) {
bgGraphics = context.getGraphic2DForColor(Color.green);
} else if (acid.getSymbol() == '*') {
bgGraphics = context.getGraphic2DForColor(Color.RED);
}
bgGraphics.fill(aaRect);
String tmp = new String(new char[]{acid.getSymbol()});
GraphicUtils.drawCenteredText(tmp, aaRect, fontGraphics);
}
odd = !odd;
aaSeqStartPosition += 3;
}
}
if (aaSeqStartPosition < exon.getEnd()) {
// The last codon is not complete (continues on next exon).
// TODO -- get base from previous exon and compute aaSequence
int cdEnd = Math.min(exon.getCdEnd(), exon.getEnd());
aaRect.x = getPixelFromChromosomeLocation(exon.getChr(), aaSeqStartPosition, theOrigin, locationScale);
aaRect.width = getPixelFromChromosomeLocation(exon.getChr(), cdEnd, theOrigin, locationScale) - aaRect.x;
Graphics2D bgGraphics = context.getGraphic2DForColor(odd ? AA_COLOR_1 : AA_COLOR_2);
odd = !odd;
bgGraphics.fill(aaRect);
}
}
}
/**
* Method description
*
* @return
*/
public String getDisplayName() {
return "Basic Feature";
}
protected Color getFeatureColor(IGVFeature feature, Track track) {
// Set color used to draw the feature
Color color = null;
if (track.isItemRGB()) {
color = feature.getColor();
}
if (color == null) {
// TODO -- hack, generalize this
if (track.getTrackType() == TrackType.CNV) {
color = feature.getName().equals("gain") ? DULL_RED : DULL_BLUE;
} else {
// Only used if feature color is not set
color = track.getColor();
}
}
if (track.isUseScore()) {
float min = getViewLimitMin(track);
float max = getViewLimitMax(track);
float score = feature.getScore();
float alpha = Float.isNaN(score) ? 1 : getAlpha(min, max, feature.getScore());
color = ColorUtilities.getCompositeColor(color, alpha);
}
return color;
}
float getViewLimitMin(Track track) {
if (Float.isNaN(viewLimitMin)) {
viewLimitMin = Float.isNaN(track.getViewLimitMin()) ? 0 : track.getViewLimitMin();
}
return viewLimitMin;
}
float getViewLimitMax(Track track) {
if (Float.isNaN(viewLimitMax)) {
viewLimitMax = Float.isNaN(track.getViewLimitMax()) ? 1000 : track.getViewLimitMax();
}
return viewLimitMax;
}
private float getAlpha(float minRange, float maxRange, float value) {
float binWidth = (maxRange - minRange) / 9;
int binNumber = (int) ((value - minRange) / binWidth);
return Math.min(1.0f, 0.2f + (binNumber * 0.8f) / 9);
}
protected int getPixelFromChromosomeLocation(String chr, int chromosomeLocation, double origin,
double locationScale) {
return (int) Math.round((chromosomeLocation - origin) / locationScale);
}
@Override
public void reset() {
exonMap.clear();
exonGraph = new AlternativeSpliceGraph<Integer>();
drawnNames.clear();
}
}
|
package org.concord.data.ui;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import org.concord.framework.data.DataFlow;
import org.concord.framework.data.DataFlowCapabilities;
import org.concord.framework.simulation.Simulation;
/**
* DataFlowControlAction
* Action that controls one or more data flow or
* simulation objects
* It can start, stop or reset the data flow or
* simulation objects
* It gets enabled and disabled automatically
* if desired.
*
* Date created: Sep 20, 2004
*
* @author imoncada<p>
*
*/
public class DataFlowControlAction extends AbstractAction
{
/**
* not intended to be serialized, removes compile warning
*/
private static final long serialVersionUID = 1L;
protected Vector objsFlow; //DataFlow objects
protected int flowControlType = -1;
protected boolean autoEnable = true;
/**
* Doesn't do anything to the data flow or simulation objects
*/
public final static int FLOW_CONTROL_NONE = 0;
/**
* Indicates to START the data flow or simulation objects
*/
public final static int FLOW_CONTROL_START = 1;
/**
* Indicates to STOP the data flow or simulation objects
*/
public final static int FLOW_CONTROL_STOP = 2;
/**
* Indicates to RESET the data flow or simulation objects
*/
public final static int FLOW_CONTROL_RESET = 3;
/**
* Indicates to start or stop the simulation objects,
* depending on the current simulation state (Starts them if they
* are stopped or reset, and stops them if they are already running)
* This type works for Simulation objects only
*/
public final static int FLOW_CONTROL_START_STOP = 4;
/**
* Creates an action that controls DataFlow objects,
* according to the type specified.
* @param type One of the following types:
* FLOW_CONTROL_START to start the data flow or the simulation
* FLOW_CONTROL_STOP to stop the data flow or the simulation
* FLOW_CONTROL_RESET to reset the data flow or the simulation
* FLOW_CONTROL_START_STOP to start or stop the data flow or the simulation
*/
public DataFlowControlAction(int type)
{
super();
setEnabled(false);
objsFlow = new Vector();
setFlowControlType(type);
setDefaultProperties(type);
}
/**
* Creates an action that controls the object flowObject,
* according to the type specified.
* @param flowObject The data flow or simulation object to control
* @param type One of the following types:
* FLOW_CONTROL_START to start the data flow or the simulation
* FLOW_CONTROL_STOP to stop the data flow or the simulation
* FLOW_CONTROL_RESET to reset the data flow or the simulation
* FLOW_CONTROL_START_STOP to start or stop the data flow or the simulation
*/
public DataFlowControlAction(DataFlow flowObject, int type)
{
this(type);
addDataFlowObject(flowObject);
}
protected void setDefaultProperties(int type)
{
if (type == FLOW_CONTROL_NONE){
setName("None");
}
else if (type == FLOW_CONTROL_START){
setName("Start");
setDescription("Start the simulation");
}
else if (type == FLOW_CONTROL_STOP){
setName("Stop");
setDescription("Stop the simulation");
}
else if (type == FLOW_CONTROL_RESET){
setName("Reset");
setDescription("Reset the simulation");
}
else if (type == FLOW_CONTROL_START_STOP){
setName("Start/Stop");
setDescription("Start or Stop the simulation");
}
putValue(Action.ACTION_COMMAND_KEY, String.valueOf(type));
}
/**
* Sets the long description of the action
* (Equivalent to the Action.SHORT_DESCRIPTION property)
* @param desc long description for the action
*/
public void setDescription(String desc)
{
putValue(Action.SHORT_DESCRIPTION, desc);
}
/**
* Sets the name of the action
* (Equivalent to the Action.NAME property)
* @param name name of the action
*/
public void setName(String name)
{
putValue(Action.NAME, name);
}
/**
* Sets the icon of the action
* (Equivalent to the Action.SMALL_ICON property)
* @param icon icon of the action
*/
public void setIcon(Icon icon)
{
putValue(Action.SMALL_ICON, icon);
}
/**
* Returns the data flow or simulation object at the index specified
* @return data flow object
*/
public DataFlow getDataFlowObject(int index)
{
return (DataFlow)objsFlow.elementAt(index);
}
/**
* Adds a DataFlow object that will be controlled by this action
* @param objFlow The data flow or simulation object to control
*/
public void addDataFlowObject(DataFlow objFlow)
{
if (objFlow == null) return;
if (objsFlow.contains(objFlow)) return;
objsFlow.addElement(objFlow);
if (objFlow instanceof Simulation){
Simulation objSim = (Simulation)objFlow;
setEnabled(true);
// FIXME temporary hack until the new Startable interface is complete
//objSim.addSimulationListener(this);
}
// FIXME temporary hack until the new Startable interface is complete
//enableAction(flowControlType, getSimulationState());
//Check
checkFlowObjectValid(flowControlType, objFlow);
}
private void checkFlowObjectValid(int type, DataFlow objFlow)
{
//If the type is Start/Stop, the object has to be a Simulation object
if (type == FLOW_CONTROL_START_STOP){
if (!(objFlow instanceof Simulation)){
System.err.println("Warning: Class " + objFlow.getClass().getName() +
" does not extend Simulation. Start/Stop is only valid for Simulation objects.");
}
}
}
protected void checkFlowObjectsValid(int type)
{
for (int i=0; i<objsFlow.size(); i++){
checkFlowObjectValid(type, (DataFlow)objsFlow.elementAt(i));
}
}
/**
* Removes a DataFlow object that was previously controlled by this action
* @param objFlow The data flow or simulation object to remove and not be controlled anymore
*/
public void removeDataFlowObject(DataFlow objFlow)
{
if (objFlow instanceof Simulation){
Simulation objSim = (Simulation)objFlow;
// FIXME temporary hack until Startable Interace is complete
// objSim.removeSimulationListener(this);
}
objsFlow.removeElement(objFlow);
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
if (objsFlow == null) return;
controlFlow(flowControlType);
}
/**
* @param flowControlType2
*/
private void controlFlow(int type)
{
if (type == FLOW_CONTROL_NONE) return;
DataFlow objFlow;
for (int i=0; i<objsFlow.size(); i++){
objFlow = (DataFlow)objsFlow.elementAt(i);
if (type == FLOW_CONTROL_START){
objFlow.start();
}
else if (type == FLOW_CONTROL_STOP){
objFlow.stop();
}
else if (type == FLOW_CONTROL_RESET){
objFlow.reset();
}
else if (type == FLOW_CONTROL_START_STOP){
if (objFlow instanceof Simulation){
Simulation objSim = (Simulation)objFlow;
if (objSim.isRunning()){
objSim.stop();
}
else{
objSim.start();
}
}
}
}
}
private boolean checkCapabilities(int type)
{
// Go through each object in the data flow list
// report capabilities then we must assume the button
// should be enabled.
// if the object reports
// capabilites, check which ones are available
// if the object is a simulation and is reporing
// a simulation state then that will take precendence
// over this.
for(int i=0; i<objsFlow.size(); i++) {
Object flowObject = objsFlow.get(i);
if(!(flowObject instanceof DataFlowCapabilities)) {
return true;
}
DataFlowCapabilities.Capabilities capabilities = ((DataFlowCapabilities)flowObject).getDataFlowCapabilities();
switch (type) {
case FLOW_CONTROL_NONE:
return true;
case FLOW_CONTROL_START:
if(capabilities.canStart()) {
return true;
}
break;
case FLOW_CONTROL_STOP:
if(capabilities.canStop()) {
return true;
}
break;
case FLOW_CONTROL_RESET:
if(capabilities.canReset()) {
return true;
}
break;
}
}
return false;
}
/**
* Gets the type of action (start, stop, run)
* @return Returns the flowControlType.
*/
public int getFlowControlType()
{
return flowControlType;
}
public void setFlowControlType(int type)
{
//Checking type is valid
if (type != FLOW_CONTROL_NONE && type != FLOW_CONTROL_START &&
type != FLOW_CONTROL_STOP && type != FLOW_CONTROL_RESET &&
type != FLOW_CONTROL_START_STOP){
throw new IllegalArgumentException("Type "+type+" not valid.");
}
this.flowControlType = type;
}
/**
* @return Returns the autoEnable.
*/
public boolean isAutoEnable()
{
return autoEnable;
}
/**
* Sets if the action will be enabled/disabled automatically
* depending on the simulation state of the simulation objects
* If the auto enable is set to false, the action will
* be enabled by default.
* @param autoEnable The autoEnable to set.
*/
public void setAutoEnable(boolean autoEnable)
{
this.autoEnable = autoEnable;
if (autoEnable){
// FIXME temporary hack until the new Startable interface is complete
//enableAction(flowControlType, getSimulationState());
}
else{
setEnabled(true);
}
}
}
|
package org.jetbrains.plugins.scala;
import com.intellij.lang.Language;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.lang.Commenter;
import com.intellij.lang.ParserDefinition;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.scala.highlighter.ScalaSyntaxHighlighter;
import org.jetbrains.plugins.scala.highlighter.ScalaBraceMatcher;
import org.jetbrains.plugins.scala.highlighter.ScalaCommenter;
import org.jetbrains.plugins.scala.lang.parser.ScalaParserDefinition;
public class ScalaLanguage extends Language {
protected ScalaLanguage(String s) {
super(s);
}
protected ScalaLanguage(String s, String... strings) {
super(s, strings);
}
public ScalaLanguage() {
super("Scala");
}
public ParserDefinition getParserDefinition(){
return new ScalaParserDefinition();
}
@NotNull
public SyntaxHighlighter getSyntaxHighlighter(Project project, final VirtualFile virtualFile) {
return new ScalaSyntaxHighlighter();
}
@Nullable
public PairedBraceMatcher getPairedBraceMatcher(){
return new ScalaBraceMatcher();
}
@Nullable
public Commenter getCommenter(){
return new ScalaCommenter();
}
}
|
package org.ojalgo.array.operation;
/**
* @author apete
*/
public interface ArrayOperation {
/**
* Sets all matrix size operation thresholds to precisly this value.
*
* @param value The threshold
*/
static void setAllOperationThresholds(final int value) {
ArrayOperation.setThresholdsMaxValue(value);
ArrayOperation.setThresholdsMinValue(value);
}
/**
* Will make sure no matrix size operation thresholds are larger than the supplied value. Existing smaller
* values are unchanged.
*
* @param value The max allowed value
*/
static void setThresholdsMaxValue(final int value) {
AggregateAll.THRESHOLD = Math.min(value, AggregateAll.THRESHOLD);
ApplyCholesky.THRESHOLD = Math.min(value, ApplyCholesky.THRESHOLD);
ApplyLU.THRESHOLD = Math.min(value, ApplyLU.THRESHOLD);
FillMatchingDual.THRESHOLD = Math.min(value, FillMatchingDual.THRESHOLD);
FillMatchingSingle.THRESHOLD = Math.min(value, FillMatchingSingle.THRESHOLD);
GenerateApplyAndCopyHouseholderColumn.THRESHOLD = Math.min(value, GenerateApplyAndCopyHouseholderColumn.THRESHOLD);
GenerateApplyAndCopyHouseholderRow.THRESHOLD = Math.min(value, GenerateApplyAndCopyHouseholderRow.THRESHOLD);
HermitianRank2Update.THRESHOLD = Math.min(value, HermitianRank2Update.THRESHOLD);
HouseholderLeft.THRESHOLD = Math.min(value, HouseholderLeft.THRESHOLD);
HouseholderRight.THRESHOLD = Math.min(value, HouseholderRight.THRESHOLD);
AXPY.THRESHOLD = Math.min(value, AXPY.THRESHOLD);
ModifyAll.THRESHOLD = Math.min(value, ModifyAll.THRESHOLD);
MultiplyBoth.THRESHOLD = Math.min(value, MultiplyBoth.THRESHOLD);
MultiplyHermitianAndVector.THRESHOLD = Math.min(value, MultiplyHermitianAndVector.THRESHOLD);
MultiplyNeither.THRESHOLD = Math.min(value, MultiplyNeither.THRESHOLD);
MultiplyLeft.THRESHOLD = Math.min(value, MultiplyLeft.THRESHOLD);
MultiplyRight.THRESHOLD = Math.min(value, MultiplyRight.THRESHOLD);
RotateLeft.THRESHOLD = Math.min(value, RotateLeft.THRESHOLD);
RotateRight.THRESHOLD = Math.min(value, RotateRight.THRESHOLD);
SubstituteBackwards.THRESHOLD = Math.min(value, SubstituteBackwards.THRESHOLD);
SubstituteForwards.THRESHOLD = Math.min(value, SubstituteForwards.THRESHOLD);
}
/**
* Will make sure all matrix size operation thresholds are at least as large as the supplied value.
* Existing larger values are unchanged.
*
* @param value The min allowed value
*/
static void setThresholdsMinValue(final int value) {
AggregateAll.THRESHOLD = Math.max(value, AggregateAll.THRESHOLD);
ApplyCholesky.THRESHOLD = Math.max(value, ApplyCholesky.THRESHOLD);
ApplyLU.THRESHOLD = Math.max(value, ApplyLU.THRESHOLD);
FillMatchingDual.THRESHOLD = Math.max(value, FillMatchingDual.THRESHOLD);
FillMatchingSingle.THRESHOLD = Math.max(value, FillMatchingSingle.THRESHOLD);
GenerateApplyAndCopyHouseholderColumn.THRESHOLD = Math.max(value, GenerateApplyAndCopyHouseholderColumn.THRESHOLD);
GenerateApplyAndCopyHouseholderRow.THRESHOLD = Math.max(value, GenerateApplyAndCopyHouseholderRow.THRESHOLD);
HermitianRank2Update.THRESHOLD = Math.max(value, HermitianRank2Update.THRESHOLD);
HouseholderLeft.THRESHOLD = Math.max(value, HouseholderLeft.THRESHOLD);
HouseholderRight.THRESHOLD = Math.max(value, HouseholderRight.THRESHOLD);
AXPY.THRESHOLD = Math.max(value, AXPY.THRESHOLD);
ModifyAll.THRESHOLD = Math.max(value, ModifyAll.THRESHOLD);
MultiplyBoth.THRESHOLD = Math.max(value, MultiplyBoth.THRESHOLD);
MultiplyHermitianAndVector.THRESHOLD = Math.max(value, MultiplyHermitianAndVector.THRESHOLD);
MultiplyNeither.THRESHOLD = Math.max(value, MultiplyNeither.THRESHOLD);
MultiplyLeft.THRESHOLD = Math.max(value, MultiplyLeft.THRESHOLD);
MultiplyRight.THRESHOLD = Math.max(value, MultiplyRight.THRESHOLD);
RotateLeft.THRESHOLD = Math.max(value, RotateLeft.THRESHOLD);
RotateRight.THRESHOLD = Math.max(value, RotateRight.THRESHOLD);
SubstituteBackwards.THRESHOLD = Math.max(value, SubstituteBackwards.THRESHOLD);
SubstituteForwards.THRESHOLD = Math.max(value, SubstituteForwards.THRESHOLD);
}
int threshold();
}
|
package org.pentaho.di.core.database;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.core.xml.XMLInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.shared.SharedObjectBase;
import org.pentaho.di.shared.SharedObjectInterface;
import org.w3c.dom.Node;
/**
* This class defines the database specific parameters for a certain database type.
* It also provides static information regarding a number of well known databases.
*
* @author Matt
* @since 18-05-2003
*
*/
public class DatabaseMeta extends SharedObjectBase implements Cloneable, XMLInterface, SharedObjectInterface, VariableSpace
{
public static final String XML_TAG = "connection";
private DatabaseInterface databaseInterface;
private static DatabaseInterface[] allDatabaseInterfaces;
private VariableSpace variables = new Variables();
/**
* Indicates that the connections doesn't point to a type of database yet.
*/
public static final int TYPE_DATABASE_NONE = 0;
/**
* Connection to a MySQL database
*/
public static final int TYPE_DATABASE_MYSQL = 1;
/**
* Connection to an Oracle database
*/
public static final int TYPE_DATABASE_ORACLE = 2;
/**
* Connection to an AS/400 (IBM iSeries) DB400 database
*/
public static final int TYPE_DATABASE_AS400 = 3;
/**
* Connection to an Microsoft Access database
*/
public static final int TYPE_DATABASE_ACCESS = 4;
/**
* Connection to a Microsoft SQL Server database
*/
public static final int TYPE_DATABASE_MSSQL = 5;
/**
* Connection to an IBM DB2 database
*/
public static final int TYPE_DATABASE_DB2 = 6;
/**
* Connection to a PostgreSQL database
*/
public static final int TYPE_DATABASE_POSTGRES = 7;
/**
* Connection to an Intersystems Cache database
*/
public static final int TYPE_DATABASE_CACHE = 8;
/**
* Connection to an IBM Informix database
*/
public static final int TYPE_DATABASE_INFORMIX = 9;
/**
* Connection to a Sybase ASE database
*/
public static final int TYPE_DATABASE_SYBASE = 10;
/**
* Connection to a Gupta SQLBase database
*/
public static final int TYPE_DATABASE_GUPTA = 11;
/**
* Connection to a DBase III/IV/V database through JDBC
*/
public static final int TYPE_DATABASE_DBASE = 12;
/**
* Connection to a FireBird database
*/
public static final int TYPE_DATABASE_FIREBIRD = 13;
/**
* Connection to a SAP DB database
*/
public static final int TYPE_DATABASE_SAPDB = 14;
/**
* Connection to a Hypersonic java database
*/
public static final int TYPE_DATABASE_HYPERSONIC = 15;
/**
* Connection to a generic database
*/
public static final int TYPE_DATABASE_GENERIC = 16;
/**
* Connection to an SAP R/3 system
*/
public static final int TYPE_DATABASE_SAPR3 = 17;
/**
* Connection to an Ingress database
*/
public static final int TYPE_DATABASE_INGRES = 18;
/**
* Connection to a Borland Interbase database
*/
public static final int TYPE_DATABASE_INTERBASE = 19;
/**
* Connection to an ExtenDB database
*/
public static final int TYPE_DATABASE_EXTENDB = 20;
/**
* Connection to a Teradata database
*/
public static final int TYPE_DATABASE_TERADATA = 21;
/**
* Connection to an Oracle RDB database
*/
public static final int TYPE_DATABASE_ORACLE_RDB = 22;
/**
* Connection to an H2 database
*/
public static final int TYPE_DATABASE_H2 = 23;
/**
* Connection to a Netezza database
*/
public static final int TYPE_DATABASE_NETEZZA = 24;
/**
* Connection to an IBM UniVerse database
*/
public static final int TYPE_DATABASE_UNIVERSE = 25;
/**
* Connection to a SQLite database
*/
public static final int TYPE_DATABASE_SQLITE = 26;
/**
* Connection to an Apache Derby database
*/
public static final int TYPE_DATABASE_DERBY = 27;
/**
* Connection to a BMC Remedy Action Request System
*/
public static final int TYPE_DATABASE_REMEDY_AR_SYSTEM = 28;
/**
* Connection to a Palo MOLAP Server
*/
public static final int TYPE_DATABASE_PALO = 29;
/**
* Connection to a SybaseIQ ASE database
*/
public static final int TYPE_DATABASE_SYBASEIQ = 30;
/**
* Connect natively through JDBC thin driver to the database.
*/
public static final int TYPE_ACCESS_NATIVE = 0;
/**
* Connect to the database using ODBC.
*/
public static final int TYPE_ACCESS_ODBC = 1;
/**
* Connect to the database using OCI. (Oracle only)
*/
public static final int TYPE_ACCESS_OCI = 2;
/**
* Connect to the database using plugin specific method. (SAP R/3)
*/
public static final int TYPE_ACCESS_PLUGIN = 3;
/**
* Connect to the database using JNDI.
*/
public static final int TYPE_ACCESS_JNDI = 4;
/**
* Short description of the access type, used in XML and the repository.
*/
public static final String dbAccessTypeCode[] =
{
"Native",
"ODBC",
"OCI",
"Plugin",
"JNDI",
};
/**
* Longer description for user interactions.
*/
public static final String dbAccessTypeDesc[] =
{
"Native (JDBC)",
"ODBC",
"OCI",
"Plugin specific access method",
"JNDI",
"Custom",
};
/**
* Use this length in a String value to indicate that you want to use a CLOB in stead of a normal text field.
*/
public static final int CLOB_LENGTH = 9999999;
/**
* The value to store in the attributes so that an empty value doesn't get lost...
*/
public static final String EMPTY_OPTIONS_STRING = "><EMPTY><";
/**
* Construct a new database connections. Note that not all these parameters are not always mandatory.
*
* @param name The database name
* @param type The type of database
* @param access The type of database access
* @param host The hostname or IP address
* @param db The database name
* @param port The port on which the database listens.
* @param user The username
* @param pass The password
*/
public DatabaseMeta(String name, String type, String access, String host, String db, String port, String user, String pass)
{
setValues(name, type, access, host, db, port, user, pass);
addOptions();
}
/**
* Create an empty database connection
*
*/
public DatabaseMeta()
{
setDefault();
addOptions();
}
/**
* Set default values for an Oracle database.
*
*/
public void setDefault()
{
setValues("", "Oracle", "Native", "", "", "1521", "", "");
}
/**
* Add a list of common options for some databases.
*
*/
public void addOptions()
{
String mySQL = new MySQLDatabaseMeta().getDatabaseTypeDesc();
addExtraOption(mySQL, "defaultFetchSize", "500");
addExtraOption(mySQL, "useCursorFetch", "true");
}
/**
* @return the system dependend database interface for this database metadata definition
*/
public DatabaseInterface getDatabaseInterface()
{
return databaseInterface;
}
/**
* Set the system dependend database interface for this database metadata definition
* @param databaseInterface the system dependend database interface
*/
public void setDatabaseInterface(DatabaseInterface databaseInterface)
{
this.databaseInterface = databaseInterface;
}
/**
* Search for the right type of DatabaseInterface object and clone it.
*
* @param databaseType the type of DatabaseInterface to look for (description)
* @return The requested DatabaseInterface
*
* @throws KettleDatabaseException when the type could not be found or referenced.
*/
private static final DatabaseInterface getDatabaseInterface(String databaseType) throws KettleDatabaseException
{
return (DatabaseInterface)findDatabaseInterface(databaseType).clone();
}
/**
* Search for the right type of DatabaseInterface object and return it.
*
* @param databaseType the type of DatabaseInterface to look for (description)
* @return The requested DatabaseInterface
*
* @throws KettleDatabaseException when the type could not be found or referenced.
*/
private static final DatabaseInterface findDatabaseInterface(String databaseTypeDesc) throws KettleDatabaseException
{
DatabaseInterface di[] = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseTypeDesc().equalsIgnoreCase(databaseTypeDesc) ||
di[i].getDatabaseTypeDescLong().equalsIgnoreCase(databaseTypeDesc)
) return di[i];
}
throw new KettleDatabaseException("database type ["+databaseTypeDesc+"] couldn't be found!");
}
/**
*
* Load the Database Info
*/
public DatabaseMeta(Repository rep, long id_database) throws KettleException
{
this();
try
{
RowMetaAndData r = rep.getDatabase(id_database);
if (r!=null)
{
long id_database_type = r.getInteger("ID_DATABASE_TYPE", 0); // con_type
String dbTypeDesc = rep.getDatabaseTypeCode(id_database_type);
if (dbTypeDesc!=null)
{
databaseInterface = getDatabaseInterface(dbTypeDesc);
setAttributes(new Properties()); // new attributes
}
else
{
// throw new KettleException("No database type was specified [id_database_type="+id_database_type+"]");
}
setID(id_database);
setName( r.getString("NAME", "") );
long id_database_contype = r.getInteger("ID_DATABASE_CONTYPE", 0); // con_access
setAccessType( getAccessType( rep.getDatabaseConTypeCode( id_database_contype)) );
setHostname( r.getString("HOST_NAME", "") );
setDBName( r.getString("DATABASE_NAME", "") );
setDBPort( r.getString("PORT", "") );
setUsername( r.getString("USERNAME", "") );
setPassword( Encr.decryptPasswordOptionallyEncrypted( r.getString("PASSWORD", "") ) );
setServername( r.getString("SERVERNAME", "") );
setDataTablespace( r.getString("DATA_TBS", "") );
setIndexTablespace( r.getString("INDEX_TBS", "") );
// Also, load all the properties we can find...
final Collection<RowMetaAndData> attrs = rep.getDatabaseAttributes();
for (RowMetaAndData row : attrs)
{
long id = row.getInteger("ID_DATABASE", -1L);
if (id==id_database)
{
String code = row.getString("CODE", "");
String attribute = row.getString("VALUE_STR", "");
// System.out.println("Attributes: "+(getAttributes()!=null)+", code: "+(code!=null)+", attribute: "+(attribute!=null));
getAttributes().put(code, Const.NVL(attribute, ""));
}
}
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Error loading database connection from repository (id_database="+id_database+")", dbe);
}
}
/**
* Saves the database information into a given repository.
*
* @param rep The repository to save the database into.
*
* @throws KettleException if an error occurs.
*/
public void saveRep(Repository rep) throws KettleException
{
try
{
// If we don't have an ID, we don't know which entry in the database we need to update.
// See if a database with the same name is already available...
if (getID()<=0)
{
setID(rep.getDatabaseID(getName()));
}
// Still not found? --> Insert
if (getID()<=0)
{
// Insert new Note in repository
setID(rep.insertDatabase( getName(),
getDatabaseTypeCode(getDatabaseType()),
getAccessTypeDesc(getAccessType()),
getHostname(),
getDatabaseName(),
getDatabasePortNumberString(),
getUsername(),
getPassword(),
getServername(),
getDataTablespace(),
getIndexTablespace()
)
);
}
else // --> found entry with the same name...
{
// Update the note...
rep.updateDatabase( getID(),
getName(),
getDatabaseTypeCode(getDatabaseType()),
getAccessTypeDesc(getAccessType()),
getHostname(),
getDatabaseName(),
getDatabasePortNumberString(),
getUsername(),
getPassword(),
getServername(),
getDataTablespace(),
getIndexTablespace()
);
}
// For the extra attributes, just delete them and re-add them.
rep.delDatabaseAttributes(getID());
// OK, now get a list of all the attributes set on the database connection...
Properties attributes = getAttributes();
Enumeration<Object> keys = getAttributes().keys();
while (keys.hasMoreElements())
{
String code = (String) keys.nextElement();
String attribute = (String)attributes.get(code);
// Save this attribute
rep.insertDatabaseAttribute(getID(), code, attribute);
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Error saving database connection or one of its attributes to the repository.", dbe);
}
}
/**
* Returns the database ID of this database connection if a repository was used before.
*
* @return the ID of the db connection.
*/
public long getID()
{
return databaseInterface.getId();
}
public void setID(long id)
{
databaseInterface.setId(id);
}
public Object clone()
{
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.replaceMeta(this);
databaseMeta.setID(-1L);
return databaseMeta;
}
public void replaceMeta(DatabaseMeta databaseMeta)
{
this.setValues(databaseMeta.getName(), databaseMeta.getDatabaseTypeDesc(), databaseMeta.getAccessTypeDesc(),
databaseMeta.getHostname(), databaseMeta.getDatabaseName(), databaseMeta.getDatabasePortNumberString(),
databaseMeta.getUsername(), databaseMeta.getPassword()
);
this.setServername(databaseMeta.getServername());
this.setDataTablespace( databaseMeta.getDataTablespace() );
this.setIndexTablespace( databaseMeta.getIndexTablespace() );
this.databaseInterface = (DatabaseInterface) databaseMeta.databaseInterface.clone();
this.setID(databaseMeta.getID());
this.setChanged();
}
public void setValues(String name, String type, String access, String host, String db, String port, String user, String pass)
{
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new RuntimeException("Database type not found!", kde);
}
setName(name);
setAccessType(getAccessType(access));
setHostname(host);
setDBName(db);
setDBPort(port);
setUsername(user);
setPassword(pass);
setServername(null);
setChanged(false);
}
public void setDatabaseType(String type)
{
DatabaseInterface oldInterface = databaseInterface;
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new RuntimeException("Database type ["+type+"] not found!", kde);
}
setName(oldInterface.getName());
setAccessType(oldInterface.getAccessType());
setHostname(oldInterface.getHostname());
setDBName(oldInterface.getDatabaseName());
setDBPort(oldInterface.getDatabasePortNumberString());
setUsername(oldInterface.getUsername());
setPassword(oldInterface.getPassword());
setServername(oldInterface.getServername());
setDataTablespace(oldInterface.getDataTablespace());
setIndexTablespace(oldInterface.getIndexTablespace());
setChanged(oldInterface.isChanged());
}
public void setValues(DatabaseMeta info)
{
databaseInterface = (DatabaseInterface)info.databaseInterface.clone();
}
/**
* Sets the name of the database connection. This name should be
* unique in a transformation and in general in a single repository.
*
* @param name The name of the database connection
*/
public void setName(String name)
{
databaseInterface.setName(name);
}
/**
* Returns the name of the database connection
* @return The name of the database connection
*/
public String getName()
{
return databaseInterface.getName();
}
/**
* Returns the type of database, one of <p>
* TYPE_DATABASE_MYSQL<p>
* TYPE_DATABASE_ORACLE<p>
* TYPE_DATABASE_...<p>
*
* @return the database type
*/
public int getDatabaseType()
{
return databaseInterface.getDatabaseType();
}
/*
* Sets the type of database.
* @param db_type The database type
public void setDatabaseType(int db_type)
{
databaseInterface
this.databaseType = db_type;
}
*/
/**
* Return the type of database access. One of <p>
* TYPE_ACCESS_NATIVE<p>
* TYPE_ACCESS_ODBC<p>
* TYPE_ACCESS_OCI<p>
* @return The type of database access.
*/
public int getAccessType()
{
return databaseInterface.getAccessType();
}
/**
* Set the type of database access.
* @param access_type The access type.
*/
public void setAccessType(int access_type)
{
databaseInterface.setAccessType(access_type);
}
/**
* Returns a short description of the type of database.
* @return A short description of the type of database.
*/
public String getDatabaseTypeDesc()
{
return databaseInterface.getDatabaseTypeDesc();
}
/**
* Gets you a short description of the type of database access.
* @return A short description of the type of database access.
*/
public String getAccessTypeDesc()
{
return dbAccessTypeCode[getAccessType()];
}
/**
* Return the hostname of the machine on which the database runs.
* @return The hostname of the database.
*/
public String getHostname()
{
return databaseInterface.getHostname();
}
/**
* Sets the hostname of the machine on which the database runs.
* @param hostname The hostname of the machine on which the database runs.
*/
public void setHostname(String hostname)
{
databaseInterface.setHostname(hostname);
}
/**
* Return the port on which the database listens as a String. Allows for parameterisation.
* @return The database port.
*/
public String getDatabasePortNumberString()
{
return databaseInterface.getDatabasePortNumberString();
}
/**
* Sets the port on which the database listens.
*
* @param db_port The port number on which the database listens
*/
public void setDBPort(String db_port)
{
databaseInterface.setDatabasePortNumberString(db_port);
}
/**
* Return the name of the database.
* @return The database name.
*/
public String getDatabaseName()
{
return databaseInterface.getDatabaseName();
}
/**
* Set the name of the database.
* @param databaseName The new name of the database
*/
public void setDBName(String databaseName)
{
databaseInterface.setDatabaseName(databaseName);
}
/**
* Get the username to log into the database on this connection.
* @return The username to log into the database on this connection.
*/
public String getUsername()
{
return databaseInterface.getUsername();
}
/**
* Sets the username to log into the database on this connection.
* @param username The username
*/
public void setUsername(String username)
{
databaseInterface.setUsername(username);
}
/**
* Get the password to log into the database on this connection.
* @return the password to log into the database on this connection.
*/
public String getPassword()
{
return databaseInterface.getPassword();
}
/**
* Sets the password to log into the database on this connection.
* @param password the password to log into the database on this connection.
*/
public void setPassword(String password)
{
databaseInterface.setPassword(password);
}
/**
* @param servername the Informix servername
*/
public void setServername(String servername)
{
databaseInterface.setServername(servername);
}
/**
* @return the Informix servername
*/
public String getServername()
{
return databaseInterface.getServername();
}
public String getDataTablespace()
{
return databaseInterface.getDataTablespace();
}
public void setDataTablespace(String data_tablespace)
{
databaseInterface.setDataTablespace(data_tablespace);
}
public String getIndexTablespace()
{
return databaseInterface.getIndexTablespace();
}
public void setIndexTablespace(String index_tablespace)
{
databaseInterface.setIndexTablespace(index_tablespace);
}
public void setChanged()
{
setChanged(true);
}
public void setChanged(boolean ch)
{
databaseInterface.setChanged(ch);
}
public boolean hasChanged()
{
return databaseInterface.isChanged();
}
public String toString()
{
return getName();
}
/**
* @return The extra attributes for this database connection
*/
public Properties getAttributes()
{
return databaseInterface.getAttributes();
}
/**
* Set extra attributes on this database connection
* @param attributes The extra attributes to set on this database connection.
*/
public void setAttributes(Properties attributes)
{
databaseInterface.setAttributes(attributes);
}
/**
* Constructs a new database using an XML string snippet.
* It expects the snippet to be enclosed in <code>connection</code> tags.
* @param xml The XML string to parse
* @throws KettleXMLException in case there is an XML parsing error
*/
public DatabaseMeta(String xml) throws KettleXMLException
{
this( XMLHandler.getSubNode(XMLHandler.loadXMLString(xml), "connection") );
}
/**
* Reads the information from an XML Node into this new database connection.
* @param con The Node to read the data from
* @throws KettleXMLException
*/
public DatabaseMeta(Node con) throws KettleXMLException
{
this();
try
{
String type = XMLHandler.getTagValue(con, "type");
try
{
databaseInterface = getDatabaseInterface(type);
}
catch(KettleDatabaseException kde)
{
throw new KettleXMLException("Unable to create new database interface", kde);
}
setName( XMLHandler.getTagValue(con, "name") );
setHostname( XMLHandler.getTagValue(con, "server") );
String acc = XMLHandler.getTagValue(con, "access");
setAccessType( getAccessType(acc) );
setDBName( XMLHandler.getTagValue(con, "database") );
setDBPort( XMLHandler.getTagValue(con, "port") );
setUsername( XMLHandler.getTagValue(con, "username") );
setPassword( Encr.decryptPasswordOptionallyEncrypted( XMLHandler.getTagValue(con, "password") ) );
setServername( XMLHandler.getTagValue(con, "servername") );
setDataTablespace( XMLHandler.getTagValue(con, "data_tablespace") );
setIndexTablespace( XMLHandler.getTagValue(con, "index_tablespace") );
// Also, read the database attributes...
Node attrsnode = XMLHandler.getSubNode(con, "attributes");
if (attrsnode!=null)
{
int nr = XMLHandler.countNodes(attrsnode, "attribute");
for (int i=0;i<nr;i++)
{
Node attrnode = XMLHandler.getSubNodeByNr(attrsnode, "attribute", i);
String code = XMLHandler.getTagValue(attrnode, "code");
String attribute = XMLHandler.getTagValue(attrnode, "attribute");
if (code!=null && attribute!=null) getAttributes().put(code, attribute);
}
}
}
catch(Exception e)
{
throw new KettleXMLException("Unable to load database connection info from XML node", e);
}
}
@SuppressWarnings("unchecked")
public String getXML()
{
StringBuffer retval = new StringBuffer(250);
retval.append(" <").append(XML_TAG).append('>').append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("name", getName()));
retval.append(" ").append(XMLHandler.addTagValue("server", getHostname()));
retval.append(" ").append(XMLHandler.addTagValue("type", getDatabaseTypeDesc()));
retval.append(" ").append(XMLHandler.addTagValue("access", getAccessTypeDesc()));
retval.append(" ").append(XMLHandler.addTagValue("database", getDatabaseName()));
retval.append(" ").append(XMLHandler.addTagValue("port", getDatabasePortNumberString()));
retval.append(" ").append(XMLHandler.addTagValue("username", getUsername()));
retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(getPassword())));
retval.append(" ").append(XMLHandler.addTagValue("servername", getServername()));
retval.append(" ").append(XMLHandler.addTagValue("data_tablespace", getDataTablespace()));
retval.append(" ").append(XMLHandler.addTagValue("index_tablespace", getIndexTablespace()));
retval.append(" <attributes>").append(Const.CR);
List list = new ArrayList( getAttributes().keySet() );
Collections.sort(list); // Sort the entry-sets to make sure we can compare XML strings: if the order is different, the XML is different.
for (Iterator iter = list.iterator(); iter.hasNext();)
{
String code = (String) iter.next();
String attribute = getAttributes().getProperty(code);
if (!Const.isEmpty(attribute))
{
retval.append(" <attribute>"+
XMLHandler.addTagValue("code", code, false)+
XMLHandler.addTagValue("attribute", attribute, false)+
"</attribute>"+Const.CR);
}
}
retval.append(" </attributes>").append(Const.CR);
retval.append(" </"+XML_TAG+">").append(Const.CR);
return retval.toString();
}
public int hashCode()
{
return getName().hashCode(); // name of connection is unique!
}
public boolean equals(Object obj)
{
return getName().equals( ((DatabaseMeta)obj).getName() );
}
public String getURL() throws KettleDatabaseException
{
return getURL(null);
}
public String getURL(String partitionId) throws KettleDatabaseException
{
// First see if we're not doing any JNDI...
if (getAccessType()==TYPE_ACCESS_JNDI) {
// We can't really determine the URL here.
}
String baseUrl;
if (isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = getPartitionMeta(partitionId);
String hostname = partition.getHostname();
String port = partition.getPort();
String databaseName = partition.getDatabaseName();
baseUrl = databaseInterface.getURL(hostname, port, databaseName);
}
else
{
baseUrl = databaseInterface.getURL(getHostname(), getDatabasePortNumberString(), getDatabaseName());
}
StringBuffer url=new StringBuffer( environmentSubstitute(baseUrl) );
if (databaseInterface.supportsOptionsInURL())
{
// OK, now add all the options...
String optionIndicator = getExtraOptionIndicator();
String optionSeparator = getExtraOptionSeparator();
String valueSeparator = getExtraOptionValueSeparator();
Map<String, String> map = getExtraOptions();
if (map.size()>0)
{
Iterator<String> iterator = map.keySet().iterator();
boolean first=true;
while (iterator.hasNext())
{
String typedParameter=(String)iterator.next();
int dotIndex = typedParameter.indexOf('.');
if (dotIndex>=0)
{
String typeCode = typedParameter.substring(0,dotIndex);
String parameter = typedParameter.substring(dotIndex+1);
String value = map.get(typedParameter);
// Only add to the URL if it's the same database type code...
if (databaseInterface.getDatabaseTypeDesc().equals(typeCode))
{
if (first) url.append(optionIndicator);
else url.append(optionSeparator);
url.append(parameter);
if (!Const.isEmpty(value) && !value.equals(EMPTY_OPTIONS_STRING))
{
url.append(valueSeparator).append(value);
}
first=false;
}
}
}
}
}
else
{
// We need to put all these options in a Properties file later (Oracle & Co.)
// This happens at connect time...
}
return url.toString();
}
public Properties getConnectionProperties()
{
Properties properties =new Properties();
Map<String, String> map = getExtraOptions();
if (map.size()>0)
{
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String typedParameter=(String)iterator.next();
int dotIndex = typedParameter.indexOf('.');
if (dotIndex>=0)
{
String typeCode = typedParameter.substring(0,dotIndex);
String parameter = typedParameter.substring(dotIndex+1);
String value = (String) map.get(typedParameter);
// Only add to the URL if it's the same database type code...
if (databaseInterface.getDatabaseTypeDesc().equals(typeCode))
{
if (value!=null && value.equals(EMPTY_OPTIONS_STRING)) value="";
properties.put(parameter, environmentSubstitute(Const.NVL(value, "")));
}
}
}
}
return properties;
}
public String getExtraOptionIndicator()
{
return databaseInterface.getExtraOptionIndicator();
}
/**
* @return The extra option separator in database URL for this platform (usually this is semicolon ; )
*/
public String getExtraOptionSeparator()
{
return databaseInterface.getExtraOptionSeparator();
}
/**
* @return The extra option value separator in database URL for this platform (usually this is the equal sign = )
*/
public String getExtraOptionValueSeparator()
{
return databaseInterface.getExtraOptionValueSeparator();
}
/**
* Add an extra option to the attributes list
* @param databaseTypeCode The database type code for which the option applies
* @param option The option to set
* @param value The value of the option
*/
public void addExtraOption(String databaseTypeCode, String option, String value)
{
databaseInterface.addExtraOption(databaseTypeCode, option, value);
}
/**
* @deprecated because the same database can support transactions or not. It all depends on the database setup. Therefor, we look at the database metadata
* DatabaseMetaData.supportsTransactions() in stead of this.
* @return true if the database supports transactions
*/
public boolean supportsTransactions()
{
return databaseInterface.supportsTransactions();
}
public boolean supportsAutoinc()
{
return databaseInterface.supportsAutoInc();
}
public boolean supportsSequences()
{
return databaseInterface.supportsSequences();
}
public String getSQLSequenceExists(String sequenceName)
{
return databaseInterface.getSQLSequenceExists(sequenceName);
}
public boolean supportsBitmapIndex()
{
return databaseInterface.supportsBitmapIndex();
}
public boolean supportsSetLong()
{
return databaseInterface.supportsSetLong();
}
/**
* @return true if the database supports schemas
*/
public boolean supportsSchemas()
{
return databaseInterface.supportsSchemas();
}
/**
* @return true if the database supports catalogs
*/
public boolean supportsCatalogs()
{
return databaseInterface.supportsCatalogs();
}
/**
*
* @return true when the database engine supports empty transaction.
* (for example Informix does not on a non-ANSI database type!)
*/
public boolean supportsEmptyTransactions()
{
return databaseInterface.supportsEmptyTransactions();
}
/**
* See if this database supports the setCharacterStream() method on a PreparedStatement.
*
* @return true if we can set a Stream on a field in a PreparedStatement. False if not.
*/
public boolean supportsSetCharacterStream()
{
return databaseInterface.supportsSetCharacterStream();
}
/**
* Get the maximum length of a text field for this database connection.
* This includes optional CLOB, Memo and Text fields. (the maximum!)
* @return The maximum text field length for this database type. (mostly CLOB_LENGTH)
*/
public int getMaxTextFieldLength()
{
return databaseInterface.getMaxTextFieldLength();
}
public final static int getDatabaseType(String dbTypeDesc)
{
// Backward compatibility...
if (dbTypeDesc.equalsIgnoreCase("ODBC-ACCESS")) return TYPE_DATABASE_ACCESS;
try
{
DatabaseInterface di = getDatabaseInterface(dbTypeDesc);
return di.getDatabaseType();
}
catch(KettleDatabaseException kde)
{
return TYPE_DATABASE_NONE;
}
}
/**
* Get a string representing the unqiue database type code
* @param dbtype the database type to get the code of
* @return The database type code
* @deprecated please use getDatabaseTypeCode()
*/
public final static String getDBTypeDesc(int dbtype)
{
return getDatabaseTypeCode(dbtype);
}
/**
* Get a string representing the unqiue database type code
* @param dbtype the database type to get the code of
* @return The database type code
*/
public final static String getDatabaseTypeCode(int dbtype)
{
// Find the DatabaseInterface for this type...
DatabaseInterface[] di = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseType() == dbtype) {
return di[i].getDatabaseTypeDesc();
}
}
return null;
}
/**
* Get a description of the database type
* @param dbtype the database type to get the description for
* @return The database type description
*/
public final static String getDatabaseTypeDesc(int dbtype)
{
// Find the DatabaseInterface for this type...
DatabaseInterface[] di = getDatabaseInterfaces();
for (int i=0;i<di.length;i++)
{
if (di[i].getDatabaseType() == dbtype) return di[i].getDatabaseTypeDescLong();
}
return null;
}
public final static int getAccessType(String dbaccess)
{
int i;
if (dbaccess==null) return TYPE_ACCESS_NATIVE;
for (i=0;i<dbAccessTypeCode.length;i++)
{
if (dbAccessTypeCode[i].equalsIgnoreCase(dbaccess))
{
return i;
}
}
for (i=0;i<dbAccessTypeDesc.length;i++)
{
if (dbAccessTypeDesc[i].equalsIgnoreCase(dbaccess))
{
return i;
}
}
return TYPE_ACCESS_NATIVE;
}
public final static String getAccessTypeDesc(int dbaccess)
{
if (dbaccess<0) return null;
if (dbaccess>dbAccessTypeCode.length) return null;
return dbAccessTypeCode[dbaccess];
}
public final static String getAccessTypeDescLong(int dbaccess)
{
if (dbaccess<0) return null;
if (dbaccess>dbAccessTypeDesc.length) return null;
return dbAccessTypeDesc[dbaccess];
}
public final static String[] getDBTypeDescLongList()
{
DatabaseInterface[] di = getDatabaseInterfaces();
String[] retval = new String[di.length];
for (int i=0;i<di.length;i++)
{
retval[i] = di[i].getDatabaseTypeDescLong();
}
return retval;
}
public final static String[] getDBTypeDescList()
{
DatabaseInterface[] di = getDatabaseInterfaces();
String[] retval = new String[di.length];
for (int i=0;i<di.length;i++)
{
retval[i] = di[i].getDatabaseTypeDesc();
}
return retval;
}
public static final DatabaseInterface[] getDatabaseInterfaces()
{
if (allDatabaseInterfaces!=null) return allDatabaseInterfaces;
Class<?> ic[] = DatabaseInterface.implementingClasses;
allDatabaseInterfaces = new DatabaseInterface[ic.length];
for (int i=0;i<ic.length;i++)
{
try
{
Class.forName(ic[i].getName());
allDatabaseInterfaces[i] = (DatabaseInterface)ic[i].newInstance();
}
catch(Exception e)
{
throw new RuntimeException("Error creating class for : "+ic[i].getName(), e);
}
}
return allDatabaseInterfaces;
}
public final static int[] getAccessTypeList(String dbTypeDesc)
{
try
{
DatabaseInterface di = findDatabaseInterface(dbTypeDesc);
return di.getAccessTypeList();
}
catch(KettleDatabaseException kde)
{
return null;
}
}
public static final int getPortForDBType(String strtype, String straccess)
{
try
{
DatabaseInterface di = getDatabaseInterface(strtype);
di.setAccessType(getAccessType(straccess));
return di.getDefaultDatabasePort();
}
catch(KettleDatabaseException kde)
{
return -1;
}
}
public int getDefaultDatabasePort()
{
return databaseInterface.getDefaultDatabasePort();
}
public int getNotFoundTK(boolean use_autoinc)
{
return databaseInterface.getNotFoundTK(use_autoinc);
}
public String getDriverClass()
{
return environmentSubstitute(databaseInterface.getDriverClass());
}
public String stripCR(String sbsql)
{
return stripCR(new StringBuffer(sbsql));
}
public String stripCR(StringBuffer sbsql)
{
// DB2 Can't handle \n in SQL Statements...
if (getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 ||
getDatabaseType() == DatabaseMeta.TYPE_DATABASE_CACHE ||
getDatabaseType() == DatabaseMeta.TYPE_DATABASE_UNIVERSE
)
{
// Remove CR's
for (int i=sbsql.length()-1;i>=0;i
{
if (sbsql.charAt(i)=='\n' || sbsql.charAt(i)=='\r') sbsql.setCharAt(i, ' ');
}
}
return sbsql.toString();
}
public String getSeqNextvalSQL(String sequenceName)
{
return databaseInterface.getSQLNextSequenceValue(sequenceName);
}
public String getSQLCurrentSequenceValue(String sequenceName)
{
return databaseInterface.getSQLCurrentSequenceValue(sequenceName);
}
public boolean isFetchSizeSupported()
{
return databaseInterface.isFetchSizeSupported();
}
/**
* Indicates the need to insert a placeholder (0) for auto increment fields.
* @return true if we need a placeholder for auto increment fields in insert statements.
*/
public boolean needsPlaceHolder()
{
return databaseInterface.needsPlaceHolder();
}
public String getFunctionSum()
{
return databaseInterface.getFunctionSum();
}
public String getFunctionAverage()
{
return databaseInterface.getFunctionAverage();
}
public String getFunctionMaximum()
{
return databaseInterface.getFunctionMaximum();
}
public String getFunctionMinimum()
{
return databaseInterface.getFunctionMinimum();
}
public String getFunctionCount()
{
return databaseInterface.getFunctionCount();
}
/**
* Check the database connection parameters and give back an array of remarks
* @return an array of remarks Strings
*/
public String[] checkParameters()
{
ArrayList<String> remarks = new ArrayList<String>();
if (getDatabaseType()==TYPE_DATABASE_NONE)
{
remarks.add("No database type was choosen");
}
if (getName()==null || getName().length()==0)
{
remarks.add("Please give this database connection a name");
}
if (!isPartitioned() && getDatabaseType()!=TYPE_DATABASE_SAPR3 && getDatabaseType()!=TYPE_DATABASE_GENERIC)
{
if (getDatabaseName()==null || getDatabaseName().length()==0)
{
remarks.add("Please specify the name of the database");
}
}
return remarks.toArray(new String[remarks.size()]);
}
/**
* Calculate the schema-table combination, usually this is the schema and table separated with a dot. (schema.table)
* @param schemaName the schema-name or null if no schema is used.
* @param tableName the table name
* @return the schemaname-tablename combination
*/
public String getSchemaTableCombination(String schemaName, String tableName)
{
if (Const.isEmpty(schemaName)) return tableName; // no need to look further
return databaseInterface.getSchemaTableCombination(schemaName, tableName);
}
public boolean isClob(ValueMetaInterface v)
{
boolean retval=true;
if (v==null || v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
retval=false;
}
else
{
return true;
}
return retval;
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc)
{
return getFieldDefinition(v, tk, pk, use_autoinc, true, true);
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
return databaseInterface.getFieldDefinition(v, tk, pk, use_autoinc, add_fieldname, add_cr);
}
public String getLimitClause(int nrRows)
{
return databaseInterface.getLimitClause(nrRows);
}
/**
* @param tableName The table or schema-table combination. We expect this to be quoted properly already!
* @return the SQL for to get the fields of this table.
*/
public String getSQLQueryFields(String tableName)
{
return databaseInterface.getSQLQueryFields(tableName);
}
public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
public String getDropColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval = databaseInterface.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, semicolon);
retval+=Const.CR;
if (semicolon) retval+=";"+Const.CR;
return retval;
}
/**
* @return an array of reserved words for the database type...
*/
public String[] getReservedWords()
{
return databaseInterface.getReservedWords();
}
/**
* @return true if reserved words need to be double quoted ("password", "select", ...)
*/
public boolean quoteReservedWords()
{
return databaseInterface.quoteReservedWords();
}
/**
* @return The start quote sequence, mostly just double quote, but sometimes [, ...
*/
public String getStartQuote()
{
return databaseInterface.getStartQuote();
}
/**
* @return The end quote sequence, mostly just double quote, but sometimes ], ...
*/
public String getEndQuote()
{
return databaseInterface.getEndQuote();
}
/**
* Returns a quoted field if this is needed: contains spaces, is a reserved word, ...
* @param field The fieldname to check for quoting
* @return The quoted field (if this is needed.
*/
public String quoteField(String field)
{
if (Const.isEmpty(field)) return null;
if (isForcingIdentifiersToLowerCase())
{
field=field.toLowerCase();
}
else if (isForcingIdentifiersToUpperCase())
{
field=field.toUpperCase();
}
// If the field already contains quotes, we don't touch it anymore, just return the same string...
if (field.indexOf(getStartQuote())>=0 || field.indexOf(getEndQuote())>=0)
{
return field;
}
if (isReservedWord(field) && quoteReservedWords())
{
return handleCase(getStartQuote()+field+getEndQuote());
}
else
{
if (databaseInterface.isQuoteAllFields() ||
hasSpacesInField(field) ||
hasSpecialCharInField(field) ||
hasDotInField(field))
{
return getStartQuote()+field+getEndQuote();
}
else
{
return field;
}
}
}
private String handleCase(String field)
{
if (databaseInterface.isDefaultingToUppercase())
{
return field.toUpperCase();
}
else
{
return field.toLowerCase();
}
}
/**
* Determines whether or not this field is in need of quoting:<br>
* - When the fieldname contains spaces<br>
* - When the fieldname is a reserved word<br>
* @param fieldname the fieldname to check if there is a need for quoting
* @return true if the fieldname needs to be quoted.
*/
public boolean isInNeedOfQuoting(String fieldname)
{
return isReservedWord(fieldname) || hasSpacesInField(fieldname);
}
/**
* Returns true if the string specified is a reserved word on this database type.
* @param word The word to check
* @return true if word is a reserved word on this database.
*/
public boolean isReservedWord(String word)
{
String reserved[] = getReservedWords();
if (Const.indexOfString(word, reserved)>=0) return true;
return false;
}
/**
* Detects if a field has spaces in the name. We need to quote the field in that case.
* @param fieldname The fieldname to check for spaces
* @return true if the fieldname contains spaces
*/
public boolean hasSpacesInField(String fieldname)
{
if( fieldname == null ) return false;
if (fieldname.indexOf(' ')>=0) return true;
return false;
}
/**
* Detects if a field has spaces in the name. We need to quote the field in that case.
* @param fieldname The fieldname to check for spaces
* @return true if the fieldname contains spaces
*/
public boolean hasSpecialCharInField(String fieldname)
{
if(fieldname==null) return false;
if (fieldname.indexOf('/')>=0) return true;
if (fieldname.indexOf('-')>=0) return true;
if (fieldname.indexOf('+')>=0) return true;
if (fieldname.indexOf(',')>=0) return true;
if (fieldname.indexOf('*')>=0) return true;
if (fieldname.indexOf('(')>=0) return true;
if (fieldname.indexOf(')')>=0) return true;
if (fieldname.indexOf('{')>=0) return true;
if (fieldname.indexOf('}')>=0) return true;
if (fieldname.indexOf('[')>=0) return true;
if (fieldname.indexOf(']')>=0) return true;
if (fieldname.indexOf('%')>=0) return true;
if (fieldname.indexOf('@')>=0) return true;
return false;
}
public boolean hasDotInField(String fieldname)
{
if(fieldname==null) return false;
if (fieldname.indexOf('.')>=0) return true;
return false;
}
/**
* Checks the fields specified for reserved words and quotes them.
* @param fields the list of fields to check
* @return true if one or more values have a name that is a reserved word on this database type.
*/
public boolean replaceReservedWords(RowMetaInterface fields)
{
boolean hasReservedWords=false;
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
if (isReservedWord(v.getName()))
{
hasReservedWords = true;
v.setName( quoteField(v.getName()) );
}
}
return hasReservedWords;
}
/**
* Checks the fields specified for reserved words
* @param fields the list of fields to check
* @return The nr of reserved words for this database.
*/
public int getNrReservedWords(RowMetaInterface fields)
{
int nrReservedWords=0;
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
if (isReservedWord(v.getName())) nrReservedWords++;
}
return nrReservedWords;
}
/**
* @return a list of types to get the available tables
*/
public String[] getTableTypes()
{
return databaseInterface.getTableTypes();
}
/**
* @return a list of types to get the available views
*/
public String[] getViewTypes()
{
return databaseInterface.getViewTypes();
}
/**
* @return a list of types to get the available synonyms
*/
public String[] getSynonymTypes()
{
return databaseInterface.getSynonymTypes();
}
/**
* @return true if we need to supply the schema-name to getTables in order to get a correct list of items.
*/
public boolean useSchemaNameForTableList()
{
return databaseInterface.useSchemaNameForTableList();
}
/**
* @return true if the database supports views
*/
public boolean supportsViews()
{
return databaseInterface.supportsViews();
}
/**
* @return true if the database supports synonyms
*/
public boolean supportsSynonyms()
{
return databaseInterface.supportsSynonyms();
}
/**
*
* @return The SQL on this database to get a list of stored procedures.
*/
public String getSQLListOfProcedures()
{
return databaseInterface.getSQLListOfProcedures();
}
/**
* @param tableName The tablename to be truncated
* @return The SQL statement to remove all rows from the specified statement, if possible without using transactions
*/
public String getTruncateTableStatement(String schema, String tableName)
{
return databaseInterface.getTruncateTableStatement(getQuotedSchemaTableCombination(schema, tableName));
}
/**
* @return true if the database rounds floating point numbers to the right precision.
* For example if the target field is number(7,2) the value 12.399999999 is converted into 12.40
*/
public boolean supportsFloatRoundingOnUpdate()
{
return databaseInterface.supportsFloatRoundingOnUpdate();
}
/**
* @param tableNames The names of the tables to lock
* @return The SQL commands to lock database tables for write purposes.
* null is returned in case locking is not supported on the target database.
*/
public String getSQLLockTables(String tableNames[])
{
return databaseInterface.getSQLLockTables(tableNames);
}
/**
* @param tableNames The names of the tables to unlock
* @return The SQL commands to unlock databases tables.
* null is returned in case locking is not supported on the target database.
*/
public String getSQLUnlockTables(String tableNames[])
{
return databaseInterface.getSQLUnlockTables(tableNames);
}
/**
* @return a feature list for the chosen database type.
*
*/
@SuppressWarnings("unchecked")
public List<RowMetaAndData> getFeatureSummary()
{
List<RowMetaAndData> list = new ArrayList<RowMetaAndData>();
RowMetaAndData r =null;
final String par = "Parameter";
final String val = "Value";
ValueMetaInterface testValue = new ValueMeta("FIELD", ValueMetaInterface.TYPE_STRING);
testValue.setLength(30);
if (databaseInterface!=null)
{
// Type of database
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Database type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabaseTypeDesc()); list.add(r);
// Type of access
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Access type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getAccessTypeDesc()); list.add(r);
// Name of database
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Database name"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabaseName()); list.add(r);
// server host name
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Server hostname"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getHostname()); list.add(r);
// Port number
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Service port"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDatabasePortNumberString()); list.add(r);
// Username
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Username"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getUsername()); list.add(r);
// Informix server
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Informix server name"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getServername()); list.add(r);
// Other properties...
Enumeration keys = getAttributes().keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
String value = getAttributes().getProperty(key);
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Extra attribute ["+key+"]"); r.addValue(val, ValueMetaInterface.TYPE_STRING, value); list.add(r);
}
// driver class
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Driver class"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDriverClass()); list.add(r);
// URL
String pwd = getPassword();
setPassword("password"); // Don't give away the password in the URL!
String url = "";
try { url = getURL(); } catch(KettleDatabaseException e) {}
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "URL"); r.addValue(val, ValueMetaInterface.TYPE_STRING, url); list.add(r);
setPassword(pwd);
// SQL: Next sequence value
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: next sequence value"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getSeqNextvalSQL("SEQUENCE")); list.add(r);
// is set fetch size supported
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supported: set fetch size"); r.addValue(val, ValueMetaInterface.TYPE_STRING, isFetchSizeSupported()?"Y":"N"); list.add(r);
// needs place holder for auto increment
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "auto increment field needs placeholder"); r.addValue(val, ValueMetaInterface.TYPE_STRING, needsPlaceHolder()?"Y":"N"); list.add(r);
// Sum function
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SUM aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionSum()); list.add(r);
// Avg function
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "AVG aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionAverage()); list.add(r);
// Minimum function
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "MIN aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionMinimum()); list.add(r);
// Maximum function
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "MAX aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionMaximum()); list.add(r);
// Count function
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "COUNT aggregate function"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getFunctionCount()); list.add(r);
// Schema-table combination
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Schema / Table combination"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getSchemaTableCombination("SCHEMA", "TABLE")); list.add(r);
// Limit clause
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "LIMIT clause for 100 rows"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getLimitClause(100)); list.add(r);
// add column statement
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Add column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getAddColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r);
// drop column statement
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Drop column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getDropColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r);
// Modify column statement
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Modify column statement"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getModifyColumnStatement("TABLE", testValue, null, false, null, false)); list.add(r);
// List of reserved words
String reserved = "";
if (getReservedWords()!=null) for (int i=0;i<getReservedWords().length;i++) reserved+=(i>0?", ":"")+getReservedWords()[i];
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, reserved); list.add(r);
// Quote reserved words?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Quote reserved words?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, quoteReservedWords()?"Y":"N"); list.add(r);
// Start Quote
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "Start quote for reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getStartQuote()); list.add(r);
// End Quote
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "End quote for reserved words"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getEndQuote()); list.add(r);
// List of table types
String types = "";
String slist[] = getTableTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC table types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r);
// List of view types
types = "";
slist = getViewTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC view types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r);
// List of synonym types
types = "";
slist = getSynonymTypes();
if (slist!=null) for (int i=0;i<slist.length;i++) types+=(i>0?", ":"")+slist[i];
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "List of JDBC synonym types"); r.addValue(val, ValueMetaInterface.TYPE_STRING, types); list.add(r);
// Use schema-name to get list of tables?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "use schema name to get table list?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, useSchemaNameForTableList()?"Y":"N"); list.add(r);
// supports view?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports views?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsViews()?"Y":"N"); list.add(r);
// supports synonyms?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports synonyms?"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsSynonyms()?"Y":"N"); list.add(r);
// SQL: get list of procedures?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: list of procedures"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getSQLListOfProcedures()); list.add(r);
// SQL: get truncate table statement?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "SQL: truncate table"); r.addValue(val, ValueMetaInterface.TYPE_STRING, getTruncateTableStatement(null, "TABLE")); list.add(r);
// supports float rounding on update?
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports floating point rounding on update/insert"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsFloatRoundingOnUpdate()?"Y":"N"); list.add(r);
// supports time stamp to date conversion
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports timestamp-date conversion"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsTimeStampToDateConversion()?"Y":"N"); list.add(r);
// supports batch updates
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports batch updates"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsBatchUpdates()?"Y":"N"); list.add(r);
// supports boolean values
r = new RowMetaAndData(); r.addValue(par, ValueMetaInterface.TYPE_STRING, "supports boolean data type"); r.addValue(val, ValueMetaInterface.TYPE_STRING, supportsBooleanDataType()?"Y":"N"); list.add(r);
}
return list;
}
/**
* @return true if the database result sets support getTimeStamp() to retrieve date-time. (Date)
*/
public boolean supportsTimeStampToDateConversion()
{
return databaseInterface.supportsTimeStampToDateConversion();
}
/**
* @return true if the database JDBC driver supports batch updates
* For example Interbase doesn't support this!
*/
public boolean supportsBatchUpdates()
{
return databaseInterface.supportsBatchUpdates();
}
/**
* @return true if the database supports a boolean, bit, logical, ... datatype
*/
public boolean supportsBooleanDataType()
{
return databaseInterface.supportsBooleanDataType();
}
/**
* Changes the names of the fields to their quoted equivalent if this is needed
* @param fields The row of fields to change
*/
public void quoteReservedWords(RowMetaInterface fields)
{
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
v.setName( quoteField(v.getName()) );
}
}
/**
* @return a map of all the extra URL options you want to set.
*/
public Map<String, String> getExtraOptions()
{
return databaseInterface.getExtraOptions();
}
/**
* @return true if the database supports connection options in the URL, false if they are put in a Properties object.
*/
public boolean supportsOptionsInURL()
{
return databaseInterface.supportsOptionsInURL();
}
/**
* @return extra help text on the supported options on the selected database platform.
*/
public String getExtraOptionsHelpText()
{
return databaseInterface.getExtraOptionsHelpText();
}
/**
* @return true if the database JDBC driver supports getBlob on the resultset. If not we must use getBytes() to get the data.
*/
public boolean supportsGetBlob()
{
return databaseInterface.supportsGetBlob();
}
/**
* @return The SQL to execute right after connecting
*/
public String getConnectSQL()
{
return databaseInterface.getConnectSQL();
}
/**
* @param sql The SQL to execute right after connecting
*/
public void setConnectSQL(String sql)
{
databaseInterface.setConnectSQL(sql);
}
/**
* @return true if the database supports setting the maximum number of return rows in a resultset.
*/
public boolean supportsSetMaxRows()
{
return databaseInterface.supportsSetMaxRows();
}
/**
* Verify the name of the database and if required, change it if it already exists in the list of databases.
* @param databases the databases to check against.
* @param oldname the old name of the database
* @return the new name of the database connection
*/
public String verifyAndModifyDatabaseName(List<DatabaseMeta> databases, String oldname)
{
String name = getName();
if (name.equalsIgnoreCase(oldname)) return name; // nothing to see here: move along!
int nr = 2;
while (DatabaseMeta.findDatabase(databases, getName())!=null)
{
setName(name+" "+nr);
nr++;
}
return getName();
}
/**
* @return true if we want to use a database connection pool
*/
public boolean isUsingConnectionPool()
{
return databaseInterface.isUsingConnectionPool();
}
/**
* @param usePool true if we want to use a database connection pool
*/
public void setUsingConnectionPool(boolean usePool)
{
databaseInterface.setUsingConnectionPool(usePool);
}
/**
* @return the maximum pool size
*/
public int getMaximumPoolSize()
{
return databaseInterface.getMaximumPoolSize();
}
/**
* @param maximumPoolSize the maximum pool size
*/
public void setMaximumPoolSize(int maximumPoolSize)
{
databaseInterface.setMaximumPoolSize(maximumPoolSize);
}
/**
* @return the initial pool size
*/
public int getInitialPoolSize()
{
return databaseInterface.getInitialPoolSize();
}
/**
* @param initalPoolSize the initial pool size
*/
public void setInitialPoolSize(int initalPoolSize)
{
databaseInterface.setInitialPoolSize(initalPoolSize);
}
/**
* @return true if the connection contains partitioning information
*/
public boolean isPartitioned()
{
return databaseInterface.isPartitioned();
}
/**
* @param partitioned true if the connection is set to contain partitioning information
*/
public void setPartitioned(boolean partitioned)
{
databaseInterface.setPartitioned(partitioned);
}
/**
* @return the available partition/host/databases/port combinations in the cluster
*/
public PartitionDatabaseMeta[] getPartitioningInformation()
{
if (!isPartitioned()) return new PartitionDatabaseMeta[] {};
return databaseInterface.getPartitioningInformation();
}
/**
* @param partitionInfo the available partition/host/databases/port combinations in the cluster
*/
public void setPartitioningInformation(PartitionDatabaseMeta[] partitionInfo)
{
databaseInterface.setPartitioningInformation(partitionInfo);
}
/**
* Finds the partition metadata for the given partition iD
* @param partitionId The partition ID to look for
* @return the partition database metadata or null if nothing was found.
*/
public PartitionDatabaseMeta getPartitionMeta(String partitionId)
{
PartitionDatabaseMeta[] partitionInfo = getPartitioningInformation();
for (int i=0;i<partitionInfo.length;i++)
{
if (partitionInfo[i].getPartitionId().equals(partitionId)) return partitionInfo[i];
}
return null;
}
public Properties getConnectionPoolingProperties()
{
return databaseInterface.getConnectionPoolingProperties();
}
public void setConnectionPoolingProperties(Properties properties)
{
databaseInterface.setConnectionPoolingProperties(properties);
}
public String getSQLTableExists(String tablename)
{
return databaseInterface.getSQLTableExists(tablename);
}
public boolean needsToLockAllTables()
{
return databaseInterface.needsToLockAllTables();
}
public String getQuotedSchemaTableCombination(String schemaName, String tableName)
{
return getSchemaTableCombination(quoteField(schemaName), quoteField(tableName));
}
/**
* @return true if the database is streaming results (normally this is an option just for MySQL).
*/
public boolean isStreamingResults()
{
return databaseInterface.isStreamingResults();
}
/**
* @param useStreaming true if we want the database to stream results (normally this is an option just for MySQL).
*/
public void setStreamingResults(boolean useStreaming)
{
databaseInterface.setStreamingResults(useStreaming);
}
/**
* @return true if all fields should always be quoted in db
*/
public boolean isQuoteAllFields()
{
return databaseInterface.isQuoteAllFields();
}
/**
* @param quoteAllFields true if all fields in DB should be quoted.
*/
public void setQuoteAllFields(boolean quoteAllFields)
{
databaseInterface.setQuoteAllFields(quoteAllFields);
}
/**
* @return true if all identifiers should be forced to lower case
*/
public boolean isForcingIdentifiersToLowerCase()
{
return databaseInterface.isForcingIdentifiersToLowerCase();
}
/**
* @param forceLowerCase true if all identifiers should be forced to lower case
*/
public void setForcingIdentifiersToLowerCase(boolean forceLowerCase)
{
databaseInterface.setForcingIdentifiersToLowerCase(forceLowerCase);
}
/**
* @return true if all identifiers should be forced to upper case
*/
public boolean isForcingIdentifiersToUpperCase()
{
return databaseInterface.isForcingIdentifiersToUpperCase();
}
/**
* @param forceLowerCase true if all identifiers should be forced to upper case
*/
public void setForcingIdentifiersToUpperCase(boolean forceUpperCase)
{
databaseInterface.setForcingIdentifiersToUpperCase(forceUpperCase);
}
/**
* Find a database with a certain name in an arraylist of databases.
* @param databases The ArrayList of databases
* @param dbname The name of the database connection
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<? extends SharedObjectInterface> databases, String dbname)
{
if (databases == null)
return null;
for (int i = 0; i < databases.size(); i++)
{
DatabaseMeta ci = (DatabaseMeta) databases.get(i);
if (ci.getName().equalsIgnoreCase(dbname))
return ci;
}
return null;
}
/**
* Find a database with a certain name in an ArrayList of databases.
* @param databases The ArrayList of databases
* @param dbname The name of the database connection
* @param exclude the name of the database connection to exclude from the search
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<DatabaseMeta> databases, String dbname, String exclude)
{
if (databases == null)
return null;
for (int i = 0; i < databases.size(); i++)
{
DatabaseMeta ci = (DatabaseMeta) databases.get(i);
if (ci.getName().equalsIgnoreCase(dbname))
return ci;
}
return null;
}
/**
* Find a database with a certain ID in an arraylist of databases.
* @param databases The ArrayList of databases
* @param id The id of the database connection
* @return The database object if one was found, null otherwise.
*/
public static final DatabaseMeta findDatabase(List<DatabaseMeta> databases, long id)
{
if (databases == null)
return null;
for (DatabaseMeta ci : databases)
{
if (ci.getID() == id) {
return ci;
}
}
return null;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
/**
* @return the SQL Server instance
*/
public String getSQLServerInstance()
{
// This is also covered/persisted by JDBC option MS SQL Server / instancename / <somevalue>
// We want to return <somevalue>
// --> MSSQL.instancename
return (String) getExtraOptions().get("MSSQL.instance");
}
/**
* @param instanceName the SQL Server instance
*/
public void setSQLServerInstance(String instanceName)
{
// This is also covered/persisted by JDBC option MS SQL Server / instancename / <somevalue>
// We want to return set <somevalue>
// --> MSSQL.instancename
addExtraOption("MSSQL", "instance", instanceName);
}
/**
* @return true if the Microsoft SQL server uses two decimals (..) to separate schema and table (default==false).
*/
public boolean isUsingDoubleDecimalAsSchemaTableSeparator()
{
return databaseInterface.isUsingDoubleDecimalAsSchemaTableSeparator();
}
/**
* @param useStreaming true if we want the database to stream results (normally this is an option just for MySQL).
*/
public void setUsingDoubleDecimalAsSchemaTableSeparator(boolean useDoubleDecimalSeparator)
{
databaseInterface.setUsingDoubleDecimalAsSchemaTableSeparator(useDoubleDecimalSeparator);
}
private StringBuffer appendConnectionInfo(StringBuffer report, String hostName, String portNumber, String dbName) {
report.append(Messages.getString("DatabaseMeta.report.Hostname")).append(hostName).append(Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseMeta.report.Port")).append(portNumber).append(Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseMeta.report.DatabaseName")).append(dbName).append(Const.CR); //$NON-NLS-1$
return report;
}
/**
* @return true if this database needs a transaction to perform a query (auto-commit turned off).
*/
public boolean isRequiringTransactionsOnQueries()
{
return databaseInterface.isRequiringTransactionsOnQueries();
}
public String testConnection() {
if (getAccessType()!=TYPE_ACCESS_PLUGIN) {
StringBuffer report = new StringBuffer();
Database db = new Database(this);
if (isPartitioned())
{
PartitionDatabaseMeta[] partitioningInformation = getPartitioningInformation();
for (int i = 0; i < partitioningInformation.length; i++)
{
try
{
db.connect(partitioningInformation[i].getPartitionId());
report.append(Messages.getString("DatabaseMeta.report.ConnectionWithPartOk", getName(), partitioningInformation[i].getPartitionId()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report.append(Messages.getString("DatabaseMeta.report.ConnectionWithPartError", getName(), partitioningInformation[i].getPartitionId(), e.toString()) + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
appendConnectionInfo(report, db.environmentSubstitute(partitioningInformation[i].getHostname()),
db.environmentSubstitute(partitioningInformation[i].getPort()),
db.environmentSubstitute(partitioningInformation[i].getDatabaseName()));
report.append(Const.CR);
}
}
else
{
try
{
db.connect();
report.append(Messages.getString("DatabaseMeta.report.ConnectionOk", getName()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report.append(Messages.getString("DatabaseMeta.report.ConnectionError", getName()) + e.toString() + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
appendConnectionInfo(report, db.environmentSubstitute(getHostname()),
db.environmentSubstitute(getDatabasePortNumberString()),
db.environmentSubstitute(getDatabaseName()));
report.append(Const.CR);
}
return report.toString();
}
else {
// If the plug-in needs to provide connection information, we ask the DatabaseInterface...
return databaseInterface.getConnectionTestReport();
}
}
}
|
package org.usfirst.frc.team339.Utils;
import com.ctre.CANTalon;
import com.ctre.CANTalon.FeedbackDevice;
import com.ctre.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* Class to make tuning PID loops easier, either by the smartdashboard, or in
* the code via some other sensor (you'll have to write the code in teleop or
* something for another sensor)
*
* @author Alex Kneipp
* @written 1/21/17
*/
public class CANPIDTuner
{
private CANTalon tunedMotorController = null;
private double F;
private double P;
private double I;
private double D;
private double setpoint;
private boolean smartDashboard;
private double errorThresh = 20;
/**
* Constructs a PID tuner object for a specific CANTalon motor.
*
* @param talon
* The motor we're tuning on. It needs to have some form of rate
* sensor attached to it's breakout board.
* @param errorThreshold
* The maximum error we find it acceptable to have (always positive,
* we use absolute value of the actual error).
*/
public CANPIDTuner (CANTalon talon, double errorThreshold)
{
this.tunedMotorController = talon;
this.P = 0;
this.I = 0;
this.D = 0;
this.setpoint = 0;
this.errorThresh = errorThreshold;
}
private boolean wasIncorrect = false;
private Timer time = new Timer();
private FeedbackDevice feedbackType;
// TODO reference CTRE doc
/**
* Initializes all the CAN stuff for the motor controller.
*
* @param feedbackType
* The type of feedback device in the MotorController.
* @param tunetype
* Speed or position. See the CTRE doc for more info
* @param codesPerRev
* The number of signals the feedback devices gives per rotation, so
* the setpoint can function in rpm or revolutions.
* @param reverseSensor
* Is the feedback device reversed.
*/
public void setupMotorController (FeedbackDevice feedbackType,
TalonControlMode tunetype, int codesPerRev,
boolean reverseSensor)
{
this.feedbackType = feedbackType;
this.tunedMotorController
.setFeedbackDevice(feedbackType);
this.tunedMotorController.changeControlMode(tunetype);
this.tunedMotorController.configEncoderCodesPerRev(codesPerRev);
this.tunedMotorController.reverseSensor(reverseSensor);
this.tunedMotorController.setProfile(0);
this.tunedMotorController.configPeakOutputVoltage(12f, -12f);
this.tunedMotorController.configNominalOutputVoltage(0f, 0f);
wasIncorrect = false;
time.stop();
time.reset();
}
/**
* Initializes everything on the smartDashboard if we have one. If not, does
* nothing.
* Puts P, I, D, Setpoint, Error, and Speed.
* P, I, D, and Setpoint are all editable and affect the function of the code.
* Setpoint is in units of RPM or revolutions if you provided a number other
* than 1 for the codesPerRev argument to setupMotorController.
*/
public void setupDashboard ()
{
this.setpoint = 0;
if (this.smartDashboard)
{
SmartDashboard.putNumber("P", this.P);
SmartDashboard.putNumber("I", this.I);
SmartDashboard.putNumber("D", this.D);
SmartDashboard.putNumber("Setpoint", this.setpoint);
SmartDashboard.putNumber("Error",
this.setpoint - this.tunedMotorController.getSpeed());
SmartDashboard.putNumber("Speed",
this.tunedMotorController.getSpeed());
System.out.println(
"PID: " + this.P + ", " + this.I + ", " + this.D);
System.out.println("Setpoint, error: " + this.setpoint + ", "
+ this.tunedMotorController.getClosedLoopError());
System.out.println(
"Speed: " + this.tunedMotorController.getSpeed());
}
}
/**
* Gets information from the smartDashboard, puts more info back onto the
* smartDashboard, and updates the values on the tuned motor controller.
* Prints out when an error beyond the provided threshold is detected, and the
* time for the PID loop to correct for it.
*/
public void update ()
{
P = SmartDashboard.getNumber("P", this.P);
I = SmartDashboard.getNumber("I", this.I);
D = SmartDashboard.getNumber("D", this.D);
this.setpoint = SmartDashboard.getNumber("Setpoint", this.setpoint);
SmartDashboard.putNumber("Error",
this.setpoint - this.tunedMotorController.getSpeed());
SmartDashboard.putNumber("Speed",
this.tunedMotorController.getSpeed());
this.tunedMotorController.set(this.setpoint);
this.tunedMotorController.setPID(this.P, this.I, this.D);
/*
* if the absolute value of the error (/4 if it's some form of quadrature)
* is greater than our threshold, tell the RIOlog and time how long it takes
* to return.
*/
if (Math.abs(
this.tunedMotorController
.getClosedLoopError()
/ (this.feedbackType == FeedbackDevice.CtreMagEncoder_Relative
|| this.feedbackType == FeedbackDevice.CtreMagEncoder_Absolute
|| this.feedbackType == FeedbackDevice.QuadEncoder
? 4 : 1)) >= this.errorThresh
&& this.wasIncorrect == false)// TODO clean up
{
this.wasIncorrect = true;
this.time.reset();
this.time.start();
System.out.println("Error detected, timing...");
}
if (Math.abs(
this.tunedMotorController
.getClosedLoopError()) <= this.errorThresh
&& this.wasIncorrect == true)
{
this.wasIncorrect = false;
this.time.stop();
System.out.println("Time to correct error: " + this.time.get());
}
}
/**
*
* @param F
* The Feed-forward value for the FPID loop;
*/
public void setF (double F)
{
this.F = F;
}
/**
*
* @param P
* The proportional constant for the PID loop.
*/
public void setP (double P)
{
this.P = P;
}
/**
*
* @param I
* The integral constant for the PID loop.
*/
public void setI (double I)
{
this.I = I;
}
/**
*
* @param D
* The derivative constant for the PID loop.
*/
public void setD (double D)
{
this.D = D;
}
/**
*
* @param P
* The proportional constant for the PID loop.
* @param I
* The integral constant for the PID loop.
* @param D
* The derivative constant for the PID loop.
* @deprecated by Alex Kneipp. Use setFPID(double, double, double, double)
* instead.
*/
@Deprecated
public void setPID (double p, double i, double d)
{
this.P = p;
this.I = i;
this.D = d;
}
/**
*
* @param f
* The feed-forward constant for the FPID loop.
* @param p
* The proportional constant for the FPID loop.
* @param i
* The integral constant for the FPID loop.
* @param d
* The derivative constant for the FPID loop.
*/
public void setFPID (double f, double p, double i, double d)
{
this.setPID(p, i, d);
this.F = f;
}
/**
*
* @return
* the feed-forward value of the FPID loop.
*/
public double getF ()
{
return this.F;
}
/**
*
* @return
* The current proportional constant for the PID loop
*/
public double getP ()
{
return this.P;
}
/**
*
* @return
* The current integral constant for the PID loop
*/
public double getI ()
{
return this.I;
}
/**
*
* @return
* The current derivative constant for the PID loop
*/
public double getD ()
{
return this.D;
}
/**
*
* @param errThresh
* Sets the error threshold that we find acceptable. Always positive.
*/
public void setErrorThreshold (double errThresh)
{
this.errorThresh = errThresh;
}
/**
*
* @return
* The current error threshold.
*/
public double getErrorThreshold ()
{
return this.errorThresh;
}
/**
*
* @param setpoint
* The target velocity or position of the motor being tuned.
* in revolutions or rpm depending on PID type.
*/
public void setSetpoint (double setpoint)
{
this.setpoint = setpoint;
}
/**
*
* @return
* The current setpoint.
*/
public double getSetpoint ()
{
return this.setpoint;
}
}
|
package peergos.server.tests.slow;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runners.*;
import peergos.server.*;
import peergos.server.tests.*;
import peergos.server.util.*;
import peergos.shared.*;
import peergos.shared.social.*;
import peergos.shared.user.*;
import peergos.shared.user.fs.*;
import peergos.shared.util.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
@RunWith(Parameterized.class)
public class SocialBenchmark {
private static int RANDOM_SEED = 666;
private final UserService service;
private final NetworkAccess network;
private final Crypto crypto = Main.initCrypto();
private static Random random = new Random(RANDOM_SEED);
public SocialBenchmark(String useIPFS, Random r) throws Exception {
Pair<UserService, NetworkAccess> pair = buildHttpNetworkAccess(useIPFS.equals("IPFS"), r);
this.service = pair.left;
this.network = pair.right;
}
private static Pair<UserService, NetworkAccess> buildHttpNetworkAccess(boolean useIpfs, Random r) throws Exception {
Args args = UserTests.buildArgs().with("useIPFS", "" + useIpfs);
UserService service = Main.PKI_INIT.main(args);
return new Pair<>(service, NetworkAccess.buildJava(new URL("http://localhost:" + args.getInt("port")), false).get());
}
@Parameterized.Parameters()
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][] {
// {"IPFS", new Random(0)}
{"NOTIPFS", new Random(0)}
});
}
// SendFollowRequest(19) duration: 2340 mS, best: 1519 mS, worst: 2340 mS, av: 1734 mS
@Test
public void social() {
String username = generateUsername();
String password = "test01";
UserContext context = ensureSignedUp(username, password, network, crypto);
List<String> names = new ArrayList<>();
IntStream.range(0, 20).forEach(i -> names.add(generateUsername()));
names.forEach(name -> ensureSignedUp(name, password, network, crypto));
long worst = 0, best = Long.MAX_VALUE, start = System.currentTimeMillis();
for (int i = 0; i < 20; i++) {
long t1 = System.currentTimeMillis();
context.sendInitialFollowRequest(names.get(i)).join();
long duration = System.currentTimeMillis() - t1;
worst = Math.max(worst, duration);
best = Math.min(best, duration);
System.err.printf("SendFollowRequest(%d) duration: %d mS, best: %d mS, worst: %d mS, av: %d mS\n", i,
duration, best, worst, (t1 + duration - start) / (i + 1));
}
}
// ReplyToFollowRequest(19) duration: 4291 mS, best: 3392 mS, worst: 5239 mS, av: 3898 mS
@Test
public void replyToFollowRequest() {
String username = generateUsername();
String password = "test01";
UserContext context = ensureSignedUp(username, password, network, crypto);
List<String> names = new ArrayList<>();
IntStream.range(0, 20).forEach(i -> names.add(generateUsername()));
List<UserContext> users = names.stream()
.map(name -> ensureSignedUp(name, password, network, crypto))
.collect(Collectors.toList());
for (int i = 0; i < 20; i++) {
users.get(i).sendInitialFollowRequest(username).join();
}
List<FollowRequestWithCipherText> pending = context.getSocialState().join().pendingIncoming;
long worst = 0, best = Long.MAX_VALUE, start = System.currentTimeMillis();
// Profile accepting the requests
for (int i = 0; i < 20; i++) {
FollowRequestWithCipherText req = pending.get(i);
long t1 = System.currentTimeMillis();
context.sendReplyFollowRequest(req, true, true).join();
long duration = System.currentTimeMillis() - t1;
worst = Math.max(worst, duration);
best = Math.min(best, duration);
System.err.printf("ReplyToFollowRequest(%d) duration: %d mS, best: %d mS, worst: %d mS, av: %d mS\n", i,
duration, best, worst, (t1 + duration - start) / (i + 1));
}
}
@Test
public void manyFriendsAndShares() {
String username = generateUsername();
String password = "password";
Pair<UserContext, Long> initial = time(() -> ensureSignedUp(username, password, network, crypto));
long initialTime = initial.right;
UserContext us = initial.left;
// Assert.assertTrue(initialTime < 30_000);
int nFriends = 20;
List<Pair<String, String>> otherUsers = IntStream.range(0, nFriends)
.mapToObj(x -> new Pair<>(generateUsername(), password))
.collect(Collectors.toList());
List<UserContext> friends = otherUsers.stream()
.map(p -> ensureSignedUp(p.left, p.right, network, crypto))
.collect(Collectors.toList());
PeergosNetworkUtils.friendBetweenGroups(Arrays.asList(us), friends);
long withFriends = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Assert.assertTrue(withFriends < 3_000);
// Add n files, each shared read only with a random friend
int nFiles = 40;
for (int i=0; i < nFiles; i++) {
byte[] fileData = "dataaaa".getBytes();
String filename = "File" + i;
us.getUserRoot().join().uploadOrReplaceFile(filename, AsyncReader.build(fileData),
fileData.length, network, crypto, x -> {}, crypto.random.randomBytes(32)).join();
String sharee = otherUsers.get(random.nextInt(otherUsers.size())).left;
us.shareReadAccessWith(Paths.get(username, filename), Collections.singleton(sharee)).join();
}
long initialWithReadSharingOut = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
long withReadSharingOut = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Add n files owned by friends, each shared read only with us
for (int i=0; i < nFiles; i++) {
byte[] fileData = "dataaaa".getBytes();
String filename = "File" + i;
UserContext friend = friends.get(random.nextInt(friends.size()));
friend.getUserRoot().join().uploadOrReplaceFile(filename, AsyncReader.build(fileData),
fileData.length, network, crypto, x -> {}, crypto.random.randomBytes(32)).join();
friend.shareReadAccessWith(Paths.get(friend.username, filename), Collections.singleton(username)).join();
}
long initialWithReadSharingIn = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
long withReadSharingIn = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Assert.assertTrue(withReadSharingIn < 4_000);
for (int i=0; i < nFiles; i++) {
byte[] fileData = "dataaaa".getBytes();
String filename = "FileW" + i;
us.getUserRoot().join().uploadOrReplaceFile(filename, AsyncReader.build(fileData),
fileData.length, network, crypto, x -> {}, crypto.random.randomBytes(32)).join();
String sharee = otherUsers.get(random.nextInt(otherUsers.size())).left;
us.shareWriteAccessWith(Paths.get(username, filename), Collections.singleton(sharee)).join();
}
long initialWithWriteSharingOut = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
long withWriteSharingOut = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Add n files owned by friends, each shared read only with us
for (int i=0; i < nFiles; i++) {
byte[] fileData = "dataaaa".getBytes();
String filename = "FileW" + i;
UserContext friend = friends.get(random.nextInt(friends.size()));
friend.getUserRoot().join().uploadOrReplaceFile(filename, AsyncReader.build(fileData),
fileData.length, network, crypto, x -> {}, crypto.random.randomBytes(32)).join();
friend.shareWriteAccessWith(Paths.get(friend.username, filename), Collections.singleton(username)).join();
}
long initialWithWriteSharingIn = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
long withWriteSharingIn = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Assert.assertTrue(withWriteSharingIn < 4_000);
int nFriendsLeaving = 5;
for (int i=0; i < nFriendsLeaving; i++) {
int index = random.nextInt(friends.size());
UserContext friend = friends.get(index);
friend.deleteAccount(otherUsers.get(index).right).join();
friends.remove(friend);
}
long afterLeaving = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
// Assert.assertTrue(afterLeaving < 4_000);
// Time login after a GC
service.gc.collect(s -> Futures.of(true));
long afterGc = time(() -> ensureSignedUp(username, password, network.clear(), crypto)).right;
Assert.assertTrue(afterGc < 4_000);
}
private String generateUsername() {
return "test" + (random.nextInt() % 10000);
}
public static UserContext ensureSignedUp(String username, String password, NetworkAccess network, Crypto crypto) {
return UserContext.ensureSignedUp(username, password, network, crypto).join();
}
public static <V> Pair<V, Long> time(Supplier<V> work) {
long t0 = System.currentTimeMillis();
V res = work.get();
long t1 = System.currentTimeMillis();
return new Pair<>(res, t1 - t0);
}
}
|
package org.flexunit.ant.launcher.commands.player;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.types.FilterSet;
import org.apache.tools.ant.types.FilterSetCollection;
import org.apache.tools.ant.types.Commandline.Argument;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.resources.URLResource;
import org.apache.tools.ant.util.ResourceUtils;
import org.flexunit.ant.LoggingUtil;
public class AdlCommand extends DefaultPlayerCommand
{
private final String ADT_JAR_PATH = "lib" + File.separatorChar + "adt.jar";
private final String DESCRIPTOR_TEMPLATE = "flexUnitDescriptor.template";
private final String DESCRIPTOR_FILE = "flexUnitDescriptor.xml";
private File precompiledAppDescriptor;
@Override
public File getFileToExecute()
{
if(getPrecompiledAppDescriptor() != null)
{
return new File(getPrecompiledAppDescriptor().getAbsolutePath());
}
return new File(getSwf().getParentFile().getAbsolutePath() + File.separatorChar + DESCRIPTOR_FILE);
}
/**
* Used to create the application descriptor used to invoke adl
*/
private void createApplicationDescriptor()
{
try
{
//Template location in JAR
URLResource template = new URLResource(getClass().getResource("/" + DESCRIPTOR_TEMPLATE));
//Descriptor location, same location as SWF due to relative path required in descriptor
File descriptor = new File(getSwf().getParentFile().getAbsolutePath() + File.separatorChar + DESCRIPTOR_FILE);
//Create tokens to filter
Double versionNumber = getVersion();
FilterSet filters = new FilterSet();
filters.addFilter("ADL_SWF", getSwf().getName());
filters.addFilter("ADT_VERSION", Double.toString(versionNumber));
if(versionNumber > 2.0) {
filters.addFilter("VERSION_PROP", "versionNumber");
} else {
filters.addFilter("VERSION_PROP", "version");
}
//Copy descriptor template to SWF folder performing token replacement
ResourceUtils.copyResource(
template,
new FileResource(descriptor),
new FilterSetCollection(filters),
null,
true,
false,
null,
null,
getProject()
);
LoggingUtil.log("Created application descriptor at [" + descriptor.getAbsolutePath() + "]");
}
catch (Exception e)
{
throw new BuildException("Could not create application descriptor");
}
}
private double getVersion()
{
String outputProperty = "AIR_VERSION";
//Execute mxmlc to find SDK version number
Java task = new Java();
task.setFork(true);
task.setFailonerror(true);
task.setJar(new File(getProject().getProperty("FLEX_HOME") + File.separatorChar + ADT_JAR_PATH));
task.setProject(getProject());
task.setDir(getProject().getBaseDir());
task.setOutputproperty(outputProperty);
Argument versionArgument = task.createArg();
versionArgument.setValue("-version");
task.execute();
double version = parseAdtVersionNumber( getProject().getProperty(outputProperty) );
LoggingUtil.log("Found AIR version: " + version);
return version;
}
private double parseAdtVersionNumber( String versionString )
{
double version;
//AIR 2.6 and greater only returns the version number.
if( versionString.startsWith("adt") )
{
//Parse version number and return as int
int prefixIndex = versionString.indexOf("adt version \"");
version = Double.parseDouble(versionString.substring(prefixIndex + 13, prefixIndex + 16));
}else
{
version = Double.parseDouble(versionString.substring(0, 3) );
}
return version;
}
@Override
public void prepare()
{
getCommandLine().setExecutable(generateExecutable());
getCommandLine().addArguments(new String[]{getFileToExecute().getAbsolutePath()});
if(getPrecompiledAppDescriptor() == null)
{
//Create Adl descriptor file
createApplicationDescriptor();
}
}
private String generateExecutable()
{
return getProject().getProperty("FLEX_HOME") + "/bin/" + getDefaults().getAdlCommand();
}
public File getPrecompiledAppDescriptor()
{
return precompiledAppDescriptor;
}
public void setPrecompiledAppDescriptor(File precompiledAppDescriptor)
{
this.precompiledAppDescriptor = precompiledAppDescriptor;
}
}
|
package org.waterforpeople.mapping.app.gwt.server.survey;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;
import org.waterforpeople.mapping.app.gwt.client.survey.OptionContainerDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDependencyDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionHelpDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionOptionDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyGroupDto;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyService;
import org.waterforpeople.mapping.app.gwt.client.survey.TranslationDto;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.util.DtoMarshaller;
import org.waterforpeople.mapping.app.web.dto.BootstrapGeneratorRequest;
import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest;
import org.waterforpeople.mapping.app.web.dto.SurveyTaskRequest;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.SurveyInstance;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.device.app.web.DeviceManagerServlet;
import com.gallatinsystems.framework.exceptions.IllegalDeletionException;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.QuestionHelpMediaDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.Translation.ParentType;
import com.gallatinsystems.survey.domain.xml.AltText;
import com.gallatinsystems.survey.domain.xml.Dependency;
import com.gallatinsystems.survey.domain.xml.Heading;
import com.gallatinsystems.survey.domain.xml.Help;
import com.gallatinsystems.survey.domain.xml.ObjectFactory;
import com.gallatinsystems.survey.domain.xml.Option;
import com.gallatinsystems.survey.domain.xml.Options;
import com.gallatinsystems.survey.domain.xml.Text;
import com.gallatinsystems.survey.domain.xml.ValidationRule;
import com.gallatinsystems.survey.xml.SurveyXMLAdapter;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class SurveyServiceImpl extends RemoteServiceServlet implements
SurveyService {
public static final String FREE_QUESTION_TYPE = "free";
public static final String OPTION_QUESTION_TYPE = "option";
public static final String GEO_QUESTION_TYPE = "geo";
public static final String VIDEO_QUESTION_TYPE = "video";
public static final String PHOTO_QUESTION_TYPE = "photo";
public static final String SCAN_QUESTION_TYPE = "scan";
public static final String STRENGTH_QUESTION_TYPE = "strength";
private static final String SURVEY_S3_PROP = "surveyuploadurl";
private static final String SURVEY_DIR_PROP = "surveyuploaddir";
private static final String PUB_CACHE_PREFIX = "pubsrv";
private static final Logger log = Logger
.getLogger(DeviceManagerServlet.class.getName());
private static final long serialVersionUID = 5557965649047558451L;
private SurveyDAO surveyDao;
private Cache cache;
public SurveyServiceImpl() {
surveyDao = new SurveyDAO();
try {
CacheFactory cacheFactory = CacheManager.getInstance()
.getCacheFactory();
cache = cacheFactory.createCache(Collections.emptyMap());
} catch (CacheException e) {
log.log(Level.SEVERE, "Could not initialize cache", e);
}
}
@Override
public SurveyDto[] listSurvey() {
List<Survey> surveys = surveyDao.list(Constants.ALL_RESULTS);
SurveyDto[] surveyDtos = null;
if (surveys != null) {
surveyDtos = new SurveyDto[surveys.size()];
for (int i = 0; i < surveys.size(); i++) {
SurveyDto dto = new SurveyDto();
Survey s = surveys.get(i);
dto.setName(s.getName());
dto.setVersion(s.getVersion() != null ? s.getVersion()
.toString() : "");
dto.setKeyId(s.getKey().getId());
surveyDtos[i] = dto;
}
}
return surveyDtos;
}
public ArrayList<SurveyGroupDto> listSurveyGroups(String cursorString,
Boolean loadSurveyFlag, Boolean loadQuestionGroupFlag,
Boolean loadQuestionFlag) {
ArrayList<SurveyGroupDto> surveyGroupDtoList = new ArrayList<SurveyGroupDto>();
SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO();
for (SurveyGroup canonical : surveyGroupDao.list(cursorString,
loadSurveyFlag, loadQuestionGroupFlag, loadQuestionFlag)) {
SurveyGroupDto dto = new SurveyGroupDto();
DtoMarshaller.copyToDto(canonical, dto);
dto.setSurveyList(null);
if (canonical.getSurveyList() != null
&& canonical.getSurveyList().size() > 0) {
for (Survey survey : canonical.getSurveyList()) {
SurveyDto surveyDto = new SurveyDto();
DtoMarshaller.copyToDto(survey, surveyDto);
surveyDto.setQuestionGroupList(null);
if (survey.getQuestionGroupMap() != null
&& survey.getQuestionGroupMap().size() > 0) {
for (QuestionGroup questionGroup : survey
.getQuestionGroupMap().values()) {
QuestionGroupDto questionGroupDto = new QuestionGroupDto();
DtoMarshaller.copyToDto(questionGroup,
questionGroupDto);
if (questionGroup.getQuestionMap() != null
&& questionGroup.getQuestionMap().size() > 0) {
for (Entry<Integer, Question> questionEntry : questionGroup
.getQuestionMap().entrySet()) {
Question question = questionEntry
.getValue();
Integer order = questionEntry.getKey();
QuestionDto questionDto = new QuestionDto();
DtoMarshaller.copyToDto(question,
questionDto);
questionGroupDto.addQuestion(questionDto,
order);
}
}
surveyDto.addQuestionGroup(questionGroupDto);
}
}
dto.addSurvey(surveyDto);
}
}
surveyGroupDtoList.add(dto);
}
return surveyGroupDtoList;
}
/**
* This method will return a list of all the questions that have a specific
* type code
*/
public QuestionDto[] listSurveyQuestionByType(Long surveyId,
QuestionType type) {
QuestionDao questionDao = new QuestionDao();
List<Question> qList = questionDao.listQuestionByType(surveyId,
Question.Type.valueOf(type.toString()));
QuestionDto[] dtoArr = new QuestionDto[qList.size()];
int i = 0;
for (Question q : qList) {
dtoArr[i] = marshalQuestionDto(q);
i++;
}
return dtoArr;
}
/**
* lists all surveys for a group
*/
@Override
public ArrayList<SurveyDto> listSurveysByGroup(String surveyGroupId) {
SurveyDAO dao = new SurveyDAO();
List<Survey> surveys = dao.listSurveysByGroup(Long
.parseLong(surveyGroupId));
ArrayList<SurveyDto> surveyDtos = null;
if (surveys != null) {
surveyDtos = new ArrayList<SurveyDto>();
for (Survey s : surveys) {
SurveyDto dto = new SurveyDto();
dto.setName(s.getName());
dto.setVersion(s.getVersion() != null ? s.getVersion()
.toString() : "");
dto.setKeyId(s.getKey().getId());
if (s.getStatus() != null) {
dto.setStatus(s.getStatus().toString());
}
surveyDtos.add(dto);
}
}
return surveyDtos;
}
@Override
public SurveyGroupDto save(SurveyGroupDto value) {
SurveyGroupDAO sgDao = new SurveyGroupDAO();
SurveyGroup surveyGroup = new SurveyGroup();
DtoMarshaller.copyToCanonical(surveyGroup, value);
surveyGroup.setSurveyList(null);
for (SurveyDto item : value.getSurveyList()) {
// SurveyDto item = value.getSurveyList().get(0);
Survey survey = new Survey();
DtoMarshaller.copyToCanonical(survey, item);
survey.setQuestionGroupMap(null);
int order = 1;
for (QuestionGroupDto qgDto : item.getQuestionGroupList()) {
QuestionGroup qg = new QuestionGroup();
DtoMarshaller.copyToCanonical(qg, qgDto);
survey.addQuestionGroup(order++, qg);
int qOrder = 1;
for (Entry<Integer, QuestionDto> qDto : qgDto.getQuestionMap()
.entrySet()) {
Question q = marshalQuestion(qDto.getValue());
qg.addQuestion(qOrder++, q);
}
}
surveyGroup.addSurvey(survey);
}
DtoMarshaller.copyToDto(sgDao.save(surveyGroup), value);
return value;
}
public static QuestionDto marshalQuestionDto(Question q) {
QuestionDto qDto = new QuestionDto();
qDto.setKeyId(q.getKey().getId());
qDto.setQuestionGroupId(q.getQuestionGroupId());
qDto.setPath(q.getPath());
qDto.setOrder(q.getOrder());
qDto.setSurveyId(q.getSurveyId());
if (q.getMandatoryFlag() != null) {
if (q.getMandatoryFlag()) {
qDto.setMandatoryFlag(true);
}
} else {
qDto.setMandatoryFlag(false);
}
if (q.getText() != null)
qDto.setText(q.getText());
if (q.getTip() != null)
qDto.setTip(q.getTip());
if (q.getType() != null)
qDto.setType(QuestionDto.QuestionType.valueOf(q.getType()
.toString()));
if (q.getValidationRule() != null)
qDto.setValidationRule(q.getValidationRule());
if (q.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia help : q.getQuestionHelpMediaMap().values()) {
QuestionHelpDto dto = new QuestionHelpDto();
Map<String, Translation> transMap = help.getTranslationMap();
help.setTranslationMap(null);
DtoMarshaller.copyToDto(help, dto);
if (transMap != null) {
dto.setTranslationMap(marshalTranslations(transMap));
}
qDto.addQuestionHelp(dto);
}
}
if (q.getQuestionOptionMap() != null) {
OptionContainerDto ocDto = new OptionContainerDto();
if (q.getAllowOtherFlag() != null)
ocDto.setAllowOtherFlag(q.getAllowOtherFlag());
if (q.getAllowMultipleFlag() != null)
ocDto.setAllowMultipleFlag(q.getAllowMultipleFlag());
for (QuestionOption qo : q.getQuestionOptionMap().values()) {
QuestionOptionDto ooDto = new QuestionOptionDto();
ooDto.setTranslationMap(marshalTranslations(qo
.getTranslationMap()));
ooDto.setKeyId(qo.getKey().getId());
if (qo.getCode() != null)
ooDto.setCode(qo.getCode());
if (qo.getText() != null)
ooDto.setText(qo.getText());
ooDto.setOrder(qo.getOrder());
ocDto.addQuestionOption(ooDto);
}
qDto.setOptionContainerDto(ocDto);
}
if (q.getDependentQuestionId() != null) {
QuestionDependencyDto qdDto = new QuestionDependencyDto();
qdDto.setQuestionId(q.getDependentQuestionId());
qdDto.setAnswerValue(q.getDependentQuestionAnswer());
qDto.setQuestionDependency(qdDto);
}
qDto.setTranslationMap(marshalTranslations(q.getTranslationMap()));
return qDto;
}
private static TreeMap<String, TranslationDto> marshalTranslations(
Map<String, Translation> translationMap) {
TreeMap<String, TranslationDto> transMap = null;
if (translationMap != null && translationMap.size() > 0) {
transMap = new TreeMap<String, TranslationDto>();
for (Translation trans : translationMap.values()) {
TranslationDto tDto = new TranslationDto();
tDto.setKeyId(trans.getKey().getId());
tDto.setLangCode(trans.getLanguageCode());
tDto.setText(trans.getText());
tDto.setParentId(trans.getParentId());
tDto.setParentType(trans.getParentType().toString());
transMap.put(tDto.getLangCode(), tDto);
}
}
return transMap;
}
private static TreeMap<String, Translation> marshalFromDtoTranslations(
Map<String, TranslationDto> translationMap) {
TreeMap<String, Translation> transMap = null;
if (translationMap != null && translationMap.size() > 0) {
transMap = new TreeMap<String, Translation>();
for (TranslationDto trans : translationMap.values()) {
Translation t = new Translation();
if (trans.getKeyId() != null)
t.setKey((KeyFactory.createKey(
Translation.class.getSimpleName(), trans.getKeyId())));
t.setLanguageCode(trans.getLangCode());
t.setText(trans.getText());
t.setParentId(trans.getParentId());
if (trans.getParentType().equals(
Translation.ParentType.QUESTION_TEXT.toString())) {
t.setParentType(ParentType.QUESTION_TEXT);
} else if (trans.getParentType().equals(
Translation.ParentType.QUESTION_OPTION.toString())) {
t.setParentType(ParentType.QUESTION_OPTION);
} else if (Translation.ParentType.QUESTION_HELP_MEDIA_TEXT
.toString().equals(trans.getParentType())) {
t.setParentType(ParentType.QUESTION_HELP_MEDIA_TEXT);
}
transMap.put(t.getLanguageCode(), t);
}
}
return transMap;
}
public Question marshalQuestion(QuestionDto qdto) {
Question q = new Question();
if (qdto.getKeyId() != null)
q.setKey((KeyFactory.createKey(Question.class.getSimpleName(),
qdto.getKeyId())));
q.setQuestionGroupId(qdto.getQuestionGroupId());
q.setOrder(qdto.getOrder());
q.setPath(qdto.getPath());
q.setMandatoryFlag(qdto.getMandatoryFlag());
q.setAllowMultipleFlag(qdto.getAllowMultipleFlag());
q.setAllowOtherFlag(qdto.getAllowOtherFlag());
if (qdto.getText() != null) {
q.setText(qdto.getText());
}
if (qdto.getTip() != null)
q.setTip(qdto.getTip());
if (qdto.getType() != null)
q.setType(Question.Type.valueOf(qdto.getType().toString()));
if (qdto.getValidationRule() != null)
q.setValidationRule(qdto.getValidationRule());
if (qdto.getQuestionHelpList() != null) {
List<QuestionHelpDto> qHListDto = qdto.getQuestionHelpList();
int i = 1;
for (QuestionHelpDto qhDto : qHListDto) {
QuestionHelpMedia qh = new QuestionHelpMedia();
DtoMarshaller.copyToCanonical(qh, qhDto);
}
}
if (qdto.getOptionContainerDto() != null) {
OptionContainerDto ocDto = qdto.getOptionContainerDto();
if (ocDto.getAllowOtherFlag() != null) {
q.setAllowOtherFlag(ocDto.getAllowOtherFlag());
}
if (ocDto.getAllowMultipleFlag() != null) {
q.setAllowMultipleFlag(ocDto.getAllowMultipleFlag());
}
if (ocDto.getOptionsList() != null) {
ArrayList<QuestionOptionDto> optionDtoList = ocDto
.getOptionsList();
for (QuestionOptionDto qoDto : optionDtoList) {
QuestionOption oo = new QuestionOption();
if (qoDto.getKeyId() != null)
oo.setKey((KeyFactory.createKey(
QuestionOption.class.getSimpleName(),
qoDto.getKeyId())));
if (qoDto.getCode() != null)
oo.setCode(qoDto.getCode());
if (qoDto.getText() != null)
oo.setText(qoDto.getText());
oo.setOrder(qoDto.getOrder());
// Hack
if (qoDto.getTranslationMap() != null) {
TreeMap<String, Translation> transTreeMap = SurveyServiceImpl
.marshalFromDtoTranslations(qoDto
.getTranslationMap());
HashMap<String, Translation> transMap = new HashMap<String, Translation>();
for (Map.Entry<String, Translation> entry : transTreeMap
.entrySet()) {
transMap.put(entry.getKey(), entry.getValue());
}
oo.setTranslationMap(transMap);
}
q.addQuestionOption(oo);
}
}
}
if (qdto.getQuestionDependency() != null) {
q.setDependentQuestionId(qdto.getQuestionDependency()
.getQuestionId());
q.setDependentQuestionAnswer(qdto.getQuestionDependency()
.getAnswerValue());
q.setDependentFlag(true);
}
if (qdto.getTranslationMap() != null) {
TreeMap<String, Translation> transMap = marshalFromDtoTranslations(qdto
.getTranslationMap());
q.setTranslationMap(transMap);
}
if (qdto.getQuestionHelpList() != null) {
int count = 0;
for (QuestionHelpDto help : qdto.getQuestionHelpList()) {
QuestionHelpMedia helpDomain = new QuestionHelpMedia();
Map<String, TranslationDto> transMap = help.getTranslationMap();
help.setTranslationMap(null);
DtoMarshaller.copyToCanonical(helpDomain, help);
if (transMap != null) {
helpDomain
.setTranslationMap(marshalFromDtoTranslations(transMap));
}
q.addHelpMedia(count++, helpDomain);
}
}
return q;
}
/**
* fully hydrates a single survey object
*/
public SurveyDto loadFullSurvey(Long surveyId) {
Survey survey = surveyDao.loadFullSurvey(surveyId);
SurveyDto dto = null;
if (survey != null) {
dto = new SurveyDto();
DtoMarshaller.copyToDto(survey, dto);
dto.setQuestionGroupList(null);
if (survey.getQuestionGroupMap() != null) {
ArrayList<QuestionGroupDto> qGroupDtoList = new ArrayList<QuestionGroupDto>();
for (QuestionGroup qg : survey.getQuestionGroupMap().values()) {
QuestionGroupDto qgDto = new QuestionGroupDto();
DtoMarshaller.copyToDto(qg, qgDto);
qgDto.setQuestionMap(null);
qGroupDtoList.add(qgDto);
if (qg.getQuestionMap() != null) {
TreeMap<Integer, QuestionDto> qDtoMap = new TreeMap<Integer, QuestionDto>();
for (Entry<Integer, Question> entry : qg
.getQuestionMap().entrySet()) {
QuestionDto qdto = marshalQuestionDto(entry
.getValue());
qDtoMap.put(entry.getKey(), qdto);
}
qgDto.setQuestionMap(qDtoMap);
}
}
dto.setQuestionGroupList(qGroupDtoList);
}
}
return dto;
}
@Override
public List<SurveyDto> listSurveysForSurveyGroup(String surveyGroupId) {
List<Survey> surveyList = surveyDao.listSurveysByGroup(Long
.parseLong(surveyGroupId));
List<SurveyDto> surveyDtoList = new ArrayList<SurveyDto>();
for (Survey canonical : surveyList) {
SurveyDto dto = new SurveyDto();
DtoMarshaller.copyToDto(canonical, dto);
surveyDtoList.add(dto);
}
return surveyDtoList;
}
@Override
public ArrayList<QuestionGroupDto> listQuestionGroupsBySurvey(
String surveyId) {
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
TreeMap<Integer, QuestionGroup> questionGroupList = questionGroupDao
.listQuestionGroupsBySurvey(new Long(surveyId));
ArrayList<QuestionGroupDto> questionGroupDtoList = new ArrayList<QuestionGroupDto>();
for (QuestionGroup canonical : questionGroupList.values()) {
QuestionGroupDto dto = new QuestionGroupDto();
DtoMarshaller.copyToDto(canonical, dto);
questionGroupDtoList.add(dto);
}
return questionGroupDtoList;
}
@Override
public ArrayList<QuestionDto> listQuestionsByQuestionGroup(
String questionGroupId, boolean needDetails) {
QuestionDao questionDao = new QuestionDao();
TreeMap<Integer, Question> questionList = questionDao
.listQuestionsByQuestionGroup(Long.parseLong(questionGroupId),
needDetails);
java.util.ArrayList<QuestionDto> questionDtoList = new ArrayList<QuestionDto>();
if (questionList != null && !questionList.isEmpty()) {
for (Question canonical : questionList.values()) {
QuestionDto dto = marshalQuestionDto(canonical);
questionDtoList.add(dto);
}
return questionDtoList;
} else {
return null;
}
}
@Override
public String deleteQuestion(QuestionDto value, Long questionGroupId) {
QuestionDao questionDao = new QuestionDao();
Question canonical = new Question();
DtoMarshaller.copyToCanonical(canonical, value);
try {
questionDao.delete(canonical);
} catch (IllegalDeletionException e) {
return e.getError();
}
return null;
}
@Override
public QuestionDto saveQuestion(QuestionDto value, Long questionGroupId) {
QuestionDao questionDao = new QuestionDao();
Question question = marshalQuestion(value);
question = questionDao.save(question, questionGroupId);
return marshalQuestionDto(question);
}
@Override
public QuestionGroupDto saveQuestionGroup(QuestionGroupDto dto,
Long surveyId) {
QuestionGroup questionGroup = new QuestionGroup();
DtoMarshaller.copyToCanonical(questionGroup, dto);
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
if (questionGroup.getOrder() == null || questionGroup.getOrder() == 0) {
Map<Integer, QuestionGroup> items = questionGroupDao
.listQuestionGroupsBySurvey(questionGroup.getSurveyId());
if (items != null) {
questionGroup.setOrder(items.size() + 1);
} else {
questionGroup.setOrder(1);
}
}
questionGroup = questionGroupDao.save(questionGroup, surveyId, null);
DtoMarshaller.copyToDto(questionGroup, dto);
return dto;
}
@Override
public List<QuestionGroupDto> saveQuestionGroups(
List<QuestionGroupDto> dtoList) {
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
if (dtoList != null) {
List<QuestionGroup> groupList = new ArrayList<QuestionGroup>();
int i = 0;
for (QuestionGroupDto dto : dtoList) {
QuestionGroup questionGroup = new QuestionGroup();
DtoMarshaller.copyToCanonical(questionGroup, dto);
if (questionGroup.getOrder() == null
|| questionGroup.getOrder() == 0) {
questionGroup.setOrder(i);
}
groupList.add(questionGroup);
i++;
}
questionGroupDao.save(groupList);
for (int j = 0; j < groupList.size(); j++) {
dtoList.get(j).setKeyId(groupList.get(j).getKey().getId());
}
}
return dtoList;
}
@Override
public SurveyDto saveSurvey(SurveyDto surveyDto, Long surveyGroupId) {
Survey canonical = new Survey();
DtoMarshaller.copyToCanonical(canonical, surveyDto);
canonical.setStatus(Survey.Status.NOT_PUBLISHED);
SurveyDAO surveyDao = new SurveyDAO();
if (canonical.getKey() != null && canonical.getSurveyGroupId() == 0) {
// fetch record from db so we don't loose assoc
Survey sTemp = surveyDao.getByKey(canonical.getKey());
canonical.setSurveyGroupId(sTemp.getSurveyGroupId());
canonical.setPath(sTemp.getPath());
}
canonical = surveyDao.save(canonical);
DtoMarshaller.copyToDto(canonical, surveyDto);
return surveyDto;
}
@Override
public SurveyGroupDto saveSurveyGroup(SurveyGroupDto dto) {
SurveyGroup canonical = new SurveyGroup();
SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO();
DtoMarshaller.copyToCanonical(canonical, dto);
canonical = surveyGroupDao.save(canonical);
DtoMarshaller.copyToDto(canonical, dto);
return dto;
}
/**
* saves or updates a list of translation objects and returns the saved
* value. If the text is null or blank and the ID is populated, that
* translation will be deleted since we shouldn't allow blank translations.
*/
@Override
public List<TranslationDto> saveTranslations(
List<TranslationDto> translations) {
TranslationDao translationDao = new TranslationDao();
List<TranslationDto> deletedItems = new ArrayList<TranslationDto>();
for (TranslationDto t : translations) {
Translation transDomain = new Translation();
// need to work around marshaller's inability to translate string to
// enumeration values. We need to set it back after the copy call
String parentType = t.getParentType();
t.setParentType(null);
DtoMarshaller.copyToCanonical(transDomain, t);
t.setParentType(parentType);
transDomain.setParentType(ParentType.valueOf(parentType));
transDomain.setLanguageCode(t.getLangCode());
if (transDomain.getKey() != null
&& (transDomain.getText() == null || transDomain.getText()
.trim().length() == 0)) {
Translation itemToDelete = translationDao.getByKey(transDomain
.getKey());
if (itemToDelete != null) {
translationDao.delete(itemToDelete);
deletedItems.add(t);
}
} else {
transDomain = translationDao.save(transDomain);
}
t.setKeyId(transDomain.getKey().getId());
}
translations.removeAll(deletedItems);
return translations;
}
@Override
public void publishSurveyAsync(Long surveyId) {
surveyDao.incrementVersion(surveyId);
Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly");
surveyAssemblyQueue.add(url("/app_worker/surveyassembly").param(
"action", SurveyAssemblyRequest.ASSEMBLE_SURVEY).param(
"surveyId", surveyId.toString()));
}
@Override
public String publishSurvey(Long surveyId) {
try {
SurveyDAO surveyDao = new SurveyDAO();
Survey survey = surveyDao.loadFullSurvey(surveyId);
SurveyXMLAdapter sax = new SurveyXMLAdapter();
ObjectFactory objFactory = new ObjectFactory();
// System.out.println("XML Marshalling for survey: " + surveyId);
com.gallatinsystems.survey.domain.xml.Survey surveyXML = objFactory
.createSurvey();
ArrayList<com.gallatinsystems.survey.domain.xml.QuestionGroup> questionGroupXMLList = new ArrayList<com.gallatinsystems.survey.domain.xml.QuestionGroup>();
for (QuestionGroup qg : survey.getQuestionGroupMap().values()) {
// System.out.println(" QuestionGroup: " + qg.getKey().getId() +
// + qg.getCode() + ":" + qg.getDescription());
com.gallatinsystems.survey.domain.xml.QuestionGroup qgXML = objFactory
.createQuestionGroup();
Heading heading = objFactory.createHeading();
heading.setContent(qg.getCode());
qgXML.setHeading(heading);
// TODO: implement questionGroup order attribute
// qgXML.setOrder(qg.getOrder());
ArrayList<com.gallatinsystems.survey.domain.xml.Question> questionXMLList = new ArrayList<com.gallatinsystems.survey.domain.xml.Question>();
if (qg.getQuestionMap() != null) {
for (Entry<Integer, Question> qEntry : qg.getQuestionMap()
.entrySet()) {
Question q = qEntry.getValue();
com.gallatinsystems.survey.domain.xml.Question qXML = objFactory
.createQuestion();
qXML.setId(new String("" + q.getKey().getId() + ""));
// ToDo fix
qXML.setMandatory("false");
if (q.getText() != null) {
Text text = new Text();
text.setContent(q.getText());
qXML.setText(text);
}
List<Help> helpList = new ArrayList<Help>();
// this is here for backward compatibility
if (q.getTip() != null) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(q.getTip());
tip.setText(t);
tip.setType("tip");
if (q.getTip() != null
&& q.getTip().trim().length() > 0
&& !"null".equalsIgnoreCase(q.getTip()
.trim())) {
helpList.add(tip);
}
}
if (q.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia helpItem : q
.getQuestionHelpMediaMap().values()) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(helpItem.getText());
if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) {
tip.setType("tip");
} else {
tip.setType(helpItem.getType().toString()
.toLowerCase());
}
if (helpItem.getTranslationMap() != null) {
List<AltText> translationList = new ArrayList<AltText>();
for (Translation trans : helpItem
.getTranslationMap().values()) {
AltText aText = new AltText();
aText.setContent(trans.getText());
aText.setLanguage(trans
.getLanguageCode());
aText.setType("translation");
translationList.add(aText);
}
if (translationList.size() > 0) {
tip.setAltText(translationList);
}
}
helpList.add(tip);
}
}
if (q.getValidationRule() != null) {
ValidationRule validationRule = objFactory
.createValidationRule();
// TODO: set validation rule xml
// validationRule.setAllowDecimal(value)
}
if (q.getType().equals(QuestionType.FREE_TEXT))
qXML.setType(FREE_QUESTION_TYPE);
else if (q.getType().equals(QuestionType.GEO))
qXML.setType(GEO_QUESTION_TYPE);
else if (q.getType().equals(QuestionType.NUMBER)) {
qXML.setType(FREE_QUESTION_TYPE);
ValidationRule vrule = new ValidationRule();
vrule.setValidationType("numeric");
vrule.setSigned("false");
qXML.setValidationRule(vrule);
} else if (q.getType().equals(QuestionType.OPTION)) {
qXML.setType(OPTION_QUESTION_TYPE);
} else if (q.getType().equals(QuestionType.STRENGTH)) {
qXML.setType(STRENGTH_QUESTION_TYPE);
} else if (q.getType().equals(QuestionType.PHOTO))
qXML.setType(PHOTO_QUESTION_TYPE);
else if (q.getType().equals(QuestionType.VIDEO))
qXML.setType(VIDEO_QUESTION_TYPE);
else if (q.getType().equals(QuestionType.SCAN))
qXML.setType(SCAN_QUESTION_TYPE);
if (qEntry.getKey() != null)
qXML.setOrder(qEntry.getKey().toString());
// ToDo set dependency xml
Dependency dependency = objFactory.createDependency();
if (q.getDependentQuestionId() != null) {
dependency.setQuestion(q.getDependentQuestionId()
.toString());
dependency.setAnswerValue(q
.getDependentQuestionAnswer());
qXML.setDependency(dependency);
}
if (q.getQuestionOptionMap() != null
&& q.getQuestionOptionMap().size() > 0) {
Options options = objFactory.createOptions();
if (q.getAllowOtherFlag() != null) {
options.setAllowOther(q.getAllowOtherFlag()
.toString());
}
ArrayList<Option> optionList = new ArrayList<Option>();
for (QuestionOption qo : q.getQuestionOptionMap()
.values()) {
Option option = objFactory.createOption();
Text t = new Text();
t.setContent(qo.getText());
option.addContent(t);
option.setValue(qo.getCode());
optionList.add(option);
}
options.setOption(optionList);
qXML.setOptions(options);
}
questionXMLList.add(qXML);
}
}
qgXML.setQuestion(questionXMLList);
questionGroupXMLList.add(qgXML);
}
surveyXML.setQuestionGroup(questionGroupXMLList);
String surveyDocument = sax.marshal(surveyXML);
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = new SurveyContainer();
sc.setSurveyId(surveyId);
sc.setSurveyDocument(new com.google.appengine.api.datastore.Text(
surveyDocument));
SurveyContainer scFound = scDao.findBySurveyId(sc.getSurveyId());
if (scFound != null) {
scFound.setSurveyDocument(sc.getSurveyDocument());
scDao.save(scFound);
} else
scDao.save(sc);
survey.setStatus(Survey.Status.PUBLISHED);
surveyDao.save(survey);
} catch (Exception ex) {
ex.printStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("Could not publish survey: \n cause: " + ex.getCause()
+ " \n message" + ex.getMessage() + "\n stack trace: ");
return sb.toString();
}
return "Survey successfully published";
}
@Override
public QuestionDto loadQuestionDetails(Long questionId) {
QuestionDao questionDao = new QuestionDao();
Question canonical = questionDao.getByKey(questionId, true);
if (canonical != null) {
return marshalQuestionDto(canonical);
} else {
return null;
}
}
@Override
public String deleteQuestionGroup(QuestionGroupDto value, Long surveyId) {
if (value != null) {
QuestionGroupDao qgDao = new QuestionGroupDao();
qgDao.delete(qgDao.getByKey(value.getKeyId()));
}
return null;
}
@Override
public String deleteSurvey(SurveyDto value, Long surveyGroupId) {
if (value != null) {
SurveyDAO surveyDao = new SurveyDAO();
try {
Survey s = new Survey();
DtoMarshaller.copyToCanonical(s, value);
surveyDao.delete(s);
} catch (IllegalDeletionException e) {
log.log(Level.SEVERE, "Could not delete survey", e);
}
}
return null;
}
@Override
public String deleteSurveyGroup(SurveyGroupDto value) {
if (value != null) {
SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO();
surveyGroupDao.delete(marshallSurveyGroup(value));
}
return null;
}
public static SurveyGroup marshallSurveyGroup(SurveyGroupDto dto) {
SurveyGroup sg = new SurveyGroup();
if (dto.getKeyId() != null)
sg.setKey(KeyFactory.createKey(SurveyGroup.class.getSimpleName(),
dto.getKeyId()));
if (dto.getCode() != null)
sg.setCode(dto.getCode());
return sg;
}
@Override
public void rerunAPMappings(Long surveyId) {
SurveyInstanceDAO siDao = new SurveyInstanceDAO();
List<SurveyInstance> siList = siDao.listSurveyInstanceBySurveyId(
surveyId, null);
if (siList != null && siList.size() > 0) {
Queue queue = QueueFactory.getDefaultQueue();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < siList.size(); i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(siList.get(i).getKey().getId());
}
queue.add(url("/app_worker/surveytask")
.param("action", "reprocessMapSurveyInstance")
.param(SurveyTaskRequest.ID_PARAM, surveyId.toString())
.param(SurveyTaskRequest.ID_LIST_PARAM, buffer.toString())
.param(SurveyTaskRequest.CURSOR_PARAM,
SurveyInstanceDAO.getCursor(siList)));
}
}
@Override
public List<QuestionHelpDto> listHelpByQuestion(Long questionId) {
QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao();
TreeMap<Integer, QuestionHelpMedia> helpMedia = helpDao
.listHelpByQuestion(questionId);
List<QuestionHelpDto> dtoList = new ArrayList<QuestionHelpDto>();
if (helpMedia != null) {
for (QuestionHelpMedia help : helpMedia.values()) {
QuestionHelpDto dto = new QuestionHelpDto();
Map<String, Translation> transMap = help.getTranslationMap();
help.setTranslationMap(null);
DtoMarshaller.copyToDto(help, dto);
if (transMap != null) {
dto.setTranslationMap(marshalTranslations(transMap));
}
dtoList.add(dto);
}
}
return dtoList;
}
public List<QuestionHelpDto> saveHelp(List<QuestionHelpDto> helpList) {
QuestionHelpMediaDao helpDao = new QuestionHelpMediaDao();
if (helpList != null && helpList.size() > 0) {
Collection<QuestionHelpMedia> domainList = new ArrayList<QuestionHelpMedia>();
for (QuestionHelpDto dto : helpList) {
QuestionHelpMedia canonical = new QuestionHelpMedia();
DtoMarshaller.copyToCanonical(canonical, dto);
domainList.add(canonical);
}
domainList = helpDao.save(domainList);
helpList.clear();
for (QuestionHelpMedia domain : domainList) {
QuestionHelpDto dto = new QuestionHelpDto();
DtoMarshaller.copyToDto(domain, dto);
helpList.add(dto);
}
}
return helpList;
}
public Map<String, TranslationDto> listTranslations(Long parentId,
String parentType) {
TranslationDao transDao = new TranslationDao();
Map<String, Translation> transMap = transDao.findTranslations(
Translation.ParentType.valueOf(parentType), parentId);
return marshalTranslations(transMap);
}
public QuestionDto copyQuestion(QuestionDto existingQuestion,
QuestionGroupDto newParentGroup) {
Question questionToSave = marshalQuestion(existingQuestion);
// now override all the IDs
questionToSave.setKey(null);
questionToSave.setPath(newParentGroup.getPath() + "/"
+ newParentGroup.getName());
questionToSave.setQuestionGroupId(newParentGroup.getKeyId());
if (questionToSave.getQuestionOptionMap() != null) {
for (QuestionOption opt : questionToSave.getQuestionOptionMap()
.values()) {
opt.setKey(null);
opt.setQuestionId(null);
if (opt.getTranslationMap() != null) {
for (Translation t : opt.getTranslationMap().values()) {
t.setKey(null);
t.setParentId(null);
}
}
}
}
if (questionToSave.getTranslationMap() != null) {
for (Translation t : questionToSave.getTranslationMap().values()) {
t.setParentId(null);
t.setKey(null);
}
}
if (questionToSave.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia help : questionToSave
.getQuestionHelpMediaMap().values()) {
help.setKey(null);
if (help.getTranslationMap() != null) {
for (Translation t : help.getTranslationMap().values()) {
t.setParentId(null);
t.setKey(null);
}
}
}
}
QuestionDao dao = new QuestionDao();
dao.save(questionToSave, newParentGroup.getKeyId());
return marshalQuestionDto(questionToSave);
}
/**
* updates the order for the list of questions passed in
*
* @param q1
* @param q2
* @return
*/
public void updateQuestionOrder(List<QuestionDto> questions) {
if (questions != null) {
List<Question> questionList = new ArrayList<Question>();
for (QuestionDto qDto : questions) {
Question q = new Question();
q.setKey(KeyFactory.createKey(Question.class.getSimpleName(),
qDto.getKeyId()));
q.setOrder(qDto.getOrder());
questionList.add(q);
}
QuestionDao dao = new QuestionDao();
dao.updateQuestionOrder(questionList);
}
}
/**
* updates the order for the list of question groups passed in
*
* @param q1
* @param q2
* @return
*/
public void updateQuestionGroupOrder(List<QuestionGroupDto> groups) {
if (groups != null) {
List<QuestionGroup> groupList = new ArrayList<QuestionGroup>();
for (QuestionGroupDto qDto : groups) {
QuestionGroup q = new QuestionGroup();
q.setKey(KeyFactory.createKey(
QuestionGroup.class.getSimpleName(), qDto.getKeyId()));
q.setOrder(qDto.getOrder());
groupList.add(q);
}
QuestionDao dao = new QuestionDao();
dao.updateQuestionGroupOrder(groupList);
}
}
/**
* updates a question with new dependency information.
*
* @param questionId
* @param dep
*/
public void updateQuestionDependency(Long questionId,
QuestionDependencyDto dep) {
QuestionDao qDao = new QuestionDao();
Question q = qDao.getByKey(questionId, false);
if (q != null) {
if (dep != null) {
q.setDependentFlag(true);
q.setDependentQuestionId(dep.getQuestionId());
q.setDependentQuestionAnswer(dep.getAnswerValue());
} else {
q.setDependentFlag(false);
}
}
}
/**
* returns a surveyDto populated from the published xml. This domain graph
* lacks many keyIds so it is not suitable for updating the survey
* structure. It is, however, suitable for rendering the survey and
* collecting responses.
*
* @param surveyId
* @return
*/
public SurveyDto getPublishedSurvey(String surveyId) {
SurveyDto dto = null;
try {
try {
if (cache != null) {
if (cache.containsKey(PUB_CACHE_PREFIX + surveyId)) {
dto = (SurveyDto) cache
.get(PUB_CACHE_PREFIX + surveyId);
if (dto != null) {
return dto;
}
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Could not check cache", e);
}
URL url = new URL(PropertyUtil.getProperty(SURVEY_S3_PROP)
+ PropertyUtil.getProperty(SURVEY_DIR_PROP) + "/"
+ surveyId + ".xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
StringBuffer buff = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buff.append(line);
}
reader.close();
String fullContent = buff.toString();
if (fullContent.trim().length() > 0) {
SurveyXmlDtoHelper helper = new SurveyXmlDtoHelper();
dto = helper.parseAsDtoGraph(fullContent.trim(), new Long(
surveyId));
try {
if (cache != null) {
cache.put(PUB_CACHE_PREFIX + surveyId, dto);
}
} catch (Exception e) {
log.log(Level.WARNING, "Could not cache result", e);
}
}
} catch (Exception e) {
log.log(Level.SEVERE, "Could not popuate survey from xml", e);
}
return dto;
}
/**
* fires an async request to generate a bootstrap xml file
*
* @param surveyIdList
* @param dbInstructions
* @param notificationEmail
*/
public void generateBootstrapFile(List<Long> surveyIdList,
String dbInstructions, String notificationEmail) {
StringBuilder buf = new StringBuilder();
if (surveyIdList != null) {
for (int i = 0; i < surveyIdList.size(); i++) {
if (i > 0) {
buf.append(BootstrapGeneratorRequest.DELMITER);
}
buf.append(surveyIdList.get(i).toString());
}
}
Queue queue = QueueFactory.getQueue("background-processing");
queue.add(url("/app_worker/bootstrapgen")
.param(BootstrapGeneratorRequest.ACTION_PARAM,
BootstrapGeneratorRequest.GEN_ACTION)
.param(BootstrapGeneratorRequest.SURVEY_ID_LIST_PARAM,
buf.toString())
.param(BootstrapGeneratorRequest.EMAIL_PARAM, notificationEmail)
.param(BootstrapGeneratorRequest.DB_PARAM,
dbInstructions != null ? dbInstructions : ""));
}
/**
* returns a survey (core info only). If you need all data, use
* loadFullSurvey.
*/
public SurveyDto findSurvey(Long id) {
SurveyDto dto = null;
if (id != null) {
Survey s = surveyDao.getById(id);
if (s != null) {
dto = new SurveyDto();
DtoMarshaller.copyToDto(s, dto);
dto.setQuestionGroupList(null);
}
}
return dto;
}
}
|
package com.strobel.expressions;
import com.strobel.compilerservices.CallerResolver;
import com.strobel.compilerservices.DebugInfoGenerator;
import com.strobel.core.StringUtilities;
import com.strobel.core.VerifyArgument;
import com.strobel.reflection.MethodInfo;
import com.strobel.reflection.Type;
import com.strobel.reflection.emit.MethodBuilder;
import com.strobel.reflection.emit.TypeBuilder;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Modifier;
/**
* @author Mike Strobel
*/
public final class LambdaExpression<T> extends Expression {
private final String _name;
private final Expression _body;
private final ParameterExpressionList _parameters;
private final Type<T> _interfaceType;
private final boolean _tailCall;
private final Type _returnType;
private Class<?> _creationContext;
LambdaExpression(
final Type<T> interfaceType,
final String name,
final Expression body,
final boolean tailCall,
final ParameterExpressionList parameters) {
if (interfaceType != null) {
_interfaceType = interfaceType;
}
else {
_interfaceType = resolveDelegateType(body, parameters);
}
_name = name;
_body = body;
_tailCall = tailCall;
_parameters = parameters;
//noinspection ConstantConditions
_returnType = Expression.getInvokeMethod(_interfaceType, true).getReturnType();
_creationContext = CallerResolver.getCallerClass(2);
}
@SuppressWarnings("unchecked")
private static <T> Type<T> resolveDelegateType(final Expression body, final ParameterExpressionList parameters) {
return (Type<T>) CustomDelegateTypeCache.get(
body.getType(),
parameters.getParameterTypes()
);
}
@Override
public final Type<T> getType() {
return _interfaceType;
}
@Override
public ExpressionType getNodeType() {
return ExpressionType.Lambda;
}
public final String getName() {
return _name;
}
public final Expression getBody() {
return _body;
}
public final ParameterExpressionList getParameters() {
return _parameters;
}
public final Type getReturnType() {
return _returnType;
}
public final boolean isTailCall() {
return _tailCall;
}
public final LambdaExpression<T> update(final Expression body, final ParameterExpressionList parameters) {
if (body == _body && parameters == _parameters) {
return this;
}
final LambdaExpression<T> updatedLambda = Expression.lambda(
_interfaceType,
getName(),
body,
isTailCall(),
parameters
);
updatedLambda._creationContext = _creationContext;
return updatedLambda;
}
@Override
protected Expression accept(final ExpressionVisitor visitor) {
return visitor.visitLambda(this);
}
@SuppressWarnings("unchecked")
final LambdaExpression<T> accept(final StackSpiller spiller) {
return spiller.rewrite(this);
}
final Class<?> getCreationContext() {
return _creationContext;
}
public final T compile() {
return compileDelegate().getInstance();
}
public final Delegate<T> compileDelegate() {
return LambdaCompiler.compile(this, DebugInfoGenerator.empty());
}
public final MethodHandle compileHandle() {
return LambdaCompiler.compile(this, DebugInfoGenerator.empty()).getMethodHandle();
}
public final void compileToMethod(final MethodBuilder methodBuilder) {
LambdaCompiler.compile(this, methodBuilder, DebugInfoGenerator.empty());
}
public final MethodInfo compileToMethod(final TypeBuilder<?> typeBuilder) {
final String name = getName();
return compileToMethod(
typeBuilder,
StringUtilities.isNullOrWhitespace(name)
? LambdaCompiler.getUniqueMethodName()
: name,
Modifier.PUBLIC
);
}
public final MethodInfo compileToMethod(
final TypeBuilder<?> typeBuilder,
final String name) {
return compileToMethod(typeBuilder, name, Modifier.PUBLIC);
}
public final MethodInfo compileToMethod(
final TypeBuilder<?> typeBuilder,
final String name,
final int modifiers) {
VerifyArgument.notNull(typeBuilder, "typeBuilder");
VerifyArgument.notNullOrWhitespace(name, "name");
final MethodInfo invokeMethod = Expression.getInvokeMethod(this);
final MethodBuilder methodBuilder = typeBuilder.defineMethod(
name,
modifiers,
invokeMethod.getReturnType(),
invokeMethod.getParameters().getParameterTypes()
);
LambdaCompiler.compile(this, methodBuilder, DebugInfoGenerator.empty());
return methodBuilder;
}
}
|
package net.wayward_realms.waywardskills;
import net.wayward_realms.waywardlib.character.Character;
import net.wayward_realms.waywardlib.character.CharacterPlugin;
import net.wayward_realms.waywardlib.character.Equipment;
import net.wayward_realms.waywardlib.character.Pet;
import net.wayward_realms.waywardlib.classes.ClassesPlugin;
import net.wayward_realms.waywardlib.skills.*;
import net.wayward_realms.waywardlib.util.file.filter.YamlFileFilter;
import net.wayward_realms.waywardskills.skill.SkillManager;
import net.wayward_realms.waywardskills.specialisation.RootSpecialisation;
import net.wayward_realms.waywardskills.spell.SpellManager;
import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static net.wayward_realms.waywardlib.util.plugin.ListenerUtils.registerListeners;
public class WaywardSkills extends JavaPlugin implements SkillsPlugin {
private static final int SPECIALISATION_POINTS_PER_LEVEL = 5;
private SpellManager spellManager;
private SkillManager skillManager;
private Specialisation rootSpecialisation;
private Map<String, Specialisation> specialisations;
@Override
public void onEnable() {
spellManager = new SpellManager(this);
skillManager = new SkillManager(this);
rootSpecialisation = new RootSpecialisation();
specialisations = new HashMap<>();
addSpecialisation(rootSpecialisation);
registerListeners(
this,
new PlayerInteractListener(this),
new EntityDamageByEntityListener(this),
new EntityTargetListener(this),
new ProjectileHitListener(),
new InventoryClickListener(this),
new EntityDamageListener(this),
new PlayerDeathListener(),
new PlayerExpChangeListener()
);
getCommand("skill").setExecutor(new SkillCommand(this));
getCommand("spell").setExecutor(new SpellCommand(this));
getCommand("bindskill").setExecutor(new BindSkillCommand(this));
getCommand("bindspell").setExecutor(new BindSpellCommand(this));
getCommand("skillinfo").setExecutor(new SkillInfoCommand(this));
getCommand("spellinfo").setExecutor(new SpellInfoCommand(this));
getCommand("getscroll").setExecutor(new GetScrollCommand(this));
getCommand("specialisation").setExecutor(new SpecialisationCommand(this));
setupMageArmourChecker();
}
private void convertFromClasses() {
getLogger().warning("Conversion from old class levels has not yet taken place!");
getLogger().info("Starting conversion...");
long startTime = System.currentTimeMillis();
RegisteredServiceProvider<CharacterPlugin> characterPluginProvider = getServer().getServicesManager().getRegistration(CharacterPlugin.class);
RegisteredServiceProvider<ClassesPlugin> classesPluginProvider = getServer().getServicesManager().getRegistration(ClassesPlugin.class);
if (characterPluginProvider != null && classesPluginProvider != null) {
CharacterPlugin characterPlugin = characterPluginProvider.getProvider();
ClassesPlugin classesPlugin = classesPluginProvider.getProvider();
int i = 1;
while (characterPlugin.getCharacter(i) != null) {
Character character = characterPlugin.getCharacter(i);
int experience = 0;
for (net.wayward_realms.waywardlib.classes.Class clazz : classesPlugin.getClasses()) {
experience += classesPlugin.getTotalExperience(character, clazz);
}
setTotalExperience(character, experience);
getLogger().info("Converted [" + character.getId() + "] " + character.getName() + " to new experience.");
i++;
}
i
getConfig().set("conversion-completed", true);
saveConfig();
getLogger().info("Converted " + i + " characters in " + (System.currentTimeMillis() - startTime) + "ms");
} else {
getLogger().info("Characters and/or classes plugin not found. Waiting for next plugin load...");
}
}
@Override
public Spell getSpell(String name) {
return spellManager.getSpell(name);
}
@Override
public void addSpell(Spell spell) {
spellManager.addSpell(spell);
}
@Override
public void removeSpell(Spell spell) {
spellManager.removeSpell(spell);
}
@Override
public Collection<? extends Spell> getSpells() {
return spellManager.getSpells();
}
@Override
public Skill getSkill(String name) {
return skillManager.getSkill(name);
}
@Override
public void addSkill(Skill skill) {
skillManager.addSkill(skill);
}
@Override
public void removeSkill(Skill skill) {
skillManager.removeSkill(skill);
}
@Override
public Collection<? extends Skill> getSkills() {
return skillManager.getSkills();
}
@SuppressWarnings("resource")
@Override
public Skill loadSkill(File file) {
try {
JarFile jarFile;
jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
String mainClass = null;
while (entries.hasMoreElements()) {
JarEntry element = entries.nextElement();
if (element.getName().equalsIgnoreCase("skill.yml")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(jarFile.getInputStream(element)));
mainClass = reader.readLine();
if (mainClass != null) {
mainClass = mainClass.substring(6);
}
break;
}
}
if (mainClass != null) {
ClassLoader loader = URLClassLoader.newInstance(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader());
Class<?> clazz = Class.forName(mainClass, true, loader);
for (Class<?> subclazz : clazz.getClasses()) {
Class.forName(subclazz.getName(), true, loader);
}
Class<? extends Skill> skillClass = clazz.asSubclass(Skill.class);
Skill skill = skillClass.newInstance();
if (skill instanceof Spell) {
addSpell((Spell) skill);
} else {
addSkill(skill);
}
return skill;
} else {
getLogger().severe("Main class not found for skill: " + file.getName());
}
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exception) {
exception.printStackTrace();
}
return null;
}
@Override
public Skill loadSkill(Class<? extends Skill> clazz) {
try {
Skill skill = clazz.newInstance();
if (skill instanceof Spell) {
addSpell((Spell) skill);
} else {
addSkill(skill);
}
return skill;
} catch (InstantiationException | IllegalAccessException exception) {
exception.printStackTrace();
}
return null;
}
@Override
public String getPrefix() {
return "";
}
@Override
public void loadState() {
File skillDirectory = new File(getDataFolder(), "skills");
if (skillDirectory.exists()) {
for (File file : skillDirectory.listFiles(new YamlFileFilter())) {
loadSkill(file);
}
}
if (!getConfig().getBoolean("conversion-completed")) {
convertFromClasses();
}
}
@Override
public void saveState() {
}
public SkillManager getSkillManager() {
return skillManager;
}
public SpellManager getSpellManager() {
return spellManager;
}
public void setupMageArmourChecker() {
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
for (Player player : getServer().getOnlinePlayers()) {
ItemStack helmet = player.getInventory().getHelmet();
if (helmet != null) {
if (helmet.hasItemMeta()) {
if (helmet.getItemMeta().hasDisplayName()) {
if (helmet.getItemMeta().getDisplayName().equals("Mage armour helmet")) {
if (helmet.getItemMeta().hasLore()) {
try {
if (System.currentTimeMillis() - Long.parseLong(helmet.getItemMeta().getLore().get(0)) >= 45000L) {
player.getInventory().setHelmet(null);
}
} catch (NumberFormatException ignore) {
ItemMeta helmetMeta = helmet.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
helmetMeta.setLore(lore);
helmet.setItemMeta(helmetMeta);
}
} else {
ItemMeta helmetMeta = helmet.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
helmetMeta.setLore(lore);
helmet.setItemMeta(helmetMeta);
}
}
}
}
}
ItemStack chestplate = player.getInventory().getChestplate();
if (chestplate != null) {
if (chestplate.hasItemMeta()) {
if (chestplate.getItemMeta().hasDisplayName()) {
if (chestplate.getItemMeta().getDisplayName().equals("Mage armour chestplate")) {
if (chestplate.getItemMeta().hasLore()) {
try {
if (System.currentTimeMillis() - Long.parseLong(chestplate.getItemMeta().getLore().get(0)) >= 45000L) {
player.getInventory().setChestplate(null);
}
} catch (NumberFormatException ignore) {
ItemMeta chestplateMeta = chestplate.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
chestplateMeta.setLore(lore);
chestplate.setItemMeta(chestplateMeta);
}
} else {
ItemMeta chestplateMeta = chestplate.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
chestplateMeta.setLore(lore);
chestplate.setItemMeta(chestplateMeta);
}
}
}
}
}
ItemStack leggings = player.getInventory().getLeggings();
if (leggings != null) {
if (leggings.hasItemMeta()) {
if (leggings.getItemMeta().hasDisplayName()) {
if (leggings.getItemMeta().getDisplayName().equals("Mage armour leggings")) {
if (leggings.getItemMeta().hasLore()) {
try {
if (System.currentTimeMillis() - Long.parseLong(leggings.getItemMeta().getLore().get(0)) >= 45000L) {
player.getInventory().setLeggings(null);
}
} catch (NumberFormatException ignore) {
ItemMeta leggingsMeta = leggings.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
leggingsMeta.setLore(lore);
leggings.setItemMeta(leggingsMeta);
}
} else {
ItemMeta leggingsMeta = leggings.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
leggingsMeta.setLore(lore);
leggings.setItemMeta(leggingsMeta);
}
}
}
}
}
ItemStack boots = player.getInventory().getBoots();
if (boots != null) {
if (boots.hasItemMeta()) {
if (boots.getItemMeta().hasDisplayName()) {
if (boots.getItemMeta().getDisplayName().equals("Mage armour boots")) {
if (boots.getItemMeta().hasLore()) {
try {
if (System.currentTimeMillis() - Long.parseLong(boots.getItemMeta().getLore().get(0)) >= 45000L) {
player.getInventory().setBoots(null);
}
} catch (NumberFormatException ignore) {
ItemMeta bootsMeta = boots.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
bootsMeta.setLore(lore);
boots.setItemMeta(bootsMeta);
}
} else {
ItemMeta bootsMeta = boots.getItemMeta();
List<String> lore = new ArrayList<>();
lore.add("" + System.currentTimeMillis());
bootsMeta.setLore(lore);
boots.setItemMeta(bootsMeta);
}
}
}
}
}
}
}
}, 100L, 100L);
}
@Override
public Specialisation getRootSpecialisation() {
return rootSpecialisation;
}
@Override
public int getSpecialisationValue(Character character, Specialisation specialisation) {
File specialisationDirectory = new File(getDataFolder(), "character-specialisations");
File characterFile = new File(specialisationDirectory, character.getId() + ".yml");
YamlConfiguration characterConfig = YamlConfiguration.loadConfiguration(characterFile);
int value = characterConfig.getInt("specialisations." + specialisation.getName());
if (!specialisation.getParentSpecialisations().isEmpty()) {
for (Specialisation parent : specialisation.getParentSpecialisations()) {
value += getSpecialisationValue(character, parent) / 10;
}
}
return value;
}
@Override
public void setSpecialisationValue(Character character, Specialisation specialisation, int value) {
File specialisationDirectory = new File(getDataFolder(), "character-specialisations");
File characterFile = new File(specialisationDirectory, character.getId() + ".yml");
YamlConfiguration characterConfig = YamlConfiguration.loadConfiguration(characterFile);
int originalValue = characterConfig.getInt("specialisations." + specialisation.getName());
characterConfig.set("assigned-specialisation-points", characterConfig.getInt("assigned-specialisation-points") + (value - originalValue));
characterConfig.set("specialisations." + specialisation.getName(), value);
try {
characterConfig.save(characterFile);
} catch (IOException exception) {
exception.printStackTrace();
}
}
@Override
public int getSpecialisationValue(Pet pet, Specialisation specialisation) {
File specialisationDirectory = new File(getDataFolder(), "pet-specialisations");
File petFile = new File(specialisationDirectory, pet.getId() + ".yml");
YamlConfiguration petConfig = YamlConfiguration.loadConfiguration(petFile);
int value = petConfig.getInt("specialisations." + specialisation.getName());
if (!specialisation.getParentSpecialisations().isEmpty()) {
for (Specialisation parent : specialisation.getParentSpecialisations()) {
value += getSpecialisationValue(pet, parent) / 10;
}
}
return value;
}
@Override
public void setSpecialisationValue(Pet pet, Specialisation specialisation, int value) {
File specialisationDirectory = new File(getDataFolder(), "pet-specialisations");
File petFile = new File(specialisationDirectory, pet.getId() + ".yml");
YamlConfiguration petConfig = YamlConfiguration.loadConfiguration(petFile);
petConfig.set("specialisations." + specialisation.getName(), value);
try {
petConfig.save(petFile);
} catch (IOException exception) {
exception.printStackTrace();
}
}
@Override
public Specialisation getSpecialisation(String name) {
return specialisations.get(name.toLowerCase());
}
@Override
public Collection<Specialisation> getSpecialisations() {
return specialisations.values();
}
@Override
public int getAssignedSpecialisationPoints(Character character) {
File specialisationDirectory = new File(getDataFolder(), "character-specialisations");
File characterFile = new File(specialisationDirectory, character.getId() + ".yml");
YamlConfiguration characterConfig = YamlConfiguration.loadConfiguration(characterFile);
return characterConfig.getInt("assigned-specialisation-points");
}
@Override
public int getUnassignedSpecialisationPoints(Character character) {
return (getLevel(character) * SPECIALISATION_POINTS_PER_LEVEL) - getAssignedSpecialisationPoints(character);
}
private void addSpecialisation(Specialisation specialisation) {
if (!specialisations.containsKey(specialisation.getName())) {
specialisations.put(specialisation.getName().toLowerCase(), specialisation);
} else {
for (Specialisation parent : specialisation.getParentSpecialisations()) {
specialisations.get(specialisation.getName()).addParentSpecialisation(parent);
}
}
for (Specialisation child : specialisation.getChildSpecialisations()) {
addSpecialisation(child);
}
}
@Override
public int getTotalExperience(Character character) {
File specialisationDirectory = new File(getDataFolder(), "character-specialisations");
File characterFile = new File(specialisationDirectory, character.getId() + ".yml");
YamlConfiguration characterConfig = YamlConfiguration.loadConfiguration(characterFile);
return characterConfig.getInt("experience");
}
@Override
public void setTotalExperience(Character character, int experience) {
int i = 0;
while (experience >= getTotalExperienceForLevel(getLevel(character) + i + 1) && getLevel(character) + i < getMaxLevel()) {
i += 1;
}
if (i >= 1) {
if (character.getPlayer().isOnline()) {
Player player = character.getPlayer().getPlayer();
player.sendMessage(getPrefix() + ChatColor.YELLOW + "Level up!");
player.sendMessage(ChatColor.YELLOW + "+" + SPECIALISATION_POINTS_PER_LEVEL + " Specialisation Points" + ChatColor.GRAY + "(Total: " + (getUnassignedSpecialisationPoints(character) + 5) + ")");
player.sendMessage(ChatColor.GRAY + "(Use /specialisation to assign them)");
for (int x = player.getLocation().getBlockX() - 4; x < player.getLocation().getBlockX() + 4; x++) {
for (int z = player.getLocation().getBlockZ() - 4; z < player.getLocation().getBlockZ() + 4; z++) {
Location location = player.getWorld().getBlockAt(x, player.getLocation().getBlockY(), z).getLocation();
if (player.getLocation().distanceSquared(location) > 9 && player.getLocation().distanceSquared(location) < 25) {
Firework firework = (Firework) player.getWorld().spawnEntity(location, EntityType.FIREWORK);
FireworkMeta meta = firework.getFireworkMeta();
meta.setPower(0);
FireworkEffect effect = FireworkEffect.builder()
.withColor(Color.YELLOW, Color.RED)
.with(FireworkEffect.Type.BURST)
.trail(true)
.build();
meta.addEffect(effect);
firework.setFireworkMeta(meta);
}
}
}
}
}
File specialisationDirectory = new File(getDataFolder(), "character-specialisations");
File characterFile = new File(specialisationDirectory, character.getId() + ".yml");
YamlConfiguration characterConfig = YamlConfiguration.loadConfiguration(characterFile);
characterConfig.set("experience", Math.min(experience, getTotalExperienceForLevel(getMaxLevel())));
try {
characterConfig.save(characterFile);
} catch (IOException exception) {
exception.printStackTrace();
}
if (character.getPlayer().isOnline()) {
updateExp(character.getPlayer().getPlayer());
updateHealth(character.getPlayer().getPlayer());
}
}
@Override
public int getExperience(Character character) {
return getTotalExperience(character) - getTotalExperienceForLevel(getLevel(character));
}
@Override
public void setExperience(Character character, int experience) {
setTotalExperience(character, getTotalExperienceForLevel(getLevel(character)) + experience);
}
@Override
public int getLevel(Character character) {
int level = 1;
while (getTotalExperienceForLevel(level + 1) <= getTotalExperience(character)) {
level += 1;
}
return level;
}
@Override
public void setLevel(Character character, int level) {
setTotalExperience(character, getTotalExperienceForLevel(level));
}
@Override
public void giveExperience(Character character, int amount) {
setTotalExperience(character, getTotalExperience(character) + amount);
}
@Override
public int getExperienceForLevel(int level) {
return 250 * (level - 1);
}
@Override
public int getTotalExperienceForLevel(int level) {
return level * (level - 1) * 125;
}
@Override
public int getMaxLevel() {
return 50;
}
@Override
public double getMaxHealth(Character character) {
return getLevel(character) * 2D;
}
@Override
public int getMaxMana(Character character) {
return getLevel(character) * 10;
}
@Override
public int getStatValue(Character character, Stat stat) {
switch (stat) {
case MELEE_ATTACK:
return getSpecialisationValue(character, getSpecialisation("Melee Offence"));
case MELEE_DEFENCE:
return getSpecialisationValue(character, getSpecialisation("Melee Defence"));
case RANGED_ATTACK:
return getSpecialisationValue(character, getSpecialisation("Ranged Offence"));
case RANGED_DEFENCE:
return getSpecialisationValue(character, getSpecialisation("Ranged Defence"));
case MAGIC_ATTACK:
return getSpecialisationValue(character, getSpecialisation("Magic Offence"));
case MAGIC_DEFENCE:
return getSpecialisationValue(character, getSpecialisation("Magic Defence"));
case SPEED:
return getSpecialisationValue(character, getSpecialisation("Nimble"));
default:
return getSpecialisationValue(character, getRootSpecialisation());
}
}
public void updateExp(Player player) {
RegisteredServiceProvider<CharacterPlugin> characterPluginProvider = getServer().getServicesManager().getRegistration(CharacterPlugin.class);
if (characterPluginProvider != null) {
CharacterPlugin characterPlugin = characterPluginProvider.getProvider();
Character character = characterPlugin.getActiveCharacter(player);
player.setExp((float) getExperience(character) / (float) getExperienceForLevel(getLevel(character) + 1));
player.setLevel(getLevel(character));
}
}
public void updateHealth(Player player) {
RegisteredServiceProvider<CharacterPlugin> characterPluginProvider = getServer().getServicesManager().getRegistration(CharacterPlugin.class);
if (characterPluginProvider != null) {
CharacterPlugin characterPlugin = characterPluginProvider.getProvider();
player.setMaxHealth(characterPlugin.getActiveCharacter(player).getMaxHealth());
}
}
@Override
public String getAttackRoll(Character character, Specialisation attack, boolean onHand) {
Equipment equipment = character.getEquipment();
ItemStack weapon = onHand ? equipment.getOnHandItem() : equipment.getOffHandItem();
if (attack.meetsAttackRequirement(weapon)) {
return "1d100+" + Math.round((double) getSpecialisationValue(character, attack) * ((equipment.getOffHandItem() == null || equipment.getOffHandItem().getType() == Material.AIR) ? 2D : (onHand ? 1D : 0.75D)));
} else {
return "0d100";
}
}
@Override
public String getDefenceRoll(Character character, Specialisation defence, boolean onHand) {
Equipment equipment = character.getEquipment();
ItemStack weapon = onHand ? equipment.getOnHandItem() : equipment.getOffHandItem();
if (defence.meetsDefenceRequirement(weapon)) {
return "1d100+" + Math.round((double) getSpecialisationValue(character, defence) * ((equipment.getOffHandItem() == null || equipment.getOffHandItem().getType() == Material.AIR) ? 2D : (onHand ? 1D : 0.75D)));
} else {
return "0d100";
}
}
public Inventory getSpecialisationInventory(Specialisation root, Character character) {
Inventory inventory = getServer().createInventory(null, 45, "Specialise");
ItemMeta meta;
List<String> lore;
int i = 0;
for (Specialisation parent : root.getParentSpecialisations()) {
ItemStack parentItem = new ItemStack(Material.WOOL);
meta = parentItem.getItemMeta();
meta.setDisplayName(parent.getName());
lore = new ArrayList<>();
lore.add("Points: " + getSpecialisationValue(character, parent));
meta.setLore(lore);
parentItem.setItemMeta(meta);
inventory.setItem(i, parentItem);
i++;
}
ItemStack rootItem = new ItemStack(Material.WOOL, 1, (short) 5);
meta = rootItem.getItemMeta();
meta.setDisplayName(root.getName());
lore = new ArrayList<>();
lore.add("Points: " + getSpecialisationValue(character, root));
lore.add("Click to assign one specialisation point");
lore.add("(You have " + getUnassignedSpecialisationPoints(character) + " unassigned specialisation points remaining)");
meta.setLore(lore);
rootItem.setItemMeta(meta);
inventory.setItem(22, rootItem);
i = 36;
for (Specialisation child : root.getChildSpecialisations()) {
ItemStack childItem = new ItemStack(Material.WOOL);
meta = childItem.getItemMeta();
meta.setDisplayName(child.getName());
lore = new ArrayList<>();
lore.add("Points: " + getSpecialisationValue(character, child));
meta.setLore(lore);
childItem.setItemMeta(meta);
inventory.setItem(i, childItem);
i++;
}
return inventory;
}
}
|
package com.javax0.jdsl;
import static com.javax0.jdsl.analyzers.terminals.NumberAnalyzer.number;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.javax0.jdsl.analyzers.AnalysisResult;
import com.javax0.jdsl.analyzers.Analyzer;
import com.javax0.jdsl.analyzers.Define;
import com.javax0.jdsl.analyzers.StringSourceCode;
import com.javax0.jdsl.executors.Context;
import com.javax0.jdsl.executors.Executor;
import com.javax0.jdsl.executors.Factory;
import com.javax0.jdsl.executors.ListExecutor;
import com.javax0.jdsl.log.NullReporter;
import com.javax0.jdsl.log.ReporterFactory;
public class GrammarTest {
private static final Logger LOG = LoggerFactory
.getLogger(GrammarTest.class);
private Analyzer defineMyGrammar() {
final Analyzer myGrammar = new GrammarDefinition() {
@Override
protected final Analyzer define() {
ReporterFactory.setReporter(new NullReporter());
skipSpaces();
final Define expression = later();
final Analyzer ifStatement = list(new IfExecutorFactory(),
kw("if", "("), expression, kw(")", "{"), expression,
kw("}"), optional(kw("else", "{"), expression, kw("}")));
expression.define(or(ifStatement, number(),
list(kw("{"), many(expression), kw("}"))));
return many(expression);
}
};
return myGrammar;
}
@Test
public void given_SimpleGrammarAndMatchingSource_when_Analyzing_then_Success() {
final Analyzer myGrammar = defineMyGrammar();
AnalysisResult result = myGrammar.analyze(new StringSourceCode(
"if(1){55}else{33}"));
Assert.assertTrue(result.wasSuccessful());
LOG.debug(result.getExecutor().toString());
Long res = (Long) result.getExecutor().execute(null);
Assert.assertEquals((Long) 55L, res);
result = myGrammar.analyze(new StringSourceCode("if(0){55}else{33}"));
LOG.debug(result.getExecutor().toString());
res = (Long) result.getExecutor().execute(null);
Assert.assertEquals((Long) 33L, res);
result = myGrammar.analyze(new StringSourceCode("if(1){55}"));
LOG.debug(result.getExecutor().toString());
res = (Long) result.getExecutor().execute(null);
Assert.assertEquals((Long) 55L, res);
result = myGrammar.analyze(new StringSourceCode(
"if(1){if(0){1}else{55}}"));
LOG.debug(result.getExecutor().toString());
res = (Long) result.getExecutor().execute(null);
Assert.assertEquals((Long) 55L, res);
}
@Test(expected = RuntimeException.class)
public void undefinedAnalyzerThrowsIllegalArgumentException() {
final Analyzer myGrammar = new GrammarDefinition() {
@Override
protected final Analyzer define() {
final Define expression = later();
return expression;
}
};
try{
myGrammar.analyze(new StringSourceCode("anything"));
}catch(Exception e) {
System.out.println("Caught: " + e);
throw e;
}
}
@Test(expected = IllegalArgumentException.class)
public void badGrammarDefinitionThrowsIllegalArgumentException() {
final Analyzer myGrammar = new GrammarDefinition() {
@Override
protected final Analyzer define() {
@SuppressWarnings("unused")
final Define notUsed = later();
return many(kw("k"));
}
};
myGrammar.analyze(new StringSourceCode("anything"));
}
private static class IfExecutorFactory implements Factory<ListExecutor> {
@Override
public ListExecutor get() {
return new IfExecutor();
}
}
private static class IfExecutor implements ListExecutor {
@Override
public Object execute(Context context) {
final Object condition = executorList.get(0).execute(context);
final Long one = (Long) condition;
if (one != 0) {
if (executorList.size() > 1) {
return executorList.get(1).execute(context);
} else {
return null;
}
} else {
if (executorList.size() > 2) {
return executorList.get(2).execute(context);
} else {
return null;
}
}
}
private List<Executor> executorList;
@Override
public void setList(final List<Executor> executorList) {
this.executorList = executorList;
}
@Override
public String toString() {
String res = "if(" + executorList.get(0).toString() + ")";
if (executorList.size() > 1) {
res += "{" + executorList.get(1).toString() + "}";
}
if (executorList.size() > 2) {
res += "else{" + executorList.get(2).toString() + "}";
}
return res;
}
}
}
|
package com.mergesort;
import junit.framework.TestCase;
public class MergeSortTest extends TestCase {
public void testMain() throws Exception {
}
}
|
package com.rox.emu.env;
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.When;
import com.pholser.junit.quickcheck.generator.InRange;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import com.rox.emu.InvalidDataTypeException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import spock.lang.Specification;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.*;
@RunWith(JUnitQuickcheck.class)
public class RoxByteTest extends Specification{
@Test
public void testEmptyByteCreation(){
final RoxByte myByte = new RoxByte();
assertNotNull(myByte);
assertEquals(0, myByte.getAsInt());
}
@Test
public void testByteFromInteger() throws InvalidDataTypeException {
final RoxByte myByte = RoxByte.signedFrom(1);
assertNotNull(myByte);
assertEquals(RoxByte.ByteFormat.SIGNED_TWOS_COMPLIMENT, myByte.getFormat());
}
@Property(trials = 30)
public void testGetAsIntWithInvalid(@When(satisfies = "#_ < -128 || #_ > 127") int byteValue){
try {
RoxByte.signedFrom(byteValue);
fail(byteValue + " was expected to be too low to convert to unsigned byte");
}catch(InvalidDataTypeException e) {
assertNotNull(e);
}
}
@Property(trials = 10)
public void testGetAsIntWithTooHigh(@InRange(min = "128", max = "300") int byteValue){
try {
RoxByte.signedFrom(byteValue);
fail(byteValue + " was expected to be too high to convert to unsigned byte");
}catch(InvalidDataTypeException e) {
assertNotNull(e);
}
}
@Test
public void testSetBit(){
final RoxByte myByte = new RoxByte();
assertEquals(1, myByte.withBit(0).getAsInt());
assertEquals(2, myByte.withBit(1).getAsInt());
assertEquals(4, myByte.withBit(2).getAsInt());
assertEquals(8, myByte.withBit(3).getAsInt());
assertEquals(16, myByte.withBit(4).getAsInt());
assertEquals(32, myByte.withBit(5).getAsInt());
assertEquals(64, myByte.withBit(6).getAsInt());
assertEquals(-128, myByte.withBit(7).getAsInt());
}
@Test
public void testSetBitInvalidChoice(){
final RoxByte myByte = new RoxByte();
try {
myByte.withBit(8);
fail("There is no bit 8, this should throw an error");
}catch(AssertionError e){
assertNotNull(e);
}
}
@Test
public void testIsBitSet(){
final RoxByte loadedByte = RoxByte.signedFrom(-1);
final RoxByte emptyByte = new RoxByte();
for (int i=0; i<8; i++){
assertTrue(loadedByte.isBitSet(i));
assertFalse(emptyByte.isBitSet(i));
}
}
@Test
public void testIsBitSetInvalidChoice(){
final RoxByte myByte = new RoxByte();
try {
myByte.isBitSet(8);
fail("There is no bit 8, this should throw an error");
}catch(AssertionError e){
assertNotNull(e);
}
}
}
|
package de.bmoth.issues;
import de.bmoth.modelchecker.ModelChecker;
import de.bmoth.modelchecker.ModelCheckingResult;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Issue59Test {
@Test
public void testIssue59() throws Exception {
String machine = "MACHINE SimpleMachine\n";
machine += "VARIABLES x\n";
machine += "INVARIANT x : INTEGER &\n";
machine += "\tx**2 = x*x \n";
machine += "INITIALISATION x := -3\n";
machine += "OPERATIONS\n";
machine += "\tIncX = SELECT x < 50 THEN x := x+1 END\n";
machine += "END";
ModelCheckingResult result = ModelChecker.doModelCheck(machine);
assertEquals(true, result.isCorrect());
}
@Test
public void testIssue59WithAdditionalInvariant() throws Exception {
String machine = "MACHINE SimpleMachine\n";
machine += "VARIABLES x\n";
machine += "INVARIANT x : INTEGER &\n";
machine += "\tx**2 = x*x &\n";
machine += "\t#x.(x:INTEGER & {x} \\/ {1,2} = {1,2})\n";
machine += "INITIALISATION x := -3\n";
machine += "OPERATIONS\n";
machine += "\tIncX = SELECT x < 50 THEN x := x+1 END\n";
machine += "END";
ModelCheckingResult result = ModelChecker.doModelCheck(machine);
assertEquals(false, result.isCorrect());
assertEquals(true, result.getMessage().startsWith("check-sat"));
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import guitests.guihandles.AlertDialogHandle;
import seedu.task.commons.events.storage.DataSavingExceptionEvent;
//import static junit.framework.TestCase.assertTrue;
//import java.io.IOException;
//import org.junit.Test;
//import guitests.guihandles.AlertDialogHandle;
//import seedu.task.commons.events.storage.DataSavingExceptionEvent;
//@@author A0163935X
public class ErrorDialogGuiTest extends AddressBookGuiTest {
@Test
public void showErrorDialogs() throws InterruptedException {
//Test DataSavingExceptionEvent dialog
raise(new DataSavingExceptionEvent(new IOException("Stub")));
AlertDialogHandle alertDialog = mainGui.getAlertDialog("File Op Error");
assertTrue(alertDialog.isMatching("Could not save data", "Could not save data to file" + ":\n"
+ "java.io.IOException: Stub"));
}
}
|
package integration;
import com.codeborne.selenide.junit.ScreenShooter;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.*;
import static org.openqa.selenium.net.PortProber.findFreePort;
public abstract class IntegrationTest {
@Rule
public ScreenShooter img = ScreenShooter.failedTests() ;
private static int port;
protected static LocalHttpServer server;
@BeforeClass
public static void runLocalHttpServer() throws Exception {
if (server == null) {
synchronized (IntegrationTest.class) {
port = findFreePort();
server = new LocalHttpServer(port).start();
}
}
}
@AfterClass
public static void restartUnstableWebdriver() {
if (isIE() || isPhantomjs()) {
closeWebDriver();
}
}
protected void openFile(String fileName) {
open("http://localhost:" + port + "/" + fileName);
}
protected <T> T openFile(String fileName, Class<T> pageObjectClass) {
return open("http://localhost:" + port + "/" + fileName, pageObjectClass);
}
}
|
package interpreter;
import com.github.stony.interpreter.Interpreter;
import org.junit.Assert;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Barebones framework to test story files. Testing classes should extend this.
*
* The idea is to test the output
*/
class InterpreterTest {
/**
* InterpreterTest should not be instantiated directly, only extended.
*/
protected InterpreterTest() {
}
/**
* Asserts if the output of the finished story is equal to the output parameter.
*
* @param filePath resource file path.
* @param output expected output.
*
* @throws FileNotFoundException when the file doesn't exist.
* @throws IOException when a read error occured.
* @throws URISyntaxException when the file path doesn't convert to a valid URI.
*/
protected void assertOutputEquals(String filePath, String output) throws IOException, URISyntaxException {
final InputStream inputStream = new ByteArrayInputStream(new byte[0]);
final OutputStream outputStream = new ByteArrayOutputStream();
final Interpreter interpreter = new Interpreter(readFileData(filePath), inputStream, outputStream);
assertOutputEquals(interpreter, output);
}
protected void assertOutputEquals(Interpreter interpreter, String output) throws IOException {
final OutputStream outputStream = interpreter.getOutputStream();
if (!(outputStream instanceof ByteArrayOutputStream)) {
throw new IllegalArgumentException("Interpreter output stream must be a ByteArrayOutputStream.");
}
while (!interpreter.isFinished()) {
interpreter.executeInstruction();
}
Assert.assertEquals(output, ((ByteArrayOutputStream) outputStream).toString("UTF-8"));
}
/**
* Returns the content of a resource file as a byte array.
*
* @param filePath path to the resource file.
* @return content of the resource file.
*
* @throws FileNotFoundException when the file doesn't exist.
* @throws IOException when a read error occured.
* @throws URISyntaxException when the file path doesn't convert to a valid URI -- should not happen.
*/
@SuppressWarnings("TryFinallyCanBeTryWithResources")
protected byte[] readFileData(String filePath) throws IOException, URISyntaxException {
final URL url = getClass().getResource(filePath);
if (url == null) {
throw new FileNotFoundException("Invalid file path: " + filePath);
}
final File file = new File(url.toURI());
final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
try {
byte[] bytes = new byte[(int) randomAccessFile.length()];
randomAccessFile.readFully(bytes);
return bytes;
} finally {
randomAccessFile.close();
}
}
}
|
package org.mariadb.jdbc;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import java.sql.*;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CancelTest extends BaseTest {
@Before
public void cancelSupported() throws SQLException {
requireMinimumVersion(5, 0);
Assume.assumeTrue(System.getenv("MAXSCALE_VERSION") == null);
}
@Test
public void cancelTest() {
Assume.assumeFalse(sharedIsAurora());
try (Connection tmpConnection = openNewConnection(connUri, new Properties())) {
Statement stmt = tmpConnection.createStatement();
ExecutorService exec = Executors.newFixedThreadPool(1);
//check blacklist shared
exec.execute(new CancelThread(stmt));
stmt.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2");
//wait for thread endings
exec.shutdown();
Assert.fail();
} catch (SQLException e) {
//normal exception
}
}
@Test(timeout = 20000, expected = SQLTimeoutException.class)
public void timeoutSleep() throws Exception {
Assume.assumeFalse(sharedIsAurora());
try (Connection tmpConnection = openNewConnection(connUri, new Properties())) {
Statement stmt = tmpConnection.createStatement();
stmt.setQueryTimeout(1); //query take more than 20 seconds (local DB)
stmt.execute("select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2");
}
}
@Test(timeout = 20000, expected = SQLTimeoutException.class)
public void timeoutPrepareSleep() throws Exception {
Assume.assumeFalse(sharedIsAurora());
try (Connection tmpConnection = openNewConnection(connUri, new Properties())) {
try (PreparedStatement stmt = tmpConnection.prepareStatement(
"select * from information_schema.columns as c1, information_schema.tables, information_schema.tables as t2")) {
stmt.setQueryTimeout(1); //query take more than 20 seconds (local DB)
stmt.execute();
}
}
}
@Test(timeout = 5000, expected = BatchUpdateException.class)
public void timeoutBatch() throws Exception {
Assume.assumeFalse(sharedIsAurora());
Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite());
createTable("timeoutBatch", "aa text");
Statement stmt = sharedConnection.createStatement();
char[] arr = new char[1000];
Arrays.fill(arr, 'a');
String str = String.valueOf(arr);
for (int i = 0; i < 20000; i++) {
stmt.addBatch("INSERT INTO timeoutBatch VALUES ('" + str + "')");
}
stmt.setQueryTimeout(1);
stmt.executeBatch();
}
@Test(timeout = 5000, expected = BatchUpdateException.class)
public void timeoutPrepareBatch() throws Exception {
Assume.assumeFalse(sharedIsAurora());
Assume.assumeTrue(!sharedOptions().allowMultiQueries && !sharedIsRewrite());
Assume.assumeTrue(!(sharedOptions().useBulkStmts && isMariadbServer() && minVersion(10,2)));
createTable("timeoutBatch", "aa text");
try (Connection tmpConnection = openNewConnection(connUri, new Properties())) {
char[] arr = new char[1000];
Arrays.fill(arr, 'a');
String str = String.valueOf(arr);
try (PreparedStatement stmt = tmpConnection.prepareStatement("INSERT INTO timeoutBatch VALUES (?)")) {
stmt.setQueryTimeout(1);
for (int i = 0; i < 20000; i++) {
stmt.setString(1, str);
stmt.addBatch();
}
stmt.executeBatch();
}
}
}
@Test
public void noTimeoutSleep() throws Exception {
Statement stmt = sharedConnection.createStatement();
stmt.setQueryTimeout(1);
stmt.execute("select sleep(0.5)");
}
@Test
public void cancelIdleStatement() throws Exception {
Statement stmt = sharedConnection.createStatement();
stmt.cancel();
ResultSet rs = stmt.executeQuery("select 1");
assertTrue(rs.next());
assertEquals(rs.getInt(1), 1);
}
private static class CancelThread implements Runnable {
private final Statement stmt;
public CancelThread(Statement stmt) {
this.stmt = stmt;
}
@Override
public void run() {
try {
Thread.sleep(100);
stmt.cancel();
} catch (SQLException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package org.neuron_di.it;
import org.junit.Test;
import org.neuron_di.api.Brain;
import org.neuron_di.api.CachingStrategy;
import org.neuron_di.api.Neuron;
import org.neuron_di.api.Synapse;
import javax.inject.Singleton;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class NeuronTest {
private final Brain brain = Brain.build();
@Test
public void testInjection() { neuron(Greeter.class).greet(); }
@Test
public void testScope() {
final Greeter g1 = neuron(Greeter.class);
final Greeter g2 = neuron(Greeter.class);
assertThat(g2, is(not(sameInstance(g1))));
}
@Test
public void testSingletonScope() {
final Greeter g1 = neuron(SingletonGreeter.class);
final Greeter g2 = neuron(SingletonGreeter.class);
assertThat(g2, is(sameInstance(g1)));
}
private <T> T neuron(Class<T> clazz) { return brain.neuron(clazz); }
@Singleton
// This annotation is redundant, but documents the default behavior:
@Neuron
static abstract class SingletonGreeter extends Greeter {
}
@Neuron
static abstract class Greeter {
// This annotation is redundant, but documents the default behavior:
@Synapse(caching = CachingStrategy.THREAD_SAFE)
abstract Greeting greeting();
void greet() { System.out.println(greeting().message()); }
}
@SuppressWarnings("WeakerAccess")
static class Greeting {
String message() { return "Hello world!"; }
}
}
|
package seedu.todo.guitests;
import static org.junit.Assert.*;
import static seedu.todo.testutil.AssertUtil.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.testfx.api.FxToolkit;
import javafx.application.Platform;
import javafx.stage.Stage;
import seedu.todo.TestApp;
import seedu.todo.commons.core.EventsCenter;
import seedu.todo.commons.events.BaseEvent;
import seedu.todo.commons.util.DateUtil;
import seedu.todo.guitests.guihandles.ConsoleHandle;
import seedu.todo.guitests.guihandles.MainGuiHandle;
import seedu.todo.guitests.guihandles.SideBarHandle;
import seedu.todo.guitests.guihandles.TaskListDateItemHandle;
import seedu.todo.guitests.guihandles.TaskListEventItemHandle;
import seedu.todo.guitests.guihandles.TaskListHandle;
import seedu.todo.guitests.guihandles.TaskListTaskItemHandle;
import seedu.todo.models.Event;
import seedu.todo.models.Task;
import seedu.todo.models.TodoListDB;
/**
* @@author A0139812A
*/
public abstract class GuiTest {
// The TestName Rule makes the current test name available inside test methods.
@Rule
public TestName name = new TestName();
TestApp testApp;
// Handles to GUI elements present at the start up are created in advance for easy access from child classes.
protected MainGuiHandle mainGui;
protected ConsoleHandle console;
protected TaskListHandle taskList;
protected SideBarHandle sidebar;
private Stage stage;
@BeforeClass
public static void setupSpec() {
try {
FxToolkit.registerPrimaryStage();
FxToolkit.hideStage();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
@Before
public void setup() throws Exception {
FxToolkit.setupStage((stage) -> {
mainGui = new MainGuiHandle(new GuiRobot(), stage);
console = mainGui.getConsole();
taskList = mainGui.getTaskList();
sidebar = mainGui.getSideBar();
// TODO: create handles for other components
this.stage = stage;
});
EventsCenter.clearSubscribers();
testApp = (TestApp) FxToolkit.setupApplication(() -> new TestApp(this::getInitialData, getDataFileLocation()));
FxToolkit.showStage();
while (!stage.isShowing());
mainGui.focusOnMainApp();
}
/**
* Override this in child classes to set the initial local data.
* Return null to use the data in the file specified in {@link #getDataFileLocation()}
*/
protected TodoListDB getInitialData() {
TodoListDB db = TodoListDB.getInstance();
return db;
}
/**
* Override this in child classes to set the data file location.
*/
protected String getDataFileLocation() {
return TestApp.SAVE_LOCATION_FOR_TESTING;
}
@After
public void cleanup() throws TimeoutException {
FxToolkit.cleanupStages();
}
public void raise(BaseEvent e) {
//JUnit doesn't run its test cases on the UI thread. Platform.runLater is used to post event on the UI thread.
Platform.runLater(() -> EventsCenter.getInstance().post(e));
}
/**
* Utility method for testing if task has been successfully added to the GUI.
* This runs a command and checks if TaskList contains TaskListTaskItem that matches
* the task that was just added.
*
* Assumption: No two events can have the same name in this test.
*/
protected void assertTaskVisibleAfterCmd(String command, Task taskToAdd) {
// Run the command in the console.
console.runCommand(command);
// Get the task date.
LocalDateTime taskDateTime = taskToAdd.getCalendarDateTime();
if (taskDateTime == null) {
taskDateTime = DateUtil.NO_DATETIME_VALUE;
}
LocalDate taskDate = taskDateTime.toLocalDate();
// Check TaskList if it contains a TaskListDateItem with the date.
TaskListDateItemHandle dateItem = taskList.getTaskListDateItem(taskDate);
assertSameDate(taskDate, dateItem);
// Check TaskListDateItem if it contains the TaskListTaskItem with the same data.
TaskListTaskItemHandle taskItem = dateItem.getTaskListTaskItem(taskToAdd.getName());
assertSameTaskName(taskToAdd, taskItem);
}
/**
* Utility method for testing if event has been successfully added to the GUI.
* This runs a command and checks if TaskList contains TaskListEventItem that matches
* the task that was just added.
*
* Assumption: No two events can have the same name in this test.
*
* TODO: Check event dates if they match.
*/
protected void assertEventVisibleAfterCmd(String command, Event eventToAdd) {
// Run the command in the console.
console.runCommand(command);
// Get the event date.
LocalDateTime eventStartDateTime = eventToAdd.getStartDate();
if (eventStartDateTime == null) {
eventStartDateTime = DateUtil.NO_DATETIME_VALUE;
}
LocalDate eventStartDate = eventStartDateTime.toLocalDate();
// Check TaskList if it contains a TaskListDateItem with the date of the event start date.
TaskListDateItemHandle dateItem = taskList.getTaskListDateItem(eventStartDate);
assertSameDate(eventStartDate, dateItem);
// Check TaskListDateItem if it contains the TaskListEventItem with the same data.
TaskListEventItemHandle eventItem = dateItem.getTaskListEventItem(eventToAdd.getName());
assertSameEventName(eventToAdd, eventItem);
}
/**
* Utility method for testing if task does not appear in the GUI after a command.
* Assumption: No two events can have the same name in this test.
*/
protected void assertTaskNotVisibleAfterCmd(String command, Task taskToAdd) {
// Run the command in the console.
console.runCommand(command);
// Get the task date.
LocalDateTime taskDateTime = taskToAdd.getCalendarDateTime();
if (taskDateTime == null) {
taskDateTime = DateUtil.NO_DATETIME_VALUE;
}
LocalDate taskDate = taskDateTime.toLocalDate();
// Check TaskList if it contains a TaskListDateItem with the date.
TaskListDateItemHandle dateItem = taskList.getTaskListDateItem(taskDate);
// It's fine if there's no task item, because it's not visible
if (dateItem == null) {
return;
}
// If there's a date item, then we make sure that it isn't a task in the date item with the same name.
TaskListTaskItemHandle taskItem = dateItem.getTaskListTaskItem(taskToAdd.getName());
assertNull(taskItem);
}
/**
* Utility method for testing if event does not appear in the GUI after a command.
* Assumption: No two events can have the same name in this test.
*/
protected void assertEventNotVisibleAfterCmd(String command, Event eventToAdd) {
// Run the command in the console.
console.runCommand(command);
// Get the event date.
LocalDateTime eventStartDateTime = eventToAdd.getStartDate();
if (eventStartDateTime == null) {
eventStartDateTime = DateUtil.NO_DATETIME_VALUE;
}
LocalDate eventStartDate = eventStartDateTime.toLocalDate();
// Gets the date item that might contain the event
TaskListDateItemHandle dateItem = taskList.getTaskListDateItem(eventStartDate);
// It's fine if there's no date item, because it's not visible.
if (dateItem == null) {
return;
}
// If there's a date item, then we make sure that there isn't an event in the date item with the same name.
TaskListEventItemHandle eventItem = dateItem.getTaskListEventItem(eventToAdd.getName());
assertNull(eventItem);
}
}
|
package goryachev.fx.edit;
import goryachev.fx.FX;
import goryachev.fx.edit.internal.CaretLocation;
import goryachev.fx.edit.internal.EditorTools;
import goryachev.fx.util.FxPathBuilder;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
/**
* Vertical Flow manages LineBoxes.
*/
public class VFlow
extends Pane
{
protected final FxEditor editor;
public final Timeline caretAnimation;
public final Path caretPath;
public final Path selectionHighlight;
protected final BooleanProperty caretVisible = new SimpleBooleanProperty(true);
protected final BooleanProperty suppressBlink = new SimpleBooleanProperty(false);
protected final Rectangle clip;
// TODO line decorations/line numbers
protected FxEditorLayout layout;
/** index of the topmost visible line */
protected int topLineIndex;
/** horizontal shift in pixels */
protected double offsetx;
/** vertical offset or the viewport relative to the topmost line. always positive */
protected double offsety;
public VFlow(FxEditor ed)
{
this.editor = ed;
clip = new Rectangle();
selectionHighlight = new Path();
FX.style(selectionHighlight, FxEditor.HIGHLIGHT);
selectionHighlight.setManaged(false);
selectionHighlight.setStroke(null);
selectionHighlight.setFill(Color.rgb(255, 255, 0, 0.25));
caretPath = new Path();
FX.style(caretPath, FxEditor.CARET);
caretPath.setManaged(false);
caretPath.setStroke(Color.BLACK);
caretAnimation = new Timeline();
caretAnimation.setCycleCount(Animation.INDEFINITE);
getChildren().addAll(selectionHighlight, caretPath);
setClip(clip);
caretPath.visibleProperty().bind(new BooleanBinding()
{
{
bind(caretVisible, editor.displayCaretProperty, editor.focusedProperty(), editor.disabledProperty(), suppressBlink);
}
protected boolean computeValue()
{
return (isCaretVisible() || suppressBlink.get()) && editor.isDisplayCaret() && editor.isFocused() && (!editor.isDisabled());
}
});
}
public void setOrigin(int top, double offy)
{
topLineIndex = top;
offsety = offy;
layoutChildren();
// update scroll
editor.setHandleScrollEvents(false);
int max = editor.getLineCount();
double v = (max == 0 ? 0.0 : top / (double)max);
editor.vscroll.setValue(v);
editor.setHandleScrollEvents(true);
}
public void setTopLineIndex(int ix)
{
topLineIndex = ix;
}
protected void layoutChildren()
{
layout = recreateLayout(layout);
updateCaretAndSelection();
}
public void invalidateLayout()
{
if(layout != null)
{
layout.removeFrom(this);
}
layout = null;
}
public void reset()
{
offsetx = 0;
offsety = 0;
topLineIndex = 0;
}
public void setSuppressBlink(boolean on)
{
suppressBlink.set(on);
if(!on)
{
// restart animation cycle
updateBlinkRate();
}
}
public void updateBlinkRate()
{
Duration d = editor.getBlinkRate();
Duration period = d.multiply(2);
caretAnimation.stop();
caretAnimation.getKeyFrames().setAll
(
new KeyFrame(Duration.ZERO, (ev) -> setCaretVisible(true)),
new KeyFrame(d, (ev) -> setCaretVisible(false)),
new KeyFrame(period)
);
caretAnimation.play();
}
/** used for blinking animation */
protected void setCaretVisible(boolean on)
{
caretVisible.set(on);
}
public boolean isCaretVisible()
{
return caretVisible.get();
}
public FxEditorLayout recreateLayout(FxEditorLayout prev)
{
if(prev != null)
{
prev.removeFrom(this);
}
double width = getWidth();
double height = getHeight();
clip.setWidth(width);
clip.setHeight(height);
// TODO is loaded?
FxEditorModel model = editor.getTextModel();
int lines = model.getLineCount();
FxEditorLayout la = new FxEditorLayout(editor, topLineIndex);
Insets pad = getInsets();
double maxy = height - pad.getBottom();
double y = pad.getTop() - offsety;
double x0 = pad.getLeft();
boolean wrap = editor.isWrapText();
// TODO account for leading, trailing components
double wid = width - x0 - pad.getRight();
for(int ix=topLineIndex; ix<lines; ix++)
{
LineBox b = (prev == null ? null : prev.getLineBox(ix));
Region nd;
if(b == null)
{
nd = model.getDecoratedLine(ix);
}
else
{
nd = b.getBox();
}
getChildren().add(nd);
nd.applyCss();
nd.setManaged(true);
double w = wrap ? wid : nd.prefWidth(-1);
nd.setMaxWidth(wrap ? wid : Double.MAX_VALUE);
double h = nd.prefHeight(w);
if(b == null)
{
b = new LineBox(ix, nd);
}
la.addLineBox(b);
b.setHeight(h);
layoutInArea(nd, x0, y, w, h, 0, null, true, true, HPos.LEFT, VPos.TOP);
y += h;
if(y > maxy)
{
break;
}
}
return la;
}
public double addAndComputePreferredHeight(Region nd)
{
// warning: the same code in recreateLayout() above
Insets pad = getInsets();
double x0 = pad.getLeft();
boolean wrap = editor.isWrapText();
double width = getWidth();
// TODO account for leading, trailing components
double wid = width - x0 - pad.getRight();
getChildren().add(nd);
nd.applyCss();
nd.setManaged(true);
double w = wrap ? wid : nd.prefWidth(-1);
nd.setMaxWidth(wrap ? wid : Double.MAX_VALUE);
return nd.prefHeight(w);
}
public void updateCaretAndSelection()
{
FxPathBuilder selectionBuilder = new FxPathBuilder();
FxPathBuilder caretBuilder = new FxPathBuilder();
for(SelectionSegment s: editor.selector.segments)
{
Marker start = s.getAnchor();
Marker end = s.getCaret();
createSelectionHighlight(selectionBuilder, start, end);
createCaretPath(caretBuilder, end);
}
selectionHighlight.getElements().setAll(selectionBuilder.getPath());
caretPath.getElements().setAll(caretBuilder.getPath());
}
protected void createCaretPath(FxPathBuilder p, Marker m)
{
CaretLocation c = editor.getCaretLocation(m);
if(c != null)
{
p.moveto(c.x, c.y0);
p.lineto(c.x, c.y1);
}
}
// FIX issue #1 selection shape is incorrect if mixing LTR and RTL languages
protected void createSelectionHighlight(FxPathBuilder b, Marker startMarker, Marker endMarker)
{
if((startMarker == null) || (endMarker == null))
{
return;
}
// make sure startMarker < endMarker
if(startMarker.compareTo(endMarker) > 0)
{
Marker tmp = startMarker;
startMarker = endMarker;
endMarker = tmp;
}
if(endMarker.getLine() < topLineIndex)
{
// selection is above visible area
return;
}
else if(startMarker.getLine() >= (topLineIndex + layout.getVisibleLineCount()))
{
// selection is below visible area
return;
}
CaretLocation beg = editor.getCaretLocation(startMarker);
CaretLocation end = editor.getCaretLocation(endMarker);
double left = 0.0;
double right = getWidth() - left;
double top = 0.0;
double bottom = getHeight();
// there is a number of possible shapes resulting from intersection of
// the selection shape and the visible area. the logic below explicitly generates
// resulting paths because the selection can be quite large.
if(beg == null)
{
if(end == null)
{
if((startMarker.getLine() < topLineIndex) && (endMarker.getLine() >= (topLineIndex + layout.getVisibleLineCount())))
{
// start is way before visible, end is way after visible
b.moveto(left, top);
b.lineto(right, top);
b.lineto(right, bottom);
b.lineto(left, bottom);
b.lineto(left, top);
}
return;
}
// start caret is above the visible area
boolean crossTop = end.containsY(top);
boolean crossBottom = end.containsY(bottom);
if(crossBottom)
{
if(crossTop)
{
b.moveto(left, top);
b.lineto(end.x, top);
b.lineto(end.x, bottom);
b.lineto(left, bottom);
b.lineto(left, top);
}
else
{
b.moveto(left, top);
b.lineto(right, top);
b.lineto(right, end.y0);
b.lineto(end.x, end.y0);
b.lineto(end.x, bottom);
b.lineto(left, bottom);
b.lineto(left, top);
}
}
else
{
if(crossTop)
{
b.moveto(left, top);
b.lineto(end.x, top);
b.lineto(end.x, end.y1);
b.lineto(left, end.y1);
b.lineto(left, top);
}
else
{
b.moveto(left, top);
b.lineto(right, top);
b.lineto(right, end.y0);
b.lineto(end.x, end.y0);
b.lineto(end.x, end.y1);
b.lineto(left, end.y1);
b.lineto(left, top);
}
}
}
else if(end == null)
{
// end caret is below the visible area
boolean crossTop = beg.containsY(top);
boolean crossBottom = beg.containsY(bottom);
if(crossTop)
{
if(crossBottom)
{
b.moveto(beg.x, top);
b.lineto(right, top);
b.lineto(right, bottom);
b.lineto(beg.x, bottom);
b.lineto(beg.x, top);
}
else
{
b.moveto(beg.x, top);
b.lineto(right, top);
b.lineto(right, bottom);
b.lineto(left, bottom);
b.lineto(left, beg.y1);
b.lineto(beg.x, beg.y1);
b.lineto(beg.x, top);
}
}
else
{
if(crossBottom)
{
b.moveto(beg.x, beg.y0);
b.lineto(right, beg.y0);
b.lineto(right, bottom);
b.lineto(beg.x, bottom);
b.lineto(beg.x, beg.y0);
}
else
{
b.moveto(beg.x, beg.y0);
b.lineto(right, beg.y0);
b.lineto(right, bottom);
b.lineto(left, bottom);
b.lineto(left, beg.y1);
b.lineto(beg.x, beg.y1);
b.lineto(beg.x, beg.y0);
}
}
}
else
{
// both carets are in the visible area
if(EditorTools.isCloseEnough(beg.y0, end.y0))
{
b.moveto(beg.x, beg.y0);
b.lineto(end.x, beg.y0);
b.lineto(end.x, end.y1);
b.lineto(beg.x, end.y1);
b.lineto(beg.x, beg.y0);
}
else
{
b.moveto(beg.x, beg.y0);
b.lineto(right, beg.y0);
b.lineto(right, end.y0);
b.lineto(end.x, end.y0);
b.lineto(end.x, end.y1);
b.lineto(left, end.y1);
b.lineto(left, beg.y1);
b.lineto(beg.x, beg.y1);
b.lineto(beg.x, beg.y0);
}
}
}
protected FxEditorLayout getEditorLayout()
{
if(layout == null)
{
layout = new FxEditorLayout(editor, topLineIndex);
}
return layout;
}
public void pageUp()
{
blockScroll(getHeight(), true);
}
public void pageDown()
{
blockScroll(getHeight(), false);
}
public void blockScroll(boolean up)
{
// this could be a preference
double BLOCK_SCROLL_FACTOR = 0.1;
double BLOCK_MIN_SCROLL = 40;
double h = getHeight();
double delta = h * BLOCK_SCROLL_FACTOR;
if(delta < BLOCK_MIN_SCROLL)
{
delta = h;
}
blockScroll(delta, up);
}
protected void blockScroll(double delta, boolean up)
{
if(up)
{
if(delta <= offsety)
{
// no need to query the model
setOrigin(topLineIndex, offsety -= delta);
return;
}
else
{
int ix = topLineIndex;
double targetY = -delta;
double y = -offsety;
for(;;)
{
--ix;
if(ix < 0)
{
// top line
setOrigin(0, 0);
return;
}
double dy = getEditorLayout().getLineHeight(ix);
y -= dy;
if(y < targetY)
{
break;
}
}
setOrigin(ix, targetY - y);
return;
}
}
else
{
int ix = topLineIndex;
double targetY = delta;
double y = -offsety;
for(;;)
{
if(ix >= editor.getLineCount())
{
// FIX need to figure out what to do in this case
break;
}
double dy = getEditorLayout().getLineHeight(ix);
if(y + dy > targetY)
{
setOrigin(ix, targetY - y);
return;
}
y += dy;
ix++;
}
}
}
}
|
package sg.ncl.adapter.deterlab;
import org.apache.commons.lang3.RandomStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.http.*;;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabProjectRepository;
import sg.ncl.adapter.deterlab.data.jpa.DeterLabUserRepository;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabProjectEntity;
import sg.ncl.adapter.deterlab.dtos.entities.DeterLabUserEntity;
import sg.ncl.adapter.deterlab.exceptions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
/**
* @author Tran Ly Vu
*/
public class AdapterDeterLabTest {
@Rule
public MockitoRule mockito = MockitoJUnit.rule();
@Rule
public ExpectedException exception = ExpectedException.none();
@Mock
private DeterLabUserRepository deterLabUserRepository;
@Mock
private DeterLabProjectRepository deterLabProjectRepository;
@Mock
private ConnectionProperties properties;
@Mock
private RestTemplate restTemplate;
@Mock
ResponseEntity response;
private AdapterDeterLab adapterDeterLab;
@Before
public void setUp(){
assertThat(mockingDetails(deterLabUserRepository).isMock()).isTrue();
assertThat(mockingDetails(properties).isMock()).isTrue();
assertThat(mockingDetails(restTemplate).isMock()).isTrue();
adapterDeterLab=new AdapterDeterLab(deterLabUserRepository, deterLabProjectRepository, properties,restTemplate);
}
//no exception thrown
@Test
public void joinProjectNewUsersTest1() {
JSONObject myobject = new JSONObject();
String stubUid = RandomStringUtils.randomAlphanumeric(8);
myobject.put("msg", "user is created");
myobject.put("uid", stubUid);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual = adapterDeterLab.joinProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProjectNewUsers();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void joinProjectNewUsersTest2(){
JSONObject myobject = new JSONObject();
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).
thenThrow(new RestClientException(""));
adapterDeterLab.joinProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProjectNewUsers();
}
//throw DeterLabOperationFailedException
@Test
public void joinProjectNewUsersTest3() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "user not found");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.joinProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProjectNewUsers();
}
//throw JSONException
@Test
public void joinProjectNewUsersTest4() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "user not found");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
adapterDeterLab.joinProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProjectNewUsers();
}
//throw EmailAlreadyExistsException
@Test
public void joinProjectNewUsersTest5() {
JSONObject myobject = new JSONObject();
String stubUid = RandomStringUtils.randomAlphanumeric(8);
myobject.put("msg", "email address in use");
exception.expect(EmailAlreadyExistsException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.joinProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProjectNewUsers();
}
//no Exception thrown
@Test
public void applyProjectNewUsersTest1() {
JSONObject myobject = new JSONObject();
String stubUid = RandomStringUtils.randomAlphanumeric(8);
myobject.put("msg", "user is created");
myobject.put("uid", stubUid);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual = adapterDeterLab.applyProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProjectNewUsers();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void applyProjectNewUsersTest2() {
JSONObject myobject = new JSONObject();
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new AdapterDeterlabConnectException());
adapterDeterLab.applyProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProjectNewUsers();
}
//throw DeterLabOperationFailedException
@Test
public void applyProjectNewUsersTest3() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "user is not created");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.applyProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProjectNewUsers();
}
//throw JSONException
@Test
public void applyProjectNewUsersTest4() {
JSONObject myobject = new JSONObject();
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
adapterDeterLab.applyProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProjectNewUsers();
}
// throw InvalidPasswordException
@Test
public void applyProjectNewUsersTest5() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "invalid password");
exception.expect(InvalidPasswordException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.applyProjectNewUsers(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProjectNewUsers();
}
//no exception thrown
@Test
public void applyProjectTest1() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "apply project request existing users success");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.applyProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProject();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void applyProjectTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "apply project request existing users success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException(""));
adapterDeterLab.applyProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProject();
}
//throw DeterLabOperationFailedException
@Test
public void applyProjectTest3(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "apply project request existing users fail");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.applyProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProject();
}
//throw JSONException
@Test
public void applyProjectTest4() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "apply project request existing users fail");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
adapterDeterLab.applyProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApplyProject();
}
//no exception thrown
@Test
public void joinProjectTest1() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "join project request existing users success");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.joinProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProject();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void joinProjectTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "join project request existing users success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException(""));
adapterDeterLab.joinProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProject();
}
//thrown DeterLabOperationFailedException
@Test
public void joinProjectTest3(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "join project request existing users failure");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.joinProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProject();
}
//throw JSONException
@Test
public void joinProjectTest4() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "join project request existing users success");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
adapterDeterLab.joinProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getJoinProject();
}
//no exception thrown
@Test
public void updateCredentialsTest1() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "password change success");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.updateCredentials(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getUpdateCredentials();
}
//throw AdapterDeterlabConnectException
@Test
public void updateCredentialsTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "password change success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenThrow(new RestClientException(""));
adapterDeterLab.updateCredentials(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getUpdateCredentials();
}
//throw CredentialsUpdateException
@Test
public void updateCredentialsTest3(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "password change failure");
exception.expect(CredentialsUpdateException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.updateCredentials(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getUpdateCredentials();
}
//throw JSONException
@Test
public void updateCredentialsTest4() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "password change success");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
adapterDeterLab.updateCredentials(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getUpdateCredentials();
}
@Test
public void saveDeterUserIdMappingTest() {
String deterUserId = "test1";
String nclUserId = "test2";
adapterDeterLab.saveDeterUserIdMapping(deterUserId, nclUserId);
verify(deterLabUserRepository,times(1)).save(any(DeterLabUserEntity.class));
}
//throw UserNotFoundException
@Test
public void getDeterUserIdByNclUserIdTest1(){
String nclUserId = "test";
exception.expect(UserNotFoundException.class);
when(deterLabUserRepository.findByNclUserId(nclUserId)).thenReturn(null);
String actual=adapterDeterLab.getDeterUserIdByNclUserId(nclUserId );
verify(deterLabUserRepository,times(1)).findByNclUserId(nclUserId);
}
//no exception thrown
@Test
public void getDeterUserIdByNclUserIdTest2(){
DeterLabUserEntity deterLabUserEntity=new DeterLabUserEntity();
deterLabUserEntity.setDeterUserId("test1");
String expected= deterLabUserEntity.getDeterUserId();
when(deterLabUserRepository.findByNclUserId(anyString())).thenReturn(deterLabUserEntity);
String actual=adapterDeterLab.getDeterUserIdByNclUserId("");
verify(deterLabUserRepository,times(1)).findByNclUserId(anyString());
assertEquals(expected,actual);
}
@Test
public void saveDeterProjectIdTest() {
String deterProjectId = "test1";
String nclTeamId = "test2";
adapterDeterLab.saveDeterProjectId(deterProjectId, nclTeamId);
verify(deterLabProjectRepository,times(1)).save(any(DeterLabProjectEntity.class));
}
@Test
public void getDeterProjectIdByNclTeamIdTestException() {
String nclTeamId = "test";
exception.expect(TeamNotFoundException.class);
when(deterLabProjectRepository.findByNclTeamId(nclTeamId)).thenReturn(null);
adapterDeterLab.getDeterProjectIdByNclTeamId(nclTeamId);
verify(deterLabProjectRepository,times(1)).findByNclTeamId(nclTeamId);
}
@Test
public void getDeterProjectIdByNclTeamIdTestGood(){
DeterLabProjectEntity deterLabProjectEntity = new DeterLabProjectEntity();
deterLabProjectEntity.setDeterProjectId("test1");
String expected = deterLabProjectEntity.getDeterProjectId();
when(deterLabProjectRepository.findByNclTeamId(anyString())).thenReturn(deterLabProjectEntity);
String actual = adapterDeterLab.getDeterProjectIdByNclTeamId("");
verify(deterLabProjectRepository,times(1)).findByNclTeamId(anyString());
assertEquals(expected,actual);
}
//no exception thrown
@Test
public void createExperimentTest1() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create success");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.createExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getCreateExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw AdapterDeterlabConnectException
@Test
public void createExperimentTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RuntimeException());
adapterDeterLab.createExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getCreateExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw NSFileParseException
@Test
public void createExperimentTest3(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create fail ns file error");
exception.expect(NSFileParseException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.createExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getCreateExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw ExpNameAlreadyExistsException
@Test
public void createExperimentTest4(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create fail exp name already in use");
exception.expect(ExpNameAlreadyExistsException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.createExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getCreateExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw JSONException
@Test
public void createExperimentTest5() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create fail");
exception.expect(AdapterDeterlabConnectException.class);
when(properties.getCreateExperiment()).thenReturn("");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.createExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getCreateExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//no exception thrown
@Test
public void startExperimentTest1() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment start success");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual= adapterDeterLab.startExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).startExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void startExperimentTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RuntimeException());
String actual=adapterDeterLab.startExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).startExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw ExpStartException()
@Test
public void startExperimentTest3(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment start fail");
exception.expect(ExpStartException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.startExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).startExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw AdapterDeterlabConnectException
@Test
public void startExperimentTest4(){
JSONObject myobject = new JSONObject();
myobject.put("msg", "");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.startExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).startExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//no exception thrown
@Test
public void stopExperimentTest1() {
JSONObject myobject = new JSONObject();
myobject.put("status", "swapped");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual= adapterDeterLab.stopExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).stopExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
assertEquals(myobject.getString("status"),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void stopExperimentTest2() {
JSONObject myobject = new JSONObject();
myobject.put("msg", "experiment create success");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RuntimeException());
String actual=adapterDeterLab.stopExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).stopExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//no exception thrown
@Test
public void deleteExperimentTest1() {
JSONObject myobject = new JSONObject();
myobject.put("status", "no experiment found");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual= adapterDeterLab.deleteExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).deleteExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
assertEquals(myobject.getString("status"),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void deleteExperimentTest2() {
JSONObject myobject = new JSONObject();
myobject.put("status", "no experiment found");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RuntimeException());
String actual=adapterDeterLab. deleteExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).deleteExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//throw ExpDeleteException
@Test
public void deleteExperimentTest3() {
JSONObject myobject = new JSONObject();
myobject.put("status", "experiment found");
exception.expect(ExpDeleteException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.deleteExperiment(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).deleteExperiment();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
}
//no exception thrown
@Test
public void getExperimentStatusTest1() {
JSONObject myobject = new JSONObject();
myobject.put("status", "test string");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual= adapterDeterLab.getExperimentStatus(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getExpStatus();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
assertEquals(myobject.toString(),actual);
}
//throw Exception
@Test
public void getExperimentStatusTest2() {
JSONObject myobject = new JSONObject();
myobject.put("status", "no experiment found");
// exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RuntimeException());
String expected="{\"status\": \"error\"}";
String actual=adapterDeterLab.getExperimentStatus(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getExpStatus();
verify(properties,times(1)).getIp();
verify(properties,times(1)).getPort();
assertEquals(expected,actual);
}
@Test
public void processJoinRequestTest1() {
JSONObject myobject = new JSONObject();
myobject.put("action", "approve");
exception.expect(IllegalArgumentException.class);
String actual= adapterDeterLab.processJoinRequest(myobject.toString());
}
//"action" is "approve" and throw AdapterDeterlabConnectException
@Test
public void processJoinRequestTest2() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "approve");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RestClientException(""));
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveJoinRequest();
}
//"action" is "approve" and throw DeterLabOperationFailedException
@Test
public void processJoinRequestTest3() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "approve");
myobject.put("msg", "process join request not OK");
exception.expect( DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveJoinRequest();
}
//"action" is "approve" and throw JSONException
@Test
public void processJoinRequestTest4() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "approve");
myobject.put("msg", "process join request OK");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveJoinRequest();
}
//"action" is "approve" and no exception thrown
@Test
public void processJoinRequestTest5() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "approve");
myobject.put("msg", "process join OK");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveJoinRequest();
assertEquals(myobject .toString(),actual);
}
//"action" is not "approve" and throw AdapterDeterlabConnectException
@Test
public void processJoinRequestTest6() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "reject");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RestClientException(""));
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectJoinRequest();
}
//"action" is not "approve" and throw DeterLabOperationFailedException
@Test
public void processJoinRequestTest7() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "reject");
myobject.put("msg", "process join request not OK");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectJoinRequest();
}
//"action" is not "approve" and throw JSONException
@Test
public void processJoinRequestTest8() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "reject");
myobject.put("msg", "process join request OK");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn("");
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectJoinRequest();
}
//"action" is not "approve" and no exception thrown
@Test
public void processJoinRequestTest9() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("approverUid", "");
myobject.put("uid", "");
myobject.put("gid", "");
myobject.put("action", "reject");
myobject.put("msg", "process join request OK");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.processJoinRequest(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectJoinRequest();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void approveProjectTest1(){
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RestClientException(""));
String actual=adapterDeterLab.approveProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveProject();
}
//throw DeterLabOperationFailedException
@Test
public void approveProjectTest2() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "approve project not OK");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.approveProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveProject();
}
//throw JSONException
@Test
public void approveProjectTest3() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "approve project OK");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.approveProject("");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveProject();
}
//no exception thrown
@Test
public void approveProjectTest4() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "approve project OK");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.approveProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getApproveProject();
assertEquals(myobject.toString(),actual);
}
//throw AdapterDeterlabConnectException
@Test
public void rejectProjectTest1(){
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RestClientException(""));
String actual=adapterDeterLab.rejectProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectProject();
}
//throw DeterLabOperationFailedException
@Test
public void rejectProjectTest2() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "reject project not OK");
exception.expect(DeterLabOperationFailedException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.rejectProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectProject();
}
//throw JSONException
@Test
public void rejectProjectTest3() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "reject project OK");
exception.expect(JSONException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.rejectProject("");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectProject();
}
//no exception thrown
@Test
public void rejectProject4() {
JSONObject myobject = new JSONObject();
myobject.put("pid", "");
myobject.put("msg", "reject project OK");
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
String actual=adapterDeterLab.rejectProject(myobject.toString());
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).getRejectProject();
assertEquals(myobject.toString(),actual);
}
@Test
public void loginSuccess() throws Exception {
JSONObject myobject = new JSONObject();
myobject.put("msg", "user is logged in");
when(properties.isEnabled()).thenReturn(true);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity());
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
adapterDeterLab.login("userId", "password");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).login();
}
@Test
public void loginFail() throws Exception {
JSONObject myobject = new JSONObject();
myobject.put("msg", "user is logged in error");
when(properties.isEnabled()).thenReturn(true);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenReturn(response);
when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity());
when(response.getBody()).thenReturn(myobject.toString());
when(response.getBody().toString()).thenReturn(myobject.toString());
exception.expect(DeterLabOperationFailedException.class);
adapterDeterLab.login("userId", "password");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).login();
}
@Test
public void loginAdapterDeterlabConnectionException() throws Exception {
when(properties.isEnabled()).thenReturn(true);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).
thenThrow(new RestClientException(""));
when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity());
exception.expect(AdapterDeterlabConnectException.class);
adapterDeterLab.login("userId", "password");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).login();
}
@Test
public void loginJSONException() throws Exception {
when(properties.isEnabled()).thenReturn(true);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class))).thenReturn(response);
when(deterLabUserRepository.findByNclUserId(eq("userId"))).thenReturn(Util.getDeterlabUserEntity());
when(response.getBody()).thenReturn("");
when(response.getBody().toString()).thenReturn("");
exception.expect(JSONException.class);
adapterDeterLab.login("userId", "password");
verify(restTemplate,times(1)).exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class));
verify(properties,times(1)).login();
}
//throw AdapterDeterlabConnectException
@Test
public void getTopoThumbnailTest() {
JSONObject myobject = new JSONObject();
myobject.put("thumbnail", "");
exception.expect(AdapterDeterlabConnectException.class);
when(restTemplate.exchange(anyString(),eq(HttpMethod.POST),anyObject(),eq(String.class)))
.thenThrow(new RestClientException(""));
adapterDeterLab.getTopologyThumbnail(myobject.toString());
}
}
|
package pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import pft.addressbook.model.GroupData;
import pft.addressbook.model.Groups;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GropuHelper extends HelperBase {
public GropuHelper(WebDriver wd) {
super(wd);
}
public void returnToGroupPage() {
click(By.linkText("group page"));
}
public void fillGroupForm(GroupData groupData) {
type(By.name("group_name"), groupData.getName());
type(By.name("group_header"), groupData.getHeader());
type(By.name("group_footer"), groupData.getFooter());
}
public void initGroupCreation() {
click(By.name("new"));
}
public void submitGroupCreation() {
click(By.name("submit"));
}
public void deleteSelectedGroups() {
click(By.name("delete"));
}
public void selectGroup(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
//click(By.name("selected[]"));
}
private void selectGroupById(int id) {
wd.findElement(By.cssSelector("input[value='" + id + "']")).click();
}
public void initGroupModification() { click(By.name("edit"));}
public void submitGroupModification() {click(By.name("update")); }
public void create(GroupData group) {
initGroupCreation();
fillGroupForm(group);
submitGroupCreation();
groupCash = null;
returnToGroupPage();
}
public void modify(GroupData group) {
selectGroupById(group.getId());
initGroupModification();
fillGroupForm(group);
submitGroupModification();
groupCash = null;
returnToGroupPage();
}
public void del(int index) {
selectGroup(index);
deleteSelectedGroups();
returnToGroupPage();
}
public void del(GroupData group) {
selectGroupById(group.getId());
deleteSelectedGroups();
groupCash = null;
returnToGroupPage();
}
public boolean isThereAGroup() {
return isElementPresent(By.name("selected[]"));
}
public int getGroupCount() {
return wd.findElements(By.name("selected[]")).size();
}
public List<GroupData> getGroupList() {
List<GroupData> groups = new ArrayList<GroupData>();
List<WebElement> elements = wd.findElements(By.cssSelector("span.group"));
for (WebElement element:elements){
String name = element.getText();
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
groups.add(new GroupData().withId(id).withName(name));
}
return groups;
}
private Groups groupCash = null;
public Groups allGroups() {
if (groupCash != null) {return groupCash;}
groupCash = new Groups();
List<WebElement> elements = wd.findElements(By.cssSelector("span.group"));
for (WebElement element:elements){
String name = element.getText();
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
groupCash.add(new GroupData().withId(id).withName(name));
}
return groupCash;
}
}
|
package org.jenkinsci.plugins.workflow.steps;
import hudson.model.Result;
import hudson.tasks.Fingerprinter;
import hudson.tasks.junit.TestResultAction;
import java.util.List;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.jvnet.hudson.test.JenkinsRule;
public class CoreStepTest {
@Rule public JenkinsRule r = new JenkinsRule();
@Test public void artifactArchiver() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition("node {sh 'touch x.txt'; step($class: 'hudson.tasks.ArtifactArchiver', artifacts: 'x.txt', fingerprint: true)}"));
WorkflowRun b = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
List<WorkflowRun.Artifact> artifacts = b.getArtifacts();
assertEquals(1, artifacts.size());
assertEquals("x.txt", artifacts.get(0).relativePath);
Fingerprinter.FingerprintAction fa = b.getAction(Fingerprinter.FingerprintAction.class);
assertNotNull(fa);
assertEquals("[x.txt]", fa.getRecords().keySet().toString());
}
@Test public void fingerprinter() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition("node {sh 'touch x.txt'; step($class: 'hudson.tasks.Fingerprinter', targets: 'x.txt')}"));
WorkflowRun b = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
Fingerprinter.FingerprintAction fa = b.getAction(Fingerprinter.FingerprintAction.class);
assertNotNull(fa);
assertEquals("[x.txt]", fa.getRecords().keySet().toString());
}
@Test public void junitResultArchiver() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"node {\n"
// Quote hell! " is Java, ''' is Groovy, ' is shell, \" is " inside XML
+ " sh '''echo '<testsuite name=\"a\"><testcase name=\"a1\"/><testcase name=\"a2\"><error>a2 failed</error></testcase></testsuite>' > a.xml'''\n"
+ " sh '''echo '<testsuite name=\"b\"><testcase name=\"b1\"/><testcase name=\"b2\"/></testsuite>' > b.xml'''\n"
+ " step($class: 'hudson.tasks.junit.JUnitResultArchiver', testResults: '*.xml')\n"
+ "}"));
WorkflowRun b = r.assertBuildStatus(Result.UNSTABLE, p.scheduleBuild2(0).get());
TestResultAction a = b.getAction(TestResultAction.class);
assertNotNull(a);
assertEquals(4, a.getTotalCount());
assertEquals(1, a.getFailCount());
}
}
|
package org.libreoffice;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.util.Log;
import org.libreoffice.kit.Document;
import org.libreoffice.kit.LibreOfficeKit;
import org.libreoffice.kit.Office;
import org.mozilla.gecko.gfx.BufferedCairoImage;
import org.mozilla.gecko.gfx.CairoImage;
import org.mozilla.gecko.gfx.GeckoLayerClient;
import org.mozilla.gecko.gfx.IntSize;
import java.nio.ByteBuffer;
public class LOKitTileProvider implements TileProvider, Document.MessageCallback {
private static final String LOGTAG = LOKitTileProvider.class.getSimpleName();
private static int TILE_SIZE = 256;
private final GeckoLayerClient mLayerClient;
private final float mTileWidth;
private final float mTileHeight;
private final String mInputFile;
private Office mOffice;
private Document mDocument;
private boolean mIsReady = false;
private TileInvalidationCallback tileInvalidationCallback = null;
private float mDPI;
private float mWidthTwip;
private float mHeightTwip;
private long objectCreationTime = System.currentTimeMillis();
public LOKitTileProvider(GeckoLayerClient layerClient, String input) {
mLayerClient = layerClient;
mDPI = (float) LOKitShell.getDpi();
mTileWidth = pixelToTwip(TILE_SIZE, mDPI);
mTileHeight = pixelToTwip(TILE_SIZE, mDPI);
LibreOfficeKit.putenv("SAL_LOG=-WARN+INFO.lok");
LibreOfficeKit.init(LibreOfficeMainActivity.mAppContext);
mOffice = new Office(LibreOfficeKit.getLibreOfficeKitHandle());
mInputFile = input;
mDocument = mOffice.documentLoad(input);
if (mDocument == null) {
LibreOfficeKit.putenv("SAL_LOG=+WARN+INFO");
Log.i(LOGTAG, "====> mOffice.documentLoad() returned null, trying to restart 'Office' and loading again");
mOffice.destroy();
Log.i(LOGTAG, "====> mOffice.destroy() done");
ByteBuffer handle = LibreOfficeKit.getLibreOfficeKitHandle();
Log.i(LOGTAG, "====> getLibreOfficeKitHandle() = " + handle);
mOffice = new Office(handle);
Log.i(LOGTAG, "====> new Office created");
mDocument = mOffice.documentLoad(input);
LibreOfficeKit.putenv("SAL_LOG=-WARN+INFO.lok");
}
Log.i(LOGTAG, "====> mDocument = " + mDocument);
if (checkDocument()) {
postLoad();
mIsReady = true;
}
}
public void postLoad() {
mDocument.initializeForRendering();
mDocument.setMessageCallback(this);
int parts = mDocument.getParts();
Log.i(LOGTAG, "Document parts: " + parts);
LibreOfficeMainActivity.mAppContext.getDocumentPartView().clear();
// Writer documents always have one part, so hide the navigation drawer.
if (mDocument.getDocumentType() != Document.DOCTYPE_TEXT) {
for (int i = 0; i < parts; i++) {
String partName = mDocument.getPartName(i);
if (partName.isEmpty()) {
partName = getGenericPartName(i);
}
Log.i(LOGTAG, "Document part " + i + " name:'" + partName + "'");
mDocument.setPart(i);
resetDocumentSize();
final DocumentPartView partView = new DocumentPartView(i, partName);
LibreOfficeMainActivity.mAppContext.getDocumentPartView().add(partView);
}
} else {
LibreOfficeMainActivity.mAppContext.disableNavigationDrawer();
}
mDocument.setPart(0);
LOKitShell.getMainHandler().post(new Runnable() {
@Override
public void run() {
LibreOfficeMainActivity.mAppContext.getDocumentPartViewListAdapter().notifyDataSetChanged();
}
});
}
private String getGenericPartName(int i) {
if (mDocument == null) {
return "";
}
switch (mDocument.getDocumentType()) {
case Document.DOCTYPE_DRAWING:
case Document.DOCTYPE_TEXT:
return "Page " + (i + 1);
case Document.DOCTYPE_SPREADSHEET:
return "Sheet " + (i + 1);
case Document.DOCTYPE_PRESENTATION:
return "Slide " + (i + 1);
case Document.DOCTYPE_OTHER:
default:
return "Part " + (i + 1);
}
}
private float twipToPixel(float input, float dpi) {
return input / 1440.0f * dpi;
}
private float pixelToTwip(float input, float dpi) {
return (input / dpi) * 1440.0f;
}
private boolean checkDocument() {
String error = null;
boolean ret;
if (mDocument == null || !mOffice.getError().isEmpty()) {
error = "Cannot open " + mInputFile + ": " + mOffice.getError();
ret = false;
} else {
ret = resetDocumentSize();
if (!ret) {
error = "Document returned an invalid size or the document is empty!";
}
}
if (!ret) {
final String message = error;
LOKitShell.getMainHandler().post(new Runnable() {
@Override
public void run() {
LibreOfficeMainActivity.mAppContext.showAlertDialog(message);
}
});
}
return ret;
}
private boolean resetDocumentSize() {
mWidthTwip = mDocument.getDocumentWidth();
mHeightTwip = mDocument.getDocumentHeight();
if (mWidthTwip == 0 || mHeightTwip == 0) {
Log.e(LOGTAG, "Document size zero - last error: " + mOffice.getError());
return false;
} else {
Log.i(LOGTAG, "Reset document size: " + mDocument.getDocumentWidth() + " x " + mDocument.getDocumentHeight());
}
return true;
}
@Override
public int getPageWidth() {
return (int) twipToPixel(mWidthTwip, mDPI);
}
@Override
public int getPageHeight() {
return (int) twipToPixel(mHeightTwip, mDPI);
}
@Override
public boolean isReady() {
return mIsReady;
}
@Override
public CairoImage createTile(float x, float y, IntSize tileSize, float zoom) {
ByteBuffer buffer = ByteBuffer.allocateDirect(tileSize.width * tileSize.height * 4);
CairoImage image = new BufferedCairoImage(buffer, tileSize.width, tileSize.height, CairoImage.FORMAT_ARGB32);
rerenderTile(image, x, y, tileSize, zoom);
return image;
}
@Override
public void rerenderTile(CairoImage image, float x, float y, IntSize tileSize, float zoom) {
if (mDocument != null && image.getBuffer() != null) {
float twipX = pixelToTwip(x, mDPI) / zoom;
float twipY = pixelToTwip(y, mDPI) / zoom;
float twipWidth = mTileWidth / zoom;
float twipHeight = mTileHeight / zoom;
long start = System.currentTimeMillis() - objectCreationTime;
//Log.i(LOGTAG, "paintTile >> @" + start + " (" + tileSize.width + " " + tileSize.height + " " + (int) twipX + " " + (int) twipY + " " + (int) twipWidth + " " + (int) twipHeight + ")");
mDocument.paintTile(image.getBuffer(), tileSize.width, tileSize.height, (int) twipX, (int) twipY, (int) twipWidth, (int) twipHeight);
long stop = System.currentTimeMillis() - objectCreationTime;
//Log.i(LOGTAG, "paintTile << @" + stop + " elapsed: " + (stop - start));
} else {
if (mDocument == null) {
Log.e(LOGTAG, "Document is null!!");
}
}
}
@Override
public Bitmap thumbnail(int size) {
int widthPixel = getPageWidth();
int heightPixel = getPageHeight();
if (widthPixel > heightPixel) {
double ratio = heightPixel / (double) widthPixel;
widthPixel = size;
heightPixel = (int) (widthPixel * ratio);
} else {
double ratio = widthPixel / (double) heightPixel;
heightPixel = size;
widthPixel = (int) (heightPixel * ratio);
}
Log.w(LOGTAG, "Thumbnail size: " + getPageWidth() + " " + getPageHeight() + " " + widthPixel + " " + heightPixel);
ByteBuffer buffer = ByteBuffer.allocateDirect(widthPixel * heightPixel * 4);
mDocument.paintTile(buffer, widthPixel, heightPixel, 0, 0, (int) mWidthTwip, (int) mHeightTwip);
Bitmap bitmap = Bitmap.createBitmap(widthPixel, heightPixel, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
if (bitmap == null) {
Log.w(LOGTAG, "Thumbnail not created!");
}
return bitmap;
}
@Override
public void close() {
Log.i(LOGTAG, "Document destroyed: " + mInputFile);
if (mDocument != null) {
mDocument.destroy();
mDocument = null;
}
}
@Override
public boolean isTextDocument() {
return mDocument != null && mDocument.getDocumentType() == Document.DOCTYPE_TEXT;
}
@Override
public void registerInvalidationCallback(TileInvalidationCallback tileInvalidationCallback) {
this.tileInvalidationCallback = tileInvalidationCallback;
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
@Override
public void changePart(int partIndex) {
mDocument.setPart(partIndex);
resetDocumentSize();
}
@Override
public int getCurrentPartNumber() {
return mDocument.getPart();
}
@Override
public void messageRetrieved(int signalNumber, String payload) {
switch (signalNumber) {
case 0:
if (!payload.equals("EMPTY")) {
String[] coordinates = payload.split(",");
if (coordinates.length == 4) {
int width = Integer.decode(coordinates[0].trim());
int height = Integer.decode(coordinates[1].trim());
int x = Integer.decode(coordinates[2].trim());
int y = Integer.decode(coordinates[3].trim());
RectF rect = new RectF(
twipToPixel(x, mDPI),
twipToPixel(y, mDPI),
twipToPixel(x + width, mDPI),
twipToPixel(y + height, mDPI)
);
Log.i(LOGTAG, "Invalidate R: " + rect +" - " + getPageWidth() + " " + getPageHeight());
tileInvalidationCallback.invalidate(rect);
}
}
}
}
}
// vim:set shiftwidth=4 softtabstop=4 expandtab:
|
package net.fabricemk.android.mycv.adapters;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import net.fabricemk.android.mycv.fragments.TripFragment;
import net.fabricemk.android.mycv.fragments.TripItemFragment;
import net.fabricemk.android.mycv.models.TripItem;
import java.util.List;
public class TripPagerAdapter extends FragmentStatePagerAdapter {
Context ctxt = null;
List<TripItem> tripList;
public TripPagerAdapter(Context ctxt, FragmentManager mgr, List<TripItem> tripList) {
super(mgr);
this.ctxt = ctxt;
this.tripList = tripList;
}
@Override
public int getCount() {
return(tripList.size());
}
@Override
public Fragment getItem(int position) {
return TripItemFragment.newInstance(tripList.get(position));
}
}
|
package edu.purdue.voltag.fragments;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.parse.ParseException;
import com.parse.ParsePush;
import com.parse.PushService;
import com.parse.SendCallback;
import java.util.List;
import edu.purdue.voltag.MainActivity;
import edu.purdue.voltag.PlayerListAdapter;
import edu.purdue.voltag.R;
import edu.purdue.voltag.bitmap.BitmapCacheHost;
import edu.purdue.voltag.data.Player;
import edu.purdue.voltag.data.VoltagDB;
import edu.purdue.voltag.interfaces.OnDatabaseRefreshListener;
import edu.purdue.voltag.tasks.DeletePlayerTask;
import edu.purdue.voltag.tasks.LeaveGameTask;
import edu.purdue.voltag.tasks.RefreshPlayersTask;
/*
* A simple {@link android.support.v4.app.Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link GameLobbyFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link GameLobbyFragment#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class GameLobbyFragment extends ListFragment implements OnDatabaseRefreshListener, BitmapCacheHost {
VoltagDB db;
ListView theList;
private NfcAdapter mNfcAdapter;
private ImageView iv;
private TextView tv;
private LruCache<String, Bitmap> mMemoryCache;
private List<Player> players;
private Player it;
private TextView tv_it;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
initMemoryCache();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.game_lobby_menu, menu);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = VoltagDB.getDB(getActivity());
}
@Override
public void onDestroy() {
super.onDestroy();
clearCache();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("GameLobbyFragment", "onCreateView()");
View v = inflater.inflate(R.layout.fragment_game_lobby, container, false);
return v;
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
Log.d("GameLobbyFragment", "onViewCreated()");
theList = (ListView) view.findViewById(android.R.id.list);
iv = (ImageView) view.findViewById(R.id.imageView);
tv = (TextView) view.findViewById(R.id.gamelobby_tv_lobbyid);
tv_it = (TextView) view.findViewById(R.id.gamelobby_tv_whosit);
String gameName;
SharedPreferences settings = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
gameName = settings.getString(MainActivity.PREF_CURRENT_GAME_NAME, "");
tv.setText(gameName);
RefreshPlayersTask task = new RefreshPlayersTask(getActivity());
task.setListener(this);
task.execute();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final SharedPreferences prefs = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
int id = item.getItemId();
switch (id) {
case R.id.drop_registration:
// Leave the game
leaveGame();
// Delete the player from parse
new DeletePlayerTask(getActivity()).execute();
// Switch the fragment back to the registration fragment
getFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(android.R.id.content, new RegistrationFragment())
.commit();
return true;
case R.id.exit_game:
// Leave the game
leaveGame();
// Switch fragment to game choosing fragming
getFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(android.R.id.content, new GameChoiceFragment())
.commit();
return true;
case R.id.share:
String gameId = null;
gameId = prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, "");
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Come join the revolt! Enter the id " + gameId;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Join the revolt");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return true;
default:
return false;
}
}
private void leaveGame() {
// Get preferences
final SharedPreferences prefs = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
// Alert other players that we've left the game
ParsePush pushDrop = new ParsePush();
pushDrop.setChannel("a"+prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, ""));
pushDrop.setMessage(prefs.getString(MainActivity.PREF_USER_NAME, "") + " has left the game.");
// Send the push and unsubscribe them from push notifications
pushDrop.sendInBackground(new SendCallback() {
@Override
public void done(ParseException e) {
PushService.unsubscribe(getActivity(), "a"+prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, ""));
}
});
// Execute task
new LeaveGameTask(getActivity()).execute();
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
assert (mMemoryCache != null);
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
assert (mMemoryCache != null);
return mMemoryCache.get(key);
}
public void initMemoryCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 15;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
}
public void clearCache() {
mMemoryCache.evictAll();
}
public Player getWhoIsIt(List<Player> list) {
Log.d("debug","getWhoIsIt called");
Player it = null;
for (Player p : list) {
if (p.getIsIt()) {
Log.d("tylor", "It: " + p.getUserName());
it = p;
}
Log.d("tylor", p.getUserName());
}
return it;
}
@Override
public void onDatabaseRefresh() {
Log.d("Lobby", "Database has refreshed!!");
// Get the players in the current game
final List<Player> players = db.getPlayersInCurrentGame();
// Create the adapter
final PlayerListAdapter adapt = new PlayerListAdapter(getActivity(), R.layout.player_list_item, R.id.name, players, GameLobbyFragment.this);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
theList.setAdapter(adapt);
}
});
// Get the player's bitmap
final Player it = getWhoIsIt(players);
final Bitmap b = it.getGravitar((int) getActivity().getResources().getDimension(R.dimen.itSize));
// Post to UI
handler.post(new Runnable() {
public void run() {
iv.setImageBitmap(b);
tv_it.setText(it.getUserName());
}
});
}
}
|
package edu.purdue.voltag.fragments;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.parse.ParseException;
import com.parse.ParsePush;
import com.parse.PushService;
import com.parse.SendCallback;
import java.util.List;
import edu.purdue.voltag.MainActivity;
import edu.purdue.voltag.PlayerListAdapter;
import edu.purdue.voltag.R;
import edu.purdue.voltag.bitmap.BitmapCacheHost;
import edu.purdue.voltag.data.Player;
import edu.purdue.voltag.data.VoltagDB;
import edu.purdue.voltag.interfaces.OnDatabaseRefreshListener;
import edu.purdue.voltag.tasks.DeletePlayerTask;
import edu.purdue.voltag.tasks.LeaveGameTask;
import edu.purdue.voltag.tasks.RefreshPlayersTask;
/*
* A simple {@link android.support.v4.app.Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link GameLobbyFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link GameLobbyFragment#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class GameLobbyFragment extends ListFragment implements OnDatabaseRefreshListener, BitmapCacheHost {
VoltagDB db;
ListView theList;
private NfcAdapter mNfcAdapter;
private ImageView iv;
private TextView tv;
private LruCache<String, Bitmap> mMemoryCache;
private List<Player> players;
private Player it;
private TextView tv_it;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
initMemoryCache();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.game_lobby_menu, menu);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = VoltagDB.getDB(getActivity());
}
@Override
public void onDestroy() {
super.onDestroy();
clearCache();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("GameLobbyFragment", "onCreateView()");
View v = inflater.inflate(R.layout.fragment_game_lobby, container, false);
return v;
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
Log.d("GameLobbyFragment", "onViewCreated()");
theList = (ListView) view.findViewById(android.R.id.list);
iv = (ImageView) view.findViewById(R.id.imageView);
tv = (TextView) view.findViewById(R.id.gamelobby_tv_lobbyid);
tv_it = (TextView) view.findViewById(R.id.gamelobby_tv_whosit);
String gameName;
SharedPreferences settings = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
gameName = settings.getString(MainActivity.PREF_CURRENT_GAME_NAME, "");
tv.setText(gameName);
RefreshPlayersTask task = new RefreshPlayersTask(getActivity());
task.setListener(this);
task.execute();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final SharedPreferences prefs = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
int id = item.getItemId();
switch (id) {
case R.id.drop_registration:
// Leave the game
leaveGame();
// Delete the player from parse
new DeletePlayerTask(getActivity()).execute();
// Switch the fragment back to the registration fragment
getFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(android.R.id.content, new RegistrationFragment())
.commit();
return true;
case R.id.exit_game:
// Leave the game
leaveGame();
// Switch fragment to game choosing fragming
getFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(android.R.id.content, new GameChoiceFragment())
.commit();
return true;
case R.id.share:
String gameId = null;
gameId = prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, "");
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Come join the revolt! Enter the id " + gameId;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Join the revolt");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return true;
default:
return false;
}
}
private void leaveGame() {
// Get preferences
final SharedPreferences prefs = getActivity().getSharedPreferences(MainActivity.SHARED_PREFS_NAME, 0);
// Alert other players that we've left the game
ParsePush pushDrop = new ParsePush();
pushDrop.setChannel("a"+prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, ""));
pushDrop.setMessage(prefs.getString(MainActivity.PREF_USER_NAME, "") + " has left the game.");
// Send the push and unsubscribe them from push notifications
pushDrop.sendInBackground(new SendCallback() {
@Override
public void done(ParseException e) {
PushService.unsubscribe(getActivity(), prefs.getString("a" + MainActivity.PREF_CURRENT_GAME_ID, ""));
}
});
// Execute task
new LeaveGameTask(getActivity()).execute();
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
assert (mMemoryCache != null);
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
assert (mMemoryCache != null);
return mMemoryCache.get(key);
}
public void initMemoryCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 15;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
}
public void clearCache() {
mMemoryCache.evictAll();
}
public Player getWhoIsIt(List<Player> list) {
Log.d("debug","getWhoIsIt called");
Player it = null;
for (Player p : list) {
if (p.getIsIt()) {
Log.d("tylor", "It: " + p.getUserName());
it = p;
}
Log.d("tylor", p.getUserName());
}
return it;
}
@Override
public void onDatabaseRefresh() {
Log.d("Lobby", "Database has refreshed!!");
// Get the players in the current game
final List<Player> players = db.getPlayersInCurrentGame();
// Create the adapter
final PlayerListAdapter adapt = new PlayerListAdapter(getActivity(), R.layout.player_list_item, R.id.name, players, GameLobbyFragment.this);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
theList.setAdapter(adapt);
}
});
// Get the player's bitmap
final Player it = getWhoIsIt(players);
final Bitmap b = it.getGravitar((int) getActivity().getResources().getDimension(R.dimen.itSize));
// Post to UI
handler.post(new Runnable() {
public void run() {
iv.setImageBitmap(b);
tv_it.setText(it.getUserName());
}
});
}
}
|
package com.emc.mongoose.api.metrics;
import com.codahale.metrics.Clock;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.SlidingTimeWindowArrayReservoir;
import com.codahale.metrics.SlidingWindowReservoir;
import com.codahale.metrics.UniformReservoir;
import com.codahale.metrics.UniformSnapshot;
import com.github.akurilov.commons.system.SizeInBytes;
import com.emc.mongoose.api.model.io.IoType;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.IntSupplier;
public final class BasicMetricsContext
implements Comparable<BasicMetricsContext>, MetricsContext {
private final Clock clock = new ResumableUserTimeClock();
private final Histogram reqDuration, respLatency, actualConcurrency;
private volatile com.codahale.metrics.Snapshot
reqDurSnapshot, respLatSnapshot, actualConcurrencySnapshot;
private final LongAdder reqDurationSum, respLatencySum;
private volatile long lastDurationSum = 0, lastLatencySum = 0;
private final CustomMeter throughputSuccess, throughputFail, reqBytes;
private final long ts;
private volatile long tsStart = -1, prevElapsedTime = 0;
private final String stepId;
private final IoType ioType;
private final IntSupplier actualConcurrencyGauge;
private final int driverCount;
private final int concurrency;
private final int thresholdConcurrency;
private final SizeInBytes itemDataSize;
private final boolean stdOutColorFlag;
private final boolean avgPersistFlag;
private final boolean sumPersistFlag;
private final boolean perfDbResultsFileFlag;
private final long outputPeriodMillis;
private volatile long lastOutputTs = 0;
private volatile Snapshot lastSnapshot = null;
private volatile MetricsListener metricsListener = null;
private volatile MetricsContext thresholdMetricsCtx = null;
private volatile boolean thresholdStateExitedFlag = false;
public BasicMetricsContext(
final String stepId, final IoType ioType, final IntSupplier actualConcurrencyGauge,
final int driverCount, final int concurrency, final int thresholdConcurrency,
final SizeInBytes itemDataSize, final int updateIntervalSec, final boolean stdOutColorFlag,
final boolean avgPersistFlag, final boolean sumPersistFlag,
final boolean perfDbResultsFileFlag
) {
this.stepId = stepId;
this.ioType = ioType;
this.actualConcurrencyGauge = actualConcurrencyGauge;
this.driverCount = driverCount;
this.concurrency = concurrency;
this.thresholdConcurrency = thresholdConcurrency > 0 ?
thresholdConcurrency : Integer.MAX_VALUE;
this.itemDataSize = itemDataSize;
this.stdOutColorFlag = stdOutColorFlag;
this.avgPersistFlag = avgPersistFlag;
this.sumPersistFlag = sumPersistFlag;
this.perfDbResultsFileFlag = perfDbResultsFileFlag;
this.outputPeriodMillis = TimeUnit.SECONDS.toMillis(updateIntervalSec);
respLatency = new Histogram(new SlidingWindowReservoir(DEFAULT_RESERVOIR_SIZE));
respLatSnapshot = respLatency.getSnapshot();
respLatencySum = new LongAdder();
reqDuration = new Histogram(new SlidingWindowReservoir(DEFAULT_RESERVOIR_SIZE));
reqDurSnapshot = reqDuration.getSnapshot();
actualConcurrency = new Histogram(
outputPeriodMillis > 0 ?
new SlidingTimeWindowArrayReservoir(
outputPeriodMillis, TimeUnit.MILLISECONDS, clock
) :
new UniformReservoir(DEFAULT_RESERVOIR_SIZE)
);
actualConcurrencySnapshot = actualConcurrency.getSnapshot();
reqDurationSum = new LongAdder();
throughputSuccess = new CustomMeter(clock, updateIntervalSec);
throughputFail = new CustomMeter(clock, updateIntervalSec);
reqBytes = new CustomMeter(clock, updateIntervalSec);
ts = System.nanoTime();
}
@Override
public final void start() {
tsStart = System.currentTimeMillis();
throughputSuccess.resetStartTime();
throughputFail.resetStartTime();
reqBytes.resetStartTime();
}
@Override
public final boolean isStarted() {
return tsStart > -1;
}
@Override
public final void markElapsedTime(final long millis) {
prevElapsedTime = millis;
}
@Override
public void close()
throws IOException {
prevElapsedTime = System.currentTimeMillis() - tsStart;
tsStart = -1;
lastSnapshot = null;
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.close();
thresholdMetricsCtx = null;
}
}
@Override
public final void markSucc(final long size, final long duration, final long latency) {
throughputSuccess.mark();
reqBytes.mark(size);
if(latency > 0 && duration > latency) {
reqDuration.update(duration);
respLatency.update(latency);
reqDurationSum.add(duration);
respLatencySum.add(latency);
}
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markSucc(size, duration, latency);
}
}
@Override
public final void markPartSucc(final long size, final long duration, final long latency) {
reqBytes.mark(size);
if(latency > 0 && duration > latency) {
reqDuration.update(duration);
respLatency.update(latency);
reqDurationSum.add(duration);
respLatencySum.add(latency);
}
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markPartSucc(size, duration, latency);
}
}
@Override
public final void markSucc(
final long count, final long bytes, final long durationValues[], final long latencyValues[]
) {
throughputSuccess.mark(count);
reqBytes.mark(bytes);
for(final long duration : durationValues) {
reqDuration.update(duration);
reqDurationSum.add(duration);
}
for(final long latency : latencyValues) {
respLatency.update(latency);
respLatencySum.add(latency);
}
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markSucc(count, bytes, durationValues, latencyValues);
}
}
@Override
public final void markPartSucc(
final long bytes, final long durationValues[], final long latencyValues[]
) {
reqBytes.mark(bytes);
for(final long duration : durationValues) {
reqDuration.update(duration);
reqDurationSum.add(duration);
}
for(final long latency : latencyValues) {
respLatency.update(latency);
respLatencySum.add(latency);
}
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markPartSucc(bytes, durationValues, latencyValues);
}
}
@Override
public final void markFail() {
throughputFail.mark();
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markFail();
}
}
@Override
public final void markFail(final long count) {
throughputFail.mark(count);
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.markFail(count);
}
}
@Override
public final String getStepId() {
return stepId;
}
@Override
public final IoType getIoType() {
return ioType;
}
@Override
public final int getDriverCount() {
return driverCount;
}
@Override
public final int getConcurrency() {
return concurrency;
}
@Override
public final int getConcurrencyThreshold() {
return thresholdConcurrency;
}
@Override
public final SizeInBytes getItemDataSize() {
return itemDataSize;
}
@Override
public final boolean getStdOutColorFlag() {
return stdOutColorFlag;
}
@Override
public final boolean getAvgPersistFlag() {
return avgPersistFlag;
}
@Override
public final boolean getSumPersistFlag() {
return sumPersistFlag;
}
@Override
public final boolean getPerfDbResultsFileFlag() {
return perfDbResultsFileFlag;
}
@Override
public final long getOutputPeriodMillis() {
return outputPeriodMillis;
}
@Override
public final long getLastOutputTs() {
return lastOutputTs;
}
@Override
public final void setLastOutputTs(final long ts) {
lastOutputTs = ts;
}
@Override
public final void refreshLastSnapshot() {
final long currentTimeMillis = System.currentTimeMillis();
final long currElapsedTime = tsStart > 0 ? currentTimeMillis - tsStart : 0;
final int actualConcurrencyLast = actualConcurrencyGauge.getAsInt();
if(currentTimeMillis - lastOutputTs > DEFAULT_DISTRIBUTION_SNAPSHOT_UPDATE_PERIOD_MILLIS) {
if(lastDurationSum != reqDurationSum.sum()) {
lastDurationSum = reqDurationSum.sum();
reqDurSnapshot = reqDuration.getSnapshot();
}
if(lastLatencySum != respLatencySum.sum()) {
lastLatencySum = respLatencySum.sum();
respLatSnapshot = respLatency.getSnapshot();
}
actualConcurrency.update(actualConcurrencyLast);
actualConcurrencySnapshot = actualConcurrency.getSnapshot();
}
lastSnapshot = new BasicSnapshot(
throughputSuccess.getCount(), throughputSuccess.getLastRate(),
throughputFail.getCount(), throughputFail.getLastRate(), reqBytes.getCount(),
reqBytes.getLastRate(), tsStart, prevElapsedTime + currElapsedTime,
actualConcurrencyLast, actualConcurrencySnapshot.getMean(),
lastDurationSum, lastLatencySum, reqDurSnapshot, respLatSnapshot
);
if(metricsListener != null) {
metricsListener.notify(lastSnapshot);
}
if(thresholdMetricsCtx != null) {
thresholdMetricsCtx.refreshLastSnapshot();
}
}
@Override
public final Snapshot getLastSnapshot() {
if(lastSnapshot == null) {
refreshLastSnapshot();
}
return lastSnapshot;
}
@Override
public final void setMetricsListener(final MetricsListener metricsListener) {
this.metricsListener = metricsListener;
}
@Override
public final boolean isThresholdStateEntered() {
return thresholdMetricsCtx != null && thresholdMetricsCtx.isStarted();
}
@Override
public final void enterThresholdState()
throws IllegalStateException {
if(thresholdMetricsCtx != null) {
throw new IllegalStateException("Nested metrics context already exists");
}
thresholdMetricsCtx = new BasicMetricsContext(
stepId, ioType, actualConcurrencyGauge, driverCount, concurrency, 0, itemDataSize,
(int) TimeUnit.MILLISECONDS.toSeconds(outputPeriodMillis), stdOutColorFlag,
avgPersistFlag, sumPersistFlag, perfDbResultsFileFlag
);
thresholdMetricsCtx.start();
}
@Override
public final MetricsContext getThresholdMetrics()
throws IllegalStateException {
if(thresholdMetricsCtx == null) {
throw new IllegalStateException("Nested metrics context is not exist");
}
return thresholdMetricsCtx;
}
@Override
public final boolean isThresholdStateExited() {
return thresholdStateExitedFlag;
}
@Override
public final void exitThresholdState()
throws IllegalStateException {
if(thresholdMetricsCtx == null) {
throw new IllegalStateException("Threshold state was not entered");
}
try {
thresholdMetricsCtx.close();
} catch(final IOException e) {
e.printStackTrace(System.err);
}
thresholdStateExitedFlag = true;
}
@Override
public final int compareTo(final BasicMetricsContext other) {
return Long.compare(ts, other.ts);
}
@Override
public final String toString() {
return "MetricsContext(" + ioType.name() + '-' + concurrency + 'x' + driverCount + '@' +
stepId + ")";
}
protected static final class BasicSnapshot
implements Snapshot {
private final long countSucc;
private final double succRateLast;
private final long countFail;
private final double failRateLast;
private final long countByte;
private final double byteRateLast;
private final long durValues[];
private transient com.codahale.metrics.Snapshot durSnapshot = null;
private final long latValues[];
private transient com.codahale.metrics.Snapshot latSnapshot = null;
private final long sumDur;
private final long sumLat;
private final long startTime;
private final long elapsedTime;
private final int actualConcurrencyLast;
private final double actualConcurrencyMean;
public BasicSnapshot(
final long countSucc, final double succRateLast, final long countFail,
final double failRateLast, final long countByte, final double byteRateLast,
final long startTime, final long elapsedTime, final int actualConcurrencyLast,
final double actualConcurrencyMean, final long sumDur, final long sumLat,
final com.codahale.metrics.Snapshot durSnapshot,
final com.codahale.metrics.Snapshot latSnapshot
) {
this.countSucc = countSucc;
this.succRateLast = succRateLast;
this.countFail = countFail;
this.failRateLast = failRateLast;
this.countByte = countByte;
this.byteRateLast = byteRateLast;
this.sumDur = sumDur;
this.sumLat = sumLat;
this.startTime = startTime;
this.elapsedTime = elapsedTime;
this.actualConcurrencyLast = actualConcurrencyLast;
this.actualConcurrencyMean = actualConcurrencyMean;
this.durSnapshot = durSnapshot;
this.durValues = durSnapshot.getValues();
this.latSnapshot = latSnapshot;
this.latValues = latSnapshot.getValues();
}
@Override
public final long getSuccCount() {
return countSucc;
}
@Override
public final double getSuccRateMean() {
return elapsedTime == 0 ? 0 : 1000.0 * countSucc / elapsedTime;
}
@Override
public final double getSuccRateLast() {
return succRateLast;
}
@Override
public final long getFailCount() {
return countFail;
}
@Override
public final double getFailRateMean() {
return elapsedTime == 0 ? 0 : 1000.0 * countFail / elapsedTime;
}
@Override
public final double getFailRateLast() {
return failRateLast;
}
@Override
public final long getByteCount() {
return countByte;
}
@Override
public final double getByteRateMean() {
return elapsedTime == 0 ? 0 : 1000.0 * countByte / elapsedTime;
}
@Override
public final double getByteRateLast() {
return byteRateLast;
}
@Override
public final long getDurationMin() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return durSnapshot.getMin();
}
@Override
public final long getDurationLoQ() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return (long) durSnapshot.getValue(0.25);
}
@Override
public final long getDurationMed() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return (long) durSnapshot.getValue(0.5);
}
@Override
public final long getDurationHiQ() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return (long) durSnapshot.getValue(0.75);
}
@Override
public final long getDurationMax() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return durSnapshot.getMax();
}
@Override
public final long getDurationSum() {
return sumDur;
}
@Override
public final double getDurationMean() {
if(durSnapshot == null) {
durSnapshot = new UniformSnapshot(durValues);
}
return durSnapshot.getMean();
}
@Override
public final long getLatencyMin() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return latSnapshot.getMin();
}
@Override
public final long getLatencyLoQ() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return (long) latSnapshot.getValue(0.25);
}
@Override
public final long getLatencyMed() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return (long) latSnapshot.getValue(0.5);
}
@Override
public final long getLatencyHiQ() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return (long) latSnapshot.getValue(0.75);
}
@Override
public final long getLatencyMax() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return latSnapshot.getMax();
}
@Override
public final long getLatencySum() {
return sumDur;
}
@Override
public final double getLatencyMean() {
if(latSnapshot == null) {
latSnapshot = new UniformSnapshot(latValues);
}
return latSnapshot.getMean();
}
@Override
public final long getStartTimeMillis() {
return startTime;
}
@Override
public final long getElapsedTimeMillis() {
return elapsedTime;
}
@Override
public final int getActualConcurrencyLast() {
return actualConcurrencyLast;
}
@Override
public final double getActualConcurrencyMean() {
return actualConcurrencyMean;
}
}
}
|
package tlc2.tool.fp;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;
public abstract class FPSetTest extends AbstractFPSetTest {
private long previousTimestamp = System.currentTimeMillis();
private long previousSize;
private final DecimalFormat df = new DecimalFormat("
public void testSimpleFill() throws IOException {
long freeMemory = getFreeMemoryInBytes();
final FPSet fpSet = getFPSet(freeMemory);
fpSet.init(1, tmpdir, filename);
long fp = 1L;
assertFalse(fpSet.put(fp));
assertTrue(fpSet.contains(fp++));
assertFalse(fpSet.put(fp));
assertTrue(fpSet.contains(fp++));
assertFalse(fpSet.put(fp));
assertTrue(fpSet.contains(fp++));
assertFalse(fpSet.put(fp));
assertTrue(fpSet.contains(fp++));
}
/**
* Test filling a {@link FPSet} with max int + 1 random
* @throws IOException
*/
public void testMaxFPSetSizeRnd() throws IOException {
Random rnd = new Random(15041980L);
// amount to ~514 (mb) with 4gb system mem
long freeMemory = getFreeMemoryInBytes();
final FPSet fpSet = getFPSet(freeMemory);
fpSet.init(1, tmpdir, filename);
if (fpSet instanceof FPSetStatistic) {
FPSetStatistic fpSetStats = (FPSetStatistic) fpSet;
System.out.println("Maximum FPSet bucket count is: " + fpSetStats.getMaxTblCnt());
}
long predecessor = 0L;
// fill with max int + 1
final long l = Integer.MAX_VALUE + 2L;
for (long i = 1; i < l; i++) {
// make sure set still contains predecessor
if (predecessor != 0L) {
assertTrue(fpSet.contains(predecessor));
}
predecessor = rnd.nextLong();
assertFalse(fpSet.put(predecessor));
long currentSize = fpSet.size();
assertTrue(i == currentSize);
printInsertionSpeed(currentSize);
}
// try creating a check point
fpSet.beginChkpt();
fpSet.commitChkpt();
assertEquals(l, fpSet.size());
}
// insertion speed
private void printInsertionSpeed(final long currentSize) {
final long currentTimestamp = System.currentTimeMillis();
// print every minute
final double factor = (currentTimestamp - previousTimestamp) / 60000d;
if (factor >= 1d) {
double insertions = (currentSize - previousSize) * factor;
System.out.println(df.format(insertions) + " insertions/min");
previousTimestamp = currentTimestamp;
previousSize = currentSize;
}
}
/**
* Test filling a {@link FPSet} with max int + 1
* @throws IOException
*/
public void testMaxFPSetSize() throws IOException {
final FPSet fpSet = getFPSet(getFreeMemoryInBytes());
fpSet.init(1, tmpdir, filename);
long counter = 0;
// fill with max int + 1
final long l = Integer.MAX_VALUE + 2L;
// choose value in the interval [-l/2, l/2]
for (long i = (l/2) * -1; i < l; i++) {
long value = -1;
if (i % 2 != 0) {
value = l - i;
} else {
value = i;
}
assertFalse(fpSet.put(value));
long currentSize = fpSet.size();
assertTrue(++counter == currentSize);
printInsertionSpeed(currentSize);
}
// try creating a check point
fpSet.beginChkpt();
fpSet.commitChkpt();
assertEquals(l, fpSet.size());
}
}
|
package org.jgrapes.http;
import java.io.Serializable;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Implements the {@link Session} interface using a {@link ConcurrentHashMap}.
*/
@SuppressWarnings("serial")
public class InMemorySession
extends ConcurrentHashMap<Serializable, Serializable>
implements Session {
@SuppressWarnings("PMD.ShortVariable")
private final String id;
private final Instant createdAt;
private Instant lastUsedAt;
private final Map<?,?> transientData = new ConcurrentHashMap<>();
/**
* Create a new session.
*/
@SuppressWarnings("PMD.ShortVariable")
public InMemorySession(String id) {
this.id = id;
createdAt = Instant.now();
lastUsedAt = createdAt;
}
/**
* Returns the session id.
*
* @return the id
*/
@SuppressWarnings("PMD.ShortMethodName")
public String id() {
return id;
}
/**
* Returns the creation time stamp.
*
* @return the creation time stamp
*/
public Instant createdAt() {
return createdAt;
}
/**
* Returns the last used (referenced in request) time stamp.
*
* @return the last used timestamp
*/
public Instant lastUsedAt() {
return lastUsedAt;
}
/**
* Updates the last used time stamp.
*/
public void updateLastUsedAt() {
this.lastUsedAt = Instant.now();
}
/* (non-Javadoc)
* @see org.jgrapes.http.Session#transientData()
*/
@Override
public Map<?, ?> transientData() {
return transientData;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
InMemorySession other = (InMemorySession) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder(50);
builder.append("InMemorySession [");
if (id != null) {
builder.append("id=");
builder.append(id);
builder.append(", ");
}
if (createdAt != null) {
builder.append("createdAt=");
builder.append(createdAt);
builder.append(", ");
}
if (lastUsedAt != null) {
builder.append("lastUsedAt=");
builder.append(lastUsedAt);
}
builder.append(']');
return builder.toString();
}
}
|
package org.spoofax.jsglr;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import aterm.AFun;
import aterm.ATerm;
public class Disambiguator {
private static final int FILTER_DRAW = 1;
private static final int FILTER_LEFT_WINS = 2;
private static final int FILTER_RIGHT_WINS = 3;
SGLR parser;
AmbiguityManager ambiguityManager;
ParseTable parseTable;
Map<AmbKey, IParseNode> resolvedTable;
Disambiguator(SGLR parser) {
this.parser = parser;
resolvedTable = new HashMap<AmbKey, IParseNode>();
}
private void initializeFromParser() {
parseTable = parser.getParseTable();
ambiguityManager = parser.getAmbiguityManager();
}
protected ATerm applyFilters(IParseNode root, String sort, int inputLength) throws SGLRException {
if(SGLR.isDebugging()) {
Tools.debug("applyFilters()");
}
initializeFromParser();
IParseNode t = root;
t = applyTopSortFilter(sort, t);
t = applyCycleDetectFilter(t);
t = applyOtherFilters(t);
return convertToATerm(t);
}
private ATerm convertToATerm(IParseNode t) {
if (SGLR.isDebugging()) {
Tools.debug("convertToATerm: ", t);
}
ambiguityManager.resetAmbiguityCount();
ATerm r = yieldTree(t);
logStatus();
int ambCount = ambiguityManager.getAmbiguitiesCount();
if (SGLR.isDebugging()) {
Tools.debug("yield: ", r);
}
final AFun parseTreeAfun = parseTable.getFactory().makeAFun("parsetree", 2, false);
return parseTable.getFactory().makeAppl(parseTreeAfun, r,
parseTable.getFactory().makeInt(ambCount));
}
private IParseNode applyOtherFilters(IParseNode t) throws FilterException {
if (SGLR.isDebugging()) {
Tools.debug("applyOtherFilters() - ", t);
}
if (parser.isFilteringEnabled()) {
t = disambiguate(t);
}
return t;
}
private IParseNode applyCycleDetectFilter(IParseNode t) throws FilterException {
if (SGLR.isDebugging()) {
Tools.debug("applyCycleDetectFilter() - ", t);
}
if (parser.isDetectCyclesEnabled()) {
if (ambiguityManager.getMaxNumberOfAmbiguities() > 0) {
if (isCyclicTerm(t)) {
throw new FilterException("Term is cyclic");
}
}
}
return t;
}
private IParseNode applyTopSortFilter(String sort, IParseNode t) throws SGLRException {
if (SGLR.isDebugging()) {
Tools.debug("applyTopSortFilter() - ", t);
}
if (sort != null) {
t = selectOnTopSort();
if (t == null) {
throw new FilterException("Desired top sort not found");
}
}
return t;
}
private void logStatus() {
Tools.logger("Number of rejects: ", parser.getRejectCount());
Tools.logger("Number of reductions: ", parser.getReductionCount());
Tools.logger("Number of ambiguities: ", ambiguityManager.getMaxNumberOfAmbiguities());
Tools.logger("Number of calls to Amb: ", ambiguityManager.getAmbiguityCallsCount());
Tools.logger("Count Eagerness Comparisons: ", ambiguityManager.getEagernessComparisonCount(), " / ", ambiguityManager.getEagernessSucceededCount());
Tools.logger("Number of Injection Counts: ", ambiguityManager.getInjectionCount());
}
private ATerm yieldTree(IParseNode t) {
return t.toParseTree(parser.getParseTable());
}
private IParseNode disambiguate(IParseNode t) throws FilterException {
// SG_FilterTree
ambiguityManager.resetClustersVisitedCount();
return filterTree(t, false);
}
private IParseNode filterTree(IParseNode t, boolean inAmbiguityCluster) throws FilterException {
// SG_FilterTreeRecursive
if (SGLR.isDebugging()) {
Tools.debug("filterTree(node) - ", t);
}
if (t instanceof Amb) {
if (!inAmbiguityCluster) {
List<IParseNode> ambs = ((Amb)t).getAlternatives();
t = filterAmbiguities(ambs);
} else {
throw new NotImplementedException();
}
} else if(t instanceof ParseNode) {
ParseNode node = (ParseNode) t;
List<IParseNode> args = node.getKids();
List<IParseNode> newArgs = filterTree(args, false);
if (isRejectFilterEnabled() && parseTable.hasRejects()) {
if (hasRejectProd(t))
throw new FilterException("");
}
t = new ParseNode(node.label, newArgs);
} else if(t instanceof ParseProductionNode) {
// leaf node -- do thing (cannot be any ambiguities here)
return t;
} else {
throw new FatalException();
}
if (parser.isAssociativityFilterEnabled()) {
return applyAssociativityPriorityFilter(t);
} else {
return t;
}
}
private boolean isRejectFilterEnabled() {
return parser.isRejectFilterEnabled();
}
private List<IParseNode> filterTree(List<IParseNode> args, boolean inAmbiguityCluster) throws FilterException {
if(SGLR.isDebugging()) {
Tools.debug("filterTree(<nodes>) - ", args);
}
List<IParseNode> newArgs = new LinkedList<IParseNode>();
boolean changed = false;
for (IParseNode n : args) {
IParseNode filtered = filterTree(n, false);
changed = !filtered.equals(n) || changed;
newArgs.add(filtered);
}
/*
* FIXME Shouldn't we do some filtering here?
if (!changed) {
Tools.debug("Dropping: ", args);
newArgs = getEmptyList();
}*/
if (parser.isFilteringEnabled()) {
List<IParseNode> filtered = new ArrayList<IParseNode>();
for (IParseNode n : newArgs)
filtered.add(applyAssociativityPriorityFilter(n));
return filtered;
} else {
return newArgs;
}
}
private IParseNode applyAssociativityPriorityFilter(IParseNode t) throws FilterException {
// SG_Associativity_Priority_Filter(pt, t)
if(SGLR.isDebugging()) {
Tools.debug("applyAssociativityPriorityFilter() - ", t);
}
IParseNode r = t;
if (t instanceof ParseNode) {
Label prodLabel = getProductionLabel(t);
ParseNode n = (ParseNode) t;
if (parser.isAssociativityFilterEnabled()) {
if (prodLabel.isLeftAssociative()) {
r = applyLeftAssociativeFilter(n, prodLabel);
} else if (prodLabel.isRightAssociative()) {
r = applyRightAssociativeFilter(n, prodLabel);
}
}
if (parser.isPriorityFilterEnabled()) {
Tools.debug(" - about to look up : ", prodLabel.labelNumber);
if (!lookupGtrPriority(prodLabel).isEmpty()) {
Tools.debug(" - found");
return applyPriorityFilter((ParseNode) r, prodLabel);
}
Tools.debug(" - not found");
}
}
return r;
}
private IParseNode applyRightAssociativeFilter(ParseNode t, Label prodLabel) throws FilterException {
// SG_Right_Associativity_Filter(t, prodl)
// - almost ok
if(SGLR.isDebugging()) {
Tools.debug("applyRightAssociativeFilter() - ", t);
}
List<IParseNode> newAmbiguities = new LinkedList<IParseNode>();
List<IParseNode> kids = t.getKids();
IParseNode firstKid = kids.get(0);
if(firstKid instanceof Amb) {
List<IParseNode> ambs = ((Amb)firstKid).getAlternatives();
List<IParseNode> restKids = kids.subList(1, t.kids.size() - 1);
for(IParseNode amb : ambs) {
if(((ParseNode)amb).getLabel() != prodLabel.labelNumber) {
newAmbiguities.add(amb);
}
}
// FIXME is this correct?
if(!newAmbiguities.isEmpty()) {
if(newAmbiguities.size() > 1)
firstKid = new Amb(newAmbiguities);
else
firstKid = newAmbiguities.get(0);
restKids.add(firstKid);
} else {
throw new FilterException("");
}
// FIXME is this correct?
return new ParseNode(t.label, restKids);
} else if(firstKid instanceof ParseNode) {
if(((ParseNode)firstKid).getLabel() == prodLabel.labelNumber)
throw new FilterException("");
}
return t;
}
private IParseNode applyPriorityFilter(ParseNode t, Label prodLabel) throws FilterException {
// SG_Priority_Filter
// - fishy
if(SGLR.isDebugging()) {
Tools.debug("applyPriorityFilter() - ", t);
}
List<IParseNode> newAmbiguities = new ArrayList<IParseNode>();
List<IParseNode> kids = t.getKids();
List<IParseNode> newKids = new LinkedList<IParseNode>();
int l0 = prodLabel.labelNumber;
for (IParseNode alt : kids) {
IParseNode newKid = alt;
IParseNode injection = jumpOverInjections(alt);
if (injection instanceof Amb) {
List<IParseNode> ambs = ((Amb) injection).getAlternatives();
newAmbiguities.clear();
for (IParseNode amb : ambs) {
IParseNode injAmb = jumpOverInjections(amb);
if (injAmb instanceof ParseNode) {
Label label = getProductionLabel(t);
if(hasGreaterPriority(l0, label.labelNumber)) {
newAmbiguities.add(amb);
}
}
}
if(!newAmbiguities.isEmpty()) {
IParseNode n = null;
if(newAmbiguities.size() > 1) {
n = new Amb(newAmbiguities);
} else {
n = newAmbiguities.get(0);
}
newKid = replaceUnderInjections(alt, injection, n);
} else {
throw new FilterException("");
}
} else if (injection instanceof ParseNode) {
int l1 = ((ParseNode) injection).label;
if (hasGreaterPriority(l0, l1)) {
throw new FilterException("");
}
}
newKids.add(newKid);
}
return new ParseNode(t.label, newKids);
}
private IParseNode replaceUnderInjections(IParseNode alt, IParseNode injection, IParseNode n) {
// SG_Replace_Under_Injections
// - not ok
throw new NotImplementedException();
}
private IParseNode jumpOverInjections(IParseNode t) {
if(SGLR.isDebugging()) {
Tools.debug("jumpOverInjections() - ", t);
}
if (t instanceof ParseNode) {
int prod = ((ParseNode) t).label;
ParseNode n = (ParseNode)t;
while (isUserDefinedLabel(prod)) {
List<IParseNode> kids = n.getKids();
IParseNode x = kids.get(0);
if(x instanceof ParseNode) {
n = (ParseNode)x;
prod = n.label;
} else {
return x;
}
}
}
return t;
}
private boolean isUserDefinedLabel(int prod) {
Label l = parseTable.lookupInjection(prod);
if(l == null)
return false;
return l.isInjection();
}
private boolean hasGreaterPriority(int l0, int l1) {
List<Label> prios = lookupGtrPriority(parseTable.getLabel(l0));
return prios.contains(parseTable.getLabel(l1));
}
private List<Label> lookupGtrPriority(Label prodLabel) {
return parseTable.getPriorities(prodLabel);
}
private IParseNode applyLeftAssociativeFilter(ParseNode t, Label prodLabel) throws FilterException {
// SG_Right_Associativity_Filter()
if(SGLR.isDebugging()) {
Tools.debug("applyLeftAssociativeFilter() - ", t);
}
List<IParseNode> newAmbiguities = new ArrayList<IParseNode>();
List<IParseNode> kids = t.getKids();
IParseNode last = kids.get(kids.size() - 1);
if (last instanceof Amb) {
List<IParseNode> rest = new ArrayList<IParseNode>();
rest.addAll(kids);
rest.remove(rest.size() - 1);
List<IParseNode> ambs = ((Amb) last).getAlternatives();
for (IParseNode amb : ambs) {
Label other = parseTable.getLabel(((ParseNode) amb).getLabel());
if (!prodLabel.equals(other)) {
newAmbiguities.add(amb);
}
}
if (!newAmbiguities.isEmpty()) {
if (newAmbiguities.size() > 1) {
last = new Amb(newAmbiguities);
} else {
last = newAmbiguities.get(0);
}
rest.add(last);
return new Amb(rest);
} else {
throw new FilterException("");
}
} else if (last instanceof ParseNode) {
Label other = parseTable.getLabel(((ParseNode) last).getLabel());
if (prodLabel.equals(other)) {
throw new FilterException("");
}
}
return t;
}
private Label getProductionLabel(IParseNode t) {
if (t instanceof ParseNode) {
return parseTable.getLabel(((ParseNode) t).getLabel());
} else if (t instanceof ParseProductionNode) {
return parseTable.getLabel(((ParseProductionNode) t).getProduction());
}
return null;
}
private boolean hasRejectProd(IParseNode t) {
return t instanceof ParseReject;
}
private IParseNode filterAmbiguities(List<IParseNode> ambs) throws FilterException {
// SG_FilterAmb
if(SGLR.isDebugging()) {
Tools.debug("filterAmbiguities() - [", ambs.size(), "]");
}
List<IParseNode> newAmbiguities = new LinkedList<IParseNode>();
for (IParseNode amb : ambs) {
newAmbiguities.add(filterTree(amb, true));
}
if (newAmbiguities.size() > 1) {
/* Handle ambiguities inside this ambiguity cluster */
List<IParseNode> oldAmbiguities = new LinkedList<IParseNode>();
oldAmbiguities.addAll(newAmbiguities);
for (IParseNode amb : oldAmbiguities) {
if (newAmbiguities.remove(amb)) {
newAmbiguities = filterAmbiguityList(newAmbiguities, amb);
}
}
}
if (newAmbiguities.isEmpty())
throw new FilterException("");
if (newAmbiguities.size() == 1)
return newAmbiguities.get(0);
return new Amb(newAmbiguities);
}
private List<IParseNode> filterAmbiguityList(List<IParseNode> ambiguities, IParseNode t) {
// SG_FilterAmbList
boolean keepT = true;
List<IParseNode> r = new LinkedList<IParseNode>();
if (ambiguities.isEmpty()) {
r.add(t);
return r;
}
for (IParseNode amb : ambiguities) {
switch (filter(t, amb)) {
case FILTER_DRAW:
r.add(amb);
break;
case FILTER_RIGHT_WINS:
r.add(amb);
keepT = false;
}
}
if (keepT) {
r.add(t);
}
return r;
}
private int filter(IParseNode left, IParseNode right) {
// SG_Filter(t0, t1)
if(SGLR.isDebugging()) {
Tools.debug("filter()");
}
if (left.equals(right)) {
return FILTER_LEFT_WINS;
}
// FIXME priority filter == preferences?
if (parser.isPriorityFilterEnabled() && parseTable.hasPriorities()) {
int r = filterOnIndirectPrefers(left, right);
if (r != FILTER_DRAW)
return r;
}
if (parser.isPriorityFilterEnabled() && parseTable.hasPriorities()) {
int r = filterOnPreferCount(left, right);
if (r != FILTER_DRAW)
return r;
}
if (parser.isInjectionCountFilterEnabled()) {
int r = filterOnInjectionCount(left, right);
if (r != FILTER_DRAW)
return r;
}
return FILTER_DRAW;
}
private int filterOnInjectionCount(IParseNode left, IParseNode right) {
if(SGLR.isDebugging()) {
Tools.debug("filterOnInjectionCount()");
}
ambiguityManager.increaseInjectionCount();
int leftInjectionCount = countAllInjections(left);
int rightInjectionCount = countAllInjections(right);
if (leftInjectionCount != rightInjectionCount) {
ambiguityManager.increaseInjectionFilterSucceededCount();
}
if (leftInjectionCount > rightInjectionCount) {
return FILTER_RIGHT_WINS;
} else if (rightInjectionCount > leftInjectionCount) {
return FILTER_LEFT_WINS;
}
return FILTER_DRAW;
}
private int countAllInjections(IParseNode t) {
// SG_CountAllInjectionsInTree
if (t instanceof Amb) {
// Trick from forest.c
return countAllInjections(((Amb) t).getAlternatives().get(0));
} else if (t instanceof ParseNode) {
int c = getProductionLabel(t).isInjection() ? 1 : 0;
return c + countAllInjections(((ParseNode) t).getKids());
}
return 0;
}
private int countAllInjections(List<IParseNode> ls) {
// SG_CountAllInjectionsInTree
int r = 0;
for (IParseNode n : ls)
r += countAllInjections(n);
return r;
}
private int filterOnPreferCount(IParseNode left, IParseNode right) {
if(SGLR.isDebugging()) {
Tools.debug("filterOnPreferCount()");
}
ambiguityManager.increaseEagernessFilterCalledCount();
int r = FILTER_DRAW;
if (parseTable.hasPrefers() || parseTable.hasAvoids()) {
int leftPreferCount = countPrefers(left);
int rightPreferCount = countPrefers(right);
int leftAvoidCount = countAvoids(left);
int rightAvoidCount = countAvoids(right);
if ((leftPreferCount > rightPreferCount && leftAvoidCount <= rightAvoidCount)
|| (leftPreferCount == rightPreferCount && leftAvoidCount < rightAvoidCount)) {
Tools.logger("Eagerness priority: ", left, " > ", right);
r = FILTER_LEFT_WINS;
}
if ((rightPreferCount > leftPreferCount && rightAvoidCount <= leftAvoidCount)
|| (rightPreferCount == leftPreferCount && rightAvoidCount < leftPreferCount)) {
if (r != FILTER_DRAW) {
Tools.logger("Symmetric eagerness priority: ", left, " == ", right);
r = FILTER_DRAW;
} else {
Tools.logger("Eagerness priority: ", right, " > ", left);
r = FILTER_RIGHT_WINS;
}
}
}
if (r != FILTER_DRAW) {
ambiguityManager.increaseEagernessFilterSucceededCount();
}
return r;
}
private int countPrefers(IParseNode t) {
// SG_CountPrefersInTree
if (t instanceof Amb) {
return countPrefers(((Amb) t).getAlternatives());
} else if (t instanceof ParseNode) {
int type = getProductionType(t);
if (type == ProductionAttributes.PREFER)
return 1;
else if (type == ProductionAttributes.AVOID)
return 0;
return countPrefers(((ParseNode) t).getKids());
}
return 0;
}
private int countPrefers(List<IParseNode> ls) {
// SG_CountPrefersInTree
int r = 0;
for (IParseNode n : ls)
r += countPrefers(n);
return r;
}
private int countAvoids(IParseNode t) {
// SG_CountAvoidsInTree
if (t instanceof Amb) {
return countAvoids(((Amb) t).getAlternatives());
} else if (t instanceof ParseNode) {
int type = getProductionType(t);
if (type == ProductionAttributes.PREFER)
return 0;
else if (type == ProductionAttributes.AVOID)
return 1;
return countAvoids(((ParseNode) t).getKids());
}
return 0;
}
private int countAvoids(List<IParseNode> ls) {
// SG_CountAvoidsInTree
int r = 0;
for (IParseNode n : ls)
r += countAvoids(n);
return r;
}
private int filterOnIndirectPrefers(IParseNode left, IParseNode right) {
// SG_Indirect_Eagerness_Filter
if(SGLR.isDebugging()) {
Tools.debug("filterOnIndirectPrefers()");
}
if (left instanceof Amb || right instanceof Amb)
return FILTER_DRAW;
if (!left.equals(right))
return filterOnDirectPrefers(left, right);
ParseNode l = (ParseNode) left;
ParseNode r = (ParseNode) right;
List<IParseNode> leftArgs = l.getKids();
List<IParseNode> rightArgs = r.getKids();
int diffs = computeDistinctArguments(leftArgs, rightArgs);
if (diffs == 1) {
for (int i = 0; i < leftArgs.size(); i++) {
IParseNode leftArg = leftArgs.get(i);
IParseNode rightArg = rightArgs.get(i);
if (!leftArg.equals(rightArg)) {
return filterOnIndirectPrefers(leftArg, rightArg);
}
}
}
return FILTER_DRAW;
}
private int filterOnDirectPrefers(IParseNode left, IParseNode right) {
// SG_Direct_Eagerness_Filter
if(SGLR.isDebugging()) {
Tools.debug("filterOnDirectPrefers()");
}
if (isLeftMoreEager(left, right))
return FILTER_LEFT_WINS;
if (isLeftMoreEager(right, left))
return FILTER_RIGHT_WINS;
return FILTER_DRAW;
}
private boolean isLeftMoreEager(IParseNode left, IParseNode right) {
if (isMoreEager(left, right))
return true;
IParseNode newLeft = jumpOverInjectionsModuloEagerness(left);
IParseNode newRight = jumpOverInjectionsModuloEagerness(right);
if (newLeft instanceof ParseNode && newRight instanceof ParseNode)
return isMoreEager(left, right);
return false;
}
private IParseNode jumpOverInjectionsModuloEagerness(IParseNode t) {
if(SGLR.isDebugging()) {
Tools.debug("jumpOverInjectionsModuloEagerness()");
}
int prodType = getProductionType(t);
if (t instanceof ParseNode && prodType != ProductionAttributes.PREFER
&& prodType != ProductionAttributes.AVOID) {
Label prod = getLabel(t);
ParseNode n = (ParseNode) t;
while (prod.isInjection()) {
IParseNode x = (ParseNode) n.getKids().get(0);
int prodTypeX = getProductionType(x);
if (x instanceof ParseNode && prodTypeX != ProductionAttributes.PREFER
&& prodTypeX != ProductionAttributes.AVOID) {
prod = getLabel(x);
} else {
return n;
}
}
}
return t;
}
private Label getLabel(IParseNode t) {
if (t instanceof ParseNode) {
ParseNode n = (ParseNode) t;
return parseTable.getLabel(n.label);
} else if (t instanceof ParseProductionNode) {
ParseProductionNode n = (ParseProductionNode) t;
return parseTable.getLabel(n.prod);
}
return null;
}
private int getProductionType(IParseNode t) {
return getLabel(t).getAttributes().type;
}
private boolean isMoreEager(IParseNode left, IParseNode right) {
int leftLabel = ((ParseNode) left).getLabel();
int rightLabel = ((ParseNode) right).getLabel();
Label leftProd = parseTable.getLabel(leftLabel);
Label rightProd = parseTable.getLabel(rightLabel);
if (leftProd.isMoreEager(rightProd))
return true;
return false;
}
private int computeDistinctArguments(List<IParseNode> leftArgs, List<IParseNode> rightArgs) {
// countDistinctArguments
int r = 0;
for (int i = 0; i < leftArgs.size(); i++) {
if (!leftArgs.equals(rightArgs))
r++;
}
return r;
}
private boolean isCyclicTerm(IParseNode t) {
ambiguityManager.dumpIndexTable();
List<IParseNode> cycles = computeCyclicTerm(t);
return cycles != null && cycles.size() > 0;
}
private List<IParseNode> computeCyclicTerm(IParseNode t) {
// FIXME rewrite to use HashMap and object id
PositionMap visited = new PositionMap(ambiguityManager.getMaxNumberOfAmbiguities());
ambiguityManager.resetAmbiguityCount();
return computeCyclicTerm(t, false, visited);
}
private List<IParseNode> computeCyclicTerm(IParseNode t, boolean inAmbiguityCluster,
PositionMap visited) {
if (SGLR.isDebugging()) {
Tools.debug("computeCyclicTerm() - ", t);
}
if (t instanceof ParseProductionNode) {
if (SGLR.isDebugging()) {
Tools.debug(" bumping");
}
return null;
} else if (t instanceof ParseNode) {
Amb ambiguities = null;
List<IParseNode> cycle = null;
int clusterIndex;
ParseNode n = (ParseNode) t;
if (inAmbiguityCluster) {
cycle = computeCyclicTerm(n.getKids(), false, visited);
} else {
/*
if (ambiguityManager.isInputAmbiguousAt(parseTreePosition)) {
ambiguityManager.increaseAmbiguityCount();
clusterIndex = ambiguityManager.getClusterIndex(t, parseTreePosition);
if (SGLR.isDebugging()) {
Tools.debug(" - clusterIndex : ", clusterIndex);
}
if (markMap.isMarked(clusterIndex)) {
return new ArrayList<IParseNode>();
}
ambiguities = ambiguityManager.getClusterOnIndex(clusterIndex);
} else {
clusterIndex = -1;
}*/
throw new NotImplementedException();
/*
if (ambiguities == null) {
cycle = computeCyclicTerm(((ParseNode) t).getKids(), false, visited);
} else {
int length = visited.getValue(clusterIndex);
int savePos = parseTreePosition;
if (length == -1) {
//markMap.mark(clusterIndex);
cycle = computeCyclicTermInAmbiguityCluster(ambiguities, visited);
visited.put(clusterIndex, parseTreePosition - savePos);
//markMap.unmark(clusterIndex);
} else {
parseTreePosition += length;
}
}
*/
}
return cycle;
} else {
throw new FatalException();
}
}
private List<IParseNode> computeCyclicTermInAmbiguityCluster(Amb ambiguities,
PositionMap visited) {
for (IParseNode n : ambiguities.getAlternatives()) {
List<IParseNode> cycle = computeCyclicTerm(n, true, visited);
if (cycle != null)
return cycle;
}
return null;
}
private List<IParseNode> computeCyclicTerm(List<IParseNode> kids, boolean b, PositionMap visited) {
for (IParseNode kid : kids) {
List<IParseNode> cycle = computeCyclicTerm(kid, false, visited);
if (cycle != null)
return cycle;
}
return null;
}
private IParseNode selectOnTopSort() {
throw new NotImplementedException();
}
}
|
package com.akexorcist.sleepingforless.config;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.akexorcist.sleepingforless.util.Contextor;
import com.akexorcist.sleepingforless.view.settings.SettingsFragment;
public class SettingsPreference {
private static SettingsPreference gcmTokenPreference;
public static SettingsPreference getInstance() {
if (gcmTokenPreference == null) {
gcmTokenPreference = new SettingsPreference();
}
return gcmTokenPreference;
}
private SharedPreferences getPreference() {
return PreferenceManager.getDefaultSharedPreferences(Contextor.getContext());
}
public boolean isNotificationEnable() {
return getPreference().getBoolean(SettingsFragment.KEY_PUSH_NOTIFICATION, true);
}
}
|
package com.aranea_apps.android.libs.commons.sample;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.aranea_apps.android.libs.commons.logging.ALog;
import com.aranea_apps.android.libs.commons.notifications.BaseNotificationUtil;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BaseNotificationUtil.makeSingleShowToast("Hello " + PreferenceUtil.getRememberMePreference().get());
PreferenceUtil.getRememberMePreference().set(!PreferenceUtil.getRememberMePreference().get());
// Log variable number separate objects or strings with he same log method
ALog.d("Hello", "World", "Bla");
}
}
|
package com.example.harry2636.emotionanalyzer;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import android.content.Intent;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class VideoWatchActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private static YouTubePlayer player;
private Camera mCamera;
private CameraPreview mPreview;
public static int cameraId = 0;
private static boolean sendFlag = false;
private static final Object sendLock = new Object();
private int randomId;
private String selectedVideoId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_watch);
Intent listIntent =getIntent();
selectedVideoId = listIntent.getStringExtra("id");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(Configuration.API_KEY, this);
/*
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
*/
Random r = new Random();
randomId = r.nextInt();
}
private void initializeCamera() {
// Create an instance of Camera
mCamera = getFrontCamera();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
@Override
protected void onResume() {
super.onResume();
initializeCamera(); // release the camera immediately on pause event
}
@Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.stopPreview();
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.removeAllViews();
mPreview = null;
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Primary camera is usually back camera*/
public Camera getPrimaryCamera(){
Camera camera = null;
try {
camera = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
// Camera is not available (in use or does not exist)
}
return camera; // returns null if camera is unavailable
}
public Camera getFrontCamera() {
int cameraCount = 0;
Camera camera = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cameraId = camIdx;
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return camera;
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("picture", "picture sent to server");
PostImageTask postImageTask = new PostImageTask(data,
VideoWatchActivity.player.getCurrentTimeMillis(), selectedVideoId);
postImageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
mCamera.startPreview();
}
};
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
/* Youtube related functions */
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(selectedVideoId);
}
VideoWatchActivity.player = player;
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
@Override
public void onBuffering(boolean arg0) {
}
@Override
public void onPaused() {
synchronized (sendLock) {
sendFlag = false;
}
//Toast.makeText(VideoWatchActivity.this, "Video is paused", Toast.LENGTH_LONG).show();
}
@Override
public void onPlaying() {
synchronized (sendLock) {
sendFlag = true;
}
//Toast.makeText(VideoWatchActivity.this, "Video is playing", Toast.LENGTH_LONG).show();
PictureLoopTask pictureLoopTask = new PictureLoopTask();
pictureLoopTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@Override
public void onSeekTo(int arg0) {
}
@Override
public void onStopped() {
synchronized (sendLock) {
sendFlag = false;
}
//Toast.makeText(VideoWatchActivity.this, "Video is stopped", Toast.LENGTH_LONG).show();
}
};
private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
@Override
public void onAdStarted() {
}
@Override
public void onError(YouTubePlayer.ErrorReason arg0) {
}
@Override
public void onLoaded(String arg0) {
//Toast.makeText(VideoWatchActivity.this, "Video is loading", Toast.LENGTH_LONG).show();
}
@Override
public void onLoading() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onVideoStarted() {
//Toast.makeText(VideoWatchActivity.this, "Video started", Toast.LENGTH_LONG).show();
}
};
private class PostImageTask extends AsyncTask<String, Void, String> {
byte[] data;
int time;
String videoId;
public PostImageTask(byte[] data, int time, String videoId) {
this.data = data;
this.time = time;
this.videoId = videoId;
}
protected String doInBackground(String... urls) {
String result = postImageToServer(data);
return result;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("result", result);
}
private String postImageToServer(byte[] data) {
try {
URL url = new URL(Configuration.SERVER_ADDRESS + "/face");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
String encodedImage = Base64.encodeToString(data, Base64.DEFAULT);
Log.d("imageLength", encodedImage.length() +"");
JSONObject object = new JSONObject();
object.put("userId", randomId);
object.put("videoId", videoId);
object.put("time", this.time);
object.put("image", encodedImage);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(object.toString());
writer.flush();
writer.close();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject result = new JSONObject(responseStrBuilder.toString());
in.close();
connection.disconnect();
return result.get("ok").toString();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return "error";
}
}
private class PictureLoopTask extends AsyncTask<String, Void, String> {
public PictureLoopTask() {
}
protected String doInBackground(String... urls) {
while (sendFlag) {
mCamera.takePicture(null, null, mPicture);
Log.d("position", VideoWatchActivity.player.getCurrentTimeMillis() + "");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "done";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("loop", result);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.