answer stringlengths 17 10.2M |
|---|
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 ZERO_WATCH_STATUS = 0;
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(ERROR_EXIT);
} 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);
}
} |
/*
*
* Adafruit16CServoDriver
*
* TODO - test with Steppers & Motors - switches on board - interface accepts motor control
*
*/
package org.myrobotlab.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.motor.MotorConfig;
import org.myrobotlab.motor.MotorConfigDualPwm;
import org.myrobotlab.motor.MotorConfigSimpleH;
import org.myrobotlab.motor.MotorConfigPulse;
import org.myrobotlab.service.interfaces.DeviceControl;
import org.myrobotlab.service.interfaces.DeviceController;
import org.myrobotlab.service.interfaces.I2CControl;
import org.myrobotlab.service.interfaces.I2CController;
import org.myrobotlab.service.interfaces.PinDefinition;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.slf4j.Logger;
public class Adafruit16CServoDriver extends Service implements I2CControl, ServoController, MotorController {
/**
* SpeedControl, calculates the next position at regular intervals to make
* the servo move at the desired speed
*
*/
public class SpeedControl extends Thread {
ServoData servoData;
String name;
public SpeedControl(String name) {
super(String.format("%s.SpeedControl", name));
servoData = servoMap.get(name);
servoData.isMoving = true;
this.name = name;
log.info(String.format("SpeedControl %s created", name));
}
@Override
public void run() {
log.info(String.format("SpeedControl %s running", name));
try {
while (servoData.isMoving) {
servoData = servoMap.get(name);
if (servoData.targetOutput > servoData.currentOutput) {
servoData.currentOutput += 1;
} else if (servoData.targetOutput < servoData.currentOutput) {
servoData.currentOutput -= 1;
} else {
// We have reached the position so shutdown the thread
servoData.isMoving = false;
log.info(String.format("SpeedControl %s shut down", name));
}
int pulseWidthOff = SERVOMIN + (int) (servoData.currentOutput * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180));
setServo(servoData.pin, pulseWidthOff);
// Calculate next step for the the new value for the motor
Thread.sleep(1000 / servoData.velocity);
}
} catch (Exception e) {
servoData.isMoving = false;
if (e instanceof InterruptedException) {
log.info(String.format("SpeedControl %s shut down", name));
} else {
logException(e);
}
}
}
}
/** version of the library */
static public final String VERSION = "0.9";
private static final long serialVersionUID = 1L;
// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos
// you have!
public final static int SERVOMIN = 150; // this
// the
// 'minimum'
// pulse
// length count (out of 4096)
public final static int SERVOMAX = 600; // this
// the
// 'maximum'
// pulse
// length count (out of 4096)
transient public I2CController controller;
// Constant for default PWM freqency
private static int pwmFreq = 60;
final static int minPwmFreq = 24;
final static int maxPwmFreq = 1526;
// List of possible addresses. Used by the GUI.
public List<String> deviceAddressList = Arrays.asList("0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46",
"0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F", "0x50", "0x51", "0x52", "0x53",
"0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F");
// Default address
public String deviceAddress = "0x40";
/**
* This address is to address all Adafruit16CServoDrivers on the i2c bus
* Don't use this address for any other device on the i2c bus since it will
* cause collisions.
*/
public String broadcastAddress = "0x70";
public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7");
public String deviceBus = "1";
public transient final static Logger log = LoggerFactory.getLogger(Adafruit16CServoDriver.class.getCanonicalName());
public static final int PCA9685_MODE1 = 0x00; // Mod
// register
public static final byte PCA9685_SLEEP = 0x10; // Set
// sleep
// mode,
// before
// changing
// prescale
// value
public static final byte PCA9685_AUTOINCREMENT = 0x20; // Set
// autoincrement
// able
// write
// more
// than
// one
// byte
// sequence
public static final byte PCA9685_PRESCALE = (byte) 0xFE; // PreScale
// register
// Pin PWM addresses 4 bytes repeats for each pin so I only define pin 0
// The rest of the addresses are calculated based on pin numbers
public static final int PCA9685_LED0_ON_L = 0x06; // First
// LED
// address
// Low
public static final int PCA9685_LED0_ON_H = 0x07; // First
// LED
// address
// High
public static final int PCA9685_LED0_OFF_L = 0x08; // First
// LED
// address
// Low
public static final int PCA9685_LED0_OFF_H = 0x08; // First
// LED
// addressHigh
// public static final int PWM_FREQ = 60; // default frequency for servos
public static final float osc_clock = 25000000; // clock
// frequency
// the
// internal
// clock
public static final float precision = 4096; // pwm_precision
// i2c controller
public List<String> controllers;
public String controllerName;
public boolean isControllerSet = false;
/**
* @Mats - added by GroG - was wondering if this would help, probably you
* need a reverse index too ?
* @GroG - I only need servoNameToPin yet. To be able to move at a set speed
* a few extra values are needed
*/
class ServoData {
int pin;
boolean pwmFreqSet = false;
int pwmFreq;
SpeedControl speedcontrol;
int velocity = 0;
boolean isMoving = false;
int targetOutput;
int currentOutput;
}
transient HashMap<String, ServoData> servoMap = new HashMap<String, ServoData>();
// Motor related constants
public static final int MOTOR_FORWARD = 1;
public static final int MOTOR_BACKWARD = 0;
public static final int defaultMotorPwmFreq = 1000;
/**
* pin named map of all the pins on the board
*/
Map<String, PinDefinition> pinMap = null;
/**
* the definitive sequence of pins - "true address"
*/
Map<Integer, PinDefinition> pinIndex = null;
public static void main(String[] args) {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.DEBUG);
Adafruit16CServoDriver driver = (Adafruit16CServoDriver) Runtime.start("pwm", "Adafruit16CServoDriver");
log.info("Driver {}", driver);
}
public Adafruit16CServoDriver(String n) {
super(n);
createPinList();
refreshControllers();
subscribe(Runtime.getInstance().getName(), "registered", this.getName(), "onRegistered");
}
public void onRegistered(ServiceInterface s) {
refreshControllers();
broadcastState();
}
/*
* Refresh the list of running services that can be selected in the GUI
*/
public List<String> refreshControllers() {
controllers = Runtime.getServiceNamesFromInterface(I2CController.class);
return controllers;
}
// TODO
// Implement MotorController
/**
* This set of methods is used to set i2c parameters
*
* @param controllerName
* = The name of the i2c controller
* @param deviceBus
* = i2c bus Should be "1" for Arduino and RasPi "0"-"7" for
* I2CMux
* @param deviceAddress
* = The i2c address of the PCA9685 ( "0x40" - "0x5F")
* @return
*/
// @Override
public boolean setController(String controllerName, String deviceBus, String deviceAddress) {
return setController((I2CController) Runtime.getService(controllerName), deviceBus, deviceAddress);
}
public boolean setController(String controllerName) {
return setController((I2CController) Runtime.getService(controllerName), this.deviceBus, this.deviceAddress);
}
@Override
public boolean setController(I2CController controller) {
return setController(controller, this.deviceBus, this.deviceAddress);
}
@Override
public void setController(DeviceController controller) {
setController(controller);
}
public boolean setController(I2CController controller, String deviceBus, String deviceAddress) {
if (controller == null) {
error("setting null as controller");
return false;
}
controllerName = controller.getName();
log.info(String.format("%s setController %s", getName(), controllerName));
controllerName = controller.getName();
this.controller = controller;
this.deviceBus = deviceBus;
this.deviceAddress = deviceAddress;
createDevice();
isControllerSet = true;
broadcastState();
return true;
}
@Override
public void unsetController() {
controller = null;
this.deviceBus = null;
this.deviceAddress = null;
isControllerSet = false;
broadcastState();
}
@Override
public void setDeviceBus(String deviceBus) {
this.deviceBus = deviceBus;
broadcastState();
}
@Override
public void setDeviceAddress(String deviceAddress) {
if (controller != null) {
if (this.deviceAddress != deviceAddress) {
controller.releaseI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
}
}
log.info(String.format("Setting device address to %s", deviceAddress));
this.deviceAddress = deviceAddress;
}
/**
* This method creates the i2c device
*/
boolean createDevice() {
if (controller != null) {
// controller.releaseI2cDevice(this, Integer.parseInt(deviceBus),
// Integer.decode(deviceAddress));
controller.createI2cDevice(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress));
} else {
log.error("Can't create device until the controller has been set");
return false;
}
log.info(String.format("Creating device on bus: %s address %s", deviceBus, deviceAddress));
return true;
}
// @Override
// boolean DeviceControl.isAttached()
public boolean isAttached() {
return controller != null;
}
/**
* Set the PWM pulsewidth
*
* @param pin
* @param pulseWidthOn
* @param pulseWidthOff
*/
public void setPWM(Integer pin, Integer pulseWidthOn, Integer pulseWidthOff) {
byte[] buffer = { (byte) (PCA9685_LED0_ON_L + (pin * 4)), (byte) (pulseWidthOn & 0xff),
(byte) (pulseWidthOn >> 8), (byte) (pulseWidthOff & 0xff), (byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* Set the PWM frequency i.e. the frequency between positive pulses.
*
* @param hz
*/
public void setPWMFreq(int pin, Integer hz) { // Analog servos run at ~60 Hz
float prescale_value;
if (hz < minPwmFreq) {
log.error(String.format("Minimum PWMFreq is %s Hz, requested freqency is %s Hz, clamping to minimum",
minPwmFreq, hz));
hz = minPwmFreq;
prescale_value = 255;
} else if (hz > maxPwmFreq) {
log.error(String.format("Maximum PWMFreq is %s Hz, requested frequency is %s Hz, clamping to maximum",
maxPwmFreq, hz));
hz = maxPwmFreq;
prescale_value = 3;
} else {
prescale_value = Math.round(osc_clock / precision / hz) - 1;
}
log.info(String.format("PWMFreq %s hz, prescale_value calculated to %s", hz, prescale_value));
// Set sleep mode before changing PWM freqency
byte[] writeBuffer = { PCA9685_MODE1, PCA9685_SLEEP };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writeBuffer,
writeBuffer.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
if (Thread.interrupted()) { // Clears interrupted status!
}
}
// Write the PWM frequency value
byte[] buffer2 = { PCA9685_PRESCALE, (byte) prescale_value };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer2, buffer2.length);
// Leave sleep mode, set autoincrement to be able to write several
// bytes
// in sequence
byte[] buffer3 = { PCA9685_MODE1, PCA9685_AUTOINCREMENT };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer3, buffer3.length);
// Wait 1 millisecond until the oscillator has stabilized
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
if (Thread.interrupted()) { // Clears interrupted status!
}
}
}
public void setServo(Integer pin, Integer pulseWidthOff) {
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.debug(
String.format("setServo %s deviceAddress %s pin %s pulse %s", pin, deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff),
(byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
/**
* this would have been nice to have Java 8 and a default implementation in
* this interface which does Servo sweeping in the Servo (already
* implemented) and only if the controller can does it do sweeping on the
* "controller"
*
* For example MrlComm can sweep internally (or it used to be implemented)
*/
@Override
public void servoSweepStart(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoSweepStop(ServoControl servo) {
log.info("Adafruit16C can not do sweeping on the controller - sweeping must be done in ServoControl");
}
@Override
public void servoWrite(ServoControl servo) {
ServoData servoData = servoMap.get(servo.getName());
if (!servoData.pwmFreqSet) {
setPWMFreq(servoData.pin, servoData.pwmFreq);
servoData.pwmFreqSet = true;
}
// Move at max speed
if (servoData.velocity == 0) {
servoData.currentOutput = servo.getTargetOutput();
servoData.targetOutput = servo.getTargetOutput();
log.debug(String.format("servoWrite %s deviceAddress %s targetOutput %d", servo.getName(), deviceAddress,
servo.getTargetOutput()));
int pulseWidthOff = SERVOMIN
+ (int) (servo.getTargetOutput() * (int) ((float) SERVOMAX - (float) SERVOMIN) / (float) (180));
setServo(servo.getPin(), pulseWidthOff);
} else {
servoData.targetOutput = servo.getTargetOutput();
// Start a thread to handle the speed for this servo
if (servoData.currentOutput != servoData.targetOutput && !servoData.isMoving) {
servoData.speedcontrol = new SpeedControl(servo.getName());
servoData.speedcontrol.start();
}
}
}
@Override
public void servoWriteMicroseconds(ServoControl servo, int uS) {
ServoData servoData = servoMap.get(servo.getName());
if (!servoData.pwmFreqSet) {
setPWMFreq(servoData.pin, servoData.pwmFreq);
servoData.pwmFreqSet = true;
}
int pin = servo.getPin();
// 1000 ms => 150, 2000 ms => 600
int pulseWidthOff = (int) (uS * 0.45) - 300;
// since pulseWidthOff can be larger than > 256 it needs to be
// sent as 2 bytes
log.info(String.format("servoWriteMicroseconds %s deviceAddress x%02X pin %s pulse %d", servo.getName(),
deviceAddress, pin, pulseWidthOff));
byte[] buffer = { (byte) (PCA9685_LED0_OFF_L + (pin * 4)), (byte) (pulseWidthOff & 0xff),
(byte) (pulseWidthOff >> 8) };
controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), buffer, buffer.length);
}
@Override
public DeviceController getController() {
return controller;
}
/**
* Device attach - this should be creating the I2C bus on MRLComm for the
* "first" servo if not already created - Since this does not use the
* Arduino <Servo.h> servos - it DOES NOT need to create "Servo" devices in
* MRLComm. It will need to keep track of the "pin" to I2C address, and
* whenever a ServoControl.moveTo(pos) - the Servo will tell this controller
* its name & location to move. Mats says. The board has a single i2c
* address that doesn't change. The Arduino only needs to keep track of the
* i2c bus, not all devices that can communicate thru it. I.e. This service
* should keep track of servos, not the Arduino or the Raspi.
*
*
* This service will translate the name & location to an I2C address & value
* write request to the MRLComm device.
*
* Mats comments on the above. MRLComm should not know anything about the
* servos in this case. This service keeps track of the servos. MRLComm
* should not know anything about what addresses are used on the i2c bus
* MRLComm should initiate the i2c bus when it receives the first i2c write
* or read This service knows nothing about other i2c devices that can be on
* the same bus. And most important. This service knows nothing about
* MRLComm at all. I.e except for this bunch of comments :-)
*
* It implements the methods defined in the ServoController and translates
* the servo requests to i2c writes defined in the I2CControl interface
*
*/
/**
* if your device controller can provided several {Type}Controller
* interfaces, there might be commonality between all of them. e.g.
* initialization of data structures, preparing communication, sending
* control and config messages, etc.. - if there is commonality, it could be
* handled here - where Type specific methods call this method
*
* This is a software representation of a board that uses the i2c protocol.
* It uses the methods defined in the I2CController interface to write
* servo-commands. The I2CController interface defines the common methods
* for all devices that use the i2c protocol. In most services I will define
* addition <device>Control methods, but this service is a "middle man" so
* it implements the ServoController methods and should not have any "own"
* methods.
*
* After our explanation of the roles of <device>Control and
* <device>Controller it's clear to me that any device that uses the i2c
* protocol needs to implement to <device>Control methods: I2CControl that
* is the generic interface for any i2c device <device>Control, that defines
* the specific methods for that device. For example the MPU6050 should
* implement both I2CControl and MPU6050Control or perhaps a AccGyroControl
* interface that would define the common methods that a
* Gyro/Accelerometer/Magnetometer device should implement.
*/
// FIXME how many do we want to support ??
// this device attachment is overloaded on the Arduino side ...
// Currently its only Servo, but it's also possible to implement
// MotorController and any device that requires pwm, like a LED dimmer.
@Override
public void deviceAttach(DeviceControl device, Object... conf) throws Exception {
if (device instanceof ServoControl) {
servoAttach((ServoControl) device, conf);
}
if (device instanceof MotorControl) {
motorAttach((MotorControl) device, conf);
}
}
void servoAttach(ServoControl device, Object... conf) {
ServoControl servo = (ServoControl) device;
// should initial pos be a requirement ?
// This will fail because the pin data has not yet been set in Servo
// servoNameToPin.put(servo.getName(), servo.getPin());
String servoName = servo.getName();
ServoData servoData = new ServoData();
servoData.pin = (int) conf[0];
servoData.pwmFreqSet = false;
servoData.pwmFreq = pwmFreq;
servoMap.put(servoName, servoData);
invoke("publishAttachedDevice", servoName);
}
void motorAttach(MotorControl device, Object... conf) {
/*
* This is where motor data could be initialized. So far all motor data
* this service needs can be requested from the motors config
*/
MotorControl motor = (MotorControl) device;
invoke("publishAttachedDevice", motor.getName());
}
@Override
public void deviceDetach(DeviceControl servo) {
servoDetach((ServoControl) servo);
servoMap.remove(servo.getName());
}
public String publishAttachedDevice(String deviceName) {
return deviceName;
}
/**
* Start sending pulses to the servo
*
*/
@Override
public void servoAttach(ServoControl servo, int pin) {
servoWrite(servo);
}
/**
* Stop sending pulses to the servo, relax
*/
@Override
public void servoDetach(ServoControl servo) {
int pin = servo.getPin();
setPWM(pin, 4096, 0);
}
@Override
public void servoSetMaxVelocity(ServoControl servo) {
// TODO Auto-generated method stub.
// perhaps cannot do this with Adafruit16CServoDriver
// Mats says: It can be done in this service. But not by the board.
}
@Override
public void motorMove(MotorControl mc) {
MotorConfig c = mc.getConfig();
if (c == null) {
error("motor config not set");
return;
}
Class<?> type = mc.getConfig().getClass();
double powerOutput = mc.getPowerOutput();
if (MotorConfigSimpleH.class == type) {
MotorConfigSimpleH config = (MotorConfigSimpleH) c;
if (config.getPwmFreq() == null) {
config.setPwmFreq(defaultMotorPwmFreq);
setPWMFreq(config.getPwrPin(), config.getPwmFreq());
}
setPinValue(config.getDirPin(), (powerOutput < 0) ? MOTOR_BACKWARD : MOTOR_FORWARD);
setPinValue(config.getPwrPin(), powerOutput);
} else if (MotorConfigDualPwm.class == type) {
MotorConfigDualPwm config = (MotorConfigDualPwm) c;
log.info(String.format("Adafrutit16C Motor DualPwm motorMove, powerOutput = %s", powerOutput));
if (config.getPwmFreq() == null) {
config.setPwmFreq(defaultMotorPwmFreq);
setPWMFreq(config.getLeftPin(), config.getPwmFreq());
setPWMFreq(config.getRightPin(), config.getPwmFreq());
}
if (powerOutput < 0) {
setPinValue(config.getLeftPin(), 0);
setPinValue(config.getRightPin(), Math.abs(powerOutput / 255));
} else if (powerOutput > 0) {
setPinValue(config.getRightPin(), 0);
setPinValue(config.getLeftPin(), Math.abs(powerOutput / 255));
} else {
setPinValue(config.getRightPin(), 0);
setPinValue(config.getLeftPin(), 0);
}
} else if (MotorPulse.class == type) {
MotorPulse motor = (MotorPulse) mc;
// sendMsg(ANALOG_WRITE, motor.getPin(Motor.PIN_TYPE_PWM_RIGHT),
// TODO implement with a -1 for "endless" pulses or a different
// command parameter :P
// TODO Change to setPwmFreq I guess
// setPwmFreq(motor.getPulsePin(), (int) Math.abs(powerOutput));
} else {
error("motorMove for motor type %s not supported", type);
}
}
@Override
public void motorMoveTo(MotorControl mc) {
// speed parameter?
// modulo - if < 1
// speed = 1 else
log.info("motorMoveTo targetPos {} powerLevel {}", mc.getTargetPos(), mc.getPowerLevel());
Class<?> type = mc.getClass();
// if pulser (with or without fake encoder
// send a series of pulses !
// with current direction
if (MotorPulse.class == type) {
MotorPulse motor = (MotorPulse) mc;
// check motor direction
// send motor direction
// TODO powerLevel = 100 * powerlevel
// FIXME !!! - this will have to send a Long for targetPos at some
// point !!!!
double target = Math.abs(motor.getTargetPos());
int b0 = (int) target & 0xff;
int b1 = ((int) target >> 8) & 0xff;
int b2 = ((int) target >> 16) & 0xff;
int b3 = ((int) target >> 24) & 0xff;
// TODO FIXME
// sendMsg(PULSE, deviceList.get(motor.getName()).id, b3, b2, b1,
// b0, (int) motor.getPowerLevel(), feedbackRate);
}
}
@Override
public void motorStop(MotorControl mc) {
MotorConfig c = mc.getConfig();
if (c == null) {
error("motor config not set");
return;
}
Class<?> type = mc.getConfig().getClass();
if (MotorConfigPulse.class == type) {
MotorConfigPulse config = (MotorConfigPulse) mc.getConfig();
setPinValue(config.getPulsePin(), 0);
} else if (MotorConfigSimpleH.class == type) {
MotorConfigSimpleH config = (MotorConfigSimpleH) mc.getConfig();
if (config.getPwmFreq() == null) {
config.setPwmFreq(500);
setPWMFreq(config.getPwrPin(), config.getPwmFreq());
}
setPinValue(config.getPwrPin(), 0);
} else if (MotorConfigDualPwm.class == type) {
MotorConfigDualPwm config = (MotorConfigDualPwm) mc.getConfig();
setPinValue(config.getLeftPin(), 0);
setPinValue(config.getRightPin(), 0);
}
}
@Override
public void motorReset(MotorControl motor) {
// perhaps this should be in the motor control
// motor.reset();
// opportunity to reset variables on the controller
// sendMsg(MOTOR_RESET, motor.getind);
}
public void setPinValue(int pin, double powerOutput) {
log.info(String.format("Adafruit16C setPinValue, pin = %s, powerOutput = %s", pin, powerOutput));
if (powerOutput < 0) {
log.error(String.format("Adafruit16CServoDriver setPinValue. Value below zero (%s). Defaulting to 0.",
powerOutput));
powerOutput = 0;
} else if (powerOutput > 1) {
log.error(
String.format("Adafruit16CServoDriver setPinValue. Value > 1 (%s). Defaulting to 1", powerOutput));
powerOutput = 1;
}
int powerOn;
int powerOff;
// No phase shift. Simple calculation
if (powerOutput == 0) {
powerOn = 4096;
powerOff = 0;
} else if (powerOutput == 1) {
powerOn = 0;
powerOff = 1;
} else {
powerOn = (int) (powerOutput * 4096);
powerOff = 4095;
}
log.info(String.format("powerOutput = %s, powerOn = %s, powerOff = %s", powerOutput, powerOn, powerOff));
setPWM(pin, powerOn, powerOff);
}
public List<PinDefinition> getPinList() {
List<PinDefinition> list = new ArrayList<PinDefinition>(pinIndex.values());
return list;
}
public Map<String, PinDefinition> createPinList() {
pinIndex = new HashMap<Integer, PinDefinition>();
for (int i = 0; i < 16; ++i) {
PinDefinition pindef = new PinDefinition();
String name = null;
name = String.format("D%d", i);
pindef.setDigital(true);
pindef.setName(name);
pindef.setAddress(i);
pinIndex.put(i, pindef);
}
return pinMap;
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Adafruit16CServoDriver.class.getCanonicalName());
meta.addDescription("Adafruit 16-Channel PWM/Servo Driver");
meta.addCategory("shield", "servo & pwm");
meta.setSponsor("Mats");
/*
* meta.addPeer("arduino", "Arduino", "our Arduino");
* meta.addPeer("raspi", "RasPi", "our RasPi");
*/
return meta;
}
@Override
public void servoSetVelocity(ServoControl servo) {
ServoData servoData = servoMap.get(servo.getName());
servoData.velocity = servo.getVelocity();
}
} |
package xdi2.example.core;
import java.io.StringReader;
import java.util.Iterator;
import xdi2.core.ContextNode;
import xdi2.core.Graph;
import xdi2.core.features.nodetypes.XdiAbstractContext;
import xdi2.core.features.nodetypes.XdiAttributeCollection;
import xdi2.core.features.nodetypes.XdiAttributeInstanceUnordered;
import xdi2.core.impl.memory.MemoryGraphFactory;
import xdi2.core.io.MimeType;
import xdi2.core.io.XDIReaderRegistry;
import xdi2.core.syntax.XDIAddress;
import xdi2.core.syntax.XDIArc;
public class Collections {
public static void main(String[] args) throws Exception {
// create and print a graph with a collection
Graph graph = MemoryGraphFactory.getInstance().openGraph();
ContextNode contextNode = graph.getRootContextNode().setContextNode(XDIArc.create("=markus"));
XdiAttributeCollection telAttributeCollection = XdiAbstractContext.fromContextNode(contextNode).getXdiAttributeCollection(XDIArc.create("[<#tel>]"), true);
telAttributeCollection.setXdiMemberUnordered(true, false).setLiteralDataString("+1.206.555.1111");
telAttributeCollection.setXdiMemberUnordered(true, false).setLiteralDataString("+1.206.555.2222");
System.out.println(graph.toString(new MimeType("application/xdi+json;pretty=1")));
// write and re-read the graph, then find and print the members of the attribute collection
Graph graph2 = MemoryGraphFactory.getInstance().openGraph();
XDIReaderRegistry.getAuto().read(graph2, new StringReader(graph.toString()));
ContextNode contextNode2 = graph.getDeepContextNode(XDIAddress.create("=markus"));
XdiAttributeCollection telCollection2 = XdiAbstractContext.fromContextNode(contextNode2).getXdiAttributeCollection(XDIArc.create("[<#tel>]"), false);
for (Iterator<XdiAttributeInstanceUnordered> i = telCollection2.getXdiMembersUnordered(); i.hasNext(); ) {
System.out.println(i.next().getLiteralNode().getLiteralData());
}
}
} |
package org.asciidoc.maven;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
/**
* Basic maven plugin to render asciidoc files using asciidoctor, a ruby port.
*
* Uses jRuby to invoke a small script to process the asciidoc files.
*/
@Mojo(name = "process-asciidoc")
public class AsciidoctorMojo extends AbstractMojo {
@Parameter(property = "sourceDir", defaultValue = "${basedir}/src/asciidoc", required = true)
protected File sourceDirectory;
@Parameter(property = "outputDir", defaultValue = "${project.build.directory}", required = true)
protected File outputDirectory;
@Parameter(property = "backend", defaultValue = "docbook", required = true)
protected String backend;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
final ScriptEngineManager engineManager = new ScriptEngineManager();
final ScriptEngine rubyEngine = engineManager.getEngineByName("jruby");
final Bindings bindings = new SimpleBindings();
bindings.put("srcDir", sourceDirectory.getAbsolutePath());
bindings.put("outputDir", outputDirectory.getAbsolutePath());
bindings.put("backend", backend);
try {
final InputStream script = AbstractMojo.class.getClassLoader().getResourceAsStream("execute_asciidoctor.rb");
final InputStreamReader streamReader = new InputStreamReader(script);
rubyEngine.eval(streamReader, bindings);
} catch (ScriptException e) {
getLog().error("Error running ruby script", e);
}
}
public File getSourceDirectory() {
return sourceDirectory;
}
public void setSourceDirectory(File sourceDirectory) {
this.sourceDirectory = sourceDirectory;
}
public File getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
public String getBackend() {
return backend;
}
public void setBackend(String backend) {
this.backend = backend;
}
} |
package org.pathvisio.biomartconnect.impl;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class TableDialog extends JDialog {
JScrollPane jt;
/*
JCheckBox ensembl_gene_id;
JCheckBox external_gene_id;
JCheckBox description;
JCheckBox chromosome_name;
JCheckBox start_position;
JCheckBox end_position;
JCheckBox strand;
JCheckBox band;
JCheckBox transcript_count;
JCheckBox percentage_gc_content;
JCheckBox status;
*/
GeneticVariationProvider bcp;
String [] attr;
public TableDialog(GeneticVariationProvider bcp, JScrollPane jt, String [] attr){
/*
ensembl_gene_id = new JCheckBox("Ensembl Gene ID");
external_gene_id = new JCheckBox("External Gene ID");
description = new JCheckBox("Description");
chromosome_name = new JCheckBox("Chromosome Name");
start_position = new JCheckBox("Start Position");
end_position = new JCheckBox("End Position");
strand = new JCheckBox("Strand");
band = new JCheckBox("Band");
transcript_count = new JCheckBox("Transcript Count");
percentage_gc_content = new JCheckBox("%GC Content");
status = new JCheckBox("Status");
*/
this.bcp = bcp;
this.jt = jt;
this.attr = attr;
initUI();
}
public final void initUI(){
JLabel title = new JLabel("Variation Data Table");
JPanel master = new JPanel();
master.setLayout(new BorderLayout());
/*
ensembl_gene_id.setSelected(true);
external_gene_id.setSelected(true);
description.setSelected(true);
chromosome_name.setSelected(true);
start_position.setSelected(true);
jp.add(ensembl_gene_id);
jp.add(external_gene_id);
jp.add(description);
jp.add(chromosome_name);
jp.add(start_position);
jp.add(end_position);
jp.add(strand);
jp.add(band);
jp.add(transcript_count);
jp.add(percentage_gc_content);
jp.add(status);
*/
/* JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bcp.sendResult();
}
});
*/
/* JPanel southPanel = new JPanel();
southPanel.setLayout(new GridBagLayout());
GridBagConstraints con = new GridBagConstraints();
con.fill = GridBagConstraints.HORIZONTAL;
con.gridx = 1;
con.gridy = 0;
con.gridwidth = 3;
southPanel.add(applyButton,con);
*/
//southPanel.add(applyButton,BorderLayout.CENTER);
//add(southPanel,BorderLayout.SOUTH);
master.add(title,BorderLayout.NORTH);
JScrollPane scrollpane = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
master.add(scrollpane,BorderLayout.CENTER);
final TableSettingsDialog tsd = new TableSettingsDialog(bcp,attr,master,scrollpane);
JButton settings = new JButton("Settings");
settings.setAlignmentX(Component.CENTER_ALIGNMENT);
settings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
tsd.setVisible(true);
}
});
JPanel southPanel = new JPanel();
southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.PAGE_AXIS));
southPanel.add(settings);
master.add(southPanel,BorderLayout.SOUTH);
add(master);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(900,660);
}
} |
package kuleuven.group2.testrunner;
import static org.junit.Assert.*;
import kuleuven.group2.testrunner.TestRunner;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
public class TestRunnerTest {
protected TestRunner testRunner;
protected kuleuven.group2.data.Test testMethod2Arg;
protected kuleuven.group2.data.Test testMethodFail;
protected JUnitCore junitCore;
protected boolean listenerVisited;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
junitCore = new JUnitCore();
testRunner = new TestRunner(getClass().getClassLoader(), junitCore);
testMethod2Arg = new kuleuven.group2.data.Test(
kuleuven.group2.data.signature.JavaSignatureParserTest.class.getName(),
"testMethod2Arg"
);
testMethodFail = new kuleuven.group2.data.Test(
kuleuven.group2.testrunner.TestRunnerTest.class.getName(),
"fail"
);
listenerVisited = false;
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSucceededSimple() throws Exception {
Result[] result = testRunner.runTestMethods(testMethod2Arg);
Result testMethod2ArgResult = result[0];
assertTrue(testMethod2ArgResult.wasSuccessful());
assertEquals(1, testMethod2ArgResult.getRunCount());
}
/*@Test
public void testFailedSimple() {
Result[] result = testRunner.runTestMethods(testMethodFail);
Result testMethodFailResult = result[0];
assertFalse(testMethodFailResult.wasSuccessful());
assertEquals(1, testMethodFailResult.getRunCount());
assertEquals(1, testMethodFailResult.getFailureCount());
}
// used as failing test
@Test
public void fail() {
assertTrue(false);
}*/
@Test
public void testRunListener() throws Exception {
testRunner.addRunListener(new RunListener() {
@Override
public void testStarted(Description description) throws Exception {
TestRunnerTest.this.listenerVisited();
}
});
testRunner.runTestMethods(testMethod2Arg);
assertTrue(listenerVisited);
}
public void listenerVisited() {
listenerVisited = true;
}
} |
package org.broadinstitute.hellbender;
import htsjdk.samtools.util.StringUtil;
import org.broadinstitute.hellbender.cmdline.ClassFinder;
import org.broadinstitute.hellbender.cmdline.CommandLineProgram;
import org.broadinstitute.hellbender.cmdline.CommandLineProgramGroup;
import org.broadinstitute.hellbender.cmdline.CommandLineProgramProperties;
import org.broadinstitute.hellbender.exceptions.UserException;
import org.broadinstitute.hellbender.utils.ClassUtils;
import java.io.Serializable;
import java.util.*;
/**
* This is the main class of Hellbender and is the way of executing individual command line programs.
*
* CommandLinePrograms are listed in a single command line interface based on the java package specified to instanceMain.
*
* If you want your own single command line program, extend this class and override if required:
*
* - {@link #getPackageList()} to return a list of java packages in which to search for classes that extend CommandLineProgram.
* - {@link #getClassList()} to return a list of single classes to include (e.g. required input pre-processing tools).
* - {@link #getCommandLineName()} for the name of the toolkit.
* - {@link #handleResult(Object)} for handle the result of the tool.
* - {@link #handleNonUserException(Exception)} for handle non {@link UserException}.
*
* Note: If any of the previous methods was overrided, {@link #main(String[])} should be implemented to instantiate your class
* and call {@link #mainEntry(String[])} to make the changes effective.
*/
public class Main {
/**
* Provides ANSI colors for the terminal output *
*/
private static final String KNRM = "\u001B[0m"; // reset
private static final String RED = "\u001B[31m";
private static final String GREEN = "\u001B[32m";
private static final String CYAN = "\u001B[36m";
private static final String WHITE = "\u001B[37m";
private static final String BOLDRED = "\u001B[1m\u001B[31m";
/**
* exit value when an issue with the commandline is detected, ie {@link UserException.CommandLineException}.
* This is the same value as picard uses.
*/
private static final int COMMANDLINE_EXCEPTION_EXIT_VALUE = 1;
/**
* exit value when an unrecoverable {@link UserException} occurs
*/
private static final int USER_EXCEPTION_EXIT_VALUE = 2;
/**
* exit value when any unrecoverable exception other than {@link UserException} occurs
*/
private static final int ANY_OTHER_EXCEPTION_EXIT_VALUE = 3;
private static final String STACK_TRACE_ON_USER_EXCEPTION_PROPERTY = "GATK_STACKTRACE_ON_USER_EXCEPTION";
/**
* The packages we wish to include in our command line.
*/
protected List<String> getPackageList() {
final List<String> packageList = new ArrayList<>();
packageList.addAll(Arrays.asList("org.broadinstitute.hellbender"));
return packageList;
}
/**
* The single classes we wish to include in our command line.
*/
protected List<Class<? extends CommandLineProgram>> getClassList() {
return Collections.emptyList();
}
/** Returns the command line that will appear in the usage. */
protected String getCommandLineName() {
return "";
}
/**
* The main method.
* <p/>
* Give a list of java packages in which to search for classes that extend CommandLineProgram and a list of single CommandLineProgram classes.
* Those will be included on the command line.
*
* This method is not intended to be used outside of the GATK framework and tests.
*
*/
public Object instanceMain(final String[] args, final List<String> packageList, final List<Class<? extends CommandLineProgram>> classList, final String commandLineName) {
final CommandLineProgram program = extractCommandLineProgram(args, packageList, classList, commandLineName);
if (null == program) return null; // no program found!
// we can lop off the first two arguments but it requires an array copy or alternatively we could update CLP to remove them
// in the constructor do the former in this implementation.
final String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
return program.instanceMain(mainArgs);
}
/**
* This method is not intended to be used outside of the GATK framework and tests.
*/
public Object instanceMain(final String[] args) {
return instanceMain(args, getPackageList(), getClassList(), getCommandLineName());
}
/**
* The entry point to the toolkit from commandline: it uses {@link #instanceMain(String[])} to run the command line
* program and handle the returned object with {@link #handleResult(Object)}, and exit with 0.
* If any error occurs, it handles the exception (if non-user exception, through {@link #handleNonUserException(Exception)})
* and exit with the concrete error exit value.
*
* Note: this is the only method that is allowed to call System.exit (because gatk tools may be run from test harness etc)
*/
protected final void mainEntry(final String[] args) {
try {
final Object result = instanceMain(args);
handleResult(result);
System.exit(0);
} catch (final UserException.CommandLineException e){
//the usage has already been printed so don't print it here.
if(printStackTraceOnUserExceptions()) {
e.printStackTrace();
}
System.exit(COMMANDLINE_EXCEPTION_EXIT_VALUE);
} catch (final UserException e){
CommandLineProgram.printDecoratedUserExceptionMessage(System.err, e);
if(printStackTraceOnUserExceptions()) {
e.printStackTrace();
}
System.exit(USER_EXCEPTION_EXIT_VALUE);
} catch (final Exception e){
handleNonUserException(e);
System.exit(ANY_OTHER_EXCEPTION_EXIT_VALUE);
}
}
/**
* Handle the result returned for a tool. Default implementation prints a message with the string value of the object if it is not null.
* @param result the result of the tool (may be null)
*/
protected void handleResult(final Object result) {
if (result != null) {
System.out.println("Tool returned:\n" + result);
}
}
/**
* Handle any exception that does not come from the user. Default implementation prints the stack trace.
* @param exception the exception to handle (never an {@link UserException}).
*/
protected void handleNonUserException(final Exception exception) {
exception.printStackTrace();
}
/** The entry point to GATK from commandline. It calls {@link #mainEntry(String[])} from this instance. */
public static void main(final String[] args) {
new Main().mainEntry(args);
}
private static boolean printStackTraceOnUserExceptions() {
return "true".equals(System.getenv(STACK_TRACE_ON_USER_EXCEPTION_PROPERTY)) || Boolean.getBoolean(STACK_TRACE_ON_USER_EXCEPTION_PROPERTY);
}
/**
* Returns the command line program specified, or prints the usage and exits with exit code 1 *
*/
private static CommandLineProgram extractCommandLineProgram(final String[] args, final List<String> packageList, final List<Class<? extends CommandLineProgram>> classList, final String commandLineName) {
/** Get the set of classes that are our command line programs **/
final ClassFinder classFinder = new ClassFinder();
for (final String pkg : packageList) {
classFinder.find(pkg, CommandLineProgram.class);
}
String missingAnnotationClasses = "";
final Set<Class<?>> toCheck = classFinder.getClasses();
toCheck.addAll(classList);
final Map<String, Class<?>> simpleNameToClass = new LinkedHashMap<>();
for (final Class<?> clazz : toCheck) {
// No interfaces, synthetic, primitive, local, or abstract classes.
if (ClassUtils.canMakeInstances(clazz)) {
final CommandLineProgramProperties property = getProgramProperty(clazz);
// Check for missing annotations
if (null == property) {
if (missingAnnotationClasses.isEmpty()) missingAnnotationClasses += clazz.getSimpleName();
else missingAnnotationClasses += ", " + clazz.getSimpleName();
} else if (!property.omitFromCommandLine()) { /** We should check for missing annotations later **/
if (simpleNameToClass.containsKey(clazz.getSimpleName())) {
throw new RuntimeException("Simple class name collision: " + clazz.getSimpleName());
}
simpleNameToClass.put(clazz.getSimpleName(), clazz);
}
}
}
if (!missingAnnotationClasses.isEmpty()) {
throw new RuntimeException("The following classes are missing the required CommandLineProgramProperties annotation: " + missingAnnotationClasses);
}
final Set<Class<?>> classes = new LinkedHashSet<>();
classes.addAll(simpleNameToClass.values());
if (args.length < 1) {
printUsage(classes, commandLineName);
} else {
if (args[0].equals("-h") || args[0].equals("--help")) {
printUsage(classes, commandLineName);
} else {
if (simpleNameToClass.containsKey(args[0])) {
final Class<?> clazz = simpleNameToClass.get(args[0]);
try {
return (CommandLineProgram) clazz.newInstance();
} catch (final InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
printUsage(classes, commandLineName);
throw new UserException(getUnknownCommandMessage(classes, args[0]));
}
}
return null;
}
public static CommandLineProgramProperties getProgramProperty(Class<?> clazz) {
return clazz.getAnnotation(CommandLineProgramProperties.class);
}
private static class SimpleNameComparator implements Comparator<Class<?>>, Serializable {
private static final long serialVersionUID = 1096632824580028876L;
@Override
public int compare(final Class<?> aClass, final Class<?> bClass) {
return aClass.getSimpleName().compareTo(bClass.getSimpleName());
}
}
private static void printUsage(final Set<Class<?>> classes, final String commandLineName) {
final StringBuilder builder = new StringBuilder();
builder.append(BOLDRED + "USAGE: " + commandLineName + " " + GREEN + "<program name>" + BOLDRED + " [-h]\n\n" + KNRM)
.append(BOLDRED + "Available Programs:\n" + KNRM);
/** Group CommandLinePrograms by CommandLineProgramGroup **/
final Map<Class<? extends CommandLineProgramGroup>, CommandLineProgramGroup> programGroupClassToProgramGroupInstance = new LinkedHashMap<>();
final Map<CommandLineProgramGroup, List<Class<?>>> programsByGroup = new TreeMap<>(CommandLineProgramGroup.comparator);
final Map<Class<?>, CommandLineProgramProperties> programsToProperty = new LinkedHashMap<>();
for (final Class<?> clazz : classes) {
// Get the command line property for this command line program
final CommandLineProgramProperties property = getProgramProperty(clazz);
if (null == property) {
throw new RuntimeException(String.format("The class '%s' is missing the required CommandLineProgramProperties annotation.", clazz.getSimpleName()));
}
programsToProperty.put(clazz, property);
// Get the command line program group for the command line property
// NB: we want to minimize the number of times we make a new instance, hence programGroupClassToProgramGroupInstance
CommandLineProgramGroup programGroup = programGroupClassToProgramGroupInstance.get(property.programGroup());
if (null == programGroup) {
try {
programGroup = property.programGroup().newInstance();
} catch (final InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
programGroupClassToProgramGroupInstance.put(property.programGroup(), programGroup);
}
List<Class<?>> programs = programsByGroup.get(programGroup);
if (null == programs) {
programsByGroup.put(programGroup, programs = new ArrayList<>());
}
programs.add(clazz);
}
/** Print out the programs in each group **/
for (final Map.Entry<CommandLineProgramGroup, List<Class<?>>> entry : programsByGroup.entrySet()) {
final CommandLineProgramGroup programGroup = entry.getKey();
builder.append(WHITE + "
builder.append(String.format("%s%-48s %-45s%s\n", RED, programGroup.getName() + ":", programGroup.getDescription(), KNRM));
final List<Class<?>> sortedClasses = new ArrayList<>();
sortedClasses.addAll(entry.getValue());
Collections.sort(sortedClasses, new SimpleNameComparator());
for (final Class<?> clazz : sortedClasses) {
final CommandLineProgramProperties property = programsToProperty.get(clazz);
if (null == property) {
throw new RuntimeException(String.format("Unexpected error: did not find the CommandLineProgramProperties annotation for '%s'", clazz.getSimpleName()));
}
if (clazz.getSimpleName().length() >= 45) {
builder.append(String.format("%s %s %s%s%s\n", GREEN, clazz.getSimpleName(), CYAN, property.oneLineSummary(), KNRM));
} else {
builder.append(String.format("%s %-45s%s%s%s\n", GREEN, clazz.getSimpleName(), CYAN, property.oneLineSummary(), KNRM));
}
}
builder.append(String.format("\n"));
}
builder.append(WHITE + "
System.err.println(builder.toString());
}
/**
* similarity floor for matching in getUnknownCommandMessage *
*/
private static final int HELP_SIMILARITY_FLOOR = 7;
private static final int MINIMUM_SUBSTRING_LENGTH = 5;
/**
* When a command does not match any known command, searches for similar commands, using the same method as GIT *
* @return returns an error message including the closes match if relevant.
*/
public static String getUnknownCommandMessage(final Set<Class<?>> classes, final String command) {
final Map<Class<?>, Integer> distances = new LinkedHashMap<>();
int bestDistance = Integer.MAX_VALUE;
int bestN = 0;
// Score against all classes
for (final Class<?> clazz : classes) {
final String name = clazz.getSimpleName();
final int distance;
if (name.equals(command)) {
throw new RuntimeException("Command matches: " + command);
}
if (name.startsWith(command) || (MINIMUM_SUBSTRING_LENGTH <= command.length() && name.contains(command))) {
distance = 0;
} else {
distance = StringUtil.levenshteinDistance(command, name, 0, 2, 1, 4);
}
distances.put(clazz, distance);
if (distance < bestDistance) {
bestDistance = distance;
bestN = 1;
} else if (distance == bestDistance) {
bestN++;
}
}
// Upper bound on the similarity score
if (0 == bestDistance && bestN == classes.size()) {
bestDistance = HELP_SIMILARITY_FLOOR + 1;
}
StringBuilder message = new StringBuilder();
// Output similar matches
message.append(String.format("'%s' is not a valid command.", command));
message.append(System.lineSeparator());
if (bestDistance < HELP_SIMILARITY_FLOOR) {
message.append(String.format("Did you mean %s?", (bestN < 2) ? "this" : "one of these"));
message.append(System.lineSeparator());
for (final Class<?> clazz : classes) {
if (bestDistance == distances.get(clazz)) {
message.append(String.format(" %s", clazz.getSimpleName()));
}
}
}
return message.toString();
}
} |
package org.pentaho.di.core.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import org.pentaho.di.core.Condition;
import org.pentaho.di.core.Const;
public class StringSearcher
{
public static final void findMetaData(Object object, int level, List stringList, Object parentObject, Object grandParentObject)
{
// System.out.println(Const.rightPad(" ", level)+"Finding strings in "+object.toString());
if (level>5) return;
Class baseClass = object.getClass();
Field[] fields = baseClass.getDeclaredFields();
for (int i=0;i<fields.length;i++)
{
Field field = fields[i];
boolean processThisOne = true;
if ( (field.getModifiers()&Modifier.FINAL ) > 0) processThisOne=false;
if ( (field.getModifiers()&Modifier.STATIC) > 0) processThisOne=false;
if ( field.toString().indexOf("be.ibridge.kettle")<0 ) processThisOne=false; // Stay in this code-base.
if (processThisOne)
{
try
{
Object obj = field.get(object);
if (obj!=null)
{
if (obj instanceof String)
{
// OK, let's add the String
stringList.add(new StringSearchResult((String)obj, parentObject, grandParentObject, field.getName()));
}
else
if (obj instanceof String[])
{
String[] array = (String[])obj;
for (int x=0;x<array.length;x++)
{
if (array[x]!=null)
{
stringList.add(new StringSearchResult(array[x], parentObject, grandParentObject, field.getName()+"
}
}
}
else
if (obj instanceof Boolean)
{
// OK, let's add the String
stringList.add(new StringSearchResult(((Boolean)obj).toString(), parentObject, grandParentObject, field.getName()+" (Boolean)"));
}
else
if (obj instanceof Condition)
{
stringList.add(new StringSearchResult(((Condition)obj).toString(), parentObject, grandParentObject, field.getName()+" (Condition)"));
}
else
if (obj instanceof Object[])
{
for (int j=0;j<((Object[])obj).length;j++) findMetaData( ((Object[])obj)[j], level+1, stringList, parentObject, grandParentObject);
}
else {
findMetaData(obj, level+1, stringList, parentObject, grandParentObject);
}
}
}
catch(IllegalAccessException e)
{
// OK, it's private, let's see if we can go there later on using getters and setters...
// fileName becomes: getFileName();
Method method = findMethod(baseClass, field.getName());
if (method!=null)
{
String fullMethod = baseClass.getName()+"."+method.getName()+"()";
// OK, how do we get the value now?
try
{
// System.out.println(Const.rightPad(" ", level)+" Invoking method: "+fullMethod+", on object: "+object.toString());
Object string = method.invoke(object, null);
if (string!=null)
{
if (string instanceof String)
{
stringList.add(new StringSearchResult((String)string, parentObject, grandParentObject, field.getName()));
// System.out.println(Const.rightPad(" ", level)+" "+field.getName()+" : method "+fullMethod+" --> "+((String)string));
}
else
if (string instanceof String[])
{
String[] array = (String[])string;
for (int x=0;x<array.length;x++)
{
if (array[x]!=null)
{
stringList.add(new StringSearchResult(array[x], parentObject, grandParentObject, field.getName()+"
/// System.out.println(Const.rightPad(" ", level)+" "+field.getName()+" : method "+fullMethod+" --> String #"+x+" = "+array[x]);
}
}
}
else
if (string instanceof Boolean)
{
// OK, let's add the String
stringList.add(new StringSearchResult(((Boolean)string).toString(), parentObject, grandParentObject, field.getName()+" (Boolean)"));
}
else
if (string instanceof Condition)
{
stringList.add(new StringSearchResult(((Condition)string).toString(), parentObject, grandParentObject, field.getName()+" (Condition)"));
}
else
if (string instanceof Object[])
{
for (int j=0;j<((Object[])string).length;j++) findMetaData( ((Object[])string)[j], level+1, stringList, parentObject, grandParentObject);
}
else
{
findMetaData(string, level+1, stringList, parentObject, grandParentObject);
}
}
}
catch(Exception ex)
{
System.out.println(Const.rightPad(" ", level)+" Unable to get access to method "+fullMethod+" : "+e.toString());
}
}
}
}
}
}
private static Method findMethod(Class baseClass, String name)
{
// baseClass.getMethod(methodName[m], null);
Method[] methods = baseClass.getDeclaredMethods();
Method method = null;
// getName()
if (method==null)
{
String getter = constructGetter(name);
method = searchGetter(getter, baseClass, methods);
}
// isName()
if (method==null)
{
String getter = constructIsGetter(name);
method = searchGetter(getter, baseClass, methods);
}
// name()
if (method==null)
{
String getter = name;
method = searchGetter(getter, baseClass, methods);
}
return method;
}
private static Method searchGetter(String getter, Class baseClass, Method[] methods)
{
Method method =null;
try
{
method=baseClass.getMethod(getter, null);
}
catch(Exception e)
{
// Nope try case insensitive.
for (int i=0;i<methods.length;i++)
{
String methodName = methods[i].getName();
if (methodName.equalsIgnoreCase(getter))
{
return methods[i];
}
}
}
return method;
}
public static final String constructGetter(String name)
{
StringBuffer buf = new StringBuffer();
buf.append("get");
buf.append(name.substring(0,1).toUpperCase());
buf.append(name.substring(1));
return buf.toString();
}
public static final String constructIsGetter(String name)
{
StringBuffer buf = new StringBuffer();
buf.append("is");
buf.append(name.substring(0,1).toUpperCase());
buf.append(name.substring(1));
return buf.toString();
}
} |
package org.realityforge.getopt4j;
/**
* Token handles tokenizing the CLI arguments
*/
class Token
{
/**
* Type for a separator token
*/
static final int TOKEN_SEPARATOR = 0;
/**
* Type for a text token
*/
static final int TOKEN_STRING = 1;
private final int m_type;
private final String m_value;
/**
* New Token object with a type and value
*/
Token(final int type, final String value)
{
m_type = type;
m_value = value;
}
/**
* Get the value of the token
*/
final String getValue()
{
return m_value;
}
/**
* Get the type of the token
*/
final int getType()
{
return m_type;
}
/**
* Convert to a string
*/
public final String toString()
{
return m_type + ":" + m_value;
}
} |
package org.springframework.core.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Resource implementation for class path resources.
* Uses either the Thread context class loader or a given
* Class for loading resources.
*
* <p>Supports resolution as File if the class path resource
* resides in the file system, but not for resources in a JAR.
*
* @author Juergen Hoeller
* @since 28.12.2003
* @see java.lang.Thread#getContextClassLoader
* @see java.lang.ClassLoader#getResourceAsStream
* @see java.lang.Class#getResourceAsStream
*/
public class ClassPathResource extends AbstractResource {
private static final String URL_PROTOCOL_FILE = "file";
private final String path;
private Class clazz;
/**
* Create a new ClassPathResource for ClassLoader usage.
* A leading slash will be removed, as the ClassLoader
* resource access methods will not accept it.
* @param path the absolute path within the classpath
* @see java.lang.ClassLoader#getResourceAsStream
*/
public ClassPathResource(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
this.path = path;
}
/**
* Create a new ClassPathResource for Class usage.
* The path can be relative to the given class,
* or absolute within the classpath via a leading slash.
* @param path relative or absolute path within the classpath
* @param clazz the class to load resources with
* @see java.lang.Class#getResourceAsStream
*/
public ClassPathResource(String path, Class clazz) {
this.path = path;
this.clazz = clazz;
}
public InputStream getInputStream() throws IOException {
InputStream is = null;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
is = ccl.getResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException("Could not open " + getDescription());
}
return is;
}
public File getFile() throws IOException {
URL url = null;
if (this.clazz != null) {
url = this.clazz.getResource(this.path);
}
else {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
url = ccl.getResource(this.path);
}
if (url == null) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path " +
"because it does not exist");
}
if (!URL_PROTOCOL_FILE.equals(url.getProtocol())) {
throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path " +
"because it does not reside in the file system: URL=[" + url + "]");
}
return new File(url.getFile());
}
public String getDescription() {
return "classpath resource [" + this.path + "]";
}
} |
package mil.nga.geopackage.test;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.attributes.AttributesColumn;
import mil.nga.geopackage.attributes.AttributesDao;
import mil.nga.geopackage.attributes.AttributesRow;
import mil.nga.geopackage.attributes.AttributesTable;
import mil.nga.geopackage.core.contents.Contents;
import mil.nga.geopackage.core.contents.ContentsDao;
import mil.nga.geopackage.core.contents.ContentsDataType;
import mil.nga.geopackage.core.srs.SpatialReferenceSystem;
import mil.nga.geopackage.core.srs.SpatialReferenceSystemDao;
import mil.nga.geopackage.db.GeoPackageDataType;
import mil.nga.geopackage.extension.CrsWktExtension;
import mil.nga.geopackage.extension.GeometryExtensions;
import mil.nga.geopackage.extension.RTreeIndexExtension;
import mil.nga.geopackage.extension.WebPExtension;
import mil.nga.geopackage.extension.coverage.CoverageDataPng;
import mil.nga.geopackage.extension.coverage.CoverageDataTiff;
import mil.nga.geopackage.extension.coverage.GriddedCoverage;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDao;
import mil.nga.geopackage.extension.coverage.GriddedCoverageDataType;
import mil.nga.geopackage.extension.coverage.GriddedCoverageEncodingType;
import mil.nga.geopackage.extension.coverage.GriddedTile;
import mil.nga.geopackage.extension.coverage.GriddedTileDao;
import mil.nga.geopackage.extension.index.FeatureTableIndex;
import mil.nga.geopackage.extension.related.ExtendedRelation;
import mil.nga.geopackage.extension.related.RelatedTablesExtension;
import mil.nga.geopackage.extension.related.RelationType;
import mil.nga.geopackage.extension.related.UserMappingDao;
import mil.nga.geopackage.extension.related.UserMappingRow;
import mil.nga.geopackage.extension.related.UserMappingTable;
import mil.nga.geopackage.extension.related.dublin.DublinCoreMetadata;
import mil.nga.geopackage.extension.related.dublin.DublinCoreType;
import mil.nga.geopackage.extension.related.media.MediaDao;
import mil.nga.geopackage.extension.related.media.MediaRow;
import mil.nga.geopackage.extension.related.media.MediaTable;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.features.columns.GeometryColumnsDao;
import mil.nga.geopackage.features.user.FeatureColumn;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureResultSet;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.features.user.FeatureTable;
import mil.nga.geopackage.geom.GeoPackageGeometryData;
import mil.nga.geopackage.io.GeoPackageIOUtils;
import mil.nga.geopackage.manager.GeoPackageManager;
import mil.nga.geopackage.metadata.Metadata;
import mil.nga.geopackage.metadata.MetadataDao;
import mil.nga.geopackage.metadata.MetadataScopeType;
import mil.nga.geopackage.metadata.reference.MetadataReference;
import mil.nga.geopackage.metadata.reference.MetadataReferenceDao;
import mil.nga.geopackage.metadata.reference.ReferenceScopeType;
import mil.nga.geopackage.schema.columns.DataColumns;
import mil.nga.geopackage.schema.columns.DataColumnsDao;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintType;
import mil.nga.geopackage.schema.constraints.DataColumnConstraints;
import mil.nga.geopackage.schema.constraints.DataColumnConstraintsDao;
import mil.nga.geopackage.test.extension.related.RelatedTablesUtils;
import mil.nga.geopackage.tiles.TileBoundingBoxUtils;
import mil.nga.geopackage.tiles.TileGenerator;
import mil.nga.geopackage.tiles.TileGrid;
import mil.nga.geopackage.tiles.features.DefaultFeatureTiles;
import mil.nga.geopackage.tiles.features.FeatureTileGenerator;
import mil.nga.geopackage.tiles.features.FeatureTiles;
import mil.nga.geopackage.tiles.matrix.TileMatrix;
import mil.nga.geopackage.tiles.matrix.TileMatrixDao;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSet;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSetDao;
import mil.nga.geopackage.tiles.user.TileDao;
import mil.nga.geopackage.tiles.user.TileRow;
import mil.nga.geopackage.tiles.user.TileTable;
import mil.nga.geopackage.user.ContentValues;
import mil.nga.geopackage.user.custom.UserCustomColumn;
import mil.nga.sf.CircularString;
import mil.nga.sf.CompoundCurve;
import mil.nga.sf.CurvePolygon;
import mil.nga.sf.Geometry;
import mil.nga.sf.GeometryEnvelope;
import mil.nga.sf.GeometryType;
import mil.nga.sf.LineString;
import mil.nga.sf.MultiLineString;
import mil.nga.sf.MultiPolygon;
import mil.nga.sf.Point;
import mil.nga.sf.Polygon;
import mil.nga.sf.proj.Projection;
import mil.nga.sf.proj.ProjectionConstants;
import mil.nga.sf.proj.ProjectionFactory;
import mil.nga.sf.proj.ProjectionTransform;
import mil.nga.sf.util.GeometryEnvelopeBuilder;
import mil.nga.sf.wkb.GeometryCodes;
/**
* Creates an example GeoPackage file
*
* @author osbornb
*/
public class GeoPackageExample {
private static final String GEOPACKAGE_FILE = "example.gpkg";
private static final boolean FEATURES = true;
private static final boolean TILES = true;
private static final boolean ATTRIBUTES = true;
private static final boolean SCHEMA = true;
private static final boolean NON_LINEAR_GEOMETRY_TYPES = true;
private static final boolean RTREE_SPATIAL_INDEX = true;
private static final boolean WEBP = true;
private static final boolean CRS_WKT = true;
private static final boolean METADATA = true;
private static final boolean COVERAGE_DATA = true;
private static final boolean RELATED_TABLES_MEDIA = true;
private static final boolean RELATED_TABLES_FEATURES = true;
private static final boolean RELATED_TABLES_SIMPLE_ATTRIBUTES = true;
private static final boolean GEOMETRY_INDEX = true;
private static final boolean FEATURE_TILE_LINK = true;
private static final String ID_COLUMN = "id";
private static final String GEOMETRY_COLUMN = "geometry";
private static final String TEXT_COLUMN = "text";
private static final String REAL_COLUMN = "real";
private static final String BOOLEAN_COLUMN = "boolean";
private static final String BLOB_COLUMN = "blob";
private static final String INTEGER_COLUMN = "integer";
private static final String TEXT_LIMITED_COLUMN = "text_limited";
private static final String BLOB_LIMITED_COLUMN = "blob_limited";
private static final String DATE_COLUMN = "date";
private static final String DATETIME_COLUMN = "datetime";
public static void main(String[] args) throws SQLException, IOException {
System.out.println("Creating: " + GEOPACKAGE_FILE);
GeoPackage geoPackage = createGeoPackage();
System.out.println("CRS WKT Extension: " + CRS_WKT);
if (CRS_WKT) {
createCrsWktExtension(geoPackage);
}
System.out.println("Features: " + FEATURES);
if (FEATURES) {
createFeatures(geoPackage);
System.out.println("Schema Extension: " + SCHEMA);
if (SCHEMA) {
createSchemaExtension(geoPackage);
}
System.out.println("Geometry Index Extension: " + GEOMETRY_INDEX);
if (GEOMETRY_INDEX) {
createGeometryIndexExtension(geoPackage);
}
System.out.println("Feature Tile Link Extension: "
+ FEATURE_TILE_LINK);
if (FEATURE_TILE_LINK) {
createFeatureTileLinkExtension(geoPackage);
}
System.out.println("Non-Linear Geometry Types Extension: "
+ NON_LINEAR_GEOMETRY_TYPES);
if (NON_LINEAR_GEOMETRY_TYPES) {
createNonLinearGeometryTypesExtension(geoPackage);
}
System.out.println("RTree Spatial Index Extension: "
+ RTREE_SPATIAL_INDEX);
if (RTREE_SPATIAL_INDEX) {
createRTreeSpatialIndexExtension(geoPackage);
}
System.out.println("Related Tables Media Extension: "
+ RELATED_TABLES_MEDIA);
if (RELATED_TABLES_MEDIA) {
createRelatedTablesMediaExtension(geoPackage);
}
System.out.println("Related Tables Features Extension: "
+ RELATED_TABLES_FEATURES);
if (RELATED_TABLES_FEATURES) {
createRelatedTablesFeaturesExtension(geoPackage);
}
} else {
System.out.println("Schema Extension: " + FEATURES);
System.out.println("Geometry Index Extension: " + FEATURES);
System.out.println("Feature Tile Link Extension: " + FEATURES);
System.out.println("Non-Linear Geometry Types Extension: "
+ FEATURES);
System.out.println("RTree Spatial Index Extension: " + FEATURES);
System.out.println("Related Tables Media Extension: "
+ RELATED_TABLES_MEDIA);
System.out.println("Related Tables Features Extension: "
+ RELATED_TABLES_FEATURES);
}
System.out.println("Tiles: " + TILES);
if (TILES) {
createTiles(geoPackage);
System.out.println("WebP Extension: " + WEBP);
if (WEBP) {
createWebPExtension(geoPackage);
}
} else {
System.out.println("WebP Extension: " + TILES);
}
System.out.println("Attributes: " + ATTRIBUTES);
if (ATTRIBUTES) {
createAttributes(geoPackage);
System.out.println("Related Tables Simple Attributes Extension: "
+ RELATED_TABLES_SIMPLE_ATTRIBUTES);
if (RELATED_TABLES_SIMPLE_ATTRIBUTES) {
createRelatedTablesSimpleAttributesExtension(geoPackage);
}
} else {
System.out.println("Related Tables Simple Attributes Extension: "
+ RELATED_TABLES_SIMPLE_ATTRIBUTES);
}
System.out.println("Metadata: " + METADATA);
if (METADATA) {
createMetadataExtension(geoPackage);
}
System.out.println("Coverage Data: " + COVERAGE_DATA);
if (COVERAGE_DATA) {
createCoverageDataExtension(geoPackage);
}
geoPackage.close();
System.out.println("Created: " + geoPackage.getPath());
}
private static GeoPackage createGeoPackage() {
File file = new File(GEOPACKAGE_FILE);
if (file.exists()) {
file.delete();
}
GeoPackageManager.create(file);
GeoPackage geoPackage = GeoPackageManager.open(file);
return geoPackage;
}
private static void createFeatures(GeoPackage geoPackage)
throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
geoPackage.createGeometryColumnsTable();
Point point1 = new Point(-104.801918, 39.720014);
String point1Name = "BIT Systems";
createFeatures(geoPackage, srs, "point1", GeometryType.POINT, point1,
point1Name);
Point point2 = new Point(-77.196736, 38.753370);
String point2Name = "NGA";
createFeatures(geoPackage, srs, "point2", GeometryType.POINT, point2,
point2Name);
LineString line1 = new LineString();
String line1Name = "East Lockheed Drive";
line1.addPoint(new Point(-104.800614, 39.720721));
line1.addPoint(new Point(-104.802174, 39.720726));
line1.addPoint(new Point(-104.802584, 39.720660));
line1.addPoint(new Point(-104.803088, 39.720477));
line1.addPoint(new Point(-104.803474, 39.720209));
createFeatures(geoPackage, srs, "line1", GeometryType.LINESTRING,
line1, line1Name);
LineString line2 = new LineString();
String line2Name = "NGA";
line2.addPoint(new Point(-77.196650, 38.756501));
line2.addPoint(new Point(-77.196414, 38.755979));
line2.addPoint(new Point(-77.195518, 38.755208));
line2.addPoint(new Point(-77.195303, 38.755272));
line2.addPoint(new Point(-77.195351, 38.755459));
line2.addPoint(new Point(-77.195863, 38.755697));
line2.addPoint(new Point(-77.196328, 38.756069));
line2.addPoint(new Point(-77.196568, 38.756526));
createFeatures(geoPackage, srs, "line2", GeometryType.LINESTRING,
line2, line2Name);
Polygon polygon1 = new Polygon();
String polygon1Name = "BIT Systems";
LineString ring1 = new LineString();
ring1.addPoint(new Point(-104.802246, 39.720343));
ring1.addPoint(new Point(-104.802246, 39.719753));
ring1.addPoint(new Point(-104.802183, 39.719754));
ring1.addPoint(new Point(-104.802184, 39.719719));
ring1.addPoint(new Point(-104.802138, 39.719694));
ring1.addPoint(new Point(-104.802097, 39.719691));
ring1.addPoint(new Point(-104.802096, 39.719648));
ring1.addPoint(new Point(-104.801646, 39.719648));
ring1.addPoint(new Point(-104.801644, 39.719722));
ring1.addPoint(new Point(-104.801550, 39.719723));
ring1.addPoint(new Point(-104.801549, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720207));
ring1.addPoint(new Point(-104.801648, 39.720341));
ring1.addPoint(new Point(-104.802246, 39.720343));
polygon1.addRing(ring1);
createFeatures(geoPackage, srs, "polygon1", GeometryType.POLYGON,
polygon1, polygon1Name);
Polygon polygon2 = new Polygon();
String polygon2Name = "NGA Visitor Center";
LineString ring2 = new LineString();
ring2.addPoint(new Point(-77.195299, 38.755159));
ring2.addPoint(new Point(-77.195203, 38.755080));
ring2.addPoint(new Point(-77.195410, 38.754930));
ring2.addPoint(new Point(-77.195350, 38.754884));
ring2.addPoint(new Point(-77.195228, 38.754966));
ring2.addPoint(new Point(-77.195135, 38.754889));
ring2.addPoint(new Point(-77.195048, 38.754956));
ring2.addPoint(new Point(-77.194986, 38.754906));
ring2.addPoint(new Point(-77.194897, 38.754976));
ring2.addPoint(new Point(-77.194953, 38.755025));
ring2.addPoint(new Point(-77.194763, 38.755173));
ring2.addPoint(new Point(-77.194827, 38.755224));
ring2.addPoint(new Point(-77.195012, 38.755082));
ring2.addPoint(new Point(-77.195041, 38.755104));
ring2.addPoint(new Point(-77.195028, 38.755116));
ring2.addPoint(new Point(-77.195090, 38.755167));
ring2.addPoint(new Point(-77.195106, 38.755154));
ring2.addPoint(new Point(-77.195205, 38.755233));
ring2.addPoint(new Point(-77.195299, 38.755159));
polygon2.addRing(ring2);
createFeatures(geoPackage, srs, "polygon2", GeometryType.POLYGON,
polygon2, polygon2Name);
List<Geometry> geometries1 = new ArrayList<>();
List<String> geometries1Names = new ArrayList<>();
geometries1.add(point1);
geometries1Names.add(point1Name);
geometries1.add(line1);
geometries1Names.add(line1Name);
geometries1.add(polygon1);
geometries1Names.add(polygon1Name);
createFeatures(geoPackage, srs, "geometry1", GeometryType.GEOMETRY,
geometries1, geometries1Names);
List<Geometry> geometries2 = new ArrayList<>();
List<String> geometries2Names = new ArrayList<>();
geometries2.add(point2);
geometries2Names.add(point2Name);
geometries2.add(line2);
geometries2Names.add(line2Name);
geometries2.add(polygon2);
geometries2Names.add(polygon2Name);
createFeatures(geoPackage, srs, "geometry2", GeometryType.GEOMETRY,
geometries2, geometries2Names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
Geometry geometry, String name) throws SQLException {
List<Geometry> geometries = new ArrayList<>();
geometries.add(geometry);
List<String> names = new ArrayList<>();
names.add(name);
createFeatures(geoPackage, srs, tableName, type, geometries, names);
}
private static void createFeatures(GeoPackage geoPackage,
SpatialReferenceSystem srs, String tableName, GeometryType type,
List<Geometry> geometries, List<String> names) throws SQLException {
GeometryEnvelope envelope = null;
for (Geometry geometry : geometries) {
if (envelope == null) {
envelope = GeometryEnvelopeBuilder.buildEnvelope(geometry);
} else {
GeometryEnvelopeBuilder.buildEnvelope(geometry, envelope);
}
}
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(tableName);
contents.setDataType(ContentsDataType.FEATURES);
contents.setIdentifier(tableName);
contents.setDescription("example: " + tableName);
contents.setMinX(envelope.getMinX());
contents.setMinY(envelope.getMinY());
contents.setMaxX(envelope.getMaxX());
contents.setMaxY(envelope.getMaxY());
contents.setSrs(srs);
List<FeatureColumn> columns = new ArrayList<FeatureColumn>();
int columnNumber = 0;
columns.add(FeatureColumn.createPrimaryKeyColumn(columnNumber++,
ID_COLUMN));
columns.add(FeatureColumn.createGeometryColumn(columnNumber++,
GEOMETRY_COLUMN, type, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(FeatureColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BOOLEAN_COLUMN,
GeoPackageDataType.BOOLEAN, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, INTEGER_COLUMN,
GeoPackageDataType.INTEGER, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(FeatureColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(FeatureColumn.createColumn(columnNumber++, DATETIME_COLUMN,
GeoPackageDataType.DATETIME, false, null));
FeatureTable table = new FeatureTable(tableName, columns);
geoPackage.createFeatureTable(table);
contentsDao.create(contents);
GeometryColumnsDao geometryColumnsDao = geoPackage
.getGeometryColumnsDao();
GeometryColumns geometryColumns = new GeometryColumns();
geometryColumns.setContents(contents);
geometryColumns.setColumnName(GEOMETRY_COLUMN);
geometryColumns.setGeometryType(type);
geometryColumns.setSrs(srs);
geometryColumns.setZ((byte) 0);
geometryColumns.setM((byte) 0);
geometryColumnsDao.create(geometryColumns);
FeatureDao dao = geoPackage.getFeatureDao(geometryColumns);
for (int i = 0; i < geometries.size(); i++) {
Geometry geometry = geometries.get(i);
String name;
if (names != null) {
name = names.get(i);
} else {
name = UUID.randomUUID().toString();
}
FeatureRow newRow = dao.newRow();
GeoPackageGeometryData geometryData = new GeoPackageGeometryData(
geometryColumns.getSrsId());
geometryData.setGeometry(geometry);
newRow.setGeometry(geometryData);
newRow.setValue(TEXT_COLUMN, name);
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
dao.create(newRow);
}
}
private static void createTiles(GeoPackage geoPackage) throws IOException,
SQLException {
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, "bit_systems", bitsBoundingBox, 15, 17, "png");
BoundingBox ngaBoundingBox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
createTiles(geoPackage, "nga", ngaBoundingBox, 15, 16, "png");
}
private static void createTiles(GeoPackage geoPackage, String name,
BoundingBox boundingBox, int minZoomLevel, int maxZoomLevel,
String extension) throws SQLException, IOException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WEB_MERCATOR);
TileGrid totalTileGrid = TileBoundingBoxUtils.getTileGrid(boundingBox,
minZoomLevel);
BoundingBox totalBoundingBox = TileBoundingBoxUtils
.getWebMercatorBoundingBox(totalTileGrid, minZoomLevel);
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = new Contents();
contents.setTableName(name);
contents.setDataType(ContentsDataType.TILES);
contents.setIdentifier(name);
contents.setDescription(name);
contents.setMinX(totalBoundingBox.getMinLongitude());
contents.setMinY(totalBoundingBox.getMinLatitude());
contents.setMaxX(totalBoundingBox.getMaxLongitude());
contents.setMaxY(totalBoundingBox.getMaxLatitude());
contents.setSrs(srs);
TileTable tileTable = TestUtils.buildTileTable(contents.getTableName());
geoPackage.createTileTable(tileTable);
contentsDao.create(contents);
TileMatrixSetDao tileMatrixSetDao = geoPackage.getTileMatrixSetDao();
TileMatrixSet tileMatrixSet = new TileMatrixSet();
tileMatrixSet.setContents(contents);
tileMatrixSet.setSrs(contents.getSrs());
tileMatrixSet.setMinX(contents.getMinX());
tileMatrixSet.setMinY(contents.getMinY());
tileMatrixSet.setMaxX(contents.getMaxX());
tileMatrixSet.setMaxY(contents.getMaxY());
tileMatrixSetDao.create(tileMatrixSet);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
final String tilesPath = "tiles/";
TileGrid tileGrid = totalTileGrid;
for (int zoom = minZoomLevel; zoom <= maxZoomLevel; zoom++) {
final String zoomPath = tilesPath + zoom + "/";
Integer tileWidth = null;
Integer tileHeight = null;
TileDao dao = geoPackage.getTileDao(tileMatrixSet);
for (long x = tileGrid.getMinX(); x <= tileGrid.getMaxX(); x++) {
final String xPath = zoomPath + x + "/";
for (long y = tileGrid.getMinY(); y <= tileGrid.getMaxY(); y++) {
final String yPath = xPath + y + "." + extension;
if (TestUtils.class.getResource("/" + yPath) != null) {
File tileFile = TestUtils.getTestFile(yPath);
byte[] tileBytes = GeoPackageIOUtils
.fileBytes(tileFile);
if (tileWidth == null || tileHeight == null) {
BufferedImage tileImage = ImageIO.read(tileFile);
if (tileImage != null) {
tileHeight = tileImage.getHeight();
tileWidth = tileImage.getWidth();
}
}
TileRow newRow = dao.newRow();
newRow.setZoomLevel(zoom);
newRow.setTileColumn(x - tileGrid.getMinX());
newRow.setTileRow(y - tileGrid.getMinY());
newRow.setTileData(tileBytes);
dao.create(newRow);
}
}
}
if (tileWidth == null) {
tileWidth = 256;
}
if (tileHeight == null) {
tileHeight = 256;
}
long matrixWidth = tileGrid.getMaxX() - tileGrid.getMinX() + 1;
long matrixHeight = tileGrid.getMaxY() - tileGrid.getMinY() + 1;
double pixelXSize = (tileMatrixSet.getMaxX() - tileMatrixSet
.getMinX()) / (matrixWidth * tileWidth);
double pixelYSize = (tileMatrixSet.getMaxY() - tileMatrixSet
.getMinY()) / (matrixHeight * tileHeight);
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(contents);
tileMatrix.setZoomLevel(zoom);
tileMatrix.setMatrixWidth(matrixWidth);
tileMatrix.setMatrixHeight(matrixHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setPixelXSize(pixelXSize);
tileMatrix.setPixelYSize(pixelYSize);
tileMatrixDao.create(tileMatrix);
tileGrid = TileBoundingBoxUtils.tileGridZoomIncrease(tileGrid, 1);
}
}
private static void createAttributes(GeoPackage geoPackage) {
List<AttributesColumn> columns = new ArrayList<AttributesColumn>();
int columnNumber = 1;
columns.add(AttributesColumn.createColumn(columnNumber++, TEXT_COLUMN,
GeoPackageDataType.TEXT, false, ""));
columns.add(AttributesColumn.createColumn(columnNumber++, REAL_COLUMN,
GeoPackageDataType.REAL, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
BOOLEAN_COLUMN, GeoPackageDataType.BOOLEAN, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, BLOB_COLUMN,
GeoPackageDataType.BLOB, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
INTEGER_COLUMN, GeoPackageDataType.INTEGER, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
TEXT_LIMITED_COLUMN, GeoPackageDataType.TEXT, (long) UUID
.randomUUID().toString().length(), false, null));
columns.add(AttributesColumn
.createColumn(columnNumber++, BLOB_LIMITED_COLUMN,
GeoPackageDataType.BLOB, (long) UUID.randomUUID()
.toString().getBytes().length, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++, DATE_COLUMN,
GeoPackageDataType.DATE, false, null));
columns.add(AttributesColumn.createColumn(columnNumber++,
DATETIME_COLUMN, GeoPackageDataType.DATETIME, false, null));
AttributesTable attributesTable = geoPackage
.createAttributesTableWithId("attributes", columns);
AttributesDao attributesDao = geoPackage
.getAttributesDao(attributesTable.getTableName());
for (int i = 0; i < 10; i++) {
AttributesRow newRow = attributesDao.newRow();
newRow.setValue(TEXT_COLUMN, UUID.randomUUID().toString());
newRow.setValue(REAL_COLUMN, Math.random() * 5000.0);
newRow.setValue(BOOLEAN_COLUMN, Math.random() < .5 ? false : true);
newRow.setValue(BLOB_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(INTEGER_COLUMN, (int) (Math.random() * 500));
newRow.setValue(TEXT_LIMITED_COLUMN, UUID.randomUUID().toString());
newRow.setValue(BLOB_LIMITED_COLUMN, UUID.randomUUID().toString()
.getBytes());
newRow.setValue(DATE_COLUMN, new Date());
newRow.setValue(DATETIME_COLUMN, new Date());
attributesDao.create(newRow);
}
}
private static void createGeometryIndexExtension(GeoPackage geoPackage) {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTableIndex featureTableIndex = new FeatureTableIndex(
geoPackage, featureDao);
featureTableIndex.index();
}
}
private static void createFeatureTileLinkExtension(GeoPackage geoPackage)
throws SQLException, IOException {
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTiles featureTiles = new DefaultFeatureTiles(featureDao);
FeatureTableIndex featureIndex = new FeatureTableIndex(geoPackage,
featureDao);
featureTiles.setFeatureIndex(featureIndex);
BoundingBox boundingBox = featureDao.getBoundingBox();
Projection projection = featureDao.getProjection();
Projection requestProjection = ProjectionFactory
.getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = projection
.getTransformation(requestProjection);
BoundingBox requestBoundingBox = boundingBox.transform(transform);
int zoomLevel = TileBoundingBoxUtils
.getZoomLevel(requestBoundingBox);
zoomLevel = Math.min(zoomLevel, 19);
int minZoom = zoomLevel - 2;
int maxZoom = zoomLevel + 2;
TileGenerator tileGenerator = new FeatureTileGenerator(geoPackage,
featureTable + "_tiles", featureTiles, minZoom, maxZoom,
requestBoundingBox, requestProjection);
tileGenerator.generateTiles();
}
}
private static int dataColumnConstraintIndex = 0;
private static void createSchemaExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createDataColumnConstraintsTable();
DataColumnConstraintsDao dao = geoPackage.getDataColumnConstraintsDao();
DataColumnConstraints sampleRange = new DataColumnConstraints();
sampleRange.setConstraintName("sampleRange");
sampleRange.setConstraintType(DataColumnConstraintType.RANGE);
sampleRange.setMin(BigDecimal.ONE);
sampleRange.setMinIsInclusive(true);
sampleRange.setMax(BigDecimal.TEN);
sampleRange.setMaxIsInclusive(true);
sampleRange.setDescription("sampleRange description");
dao.create(sampleRange);
DataColumnConstraints sampleEnum1 = new DataColumnConstraints();
sampleEnum1.setConstraintName("sampleEnum");
sampleEnum1.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum1.setValue("1");
sampleEnum1.setDescription("sampleEnum description");
dao.create(sampleEnum1);
DataColumnConstraints sampleEnum3 = new DataColumnConstraints();
sampleEnum3.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum3.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum3.setValue("3");
sampleEnum3.setDescription("sampleEnum description");
dao.create(sampleEnum3);
DataColumnConstraints sampleEnum5 = new DataColumnConstraints();
sampleEnum5.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum5.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum5.setValue("5");
sampleEnum5.setDescription("sampleEnum description");
dao.create(sampleEnum5);
DataColumnConstraints sampleEnum7 = new DataColumnConstraints();
sampleEnum7.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum7.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum7.setValue("7");
sampleEnum7.setDescription("sampleEnum description");
dao.create(sampleEnum7);
DataColumnConstraints sampleEnum9 = new DataColumnConstraints();
sampleEnum9.setConstraintName(sampleEnum1.getConstraintName());
sampleEnum9.setConstraintType(DataColumnConstraintType.ENUM);
sampleEnum9.setValue("9");
sampleEnum9.setDescription("sampleEnum description");
dao.create(sampleEnum9);
DataColumnConstraints sampleGlob = new DataColumnConstraints();
sampleGlob.setConstraintName("sampleGlob");
sampleGlob.setConstraintType(DataColumnConstraintType.GLOB);
sampleGlob.setValue("[1-2][0-9][0-9][0-9]");
sampleGlob.setDescription("sampleGlob description");
dao.create(sampleGlob);
geoPackage.createDataColumnsTable();
DataColumnsDao dataColumnsDao = geoPackage.getDataColumnsDao();
List<String> featureTables = geoPackage.getFeatureTables();
for (String featureTable : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(featureTable);
FeatureTable table = featureDao.getTable();
for (FeatureColumn column : table.getColumns()) {
if (!column.isPrimaryKey()
&& column.getDataType() == GeoPackageDataType.INTEGER) {
DataColumns dataColumns = new DataColumns();
dataColumns.setContents(featureDao.getGeometryColumns()
.getContents());
dataColumns.setColumnName(column.getName());
dataColumns.setName(featureTable);
dataColumns.setTitle("TEST_TITLE");
dataColumns.setDescription("TEST_DESCRIPTION");
dataColumns.setMimeType("TEST_MIME_TYPE");
DataColumnConstraintType constraintType = DataColumnConstraintType
.values()[dataColumnConstraintIndex];
dataColumnConstraintIndex++;
if (dataColumnConstraintIndex >= DataColumnConstraintType
.values().length) {
dataColumnConstraintIndex = 0;
}
int value = 0;
String constraintName = null;
switch (constraintType) {
case RANGE:
constraintName = sampleRange.getConstraintName();
value = 1 + (int) (Math.random() * 10);
break;
case ENUM:
constraintName = sampleEnum1.getConstraintName();
value = 1 + ((int) (Math.random() * 5) * 2);
break;
case GLOB:
constraintName = sampleGlob.getConstraintName();
value = 1000 + (int) (Math.random() * 2000);
break;
default:
throw new GeoPackageException(
"Unexpected Constraint Type: " + constraintType);
}
dataColumns.setConstraintName(constraintName);
ContentValues values = new ContentValues();
values.put(column.getName(), value);
featureDao.update(values, null, null);
dataColumnsDao.create(dataColumns);
break;
}
}
}
}
private static void createNonLinearGeometryTypesExtension(
GeoPackage geoPackage) throws SQLException {
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.getOrCreateCode(
ProjectionConstants.AUTHORITY_EPSG,
(long) ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
GeometryExtensions extensions = new GeometryExtensions(geoPackage);
String tableName = "non_linear_geometries";
List<Geometry> geometries = new ArrayList<>();
List<String> geometryNames = new ArrayList<>();
CircularString circularString = new CircularString();
circularString.addPoint(new Point(-122.358, 47.653));
circularString.addPoint(new Point(-122.348, 47.649));
circularString.addPoint(new Point(-122.348, 47.658));
circularString.addPoint(new Point(-122.358, 47.658));
circularString.addPoint(new Point(-122.358, 47.653));
for (int i = GeometryCodes.getCode(GeometryType.CIRCULARSTRING); i <= GeometryCodes
.getCode(GeometryType.SURFACE); i++) {
GeometryType geometryType = GeometryCodes.getGeometryType(i);
extensions.getOrCreate(tableName, GEOMETRY_COLUMN, geometryType);
Geometry geometry = null;
String name = geometryType.getName().toLowerCase();
switch (geometryType) {
case CIRCULARSTRING:
geometry = circularString;
break;
case COMPOUNDCURVE:
CompoundCurve compoundCurve = new CompoundCurve();
compoundCurve.addLineString(circularString);
geometry = compoundCurve;
break;
case CURVEPOLYGON:
CurvePolygon<CircularString> curvePolygon = new CurvePolygon<>();
curvePolygon.addRing(circularString);
geometry = curvePolygon;
break;
case MULTICURVE:
MultiLineString multiCurve = new MultiLineString();
multiCurve.addLineString(circularString);
geometry = multiCurve;
break;
case MULTISURFACE:
MultiPolygon multiSurface = new MultiPolygon();
Polygon polygon = new Polygon();
polygon.addRing(circularString);
multiSurface.addPolygon(polygon);
geometry = multiSurface;
break;
case CURVE:
CompoundCurve curve = new CompoundCurve();
curve.addLineString(circularString);
geometry = curve;
break;
case SURFACE:
CurvePolygon<CircularString> surface = new CurvePolygon<>();
surface.addRing(circularString);
geometry = surface;
break;
default:
throw new GeoPackageException("Unexpected Geometry Type: "
+ geometryType);
}
geometries.add(geometry);
geometryNames.add(name);
}
createFeatures(geoPackage, srs, tableName, GeometryType.GEOMETRY,
geometries, geometryNames);
}
private static void createWebPExtension(GeoPackage geoPackage)
throws SQLException, IOException {
WebPExtension webpExtension = new WebPExtension(geoPackage);
String tableName = "webp_tiles";
webpExtension.getOrCreate(tableName);
geoPackage.createTileMatrixSetTable();
geoPackage.createTileMatrixTable();
BoundingBox bitsBoundingBox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
createTiles(geoPackage, tableName, bitsBoundingBox, 15, 15, "webp");
}
private static void createCrsWktExtension(GeoPackage geoPackage)
throws SQLException {
CrsWktExtension wktExtension = new CrsWktExtension(geoPackage);
wktExtension.getOrCreate();
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem srs = srsDao.queryForOrganizationCoordsysId(
ProjectionConstants.AUTHORITY_EPSG,
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
SpatialReferenceSystem testSrs = new SpatialReferenceSystem();
testSrs.setSrsName("test");
testSrs.setSrsId(12345);
testSrs.setOrganization("test_org");
testSrs.setOrganizationCoordsysId(testSrs.getSrsId());
testSrs.setDefinition(srs.getDefinition());
testSrs.setDescription(srs.getDescription());
testSrs.setDefinition_12_063(srs.getDefinition_12_063());
srsDao.create(testSrs);
SpatialReferenceSystem testSrs2 = new SpatialReferenceSystem();
testSrs2.setSrsName("test2");
testSrs2.setSrsId(54321);
testSrs2.setOrganization("test_org");
testSrs2.setOrganizationCoordsysId(testSrs2.getSrsId());
testSrs2.setDefinition(srs.getDefinition());
testSrs2.setDescription(srs.getDescription());
srsDao.create(testSrs2);
}
private static void createMetadataExtension(GeoPackage geoPackage)
throws SQLException {
geoPackage.createMetadataTable();
MetadataDao metadataDao = geoPackage.getMetadataDao();
Metadata metadata1 = new Metadata();
metadata1.setId(1);
metadata1.setMetadataScope(MetadataScopeType.DATASET);
metadata1.setStandardUri("TEST_URI_1");
metadata1.setMimeType("text/xml");
metadata1.setMetadata("TEST METADATA 1");
metadataDao.create(metadata1);
Metadata metadata2 = new Metadata();
metadata2.setId(2);
metadata2.setMetadataScope(MetadataScopeType.FEATURE_TYPE);
metadata2.setStandardUri("TEST_URI_2");
metadata2.setMimeType("text/xml");
metadata2.setMetadata("TEST METADATA 2");
metadataDao.create(metadata2);
Metadata metadata3 = new Metadata();
metadata3.setId(3);
metadata3.setMetadataScope(MetadataScopeType.TILE);
metadata3.setStandardUri("TEST_URI_3");
metadata3.setMimeType("text/xml");
metadata3.setMetadata("TEST METADATA 3");
metadataDao.create(metadata3);
geoPackage.createMetadataReferenceTable();
MetadataReferenceDao metadataReferenceDao = geoPackage
.getMetadataReferenceDao();
MetadataReference reference1 = new MetadataReference();
reference1.setReferenceScope(ReferenceScopeType.GEOPACKAGE);
reference1.setMetadata(metadata1);
metadataReferenceDao.create(reference1);
List<String> tileTables = geoPackage.getTileTables();
if (!tileTables.isEmpty()) {
String table = tileTables.get(0);
MetadataReference reference2 = new MetadataReference();
reference2.setReferenceScope(ReferenceScopeType.TABLE);
reference2.setTableName(table);
reference2.setMetadata(metadata2);
reference2.setParentMetadata(metadata1);
metadataReferenceDao.create(reference2);
}
List<String> featureTables = geoPackage.getFeatureTables();
if (!featureTables.isEmpty()) {
String table = featureTables.get(0);
MetadataReference reference3 = new MetadataReference();
reference3.setReferenceScope(ReferenceScopeType.ROW_COL);
reference3.setTableName(table);
reference3.setColumnName(GEOMETRY_COLUMN);
reference3.setRowIdValue(1L);
reference3.setMetadata(metadata3);
metadataReferenceDao.create(reference3);
}
}
private static void createCoverageDataExtension(GeoPackage geoPackage)
throws SQLException {
createCoverageDataPngExtension(geoPackage);
createCoverageDataTiffExtension(geoPackage);
}
private static void createCoverageDataPngExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-11667347.997449303,
4824705.2253603265, -11666125.00499674, 4825928.217812888);
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem tileMatrixSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = ProjectionFactory.getProjection(
ProjectionConstants.EPSG_WEB_MERCATOR).getTransformation(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
BoundingBox contentsBoundingBox = bbox.transform(transform);
CoverageDataPng coverageData = CoverageDataPng
.createTileTableWithMetadata(geoPackage, "coverage_png",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.INTEGER);
griddedCoverage.setDataNull(new Double(Short.MAX_VALUE
- Short.MIN_VALUE));
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 3;
int tileHeight = 3;
short[][] tilePixels = new short[tileHeight][tileWidth];
tilePixels[0][0] = (short) 1661.95;
tilePixels[0][1] = (short) 1665.40;
tilePixels[0][2] = (short) 1668.19;
tilePixels[1][0] = (short) 1657.18;
tilePixels[1][1] = (short) 1663.39;
tilePixels[1][2] = (short) 1669.65;
tilePixels[2][0] = (short) 1654.78;
tilePixels[2][1] = (short) 1660.31;
tilePixels[2][2] = (short) 1666.44;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createCoverageDataTiffExtension(GeoPackage geoPackage)
throws SQLException {
BoundingBox bbox = new BoundingBox(-8593967.964158937,
4685284.085768163, -8592744.971706374, 4687730.070673289);
SpatialReferenceSystemDao srsDao = geoPackage
.getSpatialReferenceSystemDao();
SpatialReferenceSystem contentsSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
SpatialReferenceSystem tileMatrixSrs = srsDao
.getOrCreateFromEpsg(ProjectionConstants.EPSG_WEB_MERCATOR);
ProjectionTransform transform = ProjectionFactory.getProjection(
ProjectionConstants.EPSG_WEB_MERCATOR).getTransformation(
ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D);
BoundingBox contentsBoundingBox = bbox.transform(transform);
CoverageDataTiff coverageData = CoverageDataTiff
.createTileTableWithMetadata(geoPackage, "coverage_tiff",
contentsBoundingBox, contentsSrs.getId(), bbox,
tileMatrixSrs.getId());
TileDao tileDao = coverageData.getTileDao();
TileMatrixSet tileMatrixSet = coverageData.getTileMatrixSet();
GriddedCoverageDao griddedCoverageDao = coverageData
.getGriddedCoverageDao();
GriddedCoverage griddedCoverage = new GriddedCoverage();
griddedCoverage.setTileMatrixSet(tileMatrixSet);
griddedCoverage.setDataType(GriddedCoverageDataType.FLOAT);
griddedCoverage.setDataNull((double) Float.MAX_VALUE);
griddedCoverage
.setGridCellEncodingType(GriddedCoverageEncodingType.CENTER);
griddedCoverageDao.create(griddedCoverage);
GriddedTileDao griddedTileDao = coverageData.getGriddedTileDao();
int width = 1;
int height = 1;
int tileWidth = 4;
int tileHeight = 4;
float[][] tilePixels = new float[tileHeight][tileWidth];
tilePixels[0][0] = 71.78f;
tilePixels[0][1] = 74.31f;
tilePixels[0][2] = 70.19f;
tilePixels[0][3] = 68.07f;
tilePixels[1][0] = 61.01f;
tilePixels[1][1] = 69.66f;
tilePixels[1][2] = 68.65f;
tilePixels[1][3] = 72.02f;
tilePixels[2][0] = 41.58f;
tilePixels[2][1] = 69.46f;
tilePixels[2][2] = 67.56f;
tilePixels[2][3] = 70.42f;
tilePixels[3][0] = 54.03f;
tilePixels[3][1] = 71.32f;
tilePixels[3][2] = 57.61f;
tilePixels[3][3] = 54.96f;
byte[] imageBytes = coverageData.drawTileData(tilePixels);
TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao();
TileMatrix tileMatrix = new TileMatrix();
tileMatrix.setContents(tileMatrixSet.getContents());
tileMatrix.setMatrixHeight(height);
tileMatrix.setMatrixWidth(width);
tileMatrix.setTileHeight(tileHeight);
tileMatrix.setTileWidth(tileWidth);
tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox
.getMinLongitude()) / width / tileWidth);
tileMatrix
.setPixelYSize((bbox.getMaxLatitude() - bbox.getMinLatitude())
/ height / tileHeight);
tileMatrix.setZoomLevel(15);
tileMatrixDao.create(tileMatrix);
TileRow tileRow = tileDao.newRow();
tileRow.setTileColumn(0);
tileRow.setTileRow(0);
tileRow.setZoomLevel(tileMatrix.getZoomLevel());
tileRow.setTileData(imageBytes);
long tileId = tileDao.create(tileRow);
GriddedTile griddedTile = new GriddedTile();
griddedTile.setContents(tileMatrixSet.getContents());
griddedTile.setTableId(tileId);
griddedTileDao.create(griddedTile);
}
private static void createRTreeSpatialIndexExtension(GeoPackage geoPackage) {
RTreeIndexExtension extension = new RTreeIndexExtension(geoPackage);
List<String> featureTables = geoPackage.getFeatureTables();
for (String tableName : featureTables) {
FeatureDao featureDao = geoPackage.getFeatureDao(tableName);
FeatureTable featureTable = featureDao.getTable();
extension.create(featureTable);
}
}
private static void createRelatedTablesMediaExtension(GeoPackage geoPackage) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
List<UserCustomColumn> additionalMediaColumns = RelatedTablesUtils
.createAdditionalUserColumns(MediaTable.numRequiredColumns());
MediaTable mediaTable = MediaTable.create("media",
additionalMediaColumns);
List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
.createAdditionalUserColumns(UserMappingTable
.numRequiredColumns());
String tableName1 = "geometry1";
UserMappingTable userMappingTable1 = UserMappingTable.create(tableName1
+ "_" + mediaTable.getTableName(), additionalMappingColumns);
ExtendedRelation relation1 = relatedTables.addRelationship(tableName1,
mediaTable, userMappingTable1);
insertRelatedTablesMediaExtensionRows(geoPackage, relation1,
"BIT Systems%", "BIT Systems", "BITSystems_Logo.png",
"image/png", "BIT Systems Logo", "http:
String tableName2 = "geometry2";
UserMappingTable userMappingTable2 = UserMappingTable.create(tableName2
+ "_" + mediaTable.getTableName(), additionalMappingColumns);
ExtendedRelation relation2 = relatedTables.addRelationship(tableName2,
mediaTable, userMappingTable2);
insertRelatedTablesMediaExtensionRows(geoPackage, relation2, "NGA%",
"NGA", "NGA_Logo.png", "image/png", "NGA Logo",
"http:
insertRelatedTablesMediaExtensionRows(geoPackage, relation2, "NGA",
"NGA", "NGA.jpg", "image/jpeg", "Aerial View of NGA East",
"http:
}
private static void insertRelatedTablesMediaExtensionRows(
GeoPackage geoPackage, ExtendedRelation relation, String query,
String name, String file, String contentType, String description,
String source) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
FeatureDao featureDao = geoPackage.getFeatureDao(relation
.getBaseTableName());
MediaDao mediaDao = relatedTables.getMediaDao(relation);
UserMappingDao userMappingDao = relatedTables.getMappingDao(relation);
MediaRow mediaRow = mediaDao.newRow();
mediaRow.setData(TestUtils.getTestFileBytes(file));
mediaRow.setContentType(contentType);
RelatedTablesUtils.populateUserRow(mediaDao.getTable(), mediaRow,
MediaTable.requiredColumns());
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.TITLE, name);
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.DESCRIPTION,
description);
DublinCoreMetadata.setValue(mediaRow, DublinCoreType.SOURCE, source);
long mediaRowId = mediaDao.create(mediaRow);
FeatureResultSet featureResultSet = featureDao.queryForLike(
TEXT_COLUMN, query);
while (featureResultSet.moveToNext()) {
FeatureRow featureRow = featureResultSet.getRow();
UserMappingRow userMappingRow = userMappingDao.newRow();
userMappingRow.setBaseId(featureRow.getId());
userMappingRow.setRelatedId(mediaRowId);
RelatedTablesUtils.populateUserRow(userMappingDao.getTable(),
userMappingRow, UserMappingTable.requiredColumns());
String featureName = featureRow.getValue(TEXT_COLUMN).toString();
DublinCoreMetadata.setValue(userMappingRow, DublinCoreType.TITLE,
featureName + " - " + name);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.DESCRIPTION, featureName + " - "
+ description);
DublinCoreMetadata.setValue(userMappingRow, DublinCoreType.SOURCE,
source);
userMappingDao.create(userMappingRow);
}
featureResultSet.close();
}
private static void createRelatedTablesFeaturesExtension(
GeoPackage geoPackage) {
createRelatedTablesFeaturesExtension(geoPackage, "point1", "polygon1");
createRelatedTablesFeaturesExtension(geoPackage, "point2", "line2");
}
private static void createRelatedTablesFeaturesExtension(
GeoPackage geoPackage, String tableName1, String tableName2) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
List<UserCustomColumn> additionalMappingColumns = RelatedTablesUtils
.createAdditionalUserColumns(UserMappingTable
.numRequiredColumns());
UserMappingTable userMappingTable = UserMappingTable.create(tableName1
+ "_" + tableName2, additionalMappingColumns);
ExtendedRelation relation = relatedTables.addRelationship(tableName1,
tableName2, userMappingTable, RelationType.FEATURES);
insertRelatedTablesFeaturesExtensionRows(geoPackage, relation);
}
private static void insertRelatedTablesFeaturesExtensionRows(
GeoPackage geoPackage, ExtendedRelation relation) {
RelatedTablesExtension relatedTables = new RelatedTablesExtension(
geoPackage);
UserMappingDao userMappingDao = relatedTables.getMappingDao(relation);
FeatureDao featureDao1 = geoPackage.getFeatureDao(relation
.getBaseTableName());
FeatureDao featureDao2 = geoPackage.getFeatureDao(relation
.getRelatedTableName());
FeatureResultSet featureResultSet1 = featureDao1.queryForAll();
while (featureResultSet1.moveToNext()) {
FeatureRow featureRow1 = featureResultSet1.getRow();
String featureName = featureRow1.getValue(TEXT_COLUMN).toString();
FeatureResultSet featureResultSet2 = featureDao2.queryForEq(
TEXT_COLUMN, featureName);
while (featureResultSet2.moveToNext()) {
FeatureRow featureRow2 = featureResultSet2.getRow();
UserMappingRow userMappingRow = userMappingDao.newRow();
userMappingRow.setBaseId(featureRow1.getId());
userMappingRow.setRelatedId(featureRow2.getId());
RelatedTablesUtils.populateUserRow(userMappingDao.getTable(),
userMappingRow, UserMappingTable.requiredColumns());
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.TITLE, featureName);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.DESCRIPTION, featureName);
DublinCoreMetadata.setValue(userMappingRow,
DublinCoreType.SOURCE, featureName);
userMappingDao.create(userMappingRow);
}
featureResultSet2.close();
}
featureResultSet1.close();
}
private static void createRelatedTablesSimpleAttributesExtension(
GeoPackage geoPackage) {
// TODO
}
} |
package org.cryptomator.cryptofs;
import java.nio.ByteBuffer;
class ChunkData {
private final ByteBuffer bytes;
private final boolean written;
private ChunkData(ByteBuffer bytes, boolean written) {
this.bytes = bytes;
this.written = written;
}
public static ChunkData writtenChunkData(ByteBuffer bytes) {
return new ChunkData(bytes, true);
}
public static ChunkData readChunkData(ByteBuffer bytes) {
return new ChunkData(bytes, false);
}
public ByteBuffer bytes() {
return bytes;
}
public boolean wasWritten() {
return written;
}
} |
package org.swellrt.server.box.servlet;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.swellrt.server.box.SwellRtModule;
import org.waveprotocol.box.server.authentication.SessionManager;
import org.waveprotocol.box.server.persistence.mongodb.MongoDbProvider;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.util.logging.Log;
import java.io.IOException;
import java.net.URLDecoder;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A Servlet providing SwellRt REST operations.
*
* TODO: to use a "cool" REST framework
*
*
* @author pablojan@gmail.com
*
*/
@Singleton
@SuppressWarnings("serial")
public class SwellRtServlet extends HttpServlet {
private static final Log LOG = Log.get(SwellRtServlet.class);
private final SessionManager sessionManager;
// TODO replace with a Persistence Class. Avoid direct access to MongoDb
// Collection here.
private DBCollection store;
@Inject
public SwellRtServlet(SessionManager sessionManager, MongoDbProvider mongoDbProvider) {
this.sessionManager = sessionManager;
try {
this.store = mongoDbProvider.getDBCollection(SwellRtModule.MONGO_COLLECTION);
} catch (Exception e) {
LOG.warning("Unable to get MongoDB collection. SwellRT servlet won't work!", e);
this.store = null;
}
}
private DBObject parseParam(String param) throws IOException {
param = URLDecoder.decode(param, "UTF-8");
DBObject objectQuery = null;
if (param == null || param.isEmpty()) {
objectQuery = new BasicDBObject();
} else {
objectQuery = (DBObject) JSON.parse(param);
}
return objectQuery;
}
/**
* Create an http response to the fetch query. Main entrypoint for this class.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException {
ParticipantId user = sessionManager.getLoggedInUser(req.getSession(false));
if (store == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Error accesing data model index");
return;
}
if (user == null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// /rest/[api_version]/model?q={MongoDB query}?p={MongoDB projection}
String pathInfo = req.getPathInfo();
String entity = pathInfo.substring(pathInfo.lastIndexOf("/") + 1, pathInfo.length());
if (!entity.equals("model")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
DBObject objectQuery = parseParam(req.getParameter("q"));
if (objectQuery == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad JSON format");
return;
}
String projection = req.getParameter("p");
DBObject objectProjection;
if (projection != null) {
objectProjection = parseParam(projection);
if (objectProjection == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad JSON format");
return;
}
} else {
objectProjection = new BasicDBObject();
}
BasicDBList limitPartQuery = new BasicDBList();
// Get models where user is participant
limitPartQuery.add(new BasicDBObject("participants",user.getAddress()));
// Get public models
limitPartQuery.add(new BasicDBObject("participants","@"+user.getDomain()));
objectQuery.put("$or",limitPartQuery);
// exclude internal mongoDb _id
objectProjection.put("_id", 0);
// You cannot currently mix including and excluding fields
if (!objectProjection.toMap().containsValue(1)) {
objectProjection.put("wavelet_id", 0);
}
DBCursor result = store.find(objectQuery, objectProjection);
StringBuilder JSONbuilder = new StringBuilder();
JSONbuilder.append("{\"result\":[");
while (result.hasNext()) {
JSON.serialize(result.next(), JSONbuilder);
if (result.hasNext()) JSONbuilder.append(",");
}
JSONbuilder.append("]}");
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store");
response.getWriter().append(JSONbuilder);
}
} |
package org.animotron.games.whouse;
import org.animotron.ATest;
import org.animotron.expression.Expression;
import org.animotron.expression.JSONExpression;
import org.codehaus.jackson.JsonFactory;
import org.junit.Test;
import static org.animotron.expression.AnimoExpression.__;
//import org.codehaus.jackson.JsonFactory;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class WHouseFormTest extends ATest {
private static final JsonFactory FACTORY = new JsonFactory();
@Test
public void test_00() throws Throwable {
__(
"def companyA (party) (word \"Company A & Co.\")",
"def centralWhouse (party) (word \"Central warehouse\")",
"def book (goods).",
"def ISBN:0-387-97061-4 (book) (word \"Origins of Programming\")",
"def ISBN:3-540-11157-3 (book) (word \"Algorithms in Modern Mathematics and Computer Science: Proceedings, Urgench, Uzbek SSR September 16-22, 1979 (Lecture Notes in Computer Science)\")",
"def pcs (UoM) (word \"pcs\")",
"def EUR (currency) (word \"EUR\")",
"def USD (currency) (word \"USD\")"
);
Expression doc = new JSONExpression(FACTORY.createJsonParser(
"{" +
"\"event\" : null, " +
"\"date\" : \"D2012-02-11\", " +
"\"issue-party\" : {\"companyA\" : null}, " +
"\"receive-party\" : {\"centralWhouse\" : null}, " +
"\"SKU\" : {" +
"\"uuidA\" : {" +
"\"goods\" : {\"ISBN:0-387-97061-4\" : null}, " +
"\"qty\" : {\"number\" : 1, \"UoM\" : {\"pcs\" : null}}, " +
"\"price\" : {\"number\" : 35, \"currency\" : {\"EUR\" : null}, \"UoM\" : {\"pcs\" : null}}, " +
"\"cost\" : {\"number\" : 35, \"currency\" : {\"EUR\" : null}}" +
"}, " +
"\"uuidB\" : {" +
"\"goods\" : {\"ISBN:3-540-11157-3\" : null}, " +
"\"qty\" : {\"number\" : 1, \"UoM\" : {\"pcs\" : null}}, " +
"\"price\" : {\"number\" : 35, \"currency\" : {\"USD\" : null}, \"UoM\" : {\"pcs\" : null}}, " +
"\"cost\" : {\"number\" : 35, \"currency\" : {\"USD\" : null}}" +
"}" +
"}" +
"}"
), "docA");
assertAnimo(
doc,
"def docA " +
"(event) " +
"(date \"D2012-02-11\") " +
"(issue-party companyA) " +
"(receive-party centralWhouse) " +
"(SKU " +
"(uuidA " +
"(goods ISBN:0-387-97061-4) " +
"(qty (number 1) (UoM pcs)) " +
"(price (number 35) (currency EUR) (UoM pcs)) " +
"(cost (number 35) (currency EUR))) " +
"(uuidB " +
"(goods ISBN:3-540-11157-3) " +
"(qty (number 1) (UoM pcs)) " +
"(price (number 35) (currency USD) (UoM pcs)) " +
"(cost (number 35) (currency USD))))."
);
assertAnimoResult(
"all event (with party centralWhouse) (with date \"D2012-02-11\")",
"def docA (event) (date) (issue-party) (receive-party) (SKU).");
assertAnimoResult(
"all event (with receive-party centralWhouse) (with date \"D2012-02-11\")",
"def docA (event) (date) (issue-party) (receive-party) (SKU).");
// assertAnimoResult(
// "all event (with centralWhouse) (with date \"D2012-02-11\")",
// "def docA (event) (date) (issue-party) (receive-party) (SKU).");
assertAnimoResult(
"get SKU all event (with receive-party centralWhouse) (with date \"D2012-02-11\")",
"uuidA. uuidB.");
__(
"def person party.",
"def personA person.",
"def docB " +
"(event) " +
"(date \"D2012-02-12\") " +
"(issue-party centralWhouse) " +
"(receive-party personA) " +
"(SKU " +
"(uuidA " +
"(goods ISBN:0-387-97061-4) " +
"(qty (number 1) (UoM pcs)) " +
"(price (number 35) (currency EUR) (UoM pcs)) " +
"(cost (number 35) (currency EUR)))" +
")."
);
assertAnimoResult(
"get SKU all event (with party centralWhouse) (between date (\"D2012-02-11\") (\"D2012-02-12\")) ",
"SKU (uuidA) (uuidB). SKU uuidA.");
__(
"def whouse-issue " +
"(word \"warehouse issue document\") " +
"(part (date) (issue-party) (receive-party) (table row SKU)).",
"def SKU part (goods) (qty) (price) (cost).",
"def date word \"date\".",
"def receice-party (word \"receiver\") (party,receive).",
"def issue-party (word \"issue\") (party,issue).",
"def goods word \"goods\".",
"def qty (word \"quantity\") (part (number) (UoM)).",
"def price (word \"price\") (part (number) (currency) (UoM)).",
"def cost (word \"cost\") (part (number) (currency)).",
"def generate-form each (get prism) (any form-widget).",
"def generate-table-row each (get row get prism) (any table-row-widget).",
"def html-form " +
"(form-widget)" +
"(\\form (@name id this prism)" +
"(each (get part) " +
"(ptrn (this part) " +
"(?is table html-table) " +
"(html-label-input)))).",
"def html-input \\input (@name id this part).",
"def html-label-input \\label (word this part) (html-input).",
"def html-table " +
"each (get row this part) "+
"(\\table (@name id this row) " +
"(html-table-head) (html-table-row)).",
"def html-table-head \\tr each (get part this row) (\\th word this part).",
"def html-table-row (table-row-widget) (\\tr (@name \"uuid\") (each (get part this row) (\\td html-input))).",
"def fill-form " +
"each (get prism) " +
"(each (get part this prism) " +
"(ptrn (this part) " +
"(?is table fill-table) " +
"(fill-input))).",
"def fill-table " +
"each (get row this part) " +
"(fill-form prizm this row).",
"def fill-input \\input " +
"(@name id this part) " +
"(each (get (this part) (this object)) " +
"(@id id this this part)" +
"(@value word this this part))."
);
assertAnimoResult(
"generate-form prism whouse-issue",
"generate-form " +
"def html-form " +
"(form-widget) " +
"(\\form (@name \"whouse-issue\") " +
"(html-label-input " +
"\\label \"date\" (html-input \\input @name \"date\")) " +
"(html-label-input " +
"\\label \"issue\" (html-input \\input @name \"issue-party\")) " +
"(html-label-input " +
"\\label \"warehouse\" (html-input \\input @name \"whouse-party\")) " +
"(html-table " +
"\\table (@name \"SKU\") " +
"(html-table-head \\tr (\\th \"goods\") (\\th \"quantity\") (\\th \"price\") (\\th \"cost\")) " +
"(html-table-row (table-row-widget) " +
"(\\tr (@name \"uuid\") " +
"(\\td html-input \\input @name \"goods\") " +
"(\\td html-input \\input @name \"qty\") " +
"(\\td html-input \\input @name \"price\") " +
"(\\td html-input \\input @name \"cost\")))))."
);
assertAnimoResult(
"generate-table-row prism whouse-issue",
"generate-table-row " +
"def html-table-row (table-row-widget) " +
"(\\tr (@name \"uuid\") " +
"(\\td html-input \\input @name \"goods\") " +
"(\\td html-input \\input @name \"qty\") " +
"(\\td html-input \\input @name \"price\") " +
"(\\td html-input \\input @name \"cost\"))."
);
assertAnimoResult(
"fill-form (prism whouse-issue) ",// (object docA) ",
"fill-form " +
"def html-table-row (table-row-widget) " +
"(\\tr (@name \"uuid\") " +
"(\\td html-input \\input @name \"goods\") " +
"(\\td html-input \\input @name \"qty\") " +
"(\\td html-input \\input @name \"price\") " +
"(\\td html-input \\input @name \"cost\"))."
);
}
@Test
public void test_01() throws Throwable {
__(
"def form part field.",
"def generator " +
"\\form " +
"(@id id this generator) " +
"(each (get part this generator) (\\input @name id this part))"
);
assertAnimoResult("generator form", "generator \\form (@id \"form\") (\\input @name \"field\").");
__(
"def form2 part (field1) (field2)."
);
assertAnimoResult(
"generator form2",
"generator \\form (@id \"form2\") (\\input @name \"field1\") (\\input @name \"field2\").");
}
} |
package org.torproject.jtor.directory.impl;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import org.torproject.jtor.TorException;
import org.torproject.jtor.crypto.TorPublicKey;
import org.torproject.jtor.data.HexDigest;
import org.torproject.jtor.data.IPv4Address;
import org.torproject.jtor.directory.Router;
import org.torproject.jtor.directory.RouterDescriptor;
import org.torproject.jtor.directory.RouterStatus;
import org.torproject.jtor.geoip.CountryCodeService;
public class RouterImpl implements Router {
static RouterImpl createFromRouterStatus(RouterStatus status) {
return new RouterImpl(status);
}
private final HexDigest identityHash;
protected RouterStatus status;
private RouterDescriptor descriptor;
private volatile String cachedCountryCode;
protected RouterImpl(RouterStatus status) {
identityHash = status.getIdentity();
this.status = status;
}
void updateStatus(RouterStatus status) {
if(!identityHash.equals(status.getIdentity()))
throw new TorException("Identity hash does not match status update");
this.status = status;
this.cachedCountryCode = null;
}
void updateDescriptor(RouterDescriptor descriptor) {
this.descriptor = descriptor;
}
public boolean isDescriptorDownloadable() {
if(descriptor != null && descriptor.getDescriptorDigest().equals(status.getDescriptorDigest()))
return false;
final Date now = new Date();
final long diff = now.getTime() - status.getPublicationTime().getDate().getTime();
return diff > (1000 * 60 * 10);
}
public String getVersion() {
return status.getVersion();
}
public HexDigest getDescriptorDigest() {
return status.getDescriptorDigest();
}
public IPv4Address getAddress() {
return status.getAddress();
}
public RouterDescriptor getCurrentDescriptor() {
return descriptor;
}
public boolean hasFlag(String flag) {
return status.hasFlag(flag);
}
public boolean isHibernating() {
if(descriptor == null)
return false;
return descriptor.isHibernating();
}
public boolean isRunning() {
return hasFlag("Running");
}
public boolean isValid() {
return hasFlag("Valid");
}
public boolean isBadExit() {
return hasFlag("BadExit");
}
public boolean isPossibleGuard() {
return hasFlag("Guard");
}
public boolean isExit() {
return hasFlag("Exit");
}
public boolean isFast() {
return hasFlag("Fast");
}
public boolean isStable() {
return hasFlag("Stable");
}
public boolean isHSDirectory() {
return hasFlag("HSDir");
}
public int getDirectoryPort() {
return status.getDirectoryPort();
}
public HexDigest getIdentityHash() {
return identityHash;
}
public TorPublicKey getIdentityKey() {
if(descriptor != null) {
return descriptor.getIdentityKey();
} else {
return null;
}
}
public String getNickname() {
return status.getNickname();
}
public int getOnionPort() {
return status.getRouterPort();
}
public TorPublicKey getOnionKey() {
if(descriptor != null) {
return descriptor.getOnionKey();
} else {
return null;
}
}
public boolean hasBandwidth() {
return status.hasBandwidth();
}
public int getEstimatedBandwidth() {
return status.getEstimatedBandwidth();
}
public int getMeasuredBandwidth() {
return status.getMeasuredBandwidth();
}
public Set<String> getFamilyMembers() {
if(descriptor == null) {
return Collections.emptySet();
}
return descriptor.getFamilyMembers();
}
public int getAverageBandwidth() {
if(descriptor == null)
return 0;
return descriptor.getAverageBandwidth();
}
public int getBurstBandwidth() {
if(descriptor == null)
return 0;
return descriptor.getBurstBandwidth();
}
public int getObservedBandwidth() {
if(descriptor == null)
return 0;
return descriptor.getObservedBandwidth();
}
public boolean exitPolicyAccepts(IPv4Address address, int port) {
if(descriptor == null)
return false;
if(address == null)
return descriptor.exitPolicyAccepts(port);
return descriptor.exitPolicyAccepts(address, port);
}
public boolean exitPolicyAccepts(int port) {
return exitPolicyAccepts(null, port);
}
public String toString() {
return "Router["+ getNickname() +" ("+getAddress() +":"+ getOnionPort() +")]";
}
public String getCountryCode() {
String cc = cachedCountryCode;
if(cc == null) {
cc = CountryCodeService.getInstance().getCountryCodeForAddress(getAddress());
cachedCountryCode = cc;
}
return cc;
}
} |
package org.usfirst.frc.team910.robot.Auton;
import java.util.ArrayList;
import org.usfirst.frc.team910.robot.Functions.AutoDelivererer;
import org.usfirst.frc.team910.robot.Functions.AutoShoot;
import org.usfirst.frc.team910.robot.IO.Inputs;
import org.usfirst.frc.team910.robot.IO.Sensors;
import org.usfirst.frc.team910.robot.Subsystems.Climber;
import org.usfirst.frc.team910.robot.Subsystems.DriveTrain;
import org.usfirst.frc.team910.robot.Subsystems.GearSystem;
import org.usfirst.frc.team910.robot.Subsystems.Shooter;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Preferences;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class AutonMain {
private static int AUTON_PROFILE = 0;
private static final int RED = 0;
private static final int BLUE = 1;
private static int DEFAULT_ALLIANCE = RED;
private static boolean OVERRIDE_ALLIANCE = false;
private boolean blueAlliance = false;
private static double CLIMBER_RUN_TIME = 0.35;
//drive to hopper
//b4msc was private static final double r = 21;//was 21//red start turn distance
//b4msc was private static final double b = 21; //was21//b4 msc: 23;//blue start turn distance
private static final double r = 31; //was 36 in match32 //45;//was 21//red start turn distance
private static final double b = 29; //was 36 in match32 //Add 3? //was21//b4 msc: 23;//blue start turn distance
private static final double[] turnPowerL_2Hopper = { 1, 1, 1, -0.5, -0.2, 1, 0.5, 0.2 }; //Inside
//b4msc was private static final double[] turnPowerL_2Hopper = { 1, 1, 1, -1, -.4, 1, 1, 0.5 }; //Inside
//BLUE
//private static final double[] turnPowerL_2Hopper = { 1, 1, 1, -1, 0.2, .3, .5, 0.1 }; //Inside //BLUE
//private static final double[] turnPowerR_2Hopper = { 1, 1, 1, 1, 1, 1, 1, -0.15 }; //Outside BLUE
//private static final double[] turnPowerR_2Hopper = { 1, 1, 1, 1, 1, 1, 1, -0.65 }; //Outside
private static final double[] turnPowerR_2Hopper = { 1, 1, 1, 1, 1, 1, 1, -0.45 }; //Outside B4 MSC
/* //RED
private static final double[] turnPowerL_2Hopper = { 1, 1, 1, -1, .2, .3, .6, 0.1 }; //Inside //RED
private static final double[] turnPowerR_2Hopper = { 1, 1, 1, 1, 1, 1, 1, -0.15 }; //Outside RED
*/
private static final double[] xDistAxis_2Hopper_Red = { 0, 0, r, r+23, r+44, r+58, r+71, r+93 }; //B4 MSC was 95 on last one, end dist is ~121
private static final double[] xDistAxis_2Hopper_Blue = { 0, 0, b, b+23, b+44, b+58, b+71, b+93 }; //B4 MSC was 95 on last one, switch to this when blue
/* B4 MSC:
private static final double[] xDistAxis_2Hopper_Red = { 0, 0, r, r+23, r+44, r+58, r+71, r+95 }; //end dist is ~121
private static final double[] xDistAxis_2Hopper_Blue = { 0, 0, b, b+23, b+44, b+58, b+71, b+95 }; //switch to this when blue
*/
//Next line NOT USED
private static final double[] turnAngle_2Hopper = { 0, 0, 0, 0, 45, 80, 90, 90 };
//drive from hopper to boiler
/* B4 MSC:
private static final double[] turnPowerL_From_Hopper = { -1, -1, -1, 0.75, 1, 0.55, -1 }; //Outside of backup then Inside of Forward
private static final double[] turnPowerR_From_Hopper = { -1, -1, 0.1, 1, 1, 0.55, -1 }; //Inside of backup then Outside of Forward
private static final double[] turnAngle_From_Hopper = { 90, 90, 90, 160, 160, 160, 160 };
private static final double[] xDistAxis_From_Hopper = { 0, 0, 20, 30, 40, 55, 64 };//TAKE 3 OFF LAST 2 VALUES? end dist is ~63
*/
//BLUE
private static final double[] turnPowerL_From_Hopper = { -1, -1, -1, 0.75, 1, 0.55, -1 }; //Outside of backup then Inside of Forward
private static final double[] turnPowerR_From_Hopper = { -1, -1, 0, 1, 1, 0.55, -1 }; //Inside of backup then Outside of Forward
private static final double[] turnAngle_From_Hopper = { 90, 90, 90, 160, 160, 160, 160 };
/*// RED
private static final double[] turnPowerL_From_Hopper = { -1, -1, -1, 0.75, 1, 0.55, -1 }; //Outside of backup then Inside of Forward
private static final double[] turnPowerR_From_Hopper = { -1, -1, 0.4, 1, 1, 0.55, -1 }; //Inside of backup then Outside of Forward
private static final double[] turnAngle_From_Hopper = { 90, 90, 90, 160, 160, 160, 160 };
//private static final double[] turnAngle_From_Hopper = { 90, 90, 90, 160, 160, 160, 160 };
//private static final double[] xDistAxis_From_Hopper = { 0, 0, 20, 30, 40, 55, 64 };//end dist is ~63
*/
private static final double[] xDistAxis_From_Hopper = { 0, 0, 20, 30, 40, 52, 61 };//TAKE 3 OFF LAST 2 VALUES? end dist is ~63
//drive to gear peg left
private static final double[] turnPowerL_gearL = { -1, -1, -1, -1, -1, -1, 1 };
private static final double[] turnPowerR_gearL = { -1, -1, -1, -0.15, -1, -1, 1 };
private static final double[] turnAngle_gearL = { 0, 0, 0, -45, -60, -60, -60 };
private static final double[] xDistAxis_gearL = { 0, 0, 90, 115, 140, 150, 160 };
//drive to gear peg left
private static final double[] turnPowerL_gearR = { -1, -1, -1, -1, -1, -1, 1 };
private static final double[] turnPowerR_gearR = { -1, -1, -1, -0.15, -1, -1, 1 };
private static final double[] turnAngle_gearR = { 0, 0, 0, -45, -60, -60, -60 };
private static final double[] xDistAxis_gearR = { 0, 0, 90, 115, 140, 150, 160 };
//drive to center gear
private static final double[] turnPowerL_gearC = { -1, -1, -1, 1, 1 }; //use these if you want to drive straight
private static final double[] turnPowerR_gearC = { -1, -1, -1, 1, 1 };
//private static final double[] turnPowerL_gearC = { -1, -1, -1, 1, 1, 0.5 }; //use these to turn on the way out
//private static final double[] turnPowerR_gearC = { -1, -1, -1, 1, 0.1, 0.5 };
private static final double[] turnAngle_gearC = { 0, 0, 0, 0, 0, 0 };
private static final double[] xDistAxis_gearC = { 0, 0, 56, 76, 90, 165 };
//hopper end points
private static final double End_Point_To_Hopper = 36; //COULD be a tiny bit more! //how far on the y axis to travel into the hopper
private static final double End_Point_From_Hopper = -18; // LOWER IF POSS! WAS -22; //was26 //how far on the x axis to drive to the boiler
private static final double End_Point_To_Center_Gear = 80; //use if only driving straight
//private static final double End_Point_To_Center_Gear = 160; //use for the turning part
private static final double End_Point_To_Side_Gear_L = 154;
private static final double End_Point_To_Side_Gear_R = 154;
ArrayList<AutonStep> steps;
private static final int HOPPER_SHOOT_AUTO = 1;
//ArrayList<AutonStep> hopperShootAutonBlue;
//ArrayList<AutonStep> hopperShootAutonRed;
ArrayList<AutonStep> hopperShootAuto;
private static final int LEFT_GEAR_AUTO = 2;
private static final int RIGHT_GEAR_AUTO = 4;
private static final int CENTER_GEAR_AUTO = 3;
ArrayList<AutonStep> leftGearAuto;
ArrayList<AutonStep> centerGearAuto;
ArrayList<AutonStep> rightGearAuto;
private static final int JUST_DRIVE_AUTO = 0;
ArrayList<AutonStep> justDrive;
ArrayList<AutonStep> doNothing;
private static final int PIVIT_SHOT_AUTO = 5;
ArrayList<AutonStep> pivitShot;
public int currentStep = 0;
ArrayList<AutonStep> gearAuto;
public AutonMain() {
MotionProfileInputs mi = new MotionProfileInputs();
mi.leftSegments = new double[2]; mi.rightSegments = new double[2];
mi.leftSegments[0] = 60; mi.rightSegments[0] = 20;
mi.leftSegments[1] = 10; mi.rightSegments[1] = 10.1;
//mi.leftSegments[2] = 12; mi.rightSegments[2] = 12;
mi.leftBrakeDist = mi.leftSegments[0] + mi.leftSegments[1] /*+ mi.rightSegments[2]*/ - 28; //start brake 4in into last segment
mi.rightBrakeDist = mi.rightSegments[0] + mi.rightSegments[1] /*+ mi.rightSegments[2]*/ - 0; //start brake 4in into last segment
mi.endL = 75;
mi.endR = 35;
mi.endTime = 1.5;
mi.endAccel = 999;
mi.powerLimit = 0.9;
justDrive = new ArrayList<AutonStep>();
justDrive.add(new AutonResetAngle());
//justDrive.add(new AutonUnlatchClimber(CLIMBER_RUN_TIME)); //remove later
justDrive.add(new AutonDriveTime(0.5, 1.5, 0, false)); //make positive power again
//justDrive.add(new AutonMotionProfiler(mi));
//justDrive.add(new AutonWait(1.5)); //remove later
//justDrive.add(new AutonAllianceDrive(new AutonDriveTime(0.3,1.75,-30,false), new AutonDriveTime(0.3,1.75,30,false)));//remove later
//justDrive.add(new AutonWait(1));//remove later
//justDrive.add(new AutonAutoShoot(10)); //remove later
/*justDrive.add(new AutonFastArc(false, true, 0.9, turnPowerL_2Hopper, turnPowerR_2Hopper, turnAngle_2Hopper, xDistAxis_2Hopper_Blue, new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return Math.abs(y) > End_Point_To_Side_Gear_R
|| l > xDistAxis_2Hopper_Red[xDistAxis_2Hopper_Red.length-1] && blueAlliance
|| r > xDistAxis_2Hopper_Blue[xDistAxis_2Hopper_Blue.length-1] && !blueAlliance;
}
}));*/
justDrive.add(new AutonEndStep());
pivitShot = new ArrayList<AutonStep>();
pivitShot.add(new AutonResetAngle());
pivitShot.add(new AutonUnlatchClimber(CLIMBER_RUN_TIME)); //remove later
pivitShot.add(new AutonDriveTime(-0.5, 1.5, 0, false)); //make positive power again
pivitShot.add(new AutonWait(1.5)); //remove later
pivitShot.add(new AutonAllianceDrive(new AutonDriveTime(0.3,1.75,-30,false), new AutonDriveTime(0.3,1.75,30,false)));//remove later
pivitShot.add(new AutonWait(1));//remove later
pivitShot.add(new AutonAutoShoot(10)); //remove later
/*justDrive.add(new AutonFastArc(false, true, 0.9, turnPowerL_2Hopper, turnPowerR_2Hopper, turnAngle_2Hopper, xDistAxis_2Hopper_Blue, new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return Math.abs(y) > End_Point_To_Side_Gear_R
|| l > xDistAxis_2Hopper_Red[xDistAxis_2Hopper_Red.length-1] && blueAlliance
|| r > xDistAxis_2Hopper_Blue[xDistAxis_2Hopper_Blue.length-1] && !blueAlliance;
}
}));*/
pivitShot.add(new AutonEndStep());
//old pivot shot
/*
pivitShot = new ArrayList<AutonStep>();
pivitShot.add(new AutonResetAngle());
pivitShot.add(new AutonAllianceDrive(new AutonDriveTime(-0.5, 1.5, -35, true), new AutonDriveTime(-0.5, 1.5, 35, true)));
pivitShot.add(new AutonAllianceDrive(new AutonDriveTime(0.5, 1.0, -60, true), new AutonDriveTime(0.5, 1.0, 60, true)));
//pivitShot.add(new AutonPrime());
pivitShot.add(new AutonAutoShoot(13));
pivitShot.add(new AutonEndStep());
*/
//old autons
/*hopperShootAutonBlue = new ArrayList<AutonStep>();
hopperShootAutonBlue.add(new AutonResetAngle());
hopperShootAutonBlue.add(new AutonDriveStraight(4*12, 0.4, 0));
hopperShootAutonBlue.add(new AutonDriveCircle(2*Math.PI*2.5*12/4, 0.7, 0, 2.5*12, 90, false));
hopperShootAutonBlue.add(new AutonDriveTimeClimb(0.7, 0.75, 90));
hopperShootAutonBlue.add(new AutonWaitAtHopper(3));
hopperShootAutonBlue.add(new AutonDriveTime(-0.9, 0.5, 90, true));
hopperShootAutonBlue.add(new AutonDriveTime(0.9, 0.5, 142, true));
hopperShootAutonBlue.add(new AutonAutoShoot(6));
hopperShootAutonBlue.add(new AutonEndStep());
hopperShootAutonRed = new ArrayList<AutonStep>();
hopperShootAutonRed.add(new AutonResetAngle());
hopperShootAutonRed.add(new AutonDriveStraight(4*12, 0.4, 0));
hopperShootAutonRed.add(new AutonDriveCircle(2*Math.PI*2.5*12/4, 0.7, 0, 2.5*12, -90, true));
hopperShootAutonRed.add(new AutonDriveTimeClimb(0.7, 0.75, -90));
hopperShootAutonRed.add(new AutonWaitAtHopper(3));
hopperShootAutonRed.add(new AutonDriveTime(-0.9, 0.5, -90, true));
hopperShootAutonRed.add(new AutonDriveTime(0.9, 0.45, -135, true));
hopperShootAutonRed.add(new AutonAutoShoot(6));
hopperShootAutonRed.add(new AutonEndStep());*/
/*
gearAuto = new ArrayList<AutonStep>();
gearAuto.add(new AutonResetAngle());
gearAuto.add(new AutonDriveStraight(5*12 , 0.4, 0));
gearAuto.add(new AutonDriveTime(0.5, 2.5, -45, false));
gearAuto.add(new AutonGearDeploy());
gearAuto.add(new AutonEndStep());
*/
double gearDrivePwr = 0.45; //was .75 with other drive cycle
/*
leftGearAuto = new ArrayList<AutonStep>();
leftGearAuto.add(new AutonResetAngle());
leftGearAuto.add(new AutonDriveStraight(5*12 , gearDrivePwr, 0));
leftGearAuto.add(new AutonDriveTime(gearDrivePwr, 2, -60, false));
leftGearAuto.add(new AutonGearDeploy());
leftGearAuto.add(new AutonDriveTime(-gearDrivePwr, 2, -60, false));
leftGearAuto.add(new AutonAllianceDrive(new AutonDriveTime(gearDrivePwr, 2, 150, true), new AutonDriveCircle(Math.PI*6*12*4/6, 1, 30, 6*12, 180, true)));
leftGearAuto.add(new AutonAutoShoot(6));
leftGearAuto.add(new AutonEndStep());
rightGearAuto = new ArrayList<AutonStep>();
rightGearAuto.add(new AutonResetAngle());
rightGearAuto.add(new AutonDriveStraight(5*12 , gearDrivePwr, 0));
rightGearAuto.add(new AutonDriveTime(gearDrivePwr, 2, 60, false));
rightGearAuto.add(new AutonGearDeploy());
rightGearAuto.add(new AutonDriveTime(-gearDrivePwr, 2, 60, false));
rightGearAuto.add(new AutonAllianceDrive(new AutonDriveCircle(Math.PI*6*12*4/6, 1, -30, 6*12, 180, false), new AutonDriveTime(gearDrivePwr, 2, -150, true)));
rightGearAuto.add(new AutonAutoShoot(6));
rightGearAuto.add(new AutonEndStep());
*/
//Center Gear Auto
//start
centerGearAuto = new ArrayList<AutonStep>();
centerGearAuto.add(new AutonResetAngle());
/*list.add( new AutonFastArc(false,true,gearDrivePwr,turnPowerL_gearC,turnPowerR_gearC,turnAngle_gearC,xDistAxis_gearC,new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return Math.abs(l) > End_Point_To_Center_Gear;
}
}));*/
/*
// hold on to something this is where trevor takes over
//run auto gear delivery
centerGearAuto.add(new AutoDelivererer());
*/
//deliver gear (no longer needed with passive deployer)
//centerGearAuto.add(new AutonGearDeploy());
//drive forward
centerGearAuto.add(new AutonDriveTime(-gearDrivePwr, 1.6, 0, false));
//reverse
centerGearAuto.add(new AutonDriveTime(gearDrivePwr, 0.75, 0, false));
//drive towards boiler (not needed when we are using the table with the turn at the end -- 4/7)
ArrayList<AutonStep> list = new ArrayList<AutonStep>();
list.add(new AutonUnlatchClimber(CLIMBER_RUN_TIME));
list.add(new AutonAllianceDrive(new AutonDriveTime(gearDrivePwr, 2.4, -95, false), new AutonDriveTime(gearDrivePwr, 2.4, 95, false)));
ParallelStep ps = new ParallelStep(list);
centerGearAuto.add(ps);
//shoot
centerGearAuto.add(new AutonAutoShoot(10));
centerGearAuto.add(new AutonEndStep());
//new auto
double drivePwr = 0.9;
hopperShootAuto = new ArrayList<AutonStep>();
//step 1: reset navX
hopperShootAuto.add(new AutonResetAngle());
//step 2: briefly run the climber and drive to the hopper
list = new ArrayList<AutonStep>();
list.add(new AutonUnlatchClimber(CLIMBER_RUN_TIME));//was.75
AutonFastArc afaBlue = new AutonFastArc(false, true, drivePwr, turnPowerL_2Hopper, turnPowerR_2Hopper, turnAngle_2Hopper, xDistAxis_2Hopper_Blue, new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return Math.abs(y) > End_Point_To_Hopper
|| r > xDistAxis_2Hopper_Red[xDistAxis_2Hopper_Red.length-1] && blueAlliance
|| l > xDistAxis_2Hopper_Blue[xDistAxis_2Hopper_Blue.length-1] && !blueAlliance;
}
});
AutonFastArc afaRed = new AutonFastArc(false, true, drivePwr, turnPowerL_2Hopper, turnPowerR_2Hopper, turnAngle_2Hopper, xDistAxis_2Hopper_Red, new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return Math.abs(y) > End_Point_To_Hopper
|| r > xDistAxis_2Hopper_Red[xDistAxis_2Hopper_Red.length-1] && blueAlliance
|| l > xDistAxis_2Hopper_Blue[xDistAxis_2Hopper_Blue.length-1] && !blueAlliance;
}
});
list.add(new AutonAllianceDrive(afaBlue, afaRed));
ps = new ParallelStep(list);
hopperShootAuto.add(ps);
//step 3: start priming and crashing into the hopper to get all the balls into the robot
list = new ArrayList<AutonStep>();
list.add(new AutonWaitAtHopper(3));
//list.add(new AutonWait(3)); //replace this for competition
list.add(new AutonPrime());
ps = new ParallelStep(list);
hopperShootAuto.add(ps);
//step 4: drive away from the hopper and keep priming
list = new ArrayList<AutonStep>();
list.add(new AutonFastArc(true, true, drivePwr, turnPowerL_From_Hopper, turnPowerR_From_Hopper, turnAngle_From_Hopper, xDistAxis_From_Hopper, new DriveComplete(){
public boolean isDone(double l, double r, double x, double y, boolean blueAlliance){
return x < End_Point_From_Hopper
|| r > xDistAxis_From_Hopper[xDistAxis_From_Hopper.length - 1] && blueAlliance
|| l > xDistAxis_From_Hopper[xDistAxis_From_Hopper.length - 1] && !blueAlliance;
}
}));
list.add(new AutonPrime());
ps = new ParallelStep(list);
hopperShootAuto.add(ps);
//step 5: run the auto shoot function for whatever time is left
hopperShootAuto.add(new AutonAutoShoot(10));
//step 6: call the end step to make sure everything stops
hopperShootAuto.add(new AutonEndStep());
doNothing = new ArrayList<AutonStep>();
//steps.add(new AutonResetAngle());
//steps.add(new AutonDriveStraight(192, 0.5, 0));
//steps.add(new AutonDriveCircle(9.5*12, 0.4, 0, 6*12, true));
doNothing.add(new AutonEndStep());
steps = doNothing;
//steps = hopperShootAutonRed;
//steps = hopperShootAuto;
}
public void init(Inputs in, Sensors sense, DriveTrain drive, GearSystem gear, Shooter shoot, Climber climb, AutoShoot as) {
AutonStep.setRobotReferences(in, sense, drive, gear, shoot, climb, as);
SmartDashboard.putString("AutonKey", "Auton Profiles:\n0) Just Drive Forward\n1) Hopper Shoot Drive\n2) Left Gear\n3) Center Gear\n4) Right Gear\n5) Pivot Shot");
}
public void setAutonProfile(){
//blueAlliance = false;
/*switch(AutonStep.in.autonSelection){
case 1:
steps = hopperShootAutonBlue;
break;
case 2:
steps = justDrive;
break;
case 3:
steps = hopperShootAutonRed;
break;
default:
}
*/
DriverStation ds = DriverStation.getInstance();
AUTON_PROFILE = Preferences.getInstance().getInt("AUTON_PROFILE", AUTON_PROFILE);
SmartDashboard.putNumber("AutonProfile", AUTON_PROFILE);
DEFAULT_ALLIANCE = Preferences.getInstance().getInt("DEFAULT_ALLIANCE", DEFAULT_ALLIANCE);
OVERRIDE_ALLIANCE = Preferences.getInstance().getBoolean("OVERRIDE_ALLIANCE", OVERRIDE_ALLIANCE);
SmartDashboard.putNumber("DefaultAlliance", DEFAULT_ALLIANCE);
DriverStation.Alliance alliance = ds.getAlliance();
if(alliance == DriverStation.Alliance.Invalid){
switch(DEFAULT_ALLIANCE){
case RED:
alliance = DriverStation.Alliance.Red;
break;
case BLUE:
alliance = DriverStation.Alliance.Blue;
break;
}
}
//allow overriding of the alliance if the field is not cooperating
if(OVERRIDE_ALLIANCE){
switch(DEFAULT_ALLIANCE){
case RED:
alliance = DriverStation.Alliance.Red;
break;
case BLUE:
alliance = DriverStation.Alliance.Blue;
break;
}
}
//blue alliance will be true when we are blue, otherwise false
blueAlliance = alliance == DriverStation.Alliance.Blue;
SmartDashboard.putBoolean("blueAlliance", blueAlliance);
switch(AUTON_PROFILE){
case HOPPER_SHOOT_AUTO:
steps = hopperShootAuto;
break;
case JUST_DRIVE_AUTO:
steps = justDrive;
break;
case LEFT_GEAR_AUTO:
//steps = leftGearAuto;
steps = justDrive;
break;
case CENTER_GEAR_AUTO:
steps = centerGearAuto;
//steps = justDrive;
break;
case RIGHT_GEAR_AUTO:
//steps = rightGearAuto;
steps = justDrive;
break;
case PIVIT_SHOT_AUTO:
steps = pivitShot;
break;
default:
steps = doNothing;
break;
}
SmartDashboard.putString("ChosenAuton", steps.getClass().getName());
}
public void run() {
SmartDashboard.putNumber("AutonStep", currentStep);
steps.get(currentStep).run(); // institutes a state machine as an array of autons, works similarly to a "switch"
if (steps.get(currentStep).isDone()) {
currentStep++;
steps.get(currentStep).setup(blueAlliance);
}
}
} |
package org.graylog2.gelfclient;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.*;
public class ConfigurationTest {
private Configuration config;
@BeforeMethod
public void setup() {
this.config = new Configuration();
}
@Test
public void testQueueSize() {
// Check default value.
assertEquals(5, config.getQueueSize());
config.setQueueSize(124);
assertEquals(124, config.getQueueSize());
}
@Test
public void testHost() {
// Check default value.
assertEquals("127.0.0.1", config.getHost());
config.setHost("10.0.0.1");
assertEquals("10.0.0.1", config.getHost());
}
@Test
public void testPort() {
// Check default value.
assertEquals(12201, config.getPort());
config.setPort(10000);
assertEquals(10000, config.getPort());
}
@Test
public void testProtocol() {
// Check default value.
assertEquals(GelfTransports.TCP, config.getProtocol());
// We only have TCP for now so this is pretty useless.
config.setProtocol(GelfTransports.TCP);
assertEquals(GelfTransports.TCP, config.getProtocol());
}
@Test
public void testReconnectDelay() {
// Check default value.
assertEquals(1000, config.getReconnectDelay());
config.setReconnectDelay(5000);
assertEquals(5000, config.getReconnectDelay());
}
} |
package org.hocate.http.server;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hocate.http.message.Request;
import org.hocate.http.message.packet.Cookie;
public class HttpRequest extends Request {
private HttpSession session;
private String remoteAddres;
private int remotePort;
private String characterSet;
private Map<String, String> parameters;
protected HttpRequest(Request request){
super(request);
characterSet="UTF-8";
parameters = new HashMap<String, String>();
parseParameters();
}
/**
* Cookie Cookie
* @param name
* @return
*/
public Cookie getCookie(String name){
for(Cookie cookie : this.cookies()){
if(cookie.getName().equals(name)){
return cookie;
}
}
return null;
}
/**
* Session
* @return
*/
public HttpSession getSession() {
return session;
}
/**
* Session
* @param session
*/
protected void setSession(HttpSession session) {
this.session = session;
}
/**
* IP
* @return
*/
public String getRemoteAddres() {
String xForwardedFor = header().get("X-Forwarded-For");
if(xForwardedFor==null){
return remoteAddres;
}else{
return xForwardedFor.split(",")[0].trim();
}
}
/**
* IP
* @param remoteAddres
*/
protected void setRemoteAddres(String remoteAddres) {
this.remoteAddres = remoteAddres;
}
/**
*
* @return
*/
public int getRemotePort() {
return remotePort;
}
/**
*
* @param port
*/
protected void setRemotePort(int port) {
this.remotePort = port;
}
/**
*
* @return
*/
public String getCharacterSet() {
return characterSet;
}
/**
*
* @param charset
*/
public void setCharacterSet(String charset) {
this.characterSet = charset;
}
/**
*
* @return
*/
public String getQueryString(){
return getQueryString(characterSet);
}
/**
*
* @return
*/
protected Map<String, String> getParameters() {
return parameters;
}
/**
*
* @param paramName
* @return
*/
public String getParameter(String paramName){
return parameters.get(paramName);
}
/**
*
* @param paramName
* @return
*/
public List<String> getParameterNames(){
return Arrays.asList(parameters.keySet().toArray(new String[]{}));
}
private void parseParameters() {
if(getQueryString()!=null){
String[] parameterEquals = getQueryString().split("&");
for(String parameterEqual :parameterEquals){
int equalFlagPos = parameterEqual.indexOf("=");
if(equalFlagPos>0){
String name = parameterEqual.substring(0, equalFlagPos);
String value = parameterEqual.substring(equalFlagPos+1, parameterEqual.length());
parameters.put(name, value);
}else{
parameters.put(parameterEqual, null);
}
}
}
}
} |
package scrum.client.pr;
import ilarkesto.core.base.Str;
import ilarkesto.gwt.client.AMultiSelectionViewEditWidget;
import ilarkesto.gwt.client.AOutputViewEditWidget;
import ilarkesto.gwt.client.TableBuilder;
import scrum.client.ScrumGwt;
import scrum.client.admin.User;
import scrum.client.common.AScrumWidget;
import scrum.client.journal.ChangeHistoryWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class BlogEntryWidget extends AScrumWidget {
private BlogEntry blogEntry;
public BlogEntryWidget(BlogEntry blogEntry) {
super();
this.blogEntry = blogEntry;
}
@Override
protected Widget onInitialization() {
TableBuilder tb = ScrumGwt.createFieldTable();
tb.addFieldRow("Title", blogEntry.getTitleModel());
tb.addFieldRow("Text", blogEntry.getTextModel());
tb.addFieldRow("Date", blogEntry.getDateAndTimeModel());
tb.addFieldRow("Authors", new AMultiSelectionViewEditWidget<User>() {
@Override
protected void onViewerUpdate() {
setViewerItems(blogEntry.getAuthors());
}
@Override
protected void onEditorUpdate() {
setEditorItems(blogEntry.getProject().getParticipants());
setEditorSelectedItems(blogEntry.getAuthors());
}
@Override
protected void onEditorSubmit() {
blogEntry.setAuthors(getEditorSelectedItems());
}
@Override
public boolean isEditable() {
return true;
}
});
if (blogEntry.isPublished() && blogEntry.getProject().getHomepageDir() != null) {
tb.addFieldRow("Public URL", new AOutputViewEditWidget() {
@Override
protected void onViewerUpdate() {
String url = blogEntry.getProject().getHomepageUrl();
if (Str.isBlank(url)) {
setViewer(new Label("Yes"));
} else {
if (!url.endsWith("/")) url += "/";
url += blogEntry.getReference() + ".html";
setViewer(new HTML("<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>"));
}
}
});
}
tb.addRow(new ChangeHistoryWidget(blogEntry), 2);
return TableBuilder.row(20, tb.createTable(), ScrumGwt.createEmoticonsAndComments(blogEntry));
}
} |
package com.expidev.gcmapp;
import static com.expidev.gcmapp.BuildConfig.THEKEY_CLIENTID;
import static com.expidev.gcmapp.Constants.PREFS_SETTINGS;
import static com.expidev.gcmapp.Constants.PREF_CURRENT_MINISTRY;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.expidev.gcmapp.GcmTheKey.GcmBroadcastReceiver;
import com.expidev.gcmapp.db.MinistriesDao;
import com.expidev.gcmapp.db.TrainingDao;
import com.expidev.gcmapp.map.GcmMarker;
import com.expidev.gcmapp.map.MarkerRender;
import com.expidev.gcmapp.model.AssociatedMinistry;
import com.expidev.gcmapp.model.Training;
import com.expidev.gcmapp.service.MinistriesService;
import com.expidev.gcmapp.service.TrainingService;
import com.expidev.gcmapp.service.Type;
import com.expidev.gcmapp.support.v4.content.CurrentMinistryLoader;
import com.expidev.gcmapp.utils.BroadcastUtils;
import com.expidev.gcmapp.utils.Device;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterManager;
import org.ccci.gto.android.common.support.v4.app.SimpleLoaderCallbacks;
import java.util.List;
import me.thekey.android.TheKey;
import me.thekey.android.lib.TheKeyImpl;
import me.thekey.android.lib.support.v4.content.AttributesLoader;
import me.thekey.android.lib.support.v4.dialog.LoginDialogFragment;
public class MainActivity extends ActionBarActivity
implements OnMapReadyCallback
{
private final String TAG = this.getClass().getSimpleName();
private static final int LOADER_THEKEY_ATTRIBUTES = 1;
private static final int LOADER_CURRENT_MINISTRY = 2;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
TheKey theKey;
private LocalBroadcastManager manager;
private GcmBroadcastReceiver gcmBroadcastReceiver;
private ActionBar actionBar;
private boolean targets;
private boolean groups;
private boolean churches;
private boolean multiplyingChurches;
private boolean trainingActivities;
private boolean campuses;
private SharedPreferences mapPreferences;
private SharedPreferences preferences;
private BroadcastReceiver broadcastReceiver;
private List<AssociatedMinistry> associatedMinistries;
// try to cut down on api calls
private boolean trainingDownloaded = false;
@Nullable
private GoogleMap map;
private ClusterManager<GcmMarker> clusterManager;
@Nullable
private AssociatedMinistry mCurrentMinistry;
private AssociatedMinistry currentMinistry;
private boolean currentAssignmentSet = false;
private boolean refreshAssignment;
private TextView mapOverlayText;
private List<Training> allTraining;
/* BEGIN lifecycle */
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
actionBar = getSupportActionBar();
mapOverlayText = (TextView) findViewById(R.id.map_text);
preferences = getSharedPreferences(PREFS_SETTINGS, Context.MODE_PRIVATE);
getMapPreferences();
setupBroadcastReceivers();
theKey = TheKeyImpl.getInstance(getApplicationContext(), THEKEY_CLIENTID);
manager = LocalBroadcastManager.getInstance(getApplicationContext());
gcmBroadcastReceiver = new GcmBroadcastReceiver(theKey, this);
gcmBroadcastReceiver.registerReceiver(manager);
// This call at times will create a null pointer. However, this is no big deal since it is call
// again later. It could be removed here; however, this does help a returning user retrieve
// their saved information a little quicker.
getCurrentAssignment();
if (Device.isConnected(getApplicationContext()))
{
handleLogin();
}
else
{
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_LONG).show();
}
if (checkPlayServices())
{
SupportMapFragment map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
map.getMapAsync(this);
}
}
private void handleLogin()
{
// check for previous login sessions
if (theKey.getGuid() == null)
{
login();
}
else
{
// trigger background syncing of data
MinistriesService.syncAllMinistries(this);
MinistriesService.syncAssignments(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
protected void onStart() {
super.onStart();
startLoaders();
}
@Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent goToSettings = new Intent(this, SettingsActivity.class);
startActivity(goToSettings);
return true;
case R.id.action_refresh:
MinistriesService.syncAllMinistries(this, true);
MinistriesService.syncAssignments(this, true);
return true;
}
return super.onOptionsItemSelected(item);
}
void onLoadAttributes(@Nullable final TheKey.Attributes attrs) {
final ActionBar actionBar = getSupportActionBar();
//TODO: what should be the default text until attributes have been loaded
actionBar.setTitle(
"Welcome" + (attrs != null && attrs.getFirstName() != null ? " " + attrs.getFirstName() : ""));
}
/**
* This event is triggered when a new currentMinistry object is loaded
*
* @param ministry the new current ministry object
*/
void onLoadCurrentMinistry(@Nullable final AssociatedMinistry ministry) {
// store the current ministry
final AssociatedMinistry old = mCurrentMinistry;
mCurrentMinistry = ministry;
// determine if the current ministry changed
final String oldId = old != null ? old.getMinistryId() : null;
final String newId = ministry != null ? ministry.getMinistryId() : null;
final boolean changed = oldId != null ? !oldId.equals(newId) : newId != null;
// update the map
updateMap(changed);
// trigger some additional actions if we are changing our current ministry
if (changed) {
onChangeCurrentMinistry();
}
}
/**
* This event is triggered when the current ministry is changing from one to another
*/
void onChangeCurrentMinistry() {
// sync trainings from the backend
if (mCurrentMinistry != null) {
String mcc = getChosenMcc();
TrainingService.downloadTraining(this, mCurrentMinistry.getMinistryId(), mcc != null ? mcc : "slm");
}
}
@Override
protected void onPostResume()
{
super.onPostResume();
Log.i(TAG, "Resuming");
if (map != null) map.clear();
getMapPreferences();
refreshCurrentAssignment();
updateMap(false);
}
@Override
protected void onDestroy()
{
super.onDestroy();
removeBroadcastReceivers();
}
/* END lifecycle */
private void startLoaders() {
final LoaderManager manager = this.getSupportLoaderManager();
manager.initLoader(LOADER_THEKEY_ATTRIBUTES, null, new AttributesLoaderCallbacks());
manager.initLoader(LOADER_CURRENT_MINISTRY, null, new AssociatedMinistryLoaderCallbacks());
}
private void updateMap(final boolean zoom) {
// update map overlay text
if (mapOverlayText != null) {
mapOverlayText.setText(mCurrentMinistry != null ? mCurrentMinistry.getName() : null);
}
// update map itself if it exists
if (map != null) {
// update map zoom
if (zoom) {
zoomToLocation();
}
// update Markers on the map
if (clusterManager != null) {
// clear any previous items
clusterManager.clearItems();
// add training Markers
addTrainingMarkersToMap();
// force a recluster
clusterManager.cluster();
}
}
}
public void joinNewMinistry(MenuItem menuItem)
{
final Context context = this;
if (Device.isConnected(getApplicationContext()))
{
if (theKey.getGuid() == null)
{
login();
}
else
{
Intent goToJoinMinistryPage = new Intent(context, JoinMinistryActivity.class);
startActivity(goToJoinMinistryPage);
}
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Internet Necessary")
.setMessage("You need Internet access to access this page")
.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create();
alertDialog.show();
}
}
public void goToMeasurements(MenuItem menuItem)
{
startActivity(new Intent(getApplicationContext(), MeasurementsActivity.class));
}
public void reset(MenuItem menuItem)
{
//TODO: implement reset: clear local data-model, download from server
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Reset")
.setMessage("Re-downloading information...")
.setNeutralButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create();
alertDialog.show();
}
public void logout(MenuItem menuItem)
{
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle(R.string.logout)
.setMessage(R.string.logout_message)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
theKey.logout();
dialog.dismiss();
login();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create();
alertDialog.show();
}
private void getMapPreferences()
{
targets = preferences.getBoolean("targets", true);
groups = preferences.getBoolean("groups", true);
churches = preferences.getBoolean("churches", true);
multiplyingChurches = preferences.getBoolean("multiplyingChurches", true);
trainingActivities = preferences.getBoolean("trainingActivities", true);
campuses = preferences.getBoolean("campuses", true);
}
private void login()
{
final FragmentManager fm = this.getSupportFragmentManager();
if (fm.findFragmentByTag("loginDialog") == null)
{
LoginDialogFragment loginDialogFragment = LoginDialogFragment.builder().clientId(THEKEY_CLIENTID).build();
loginDialogFragment.show(fm.beginTransaction().addToBackStack("loginDialog"), "loginDialog");
}
}
private void getCurrentAssignment()
{
Log.i(TAG, "Need to get current Assignment: " + !currentAssignmentSet);
if (!currentAssignmentSet)
{
currentAssignmentSet = new SetCurrentMinistry().doInBackground(this);
}
}
private void refreshCurrentAssignment()
{
String chosenMinistry = preferences.getString("chosen_ministry", null);
if(chosenMinistry == null || currentMinistry == null || chosenMinistry.equals(currentMinistry.getName()))
{
return;
}
refreshAssignment = true;
refreshAssignment = !new SetCurrentMinistry().doInBackground(this);
}
private boolean checkPlayServices()
{
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
else
{
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
public void mapOptions(View view)
{
Log.i(TAG, "Map options");
Intent intent = new Intent(this, MapSettings.class);
startActivity(intent);
}
@Override
public void onMapReady(@NonNull final GoogleMap googleMap) {
Log.i(TAG, "On Map Ready");
this.map = googleMap;
clusterManager = new ClusterManager<>(this, map);
clusterManager.setRenderer(new MarkerRender(this, map, clusterManager));
map.setOnCameraChangeListener(clusterManager);
map.setOnMarkerClickListener(clusterManager);
// update the map
updateMap(true);
}
private void zoomToLocation()
{
assert map != null : "map should be set before calling zoomToLocation";
if (mCurrentMinistry != null) {
Log.i(TAG, "Zooming to: " + mCurrentMinistry.getLatitude() + ", " + mCurrentMinistry.getLongitude());
CameraUpdate center = CameraUpdateFactory
.newLatLng(new LatLng(mCurrentMinistry.getLatitude(), mCurrentMinistry.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(mCurrentMinistry.getLocationZoom());
map.moveCamera(center);
map.moveCamera(zoom);
}
}
private void addTrainingMarkersToMap() {
// do not show training activities if turned off in map settings
Log.i(TAG, "Show training: " + trainingActivities);
if (trainingActivities && trainingDownloaded) {
for (Training training : allTraining)
{
GcmMarker marker = new GcmMarker(training.getName(), training.getLatitude(), training.getLongitude());
clusterManager.addItem(marker);
}
}
}
private void setupBroadcastReceivers()
{
manager = LocalBroadcastManager.getInstance(this);
this.broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (BroadcastUtils.ACTION_START.equals(intent.getAction()))
{
Log.i(TAG, "Action Started");
}
else if (BroadcastUtils.ACTION_RUNNING.equals(intent.getAction()))
{
Log.i(TAG, "Action Running");
}
else if (BroadcastUtils.ACTION_STOP.equals(intent.getAction()))
{
Log.i(TAG, "Action Done");
Type type = (Type) intent.getSerializableExtra(BroadcastUtils.ACTION_TYPE);
switch (type)
{
case TRAINING:
Log.i(TAG, "Training search complete and training saved");
trainingDownloaded = true;
TrainingDao trainingDao = TrainingDao.getInstance(context);
allTraining = trainingDao.getAllMinistryTraining(currentMinistry.getMinistryId());
updateMap(false);
break;
case RETRIEVE_ALL_MINISTRIES:
getCurrentAssignment();
break;
case SAVE_ASSOCIATED_MINISTRIES:
getCurrentAssignment();
break;
default:
Log.i(TAG, "Unhandled Type: " + type);
}
}
}
};
manager.registerReceiver(broadcastReceiver, BroadcastUtils.startFilter());
manager.registerReceiver(broadcastReceiver, BroadcastUtils.runningFilter());
manager.registerReceiver(broadcastReceiver, BroadcastUtils.stopFilter());
}
private void removeBroadcastReceivers()
{
manager = LocalBroadcastManager.getInstance(this);
manager.unregisterReceiver(broadcastReceiver);
manager.unregisterReceiver(gcmBroadcastReceiver);
broadcastReceiver = null;
gcmBroadcastReceiver = null;
}
private class SetCurrentMinistry extends AsyncTask<Context, Void, Boolean>
{
/*
* This will allow the current assignment to be retrieved and data for the assignment will be loaded.
* If an assignment is not currently set a random parent associated ministry will be selected.
*
* Definitions:
* currentMinistry: The ministry associated with the currently selected assignment
* currentAssignment: currently selected assignment. Selected from associated assignments
* currentMinistryName: Name of currentMinistry
*/
@Override
protected Boolean doInBackground(Context... params)
{
Context context = params[0];
Log.i(TAG, "Trying to set current Assignment");
try
{
MinistriesDao ministriesDao = MinistriesDao.getInstance(context);
String currentMinistryName = preferences.getString("chosen_ministry", null);
// if currentMinistry is already set, skip getting it
if (currentMinistry == null) {
if (associatedMinistries == null || associatedMinistries.size() == 0)
{
Log.i(TAG, "associated ministries needs to be set");
associatedMinistries = ministriesDao.retrieveAssociatedMinistriesList();
}
if (associatedMinistries == null || associatedMinistries.size() == 0)
{
Log.w(TAG, "No Associated Ministries");
return false;
}
if (currentMinistryName == null)
{
Log.i(TAG, "current ministry id needs to be set");
SharedPreferences.Editor editor = preferences.edit();
int i = 0;
boolean parent = false;
do
{
parent = associatedMinistries.get(i).getParentMinistryId() == null;
if(!parent)
{
i++;
}
} while (!parent);
currentMinistry = associatedMinistries.get(i);
currentMinistryName = currentMinistry.getName();
editor.putString("chosen_ministry", currentMinistryName);
editor.putString(PREF_CURRENT_MINISTRY, currentMinistry.getMinistryId());
editor.apply();
}
else
{
setMinistry(associatedMinistries, currentMinistryName);
}
}
else if(refreshAssignment)
{
setMinistry(associatedMinistries, currentMinistryName);
// If we are changing assignments/ministries, we need to reload the training
TrainingDao trainingDao = TrainingDao.getInstance(context);
allTraining = trainingDao.getAllMinistryTraining(currentMinistry.getMinistryId());
}
if (currentMinistry == null)
{
Log.i(TAG, "current ministry is still null");
return false;
}
Log.i(TAG, "currentMinistry: " + currentMinistry.getName());
return true;
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return false;
}
}
private void setMinistry(
final List<AssociatedMinistry> associatedMinistries,
final String ministryName) {
for (AssociatedMinistry ministry : associatedMinistries)
{
if (ministry.getName().equals(ministryName))
{
currentMinistry = ministry;
break;
}
}
}
@Nullable
private String getChosenMcc() {
if (mCurrentMinistry != null) {
String mcc = preferences.getString("chosen_mcc", null);
if (mcc == null || "No MCC Options".equals(mcc)) {
if (mCurrentMinistry.hasSlm()) {
mcc = "SLM";
} else if (mCurrentMinistry.hasGcm()) {
mcc = "GCM";
} else if (mCurrentMinistry.hasLlm()) {
mcc = "LLM";
} else if (mCurrentMinistry.hasDs()) {
mcc = "DS";
}
preferences.edit().putString("chosen_mcc", mcc).apply();
}
return mcc;
}
return null;
}
private class AssociatedMinistryLoaderCallbacks extends SimpleLoaderCallbacks<AssociatedMinistry> {
@Override
public Loader<AssociatedMinistry> onCreateLoader(final int id, final Bundle bundle) {
switch (id) {
case LOADER_CURRENT_MINISTRY:
return new CurrentMinistryLoader(MainActivity.this);
default:
return null;
}
}
@Override
public void onLoadFinished(final Loader<AssociatedMinistry> loader,
@Nullable final AssociatedMinistry ministry) {
switch (loader.getId()) {
case LOADER_CURRENT_MINISTRY:
onLoadCurrentMinistry(ministry);
break;
}
}
}
private class AttributesLoaderCallbacks extends SimpleLoaderCallbacks<TheKey.Attributes> {
@Override
public Loader<TheKey.Attributes> onCreateLoader(final int id, final Bundle args) {
switch (id) {
case LOADER_THEKEY_ATTRIBUTES:
return new AttributesLoader(MainActivity.this, theKey);
default:
return null;
}
}
@Override
public void onLoadFinished(@NonNull final Loader<TheKey.Attributes> loader,
@Nullable final TheKey.Attributes attrs) {
switch (loader.getId()) {
case LOADER_THEKEY_ATTRIBUTES:
onLoadAttributes(attrs);
break;
}
}
}
} |
package org.lightmare.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.jpa.datasource.PoolConfig;
import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType;
import org.lightmare.utils.ObjectUtils;
import org.yaml.snakeyaml.Yaml;
/**
* Easy way to retrieve configuration properties from configuration file
*
* @author levan
*
*/
public class Configuration implements Cloneable {
// cache for all configuration passed programmatically or read from file
private final Map<Object, Object> config = new HashMap<Object, Object>();
// path where stored adminitrator users
public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath";
/**
* <a href="netty.io">Netty</a> server / client configuration properties for
* RPC calls
*/
public static final String IP_ADDRESS_KEY = "listeningIp";
public static final String PORT_KEY = "listeningPort";
public static final String BOSS_POOL_KEY = "bossPoolSize";
public static final String WORKER_POOL_KEY = "workerPoolSize";
public static final String CONNECTION_TIMEOUT_KEY = "timeout";
// properties for datasource path and deployment path
public static final String DEMPLOYMENT_PATH_KEY = "deploymentPath";
public static final String DATA_SOURCE_PATH_KEY = "dataSourcePath";
// runtime to get avaliable processors
private static final Runtime RUNTIME = Runtime.getRuntime();
/**
* Default properties
*/
public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties";
public static final String IP_ADDRESS_DEF = "0.0.0.0";
public static final String PORT_DEF = "1199";
public static final String BOSS_POOL_DEF = "1";
public static final int WORKER_POOL_DEF = 3;
public static final String CONNECTION_TIMEOUT_DEF = "1000";
public static final boolean SERVER_DEF = Boolean.TRUE;
public static final String DATA_SOURCE_PATH_DEF = "./ds";
/**
* Properties which version of server is running remote it requires server
* client RPC infrastructure or local (embeddable mode)
*/
private static final String REMOTE_KEY = "remote";
private static final String SERVER_KEY = "server";
private static final String CLIENT_KEY = "client";
public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>(
Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)));
public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>(
Arrays.asList("./ds"));
private static final String CONFIG_FILE = "./config/configuration.yaml";
// String prefixes for jndi names
public static final String JPA_NAME = "java:comp/env/";
public static final String EJB_NAME = "ejb:";
public static final int EJB_NAME_LENGTH = 4;
// Configuration keys properties for deployment
private static final String DEPLOY_CONFIG_KEY = "deployConfiguration";
private static final String ADMIN_USER_PATH_KEY = "adminPath";
private static final String HOT_DEPLOYMENT_KEY = "hotDeployment";
private static final String WATCH_STATUS_KEY = "watchStatus";
private static final String LIBRARY_PATH_KEY = "libraryPaths";
// Persistence provider property keys
private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities";
private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName";
private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath";
private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar";
private static final String SWAP_DATASOURCE_KEY = "swapDataSource";
private static final String SCAN_ARCHIVES_KEY = "scanArchives";
private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource";
private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties";
// Connection pool provider property keys
private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath";
private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType";
private static final String POOL_PROPERTIES_KEY = "poolProperties";
// Configuration properties for deployment
private static String ADMIN_USERS_PATH;
// Is configuration server or client (default is server)
private static boolean server = SERVER_DEF;
private static boolean remote;
// Instance of pool configuration
private static final PoolConfig POOL_CONFIG = new PoolConfig();
private static final Logger LOG = Logger.getLogger(Configuration.class);
public Configuration() {
}
@SuppressWarnings("unchecked")
private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) {
if (from == null) {
from = config;
}
Map<K, V> value = (Map<K, V>) from.get(key);
return value;
}
private <K, V> Map<K, V> getAsMap(Object key) {
return getAsMap(key, null);
}
private <K, V> void setSubConfigValue(Object key, K subKey, V value) {
Map<K, V> subConfig = getAsMap(key);
if (subConfig == null) {
subConfig = new HashMap<K, V>();
config.put(key, subConfig);
}
subConfig.put(subKey, value);
}
private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) {
V def;
Map<K, V> subConfig = getAsMap(key);
if (ObjectUtils.available(subConfig)) {
def = subConfig.get(subKey);
if (def == null) {
def = defaultValue;
}
} else {
def = defaultValue;
}
return def;
}
private <K> boolean containsSubConfigKey(Object key, K subKey) {
Map<K, ?> subConfig = getAsMap(key);
boolean valid = ObjectUtils.available(subConfig);
if (valid) {
valid = subConfig.containsKey(subKey);
}
return valid;
}
private <K> boolean containsConfigKey(K key) {
return containsSubConfigKey(DEPLOY_CONFIG_KEY, key);
}
private <K, V> V getSubConfigValue(Object key, K subKey) {
return getSubConfigValue(key, subKey, null);
}
private <K, V> void setConfigValue(K subKey, V value) {
setSubConfigValue(DEPLOY_CONFIG_KEY, subKey, value);
}
private <K, V> V getConfigValue(K subKey, V defaultValue) {
return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey, defaultValue);
}
private <K, V> V getConfigValue(K subKey) {
return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey);
}
/**
* Configuration for {@link PoolConfig} instance
*/
private void configurePool() {
Map<Object, Object> poolProperties = getConfigValue(POOL_PROPERTIES_KEY);
if (ObjectUtils.available(poolProperties)) {
setPoolProperties(poolProperties);
}
String type = getConfigValue(POOL_PROVIDER_TYPE_KEY);
if (ObjectUtils.available(type)) {
getPoolConfig().setPoolProviderType(type);
}
String path = getConfigValue(POOL_PROPERTIES_PATH_KEY);
if (ObjectUtils.available(path)) {
setPoolPropertiesPath(path);
}
}
/**
* Configures server from properties
*/
private void configureServer() {
// Sets default values to remote server configuration
boolean contains = containsConfigKey(IP_ADDRESS_KEY);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(IP_ADDRESS_KEY, IP_ADDRESS_DEF);
}
contains = containsConfigKey(PORT_KEY);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(PORT_KEY, PORT_DEF);
}
contains = containsConfigKey(BOSS_POOL_KEY);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(BOSS_POOL_KEY, BOSS_POOL_DEF);
}
contains = containsConfigKey(WORKER_POOL_KEY);
if (ObjectUtils.notTrue(contains)) {
int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF;
String workerProperty = String.valueOf(workers);
setConfigValue(WORKER_POOL_KEY, workerProperty);
}
contains = containsConfigKey(CONNECTION_TIMEOUT_KEY);
if (ObjectUtils.notTrue(contains)) {
setConfigValue(CONNECTION_TIMEOUT_KEY, CONNECTION_TIMEOUT_DEF);
}
Object serverValue = getConfigValue(SERVER_KEY);
if (ObjectUtils.notNull(serverValue)) {
if (serverValue instanceof Boolean) {
server = (Boolean) serverValue;
} else {
server = Boolean.valueOf(serverValue.toString());
}
}
Object remoteValue = getConfigValue(REMOTE_KEY);
if (ObjectUtils.notNull(remoteValue)) {
if (remoteValue instanceof Boolean) {
remote = (Boolean) remoteValue;
} else {
remote = Boolean.valueOf(remoteValue.toString());
}
}
}
/**
* Merges configuration with default properties
*/
public void configureDeployments() {
ADMIN_USERS_PATH = getConfigValue(ADMIN_USER_PATH_KEY,
ADMIN_USERS_PATH_DEF);
Boolean hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY);
if (hotDeployment == null) {
setConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE);
hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY);
}
boolean watchStatus;
if (ObjectUtils.notTrue(hotDeployment)) {
watchStatus = Boolean.TRUE;
} else {
watchStatus = Boolean.FALSE;
}
setConfigValue(WATCH_STATUS_KEY, watchStatus);
Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY);
if (deploymentPaths == null) {
deploymentPaths = DEPLOYMENT_PATHS_DEF;
setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths);
}
}
/**
* Configures server and connection pooling
*/
public void configure() {
configureServer();
configureDeployments();
configurePool();
}
/**
* Reads configuration from passed properties
*
* @param configuration
*/
public void configure(Map<Object, Object> configuration) {
if (ObjectUtils.available(configuration)) {
Map<Object, Object> newConfig = getAsMap(DEPLOY_CONFIG_KEY,
configuration);
Map<Object, Object> existingConfig = getAsMap(DEPLOY_CONFIG_KEY);
if (ObjectUtils.notNull(newConfig)) {
if (existingConfig == null) {
config.put(DEPLOY_CONFIG_KEY, newConfig);
} else {
existingConfig.putAll(newConfig);
}
}
}
}
/**
* Reads configuration from passed file path
*
* @param configuration
*/
@SuppressWarnings("unchecked")
public void configure(String path) throws IOException {
File yamlFile = new File(path);
if (yamlFile.exists()) {
InputStream stream = new FileInputStream(yamlFile);
try {
Yaml yaml = new Yaml();
Object configuration = yaml.load(stream);
if (configuration instanceof Map) {
configure((Map<Object, Object>) configuration);
}
} finally {
stream.close();
}
}
}
/**
* Gets value associated with particular key as {@link String} instance
*
* @param key
* @return {@link String}
*/
public String getStringValue(String key) {
Object value = config.get(key);
String textValue;
if (value == null) {
textValue = null;
} else {
textValue = value.toString();
}
return textValue;
}
/**
* Gets value associated with particular key as <code>int</code> instance
*
* @param key
* @return {@link String}
*/
public int getIntValue(String key) {
String value = getStringValue(key);
return Integer.parseInt(value);
}
/**
* Gets value associated with particular key as <code>long</code> instance
*
* @param key
* @return {@link String}
*/
public long getLongValue(String key) {
String value = getStringValue(key);
return Long.parseLong(value);
}
/**
* Gets value associated with particular key as <code>boolean</code>
* instance
*
* @param key
* @return {@link String}
*/
public boolean getBooleanValue(String key) {
String value = getStringValue(key);
return Boolean.parseBoolean(value);
}
public void putValue(String key, String value) {
config.put(key, value);
}
/**
* Loads configuration form file
*
* @throws IOException
*/
public void loadFromFile() throws IOException {
InputStream propertiesStream = null;
try {
File configFile = new File(CONFIG_FILE);
if (configFile.exists()) {
propertiesStream = new FileInputStream(configFile);
loadFromStream(propertiesStream);
} else {
configFile.mkdirs();
}
} catch (IOException ex) {
LOG.error("Could not open config file", ex);
} finally {
if (ObjectUtils.notNull(propertiesStream)) {
propertiesStream.close();
}
}
}
/**
* Loads configuration form file by passed file path
*
* @param configFilename
* @throws IOException
*/
public void loadFromFile(String configFilename) throws IOException {
InputStream propertiesStream = null;
try {
propertiesStream = new FileInputStream(new File(configFilename));
loadFromStream(propertiesStream);
} catch (IOException ex) {
LOG.error("Could not open config file", ex);
} finally {
if (ObjectUtils.notNull(propertiesStream)) {
propertiesStream.close();
}
}
}
/**
* Loads configuration from file contained in classpath
*
* @param resourceName
* @param loader
*/
public void loadFromResource(String resourceName, ClassLoader loader) {
InputStream resourceStream = loader
.getResourceAsStream(new StringBuilder("META-INF/").append(
resourceName).toString());
if (resourceStream == null) {
LOG.error("Configuration resource doesn't exist");
return;
}
loadFromStream(resourceStream);
try {
resourceStream.close();
} catch (IOException ex) {
LOG.error("Could not load resource", ex);
}
}
/**
* Load {@link Configuration} in memory as {@link Map} of parameters
*
* @throws IOException
*/
public void loadFromStream(InputStream propertiesStream) {
try {
Properties props = new Properties();
props.load(propertiesStream);
for (String propertyName : props.stringPropertyNames()) {
config.put(propertyName, props.getProperty(propertyName));
}
propertiesStream.close();
} catch (IOException ex) {
LOG.error("Could not load configuration", ex);
}
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remoteValue) {
remote = remoteValue;
}
public static boolean isServer() {
return server;
}
public static void setServer(boolean serverValue) {
server = serverValue;
}
public boolean isClient() {
return getConfigValue(CLIENT_KEY, Boolean.FALSE);
}
public void setClient(boolean client) {
setConfigValue(CLIENT_KEY, client);
}
/**
* Adds path for deployments file or directory
*
* @param path
* @param scan
*/
public void addDeploymentPath(String path, boolean scan) {
Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY);
if (deploymentPaths == null) {
deploymentPaths = new HashSet<DeploymentDirectory>();
setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths);
}
deploymentPaths.add(new DeploymentDirectory(path, scan));
}
/**
* Adds path for data source file
*
* @param path
*/
public void addDataSourcePath(String path) {
Set<String> dataSourcePaths = getConfigValue(DATA_SOURCE_PATH_KEY);
if (dataSourcePaths == null) {
dataSourcePaths = new HashSet<String>();
setConfigValue(DATA_SOURCE_PATH_KEY, dataSourcePaths);
}
dataSourcePaths.add(path);
}
public Set<DeploymentDirectory> getDeploymentPath() {
return getConfigValue(DEMPLOYMENT_PATH_KEY);
}
public Set<String> getDataSourcePath() {
return getConfigValue(DATA_SOURCE_PATH_KEY);
}
public boolean isScanForEntities() {
return getConfigValue(SCAN_FOR_ENTITIES_KEY, Boolean.FALSE);
}
public void setScanForEntities(boolean scanForEntities) {
setConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities);
}
public String getAnnotatedUnitName() {
return getConfigValue(ANNOTATED_UNIT_NAME_KEY);
}
public void setAnnotatedUnitName(String annotatedUnitName) {
setConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName);
}
public String getPersXmlPath() {
return getConfigValue(PERSISTENCE_XML_PATH_KEY);
}
public void setPersXmlPath(String persXmlPath) {
setConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath);
}
public String[] getLibraryPaths() {
return getConfigValue(LIBRARY_PATH_KEY);
}
public void setLibraryPaths(String[] libraryPaths) {
setConfigValue(LIBRARY_PATH_KEY, libraryPaths);
}
public boolean isPersXmlFromJar() {
return getConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE);
}
public void setPersXmlFromJar(boolean persXmlFromJar) {
setConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar);
}
public boolean isSwapDataSource() {
return getConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE);
}
public void setSwapDataSource(boolean swapDataSource) {
setConfigValue(SWAP_DATASOURCE_KEY, swapDataSource);
}
public boolean isScanArchives() {
return getConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE);
}
public void setScanArchives(boolean scanArchives) {
setConfigValue(SCAN_ARCHIVES_KEY, scanArchives);
}
public boolean isPooledDataSource() {
return getConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE);
}
public void setPooledDataSource(boolean pooledDataSource) {
setConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource);
}
public static PoolConfig getPoolConfig() {
return POOL_CONFIG;
}
public static String getAdminUsersPath() {
return ADMIN_USERS_PATH;
}
public static void setAdminUsersPath(String aDMIN_USERS_PATH) {
ADMIN_USERS_PATH = aDMIN_USERS_PATH;
}
public Map<Object, Object> getPersistenceProperties() {
return getConfigValue(PERSISTENCE_PROPERTIES_KEY);
}
public void setPersistenceProperties(
Map<Object, Object> persistenceProperties) {
setConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties);
}
public boolean isHotDeployment() {
return getConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE);
}
public void setHotDeployment(boolean hotDeployment) {
setConfigValue(HOT_DEPLOYMENT_KEY, hotDeployment);
}
public boolean isWatchStatus() {
return getConfigValue(WATCH_STATUS_KEY, Boolean.FALSE);
}
public void setWatchStatus(boolean watchStatus) {
setConfigValue(WATCH_STATUS_KEY, watchStatus);
}
public void setDataSourcePooledType(boolean dsPooledType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPooledDataSource(dsPooledType);
}
public void setPoolPropertiesPath(String path) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolPath(path);
}
public void setPoolProperties(
Map<? extends Object, ? extends Object> properties) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().putAll(properties);
}
public void addPoolProperty(Object key, Object value) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.getPoolProperties().put(key, value);
}
public void setPoolProviderType(PoolProviderType poolProviderType) {
PoolConfig poolConfig = getPoolConfig();
poolConfig.setPoolProviderType(poolProviderType);
}
@Override
public Object clone() throws CloneNotSupportedException {
Configuration cloneConfig = (Configuration) super.clone();
cloneConfig.config.clear();
cloneConfig.configure(this.config);
return cloneConfig;
}
} |
package se.kth.scs.remote;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import se.kth.scs.partitioning.ConcurrentPartition;
import se.kth.scs.partitioning.ConcurrentVertex;
import se.kth.scs.partitioning.Partition;
import se.kth.scs.partitioning.Vertex;
/**
*
* @author Hooman
*/
public class ServerStorage {
private final static short NUM_TRIES = 5;
private final ConcurrentHashMap<Integer, ConcurrentVertex> vertices = new ConcurrentHashMap<>(); // Holds partial degree of each vertex.
private final ConcurrentHashMap<Short, ConcurrentPartition> partitions;
private final short k;
public ServerStorage(short k) {
this.k = k;
partitions = new ConcurrentHashMap();
initPartitions(partitions, this.k);
}
private void initPartitions(ConcurrentHashMap<Short, ConcurrentPartition> partitions, short k) {
partitions.clear();
for (short i = 0; i < k; i++) {
partitions.put(i, new ConcurrentPartition(i));
}
}
public short getNumberOfPartitions() {
return k;
}
public void releaseResources() {
vertices.clear();
initPartitions(partitions, k);
}
/**
* Order of number of vertices. It serializes for efficiency.
*
* @param expectedSize
* @return
*/
public int[] getAllVertices(int expectedSize) {
// To work-around the concurrenthashmap's weak consistency,
// that affects inconsistent results between values().size() and the iterator over the valus.
int count = 1;
while (vertices.size() < expectedSize) {
try {
Thread.sleep(1);
System.out.println(String.format("Try number %d failed to collect expected number of vertices.", count));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
count++;
}
int[] array = new int[vertices.size() * 3];
int i = 0;
for (ConcurrentVertex v : vertices.values()) {
array[i] = v.getId();
array[i + 1] = v.getpDegree();
array[i + 2] = v.getPartitions();
i = i + 3;
}
return array;
}
public Vertex getVertex(int vid) {
//TODO: a clone should be sent in multi-threaded version.
ConcurrentVertex v = vertices.get(vid);
if (v != null) {
return v.clone();
} else {
return null;
}
}
public LinkedList<Vertex> getVertices(int[] vids) {
LinkedList<Vertex> vs = new LinkedList<>();
for (int vid : vids) {
Vertex v = getVertex(vid);
if (v != null) {
vs.add(v);
}
}
return vs;
}
public void putVertex(Vertex v) {
ConcurrentVertex shared = vertices.get(v.getId());
if (shared != null) {
shared.accumulate(v);
} else {
shared = new ConcurrentVertex(v.getId(), 0);
shared.accumulate(v);
shared = vertices.putIfAbsent(v.getId(), shared);
// Double check if the entry does not exist.
if (shared != null) {
shared.accumulate(v);
}
}
}
public void putVertices(int[] vertices) {
for (int i = 0; i < vertices.length; i = i + 3) {
Vertex v = new Vertex(vertices[i]);
v.setDegreeDelta(vertices[i + 1]);
v.setPartitionsDelta(vertices[i + 2]);
putVertex(v);
}
}
public Partition getPartition(short pid) {
ConcurrentPartition p = partitions.get(pid);
if (p != null) {
return p.clone();
} else {
return null;
}
}
public int[] getPartitions() {
int[] eSizes = new int[k];
for (short i = 0; i < k; i++) {
Partition p = getPartition(i);
if (p == null) {
eSizes[i] = 0;
} else {
eSizes[i] = p.getESize();
}
}
return eSizes;
}
public void putPartition(Partition p) {
ConcurrentPartition shared = partitions.get(p.getId());
if (shared != null) {
shared.accumulate(p);
} else {
shared = new ConcurrentPartition(p.getId());
shared.accumulate(p);
shared = partitions.putIfAbsent(p.getId(), shared);
// Double check if the entry does not exist.
if (shared != null) {
shared.accumulate(p);
}
}
}
public void putPartitions(int[] eSizes) {
for (short i = 0; i < eSizes.length; i++) {
Partition p = new Partition(i);
p.seteSizeDelta(eSizes[i]);
putPartition(p);
}
}
} |
package seedu.unburden.storage;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import seedu.unburden.commons.events.model.ListOfTaskChangedEvent;
import seedu.unburden.commons.events.storage.DataSavingExceptionEvent;
import seedu.unburden.model.ListOfTask;
import seedu.unburden.model.ReadOnlyListOfTask;
import seedu.unburden.model.UserPrefs;
import seedu.unburden.storage.JsonUserPrefsStorage;
import seedu.unburden.storage.Storage;
import seedu.unburden.storage.StorageManager;
import seedu.unburden.storage.XmlTaskListStorage;
import seedu.unburden.testutil.EventsCollector;
import seedu.unburden.testutil.TypicalTestTasks;
import java.io.IOException;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class StorageManagerTest {
private StorageManager storageManager;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Before
public void setup() {
storageManager = new StorageManager(getTempFilePath("ab"), getTempFilePath("prefs"));
}
private String getTempFilePath(String fileName) {
return testFolder.getRoot().getPath() + fileName;
}
/*
* Note: This is an integration test that verifies the StorageManager is properly wired to the
* {@link JsonUserPrefsStorage} class.
* More extensive testing of UserPref saving/reading is done in {@link JsonUserPrefsStorageTest} class.
*/
@Test
public void prefsReadSave() throws Exception {
UserPrefs original = new UserPrefs();
original.setGuiSettings(300, 600, 4, 6);
storageManager.saveUserPrefs(original);
UserPrefs retrieved = storageManager.readUserPrefs().get();
assertEquals(original, retrieved);
}
//@Test
public void taskListReadSave() throws Exception {
ListOfTask original = new TypicalTestTasks().getTypicalListOfTask();
storageManager.saveTaskList(original);
ReadOnlyListOfTask retrieved = storageManager.readTaskList().get();
assertEquals(original, new ListOfTask(retrieved));
//More extensive testing of ListOfTask saving/reading is done in XmlTaskListStorageTest
}
@Test
public void getTaskListFilePath(){
assertNotNull(storageManager.getTaskListFilePath());
}
@Test
public void handleTaskListChangedEvent_exceptionThrown_eventRaised() throws IOException {
//Create a StorageManager while injecting a stub that throws an exception when the save method is called
Storage storage = new StorageManager(new XmlTaskListStorageExceptionThrowingStub("dummy"), new JsonUserPrefsStorage("dummy"));
EventsCollector eventCollector = new EventsCollector();
storage.handleListOfTaskChangedEvent(new ListOfTaskChangedEvent(new ListOfTask()));
assertTrue(eventCollector.get(0) instanceof DataSavingExceptionEvent);
}
/**
* A Stub class to throw an exception when the save method is called
*/
class XmlTaskListStorageExceptionThrowingStub extends XmlTaskListStorage{
public XmlTaskListStorageExceptionThrowingStub(String filePath) {
super(filePath);
}
@Override
public void saveTaskList(ReadOnlyListOfTask addressBook, String filePath) throws IOException {
throw new IOException("dummy exception");
}
}
} |
package org.lightmare.rest.utils;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.process.Inflector;
import org.glassfish.jersey.server.model.Invocable;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.MetaData;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.rest.RestConfig;
import org.lightmare.rest.providers.RestInflector;
import org.lightmare.rest.providers.RestReloader;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.beans.BeanUtils;
import org.lightmare.utils.serialization.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility class for REST resources
*
* @author levan
*
*/
public class RestUtils {
public static final ObjectMapper MAPPER = new ObjectMapper();
private static RestConfig config;
private static RestConfig oldConfig;
private static void getConfig() {
oldConfig = RestConfig.get();
config = new RestConfig();
}
private static RestConfig get() {
synchronized (RestUtils.class) {
getConfig();
}
return config;
}
public static <T> T convert(String json, Class<T> valueClass)
throws IOException {
T value = JsonSerializer.read(json, valueClass);
return value;
}
public static String json(Object data) throws IOException {
return JsonSerializer.write(data);
}
/**
* Checks if class is acceptable to build {@link Resource} instance
*
* @param resourceClass
* @return <code>boolean</code>
*/
private static boolean isAcceptable(Class<?> resourceClass) {
boolean valid = Resource.isAcceptable(resourceClass)
&& resourceClass.isAnnotationPresent(Path.class);
return valid;
}
/**
* Builds new {@link Resource} from passed one with new
* {@link org.glassfish.jersey.process.Inflector} implementation
* {@link RestInflector} and with all child resources
*
* @param resource
* @return {@link Resource}
* @throws IOException
*/
public static Resource defineHandler(Resource resource) throws IOException {
Resource.Builder builder = Resource.builder(resource.getPath());
builder.name(resource.getName());
List<ResourceMethod> methods = resource.getAllMethods();
ResourceMethod.Builder methodBuilder;
Collection<Class<?>> handlers = resource.getHandlerClasses();
Class<?> beanClass;
String beanEjbName;
Iterator<Class<?>> iterator = handlers.iterator();
beanClass = iterator.next();
beanEjbName = BeanUtils.beanName(beanClass);
List<MediaType> consumedTypes;
List<MediaType> producedTypes;
Invocable invocable;
MetaData metaData = MetaContainer.getSyncMetaData(beanEjbName);
Method realMethod;
MediaType type;
List<Parameter> parameters;
for (ResourceMethod method : methods) {
consumedTypes = method.getConsumedTypes();
producedTypes = method.getProducedTypes();
invocable = method.getInvocable();
realMethod = invocable.getHandlingMethod();
parameters = invocable.getParameters();
if (ObjectUtils.available(consumedTypes)) {
type = ObjectUtils.getFirst(consumedTypes);
} else {
type = null;
}
Inflector<ContainerRequestContext, Response> inflector = new RestInflector(
realMethod, metaData, type, parameters);
methodBuilder = builder.addMethod(method.getHttpMethod());
methodBuilder.consumes(consumedTypes);
methodBuilder.produces(producedTypes);
methodBuilder.nameBindings(method.getNameBindings());
methodBuilder.handledBy(inflector);
methodBuilder.build();
}
List<Resource> children = resource.getChildResources();
if (ObjectUtils.available(children)) {
Resource child;
for (Resource preChild : children) {
child = defineHandler(preChild);
builder.addChildResource(child);
}
}
Resource intercepted = builder.build();
return intercepted;
}
public static void add(Class<?> beanClass) throws IOException {
boolean valid = isAcceptable(beanClass);
if (valid) {
RestReloader reloader = RestReloader.get();
if (ObjectUtils.notNull(reloader)) {
RestConfig conf = get();
conf.registerClass(beanClass, oldConfig);
}
}
}
public static void remove(Class<?> beanClass) {
RestReloader reloader = RestReloader.get();
if (ObjectUtils.notNull(reloader)) {
RestConfig conf = get();
conf.unregister(beanClass, oldConfig);
}
}
/**
* Gets common class loader (enriched for each {@link ClassLoader} from
* {@link MetaData}) to add to REST server
*
* @return {@link ClassLoader}
*/
public static ClassLoader getCommonLoader() {
Iterator<MetaData> iterator = MetaContainer.getBeanClasses();
MetaData metaData;
ClassLoader newLoader;
ClassLoader oldLoader = null;
ClassLoader commonLoader = null;
while (iterator.hasNext()) {
metaData = iterator.next();
newLoader = metaData.getLoader();
if (ObjectUtils.notNull(oldLoader)
&& ObjectUtils.notNull(newLoader)) {
commonLoader = LibraryLoader.createCommon(newLoader, oldLoader);
}
oldLoader = newLoader;
}
return commonLoader;
}
public static void reload() {
RestReloader reloader = RestReloader.get();
RestConfig conf = RestConfig.get();
if (ObjectUtils.notNull(conf) && ObjectUtils.notNull(reloader)) {
ClassLoader commonLoader = getCommonLoader();
if (ObjectUtils.notNull(commonLoader)) {
conf.setClassLoader(commonLoader);
}
conf.registerPreResources();
reloader.reload(conf);
}
}
} |
package com.jrvermeer.psalter;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class PsalterDb extends SQLiteAssetHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "psalter.sqlite";
private static final String TABLE_NAME = "psalter";
private SQLiteDatabase db;
public PsalterDb(final Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
setForcedUpgrade(DATABASE_VERSION);
db = getReadableDatabase();
}
public int getCount(){
try{
return (int)DatabaseUtils.queryNumEntries(db, TABLE_NAME);
} catch (Exception ex){
return 0;
}
}
public Psalter getPsalter(int number){
try{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] columns = {"_id", "psalm", "lyrics"};
String where = "_id = " + number;
qb.setTables(TABLE_NAME);
Cursor c = qb.query(db, columns, where, null, null, null, null);
if(c.moveToNext()){
Psalter p = new Psalter();
p.setNumber(c.getInt(0));
p.setPsalm(c.getInt(1));
p.setLyrics(c.getString(2));
return p;
} else {
return null;
}
} catch (Exception ex){
return null;
}
}
public Psalter[] searchPsalter(String searchText){
try{
ArrayList<Psalter> hits = new ArrayList<>();
String lyrics = LyricsReplacePunctuation();
Cursor c = db.rawQuery("select _id, psalm, " + lyrics + " from psalter where " + lyrics + " like '%" + searchText + "%'", null);
while(c.moveToNext()){
Psalter p = new Psalter();
p.setNumber(c.getInt(0));
p.setPsalm(c.getInt(1));
p.setLyrics(c.getString(2));
hits.add(p);
}
return hits.toArray(new Psalter[hits.size()]);
} catch (Exception ex){
return null;
}
}
public String LyricsReplacePunctuation(){
String replace = "lyrics";
Collections.addAll(Arrays.asList(PsalterSearchAdapter.searchIgnoreChars));
for(char replaceChar : PsalterSearchAdapter.searchIgnoreChars){
replace = "replace(" + replace + ", char(" + (int)replaceChar + "), '')";
}
return replace;
}
public Psalter[] getPsalm(int psalmNumber){
try{
ArrayList<Psalter> hits = new ArrayList<>();
Cursor c = db.rawQuery("select _id, psalm, lyrics from psalter where psalm = " + String.valueOf(psalmNumber), null);
while(c.moveToNext()){
Psalter p = new Psalter();
p.setNumber(c.getInt(0));
p.setPsalm(c.getInt(1));
p.setLyrics(c.getString(2));
hits.add(p);
}
return hits.toArray(new Psalter[hits.size()]);
} catch (Exception ex){
return null;
}
}
} |
package timeseries.models.arima;
import data.TestData;
import org.junit.Test;
import timeseries.TimeSeries;
import timeseries.models.Forecast;
import static org.junit.Assert.*;
/**
* [Insert class description]
*
* @author Jacob Rachiele
* Mar. 07, 2017
*/
public class ArimaForecastSpec {
@Test
public void whenForecastThenCorrectPredictionIntervals() {
TimeSeries timeSeries = TestData.debitcards();
Arima.FittingStrategy fittingStrategy = Arima.FittingStrategy.CSSML;
Arima.ModelCoefficients coefficients = Arima.ModelCoefficients.newBuilder().setMACoeffs(-0.6760904)
.setSeasonalMACoeffs(-0.5718134).setDifferences(1).setSeasonalDifferences(1).build();
Arima model = Arima.model(timeSeries, coefficients, fittingStrategy);
Forecast forecast = ArimaForecast.forecast(model);
double[] expectedLower = {17812.16355, 17649.219039, 18907.15779, 18689.915865, 21405.818889, 21379.160025,
22115.94079, 23456.237366, 19763.2863, 20061.21154, 19606.74272, 25360.633656};
double[] expectedUpper = {21145.198098, 21152.740005, 22573.24549, 22511.661393, 25377.125821, 25494.596649,
26370.627437, 27845.75879, 24283.622371, 24708.68161, 24377.960375, 30252.469485};
double[] lower = forecast.lowerPredictionValues().asArray();
double[] upper = forecast.upperPredictionValues().asArray();
assertArrayEquals(expectedLower, lower, 1E-1);
assertArrayEquals(expectedUpper, upper, 1E-1);
}
@Test
public void whenArimaForecastThenForecastValuesCorrect() {
TimeSeries timeSeries = TestData.debitcards();
Arima.FittingStrategy fittingStrategy = Arima.FittingStrategy.CSSML;
Arima.ModelCoefficients coefficients = Arima.ModelCoefficients.newBuilder().setMACoeffs(-0.6760904)
.setSeasonalMACoeffs(-0.5718134).setDifferences(1).setSeasonalDifferences(1).build();
Arima model = Arima.model(timeSeries, coefficients, fittingStrategy);
Forecast forecast = ArimaForecast.forecast(model, 24);
double[] expectedForecast = {19478.680824, 19400.979522, 20740.20164, 20600.788629, 23391.472355, 23436.878337,
24243.284113, 25650.998078, 22023.454336, 22384.946575, 21992.351548, 27806.551571, 20452.304145,
20374.602843, 21713.824961, 21574.411949, 24365.095675, 24410.501658, 25216.907434, 26624.621399,
22997.077656, 23358.569896, 22965.974868, 28780.174891};
double[] fcst = forecast.forecast().asArray();
assertArrayEquals(expectedForecast, fcst, 1E-1);
}
} |
package main.java.sociam.pybossa.rest;
import java.io.InputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.json.JSONException;
import org.json.JSONObject;
import sociam.pybossa.config.Config;
@Path("/sendTaskRun")
public class sendTaskRun {
private static final Logger logger = Logger.getLogger(sendTaskRun.class);
@GET
@Produces("application/json")
public Response insertTaskRun(@QueryParam("text") String text, @QueryParam("task_id") Integer task_id,
@QueryParam("project_id") Integer project_id, @QueryParam("contributor_name") String contributor_name,
@QueryParam("source") String source) throws JSONException {
JSONObject data = new JSONObject();
JSONObject status = new JSONObject();
try {
InputStream stream = sendTaskRun.class.getResourceAsStream("/log4j.properties");
PropertyConfigurator.configure(stream);
Config.reload();
if (text != null && task_id != null && project_id != null && contributor_name != null && source != null) {
logger.debug("receiving a GET request with the following data + text=" + text + " task_id=" + task_id
+ " project_id=" + project_id + " contributor_name=" + contributor_name + " source=" + source);
Boolean isInserted = sociam.pybossa.TaskCollector.insertTaskRun(text, task_id, project_id,
contributor_name, source);
if (isInserted) {
logger.info("TaskRun was inserted");
data.put("text", text);
data.put("task_id", task_id);
data.put("project_id", project_id);
data.put("contributor_name", contributor_name);
data.put("source", source);
status.put("data", data);
status.put("status", "success");
String result = status.toString();
return Response.status(200).entity(result).build();
} else {
logger.error("Task run could not be inserted");
status.put("message", "Did you already inserted the task run?");
status.put("status", "error");
return Response.status(500).entity(status.toString()).build();
}
} else {
logger.error("All parameters should be provided");
status.put("status", "Error: All parameters should be provided. text=" + text + "task_id=" + task_id
+ " project_id=" + project_id + " contributor_name=" + contributor_name + " source=" + source);
return Response.status(500).entity(status.toString()).build();
}
} catch (Exception e) {
logger.error("Error", e);
status.put("status", "internal error: " + e);
return Response.status(500).entity(status.toString()).build();
}
}
} |
package org.opencompare;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.opencompare.api.java.*;
import org.opencompare.api.java.impl.io.KMFJSONLoader;
import org.opencompare.api.java.io.HTMLExporter;
import org.opencompare.api.java.io.PCMLoader;
import org.opencompare.api.java.value.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
public class HTMLExporterCustom {
private Document doc;
private Element body;
private PCMMetadata metadata;
private Element tr;
private Param parameter;
//modif par cheisda le 9.11.2015
public String generatedHtml;
Document.OutputSettings settings = new Document.OutputSettings();
private String templateFull = "<html>\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t</body>\n</html>";
private LinkedList<AbstractFeature> nextFeaturesToVisit;
private int featureDepth;
public String toHTML(PCM pcm) {
this.settings.prettyPrint();
this.doc = Jsoup.parse(this.templateFull);
this.body = this.doc.body();
this.doc.head().select("title").first().text(pcm.getName());
if(this.metadata == null) {
this.metadata = new PCMMetadata(pcm);
}
return this.doc.outputSettings(this.settings).outerHtml();
}
public String generateHTML(PCMContainer container) {
this.metadata = container.getMetadata();
//return this.toHTML(container.getPcm());
//modif by cheisda 9.11.2015
generatedHtml = this.toHTML(container.getPcm());
return generatedHtml;
}
public void visit(PCM pcm) {
// Init html table
this.body.appendElement("h1").text(pcm.getName());
Element title = this.body.appendElement("h1");
title.attr("id", "title").text(pcm.getName());
Element table = this.body.appendElement("table");
table.attr("id", "matrix_" + pcm.getName().hashCode()).attr("border", "1");
// Get Features
this.featureDepth = pcm.getFeaturesDepth();
// List of features
LinkedList featuresToVisit = new LinkedList();
this.nextFeaturesToVisit = new LinkedList();
featuresToVisit.addAll(pcm.getFeatures());
this.tr = table.appendElement("tr");
this.tr.appendElement("th").attr("rowspan", Integer.toString(this.featureDepth)).text("Product");
Iterator var5;
/*while(var5.hasNext()) {
Product var7 = (Product)var5.next();
this.tr = table.appendElement("tr");
var7.accept(this);
}*/
}
//11.11.2015
private Param parameters;
public Param getParameters() {
return parameters;
}
public void setParameters(Param parameters) {
this.parameters = parameters;
}
//constructeur de la classe
public HTMLExporterCustom(String fileName) {
Param param = new Param(fileName);
setParameters(param);
}
/* Main */
public static void main(String[] args) throws IOException {
// Load a PCM
File pcmFile = new File("pcms/example.pcm");
File paramFile = new File("json/param1.json");
// read the json file
PCMLoader loader = new KMFJSONLoader();
PCM pcm = loader.load(pcmFile).get(0).getPcm();
//displays the HTML File into the console
HTMLExporter testHtmlExporter = new HTMLExporter();
HTMLExporterCustom testHTML = new HTMLExporterCustom("params1.json");
System.out.println("Order type récupéré : " + testHTML.getParameters().getOrderType());
System.out.println("DataStyle récupéré : " + testHTML.getParameters().getDataStyleParam());
}//fin main
public String export(PCMContainer container) {
return null;
}
public String toHTML(PCMContainer container) {
return null;
}
public void visit(Feature feature) {
}
public void visit(FeatureGroup featureGroup) {
}
public void visit(Product product) {
}
public void visit(Cell cell) {
}
// @Override
public void visit(BooleanValue booleanValue) {
}
public void visit(Conditional conditional) {
}
public void visit(DateValue dateValue) {
}
public void visit(Dimension dimension) {
}
public void visit(IntegerValue integerValue) {
}
public void visit(Multiple multiple) {
}
public void visit(NotApplicable notApplicable) {
}
public void visit(NotAvailable notAvailable) {
}
public void visit(Partial partial) {
}
public void visit(RealValue realValue) {
}
public void visit(StringValue stringValue) {
}
public void visit(Unit unit) {
}
public void visit(Version version) {
}
} |
package com.marverenic.music.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.audiofx.AudioEffect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import com.marverenic.music.instances.Song;
import com.marverenic.music.player.PlayerController;
import java.util.UUID;
import static android.content.Context.CONNECTIVITY_SERVICE;
public final class Util {
/**
* This UUID corresponds to the UUID of an Equalizer Audio Effect. It has been copied from
* {@link AudioEffect#EFFECT_TYPE_EQUALIZER} for backwards compatibility since this field was
* added in API level 18.
*/
private static final UUID EQUALIZER_UUID;
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
EQUALIZER_UUID = AudioEffect.EFFECT_TYPE_EQUALIZER;
} else {
EQUALIZER_UUID = UUID.fromString("0bed4300-ddd6-11db-8f34-0002a5d5c51b");
}
}
/**
* This class is never instantiated
*/
private Util() {
}
/**
* Checks whether the device is in a state where we're able to access the internet. If the
* device is not connected to the internet, this will return {@code false}. If the device is
* only connected to a mobile network, this will return {@code allowMobileNetwork}. If the
* device is connected to an active WiFi network, this will return {@code true.}
* @param context A context used to check the current network status
* @param allowMobileNetwork Whether or not the user allows the application to use mobile
* data. This is an internal implementation that is not enforced
* by the system, but is exposed to the user in our app's settings.
* @return Whether network calls should happen in the current connection state or not
*/
@SuppressWarnings("SimplifiableIfStatement")
public static boolean canAccessInternet(Context context, boolean allowMobileNetwork) {
ConnectivityManager connectivityManager;
connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info == null) {
// No network connections are active
return false;
} else if (!info.isAvailable() || info.isRoaming()) {
// The network isn't active, or is a roaming network
return false;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
// If it's a mobile network, return the user preference
return allowMobileNetwork;
} else {
// The network is a wifi network
return true;
}
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean hasPermission(Context context, String permission) {
return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean hasPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (!hasPermission(context, permission)) {
return false;
}
}
return true;
}
public static Intent getSystemEqIntent(Context c) {
Intent systemEq = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
systemEq.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, c.getPackageName());
systemEq.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, PlayerController.getAudioSessionId());
ActivityInfo info = systemEq.resolveActivityInfo(c.getPackageManager(), 0);
if (info != null && !info.name.startsWith("com.android.musicfx")) {
return systemEq;
} else {
return null;
}
}
/**
* Checks whether the current device is capable of instantiating and using an
* {@link android.media.audiofx.Equalizer}
* @return True if an Equalizer may be used at runtime
*/
public static boolean hasEqualizer() {
for (AudioEffect.Descriptor effect : AudioEffect.queryEffects()) {
if (EQUALIZER_UUID.equals(effect.type)) {
return true;
}
}
return false;
}
public static Bitmap fetchFullArt(Song song) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(song.getLocation());
byte[] stream = retriever.getEmbeddedPicture();
if (stream != null) {
return BitmapFactory.decodeByteArray(stream, 0, stream.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} |
package org.apache.commons.betwixt.xmlunit;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Provides xml test utilities.
* Hopefully, these might be moved into [xmlunit] sometime.
*
* @author Robert Burrell Donkin
*/
public class XmlTestCase extends TestCase {
protected static boolean debug = false;
DocumentBuilderFactory domFactory;
public XmlTestCase(String testName) {
super(testName);
}
public void xmlAssertIsomorphicContent(
org.w3c.dom.Document documentOne,
org.w3c.dom.Document documentTwo)
throws
AssertionFailedError {
log("Testing documents:" + documentOne.getDocumentElement().getNodeName()
+ " and " + documentTwo.getDocumentElement().getNodeName());
xmlAssertIsomorphicContent(documentOne, documentTwo, false);
}
public void xmlAssertIsomorphicContent(
org.w3c.dom.Document documentOne,
org.w3c.dom.Document documentTwo,
boolean orderIndependent)
throws
AssertionFailedError {
xmlAssertIsomorphicContent(null, documentOne, documentTwo, orderIndependent);
}
public void xmlAssertIsomorphicContent(
String message,
org.w3c.dom.Document documentOne,
org.w3c.dom.Document documentTwo)
throws
AssertionFailedError {
xmlAssertIsomorphicContent(message, documentOne, documentTwo, false);
}
public void xmlAssertIsomorphicContent(
String message,
org.w3c.dom.Document documentOne,
org.w3c.dom.Document documentTwo,
boolean orderIndependent)
throws
AssertionFailedError
{
// two documents have isomorphic content iff their root elements
// are isomophic
xmlAssertIsomorphic(
message,
documentOne.getDocumentElement(),
documentTwo.getDocumentElement(),
orderIndependent);
}
public void xmlAssertIsomorphic(
org.w3c.dom.Node rootOne,
org.w3c.dom.Node rootTwo)
throws
AssertionFailedError {
xmlAssertIsomorphic(rootOne, rootTwo, false);
}
public void xmlAssertIsomorphic(
org.w3c.dom.Node rootOne,
org.w3c.dom.Node rootTwo,
boolean orderIndependent)
throws
AssertionFailedError
{
xmlAssertIsomorphic(null, rootOne, rootTwo, orderIndependent);
}
public void xmlAssertIsomorphic(
String message,
org.w3c.dom.Node rootOne,
org.w3c.dom.Node rootTwo) {
xmlAssertIsomorphic(message, rootOne, rootTwo, false);
}
public void xmlAssertIsomorphic(
String message,
org.w3c.dom.Node rootOne,
org.w3c.dom.Node rootTwo,
boolean orderIndependent)
throws
AssertionFailedError
{
// first normalize the xml
rootOne.normalize();
rootTwo.normalize();
// going to use recursion so avoid normalizing each time
testIsomorphic(message, rootOne, rootTwo, orderIndependent);
}
private void testIsomorphic(
String message,
org.w3c.dom.Node nodeOne,
org.w3c.dom.Node nodeTwo)
throws
AssertionFailedError {
testIsomorphic(message, nodeOne, nodeTwo, false);
}
private void testIsomorphic(
String message,
org.w3c.dom.Node nodeOne,
org.w3c.dom.Node nodeTwo,
boolean orderIndependent)
throws
AssertionFailedError
{
try {
if (debug) {
log(
"node 1 name=" + nodeOne.getNodeName()
+ " qname=" + nodeOne.getLocalName());
log(
"node 2 name=" + nodeTwo.getNodeName()
+ " qname=" + nodeTwo.getLocalName());
}
// compare node properties
log("Comparing node properties");
assertEquals(
(null == message ? "(Unequal node types)" : message + "(Unequal node types)"),
nodeOne.getNodeType(),
nodeTwo.getNodeType());
assertEquals(
(null == message ? "(Unequal node names)" : message + "(Unequal node names)"),
nodeOne.getNodeName(),
nodeTwo.getNodeName());
assertEquals(
(null == message ? "(Unequal node values)" : message + "(Unequal node values)"),
trim(nodeOne.getNodeValue()),
trim(nodeTwo.getNodeValue()));
assertEquals(
(null == message ? "(Unequal local names)" : message + "(Unequal local names)"),
nodeOne.getLocalName(),
nodeTwo.getLocalName());
assertEquals(
(null == message ? "(Unequal namespace)" : message + "(Unequal namespace)"),
nodeOne.getNamespaceURI(),
nodeTwo.getNamespaceURI());
// compare attributes
log("Comparing attributes");
// make sure both have them first
assertEquals(
(null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"),
nodeOne.hasAttributes(),
nodeTwo.hasAttributes());
if (nodeOne.hasAttributes()) {
// do the actual comparison
// first we check the number of attributes are equal
// we then check that for every attribute of node one,
// a corresponding attribute exists in node two
// (this should be sufficient to prove equality)
NamedNodeMap attributesOne = nodeOne.getAttributes();
NamedNodeMap attributesTwo = nodeTwo.getAttributes();
assertEquals(
(null == message ? "(Unequal attributes)" : message + "(Unequal attributes)"),
attributesOne.getLength(),
attributesTwo.getLength());
for (int i=0, size=attributesOne.getLength(); i<size; i++) {
Attr attributeOne = (Attr) attributesOne.item(i);
Attr attributeTwo = (Attr) attributesTwo.getNamedItemNS(
attributeOne.getNamespaceURI(),
attributeOne.getLocalName());
if (attributeTwo == null) {
attributeTwo = (Attr) attributesTwo.getNamedItem(attributeOne.getName());
}
// check attribute two exists
if (attributeTwo == null) {
String diagnosis = "[Missing attribute (" + attributeOne.getName() + ")]";
fail((null == message ? diagnosis : message + diagnosis));
}
// now check attribute values
assertEquals(
(null == message ? "(Unequal attribute values)" : message + "(Unequal attribute values)"),
attributeOne.getValue(),
attributeTwo.getValue());
}
}
// compare children
log("Comparing children");
// this time order is important
// so we can just go down the list and compare node-wise using recursion
List listOne = sanitize(nodeOne.getChildNodes());
List listTwo = sanitize(nodeTwo.getChildNodes());
if (orderIndependent) {
log("[Order Independent]");
Comparator nodeByName = new NodeByNameComparator();
Collections.sort(listOne, nodeByName);
Collections.sort(listTwo, nodeByName);
}
Iterator it = listOne.iterator();
Iterator iter2 = listTwo.iterator();
while (it.hasNext() & iter2.hasNext()) {
Node nextOne = ((Node)it.next());
Node nextTwo = ((Node)iter2.next());
log(nextOne.getNodeName() + ":" + nextOne.getNodeValue());
log(nextTwo.getNodeName() + ":" + nextTwo.getNodeValue());
}
assertEquals(
(null == message ? "(Unequal child nodes@" + nodeOne.getNodeName() +")":
message + "(Unequal child nodes @" + nodeOne.getNodeName() +")"),
listOne.size(),
listTwo.size());
it = listOne.iterator();
iter2 = listTwo.iterator();
while (it.hasNext() & iter2.hasNext()) {
Node nextOne = ((Node)it.next());
Node nextTwo = ((Node)iter2.next());
log(nextOne.getNodeName() + " vs " + nextTwo.getNodeName());
testIsomorphic(message, nextOne, nextTwo, orderIndependent);
}
} catch (DOMException ex) {
fail((null == message ? "" : message + " ") + "DOM exception" + ex.toString());
}
}
protected DocumentBuilder createDocumentBuilder() {
try {
return getDomFactory().newDocumentBuilder();
} catch (ParserConfigurationException e) {
fail("Cannot create DOM builder: " + e.toString());
}
// just to keep the compiler happy
return null;
}
protected DocumentBuilderFactory getDomFactory() {
// lazy creation
if (domFactory == null) {
domFactory = DocumentBuilderFactory.newInstance();
}
return domFactory;
}
protected Document parseString(StringWriter writer) {
try {
return createDocumentBuilder().parse(new InputSource(new StringReader(writer.getBuffer().toString())));
} catch (SAXException e) {
fail("Cannot create parse string: " + e.toString());
} catch (IOException e) {
fail("Cannot create parse string: " + e.toString());
}
// just to keep the compiler happy
return null;
}
protected Document parseString(String string) {
try {
return createDocumentBuilder().parse(new InputSource(new StringReader(string)));
} catch (SAXException e) {
fail("Cannot create parse string: " + e.toString());
} catch (IOException e) {
fail("Cannot create parse string: " + e.toString());
}
// just to keep the compiler happy
return null;
}
protected Document parseFile(String path) {
try {
return createDocumentBuilder().parse(new File(path));
} catch (SAXException e) {
fail("Cannot create parse file: " + e.toString());
} catch (IOException e) {
fail("Cannot create parse file: " + e.toString());
}
// just to keep the compiler happy
return null;
}
private void log(String message)
{
if (debug) {
System.out.println("[XmlTestCase]" + message);
}
}
private String trim(String trimThis)
{
if (trimThis == null) {
return trimThis;
}
return trimThis.trim();
}
private List sanitize(NodeList nodes) {
ArrayList list = new ArrayList();
for (int i=0, size=nodes.getLength(); i<size; i++) {
if ( nodes.item(i).getNodeType() == Node.TEXT_NODE ) {
if ( !( nodes.item(i).getNodeValue() == null ||
nodes.item(i).getNodeValue().trim().length() == 0 )) {
list.add(nodes.item(i));
} else {
log("Ignoring text node:" + nodes.item(i).getNodeValue());
}
} else {
list.add(nodes.item(i));
}
}
return list;
}
private class NodeByNameComparator implements Comparator {
public int compare(Object objOne, Object objTwo) {
String nameOne = ((Node) objOne).getNodeName();
String nameTwo = ((Node) objTwo).getNodeName();
if (nameOne == null) {
if (nameTwo == null) {
return 0;
}
return -1;
}
if (nameTwo == null) {
return 1;
}
return nameOne.compareTo(nameTwo);
}
}
} |
package org.opencompare;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Document.OutputSettings;
import org.opencompare.api.java.AbstractFeature;
import org.opencompare.api.java.Cell;
import org.opencompare.api.java.Feature;
import org.opencompare.api.java.FeatureGroup;
import org.opencompare.api.java.PCM;
import org.opencompare.api.java.PCMContainer;
import org.opencompare.api.java.PCMMetadata;
import org.opencompare.api.java.Product;
import org.opencompare.api.java.impl.io.KMFJSONLoader;
import org.opencompare.api.java.io.HTMLExporter;
import org.opencompare.api.java.io.PCMExporter;
import org.opencompare.api.java.io.PCMLoader;
import org.opencompare.api.java.value.*;
import java.io.*;
import java.util.Comparator;
import java.util.*;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class HTMLExporterCustom extends HTMLExporter {
private Document doc;
private Element body;
private PCMMetadata metadata;
private Element tr;
Document.OutputSettings settings = new Document.OutputSettings();
private String templateFull = "<html>\n\t<head>\n\t\t<meta charset=\"utf-8\"/>\n\t\t<title></title>\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" media=\"screen\" />\n\t</head>\n\t<body>\n\t</body>\n</html>";
private LinkedList<AbstractFeature> nextFeaturesToVisit;
private int featureDepth;
private Param parameters;
public Param getParameters() {
return parameters;
}
public void setParameters(Param parameters) {
this.parameters = parameters;
}
//constructeur de la classe
public HTMLExporterCustom(String fileName) {
Param param = new Param(fileName);
setParameters(param);
}
public String export(PCMContainer container) {
return this.toHTML(container);
}
public String toHTML(PCM pcm) {
this.settings.prettyPrint();
this.doc = Jsoup.parse(this.templateFull);
this.body = this.doc.body();
this.doc.head().select("title").first().text(pcm.getName());
if(this.metadata == null) {
this.metadata = new PCMMetadata(pcm);
}
pcm.accept(this);
return this.doc.outputSettings(this.settings).outerHtml();
}
public String toHTML(PCMContainer container) {
this.metadata = container.getMetadata();
return this.toHTML(container.getPcm());
}
/*public String generateHTML(PCMContainer container) {
this.metadata = container.getMetadata();
//return this.toHTML(container.getPcm());
//modif by cheisda 9.11.2015
generatedHtml = this.toHTML(container.getPcm());
return generatedHtml;
}*/
public void visit(PCM pcm) {
this.body.appendElement("h1").text(pcm.getName());
Element title = this.body.appendElement("h1");
title.attr("id", "title").text(pcm.getName());
Element table = this.body.appendElement("table");
table.attr("id", "matrix_" + pcm.getName().hashCode()).attr("border", "1");
this.featureDepth = pcm.getFeaturesDepth();
LinkedList featuresToVisit = new LinkedList();
this.nextFeaturesToVisit = new LinkedList();
featuresToVisit.addAll(pcm.getFeatures());
/*this.tr = table.appendElement("tr");
this.tr.appendElement("th").attr("rowspan", Integer.toString(this.featureDepth)).text("Product");*/
Iterator var5;
this.featuresRow(pcm, table);
var5 = pcm.getProducts().iterator();
Iterator<DataStyle> itParam = parameters.getDataStyleParam().iterator();
String name = null;
while(var5.hasNext() || itParam.hasNext()) {
/*Product var7 = (Product)var5.next();
this.tr = table.appendElement("tr");
var7.accept(this);*/
Product var7 = (Product) var5.next();
List cells = var7.getCells();
Collections.sort(cells, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Cell cell1 = (Cell)o1;
Cell cell2 = (Cell)o2;
return HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell1.getFeature()) - HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell2.getFeature());
}
});
Iterator var3 = cells.iterator();
DataStyle ds = null;
if(itParam.hasNext()){
ds = itParam.next();
}
this.tr = table.appendElement("tr");
this.tr.appendElement("th").text(var7.getName());
//Iterator<Cell> var8 = var7.getCells().iterator();
while(var3.hasNext()) {
Cell cell = (Cell)var3.next();
cell.getContent();
//System.out.println(cell);
// this.tr = table.appendElement("tr");
/* public int compare(Cell cell1, Cell cell2) {
return HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell1.getFeature()) - HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell2.getFeature());
}*/
});
Iterator var3 = cells.iterator();
while(var3.hasNext()) {
Cell cell = (Cell)var3.next();
Element td = this.tr.appendElement("td");
td.appendElement("span").text(cell.getContent());
}
}
public void visit(Product product) {
this.tr.appendElement("th").text(product.getName());
List cells = product.getCells();
Collections.sort(cells, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Cell cell1 = (Cell)o1;
Cell cell2 = (Cell)o2;
return HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell1.getFeature()) - HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell2.getFeature());
}
/*public int compare(Cell cell1, Cell cell2) {
return HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell1.getFeature()) - HTMLExporterCustom.this.metadata.getSortedFeatures().indexOf(cell2.getFeature());
}*/
});
Iterator var3 = cells.iterator();
while(var3.hasNext()) {
Cell cell = (Cell)var3.next();
Element td = this.tr.appendElement("td");
td.appendElement("span").text(cell.getContent());
}
}
public void featuresRow(PCM pcm, Element table){
// List of features
LinkedList featuresToVisit = new LinkedList();
this.nextFeaturesToVisit = new LinkedList();
featuresToVisit.addAll(pcm.getFeatures());
this.tr = table.appendElement("tr");
this.tr.appendElement("th").attr("rowspan", Integer.toString(this.featureDepth)).text("Product");
Iterator var5;
while(!featuresToVisit.isEmpty()) {
Collections.sort(featuresToVisit, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
AbstractFeature feat1 = (AbstractFeature)o1;
AbstractFeature feat2 = (AbstractFeature)o2;
return HTMLExporterCustom.this.metadata.getFeaturePosition(feat1) - HTMLExporterCustom.this.metadata.getFeaturePosition(feat2);
}
/*public int compare(AbstractFeature feat1, AbstractFeature feat2) {
return HTMLExporterCustom.this.metadata.getFeaturePosition(feat1) - HTMLExporterCustom.this.metadata.getFeaturePosition(feat2);
}*/
});
var5 = featuresToVisit.iterator();
while(var5.hasNext()) {
AbstractFeature product = (AbstractFeature)var5.next();
product.accept(this);
}
featuresToVisit = this.nextFeaturesToVisit;
this.nextFeaturesToVisit = new LinkedList();
--this.featureDepth;
if(this.featureDepth >= 1) {
this.tr = table.appendElement("tr");
}
}
}
public static void main(String[] args) throws IOException {
// Load a PCM
File pcmFile = new File("pcms/PCM1/tesssvtttt369852147.pcm");
//File paramFile = new File("pcms/PCM1/param1.json");
// read the json file
PCMLoader loader = new KMFJSONLoader();
PCM pcm = loader.load(pcmFile).get(0).getPcm();
HTMLExporterCustom te = new HTMLExporterCustom("PCM1/params1.json");
System.out.println(te.toHTML(pcm));
HTMLExporter testHtmlExporter = new HTMLExporter();
//System.out.println(testHtmlExporter.toHTML(pcm));
//System.out.println(te.toHTML(pcm));
//modif by cheisda 24.11.2015
//generateHTMLFile(te, pcm);
try {
//TO DO : create a tmp folder
//Output file
FileOutputStream fos = new FileOutputStream("src\\"+System.currentTimeMillis()/1000+"TestArchivePDL.zip");
//Creating the output file
ZipOutputStream zos = new ZipOutputStream(fos);
//getting files to zip them
String fileGeneratedHTMLPath = "src\\HTMLGenerated.html";
String fileGeneratedCSSPath = "src\\style.css";
//getting Files size
int CSSSize = getFileSize(fileGeneratedCSSPath);
int HTMLSize = getFileSize(fileGeneratedHTMLPath);
System.out.println("Taille CSS : " + CSSSize + "octets, taille HTML : "+HTMLSize + "octets. ");
int totalFilesSize = CSSSize+HTMLSize;
//Adding to archive File
addToZipFile(fileGeneratedHTMLPath,zos, totalFilesSize);
addToZipFile(fileGeneratedCSSPath,zos,totalFilesSize);
//closing the streamsH
zos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}//fin main
//Modif by Cheisda
public static void generateHTMLFile(HTMLExporterCustom dataResults, PCM pcm) {
try {
File HTMLGeneratedFile = new File("src\\HTMLGenerated.html");
FileWriter fileWriter = new FileWriter(HTMLGeneratedFile);
fileWriter.write(dataResults.toHTML(pcm));
fileWriter.flush();
fileWriter.close();
if (HTMLGeneratedFile == null){
System.out.println("le fichier généré est vide");
} else {
System.out.println("Bravo le fichier HTML a bien été généré !");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int getFileSize(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}
return (int)file.length();
}
private static void addToZipFile(String filePath, ZipOutputStream zos,int filesSize)throws FileNotFoundException,IOException {
System.out.println("Writing '" + filePath + "' to zip file");
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(filePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[filesSize];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
private boolean rangeIn(int borneinf, int bornesup, int valuePCM) {
return ((valuePCM >= borneinf) && (valuePCM <= bornesup));
}
private boolean rangeOut(int borneinf, int bornesup, int valuePCM) {
return ((valuePCM <= borneinf) || (valuePCM >= bornesup));
}
public void visit(Cell cell) {
}
// @Override
public void visit(BooleanValue booleanValue) {
}
public void visit(Conditional conditional) {
}
public void visit(DateValue dateValue) {
}
public void visit(Dimension dimension) {
}
public void visit(IntegerValue integerValue) {
}
public void visit(Multiple multiple) {
}
public void visit(NotApplicable notApplicable) {
}
public void visit(NotAvailable notAvailable) {
}
public void visit(Partial partial) {
}
public void visit(RealValue realValue) {
}
public void visit(StringValue stringValue) {
}
public void visit(Unit unit) {
}
public void visit(Version version) {
}
} |
package com.permutassep.ui;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import com.facebook.Session;
import com.google.gson.Gson;
import com.lalongooo.permutassep.R;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeader;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.permutassep.BaseActivity;
import com.permutassep.config.Config;
import com.permutassep.interfaces.FirstLaunchCompleteListener;
import com.permutassep.model.Post;
import com.permutassep.utils.PrefUtils;
import com.permutassep.utils.Utils;
public class ActivityMain extends BaseActivity
implements
FragmentPostDetail.OnPostItemSelectedListener,
FragmentManager.OnBackStackChangedListener,
FirstLaunchCompleteListener {
@Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
if(PrefUtils.shouldReloadNewsFeed(this)){
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.fragmentContainer)).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentPagedNewsFeed()).commit();
PrefUtils.markNewsFeedToReload(this, false);
}
if(f instanceof FragmentPagedNewsFeed){
setTitle(R.string.app_name);
if(Utils.getUser(this) != null){
result.setSelectionByIdentifier(DrawerItems.HOME.id, false);
}
}else if(f instanceof FragmentMyPosts){
setTitle(R.string.my_posts_toolbar_text);
if(Utils.getUser(this) != null) {
result.setSelectionByIdentifier(DrawerItems.MY_POSTS.id, false);
}
}else if(f instanceof FragmentSearch){
setTitle(R.string.app_main_toolbar_search_action);
}else if(f instanceof FragmentResult){
setTitle(R.string.app_main_toolbar_search_results);
}else if(f instanceof FragmentCreatePost){
setTitle(R.string.app_main_toolbar_post_action);
}else if(f instanceof FragmentSettings){
setTitle(R.string.app_main_toolbar_edit_profile);
}
invalidateOptionsMenu();
}
public enum DrawerItems {
HOME(1000),
MY_POSTS(1001),
SETTINGS(1002);
public int id;
DrawerItems(int id) {
this.id = id;
}
}
public Drawer.Result result;
private AccountHeader.Result headerResult = null;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar= (Toolbar) findViewById(R.id.activity_main_toolbar);
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
if(Utils.getUser(this) != null){
final IProfile profile = new ProfileDrawerItem()
.withName(Utils.getUser(this).getName())
.withEmail(Utils.getUser(this).getEmail())
.withIcon(Uri.parse("https://graph.facebook.com/" + Utils.getUser(this).getSocialUserId() + "/picture?width=460&height=460"));
// Create the AccountHeader
headerResult = new AccountHeader()
.withActivity(this)
.withHeaderBackground(R.drawable.header)
.addProfiles(profile)
.withSavedInstance(savedInstanceState)
.build();
result = new Drawer()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(toolbar)
.addDrawerItems(
new PrimaryDrawerItem().withName(getString(R.string.app_nav_drawer_1)).withIdentifier(DrawerItems.HOME.id).withIcon(GoogleMaterial.Icon.gmd_home),
new PrimaryDrawerItem().withName(getString(R.string.app_nav_drawer_2)).withIdentifier(DrawerItems.MY_POSTS.id).withIcon(GoogleMaterial.Icon.gmd_content_paste)
// new DividerDrawerItem(),
// new PrimaryDrawerItem().withName(getString(R.string.app_nav_drawer_3)).withIdentifier(DrawerItems.SETTINGS.id).withIcon(GoogleMaterial.Icon.gmd_settings)
)
.withSelectedItem(0)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l, IDrawerItem drawerItem) {
if (drawerItem != null) {
replaceFragment(drawerItem.getIdentifier());
}
}
})
.build();
result.getListView().setVerticalScrollBarEnabled(false);
}
getSupportFragmentManager().addOnBackStackChangedListener(this);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentPagedNewsFeed()).commit();
}
private void showTOSDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.tos_dialog_text))
.setPositiveButton(getString(R.string.tos_dialog_accept),dialogClickListener)
.setNegativeButton(getString(R.string.tos_dialog_cancel),dialogClickListener).show();
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Save the state
getSharedPreferences(Config.APP_PREFERENCES_NAME, MODE_PRIVATE)
.edit()
.putBoolean("tos_accepted", false)
.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
}
}
};
public boolean onCreateOptionsMenu(Menu menu) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
if (f instanceof FragmentPagedNewsFeed){
getMenuInflater().inflate(R.menu.main, menu);
if(Utils.getUser(this) != null){
menu.findItem(R.id.action_post).setIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_add).color(Color.WHITE).actionBarSize()).setVisible(true);
menu.findItem(R.id.action_logout).setVisible(true);
}
menu.findItem(R.id.action_search).setIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_search).color(Color.WHITE).actionBarSize());
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_logout){
Session session = Session.getActiveSession();
if(session != null){
session.closeAndClearTokenInformation();
}
PrefUtils.clearApplicationPreferences(this);
startActivity(new Intent(ActivityMain.this, ActivityLoginSignUp.class));
finish();
} else {
replaceFragment(item.getItemId());
}
return false;
}
@Override
public void showPostDetail(Post post) {
String backStackEntryName = null;
if((getSupportFragmentManager().findFragmentById(R.id.fragmentContainer) instanceof FragmentPagedNewsFeed)){
backStackEntryName = "news_feed";
}else if((getSupportFragmentManager().findFragmentById(R.id.fragmentContainer) instanceof FragmentMyPosts)){
backStackEntryName = "my_posts";
}
// getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, FragmentPostDetail.instance(new Gson().toJson(post))).addToBackStack(backStackEntryName).commit();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.hide(getSupportFragmentManager().findFragmentById(R.id.fragmentContainer));
ft.add(R.id.fragmentContainer, FragmentPostDetail.instance(new Gson().toJson(post))).addToBackStack(backStackEntryName).commit();
clearDrawerSelection();
}
@Override
public void onBackPressed() {
//toolbar.setTitle(R.string.app_name);
super.onBackPressed();
}
@Override
public void onFirstLaunchComplete() {
if(!PrefUtils.firstTimeDrawerOpened(this) && Utils.getUser(this) != null){
result.openDrawer();
PrefUtils.markFirstTimeDrawerOpened(this);
}
}
public void replaceFragment(int id){
// Action Home
if(id == DrawerItems.HOME.id){
getSupportFragmentManager().popBackStackImmediate("news_feed", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
// Action Post
if(id == R.id.action_post){
clearDrawerSelection();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentCreatePost()).addToBackStack("news_feed").commit();
}
// Action Search
if(id == R.id.action_search) {
clearDrawerSelection();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentSearch()).addToBackStack("news_feed").commit();
}
// Action My posts
if(id == DrawerItems.MY_POSTS.id) {
getSupportFragmentManager().popBackStackImmediate("news_feed", FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentMyPosts()).addToBackStack("news_feed").commit();
}
// Action My posts
if(id == DrawerItems.SETTINGS.id) {
getSupportFragmentManager().popBackStackImmediate("news_feed", FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, new FragmentSettings()).addToBackStack("news_feed").commit();
}
}
private void clearDrawerSelection(){
if(Utils.getUser(this) != null){
result.setSelection(-1);
}
}
} |
package org.openremote.security;
import org.openremote.base.exception.IncorrectImplementationException;
import org.openremote.base.exception.OpenRemoteException;
import org.openremote.logging.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Abstract superclass with a shared implementation to handle keystore based operations.
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public abstract class KeyManager
{
/**
* This is the default key storage type used if nothing else is specified. Note that PKCS12
* is used for asymmetric PKI keys but not for storing symmetric secret keys. For the latter,
* other provider-specific storage types must be used. <p>
*
* Default: {@value}
*/
public final static StorageType DEFAULT_KEYSTORE_STORAGE_TYPE = StorageType.PKCS12;
/**
* The default security provider used by this instance. Note that can contain a null value
* if loading of the security provider fails. A null value should indicate using the system
* installed security providers in their preferred order rather than this explicit security
* provider. <p>
*
* Default: {@value}
*/
public final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC;
public enum StorageType
{
/**
* PKCS #12 format. Used to store private keys of a key pair along with its X.509
* certificate. Standardized format.
*/
PKCS12,
JCEKS,
/**
* BouncyCastle keystore format roughly equivalent to Sun JKS implementation. Works with
* Sun's 'keytool'. Resistant to tampering but not resistant to inspection.
*/
BKS,
/**
* Recommended BouncyCastle keystore format. Requires password verification and is
* resistant to inspection and tampering.
*/
UBER;
@Override public String toString()
{
return getStorageTypeName();
}
public String getStorageTypeName()
{
return name();
}
}
/**
* Default logger for the security package.
*/
protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT);
/**
* The key storage type used by this instance.
*/
private Storage storage = DEFAULT_KEYSTORE_STORAGE;
/**
* The storage type used by this instance.
*/
private StorageType storage = DEFAULT_KEYSTORE_STORAGE_TYPE;
/**
* Reference to the internal keystore instance that is used to persist the key entries in
* this key manager.
*/
private KeyStore keystore = null;
/**
* Creates a new key manager instance with a {@link #DEFAULT_KEYSTORE_STORAGE default} key
* storage format using {@link #DEFAULT_SECURITY_PROVIDER default} security provider.
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager() throws ConfigurationException, KeyManagerException
{
this(DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance());
}
/**
* This constructor allows the subclasses to specify both the key storage format and explicit
* security provider to use with this instance. The key storage format and security provider
* given as arguments will be used instead of the default values for this instance. <p>
*
* Note that the security provider parameter allows a null value. This indicates that the
* appropriate security provider should be searched from the JVM installed security providers
* in their preferred order.
*
*
* @param storage
* key storage format to use with this instance
*
* @param provider
* The explicit security provider to use with the key storage of this instance. If a
* null value is specified, the implementations should opt to delegate the selection
* of a security provider to the JVMs installed security provider implementations.
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(Storage storage, Provider provider)
throws ConfigurationException, KeyManagerException
{
init(storage, provider);
loadKeyStore((InputStream) null, null);
}
/**
* This constructor will load an existing keystore into memory. It expects the keystore
* to be in default key storage format as specified in {@link #DEFAULT_KEYSTORE_STORAGE}. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password) throws ConfigurationException,
KeyManagerException
{
this(
keyStoreFile, password,
DEFAULT_KEYSTORE_STORAGE,
DEFAULT_SECURITY_PROVIDER.getProviderInstance()
);
}
/**
* This constructor will load an existing keystore into memory. It allows the subclasses to
* specify the expected key storage format used by the keystore file. The storage format
* must be supported by the {@link #DEFAULT_SECURITY_PROVIDER} implementation. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
* @param storage
* key storage format to use with this instance
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password, Storage storage)
throws ConfigurationException, KeyManagerException
{
this(keyStoreFile, password, storage, DEFAULT_SECURITY_PROVIDER.getProviderInstance());
}
/**
* This constructor will load an existing keystore into memory. It allows the subclasses to
* specify both the expected key storage format and explicit security provider to be used
* when the keystore is loaded. <p>
*
* Note that the security provider parameter allows a null value. This indicates that the
* appropriate security provider should be searched from the JVM installed security providers
* in their preferred order. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
* @param storage
* key storage format to use with this instance
*
* @param provider
* The explicit security provider to use with the key storage of this instance. If a
* null value is specified, the implementations should opt to delegate the selection
* of a security provider to the JVMs installed security provider implementations.
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password, Storage storage, Provider provider)
throws ConfigurationException, KeyManagerException
{
this(storage, provider);
load(keyStoreFile, password);
}
/**
* Indicates if this key manager contains a key with a given alias.
*
* @param keyAlias
* key alias to check
*
* @return true if a key is associated with a given alias in this key manager; false
* otherwise
*/
public boolean contains(String keyAlias)
{
try
{
return keystore.containsAlias(keyAlias);
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to retrieve key info for alias '{0}' : {1}", exception,
keyAlias, exception.getMessage()
);
return false;
}
}
/**
* Returns the number of keys currently managed in this key manager.
*
* @return number of keys in this key manager
*/
public int size()
{
try
{
return keystore.size();
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to retrieve keystore size : {0}", exception,
exception.getMessage()
);
return -1;
}
}
/**
* Initialization method used by constructors to initialize this instance. Should not be
* invoked outside of a constructor. <p>
*
* @param storage
* The keystore storage type to use with this instance.
*
* @param provider
* The security provider to use with this instance. Can be null in which case
* the implementations should delegate to the JVM installed security providers
* in their preferred use order.
*/
protected void init(Storage storage, Provider provider)
{
if (storage == null)
{
throw new IllegalArgumentException("Implementation Error: null storage type");
}
this.provider = provider;
this.storage = storage;
}
/**
* Stores the keys in this key manager in a secure key store format. This implementation generates
* a file-based, persistent key store which can be shared with other applications and processes.
* <p>
* IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array
* as soon as it is no longer needed. This prevents passwords from lingering
* in JVM memory pool any longer than is necessary. Use the
* {@link #clearPassword(char[])} method for this purpose.
*
* @param uri
* The location of the file where the key store should be persisted. Must be
* an URI with file scheme.
*
* @param password
* A secret password used to access the keystore contents. NOTE: the character
* array should be set to zero values after this method call completes, via
* {@link #clearPassword(char[])} method.
*
* @see #clearPassword(char[])
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
protected void save(URI uri, char[] password) throws ConfigurationException,
KeyManagerException
{
if (uri == null)
{
throw new KeyManagerException("Save failed due to null URI.");
}
try
{
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uri)));
// Persist...
save(keystore, out, password);
}
catch (FileNotFoundException exception)
{
throw new KeyManagerException(
"File ''{0}'' cannot be created or opened : {1}", exception,
resolveFilePath(new File(uri)), exception.getMessage()
);
}
catch (SecurityException exception)
{
throw new KeyManagerException(
"Security manager has denied access to file ''{0}'' : {1}", exception,
resolveFilePath(new File(uri)), exception.getMessage()
);
}
}
/**
* Loads existing, persisted key store contents into this instance. Any previous keys in this
* key manager instance are overridden. <p>
*
* IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array
* as soon as it is no longer needed. This prevents passwords from lingering
* in JVM memory pool any longer than is necessary. Use the
* {@link #clearPassword(char[])} method for this purpose.
*
* @param uri
* URI with file scheme pointing to the file system location of the keystore
* to load
*
* @param keystorePassword
* The password to access the keystore. Note that the subclasses invoking this
* method are responsible for resetting the password character array after use.
*
* @see #clearPassword(char[])
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading the keystore fails
*/
protected void load(URI uri, char[] keystorePassword) throws KeyManagerException
{
if (uri == null)
{
throw new KeyManagerException("Implementation Error: null file URI.");
}
loadKeyStore(new File(uri), keystorePassword);
}
/**
* Adds a key entry to this instance. Use {@link #save(URI, char[])} to persist
* if desired.
*
* @param keyAlias
* A lookup name of the key entry to be added.
*
* @param entry
* Key entry to be added. Note that accepted entry types depend on the
* keystore storage format.
*
* @param param
* Protection parameters for the key entry. A null value is accepted for
* trusted certificate entries, for other type of key entries a null value
* is converted to an empty password character array.
*/
protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param)
throws KeyManagerException
{
if (keyAlias == null || keyAlias.equals(""))
{
throw new KeyManagerException(
"Implementation Error: null or empty key alias is not allowed."
);
}
if (entry == null)
{
throw new KeyManagerException(
"Implementation Error: null keystore entry is not allowed."
);
}
// Key stores appear to behave differently with regards to key entries depending what
// types of entries are stored (and possibly differing between store implementations too).
// E.g. private keys may have a strict requirement for a key protection where public
// certificates may not allow protection parameters at all.
// Doing some special handling here depending what type of entry is being stored:
// - if a null protection parameter is provided, it is converted to an empty password
// protection unless the null protection parameter is for a trusted certificate
// entry in which case it is accepted.
if (param == null)
{
param = new KeyStore.PasswordProtection(new char[] {});
}
if (entry instanceof KeyStore.TrustedCertificateEntry)
{
param = null;
}
try
{
keystore.setEntry(keyAlias, entry, param);
}
catch (KeyStoreException exception)
{
throw new KeyManagerException(
"Failed to add key '{0}' to key store : {1}", exception,
keyAlias, exception.getMessage());
}
}
/**
* Removes a key entry from this instance. Use {@link #save(URI, char[])} to persist
* if desired.
*
* @param keyAlias
* A lookup name of the key entry to be removed.
*
* @return true if key was removed, false otherwise
*/
protected boolean remove(String keyAlias)
{
try
{
keystore.deleteEntry(keyAlias);
return true;
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to remove key alias '{0}' : {1}", exception,
keyAlias, exception.getMessage()
);
return false;
}
}
/**
* Retrieves a key from underlying key storage.
*
* @param alias
* Key alias of the key to retrieve.
*
* @param protection
* Protection parameter to retrieve the key.
*
* @return a key store entry, or null if it was not found
*
* @throws KeyManagerException
* if the key could not be retrieved, due to incorrect protection parameters,
* unsupported algorithm or other reasons
*/
protected KeyStore.Entry retrieveKey(String alias, KeyStore.ProtectionParameter protection)
throws KeyManagerException
{
try
{
return keystore.getEntry(alias, protection);
}
catch (KeyStoreException exception)
{
throw new IncorrectImplementationException(
"Implementation Error: password manager has not been initialized.", exception
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"Configuration error. Required key storage algorithm is not available: {0}", exception,
exception.getMessage()
);
}
catch (UnrecoverableKeyException exception)
{
throw new KeyManagerException(
"Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " +
"protection password: {1}", exception,
alias, exception.getMessage()
);
}
catch (UnrecoverableEntryException exception)
{
throw new KeyManagerException(
"Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " +
"protection password: {1}", exception,
alias, exception.getMessage()
);
}
}
/**
* A convenience method to retrieve a certificate (rather than a private or secret key)
* from the underlying keystore.
*
* @param alias
* Certificate alias to retrieve.
*
* @return A certificate, or null if not found
*/
protected Certificate getCertificate(String alias)
{
try
{
return keystore.getCertificate(alias);
}
catch (KeyStoreException exception)
{
// This exception may happen if keystore is not initialized/loaded when asking for
// a certificate -- since we initialize the keystore instance as part of the constructor
// it should always be present. Therefore this exception should only occur in case of
// an implementation error.
throw new IncorrectImplementationException(
"Could not retrieve certificate '{0}': {1}", exception,
alias, exception.getMessage()
);
}
}
/**
* Generates a new asymmetric key pair using the given algorithm.
*
* @param keyAlgo
* algorithm for the key generator
*
* @return generated key pair
*
* @throws KeyManagerException
* in case any errors in key generation
*/
protected KeyPair generateKey(AsymmetricKeyAlgorithm keyAlgo) throws KeyManagerException
{
try
{
KeyPairGenerator keyGen;
if (provider == null)
{
keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName());
}
else
{
keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName(), provider);
}
keyGen.initialize(keyAlgo.algorithmSpec);
return keyGen.generateKeyPair();
}
catch (InvalidAlgorithmParameterException exception)
{
throw new KeyManagerException(
"Invalid algorithm parameter in {0} : {1}", exception,
keyAlgo, exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"No security provider found for {0} : {1}", exception,
keyAlgo, exception.getMessage()
);
}
}
/**
* Returns the key storage type used by this key manager.
*
* @return key storage type
*/
protected Storage getStorageType()
{
return storage;
}
/**
* Checks if key store exists at given file URI.
*
* @param uri
* the file URI to check
*
* @return true if file exists, false otherwise
*
* @throws KeyManagerException
* if security manager has denied access to file information
*/
protected boolean exists(URI uri) throws KeyManagerException
{
File file = new File(uri);
try
{
return file.exists();
}
catch (SecurityException exception)
{
String path = resolveFilePath(file);
throw new KeyManagerException(
"Security manager has prevented access to file ''{0}'' : {1}", exception,
path, exception.getMessage()
);
}
}
/**
* Clears the given password character array with zero values.
*
* @param password
* password character array to erase
*/
protected void clearPassword(char[] password)
{
if (password != null)
{
for (int i = 0; i < password.length; ++i)
{
password[i] = 0;
}
}
}
/**
* Clears the given password byte array with zero values.
*
* @param password
* password byte array to erase
*/
protected void clearPassword(byte[] password)
{
if (password != null)
{
for (int i = 0; i< password.length; ++i)
{
password[i] = 0;
}
}
}
/**
* Stores the key entries of this key manager into a keystore. The keystore is saved to the given
* output stream. The keystore can be an existing, loaded keystore or a new, empty one.
*
* @param keystore
* keystore to add keys from this key manager to
*
* @param out
* the output stream for the keystore (can be used for persisting the keystore to disk)
*
* @param password
* password to access the keystore
*
* @throws KeyManagerException
* if the save operation fails
*/
private void save(KeyStore keystore, OutputStream out, char[] password)
throws KeyManagerException
{
if (password == null || password.length == 0)
{
throw new KeyManagerException(
"Null or empty password. Keystore must be protected with a password."
);
}
BufferedOutputStream bout = new BufferedOutputStream(out);
try
{
keystore.store(bout, password);
}
catch (KeyStoreException exception)
{
throw new KeyManagerException(
"Storing the key pair failed : {0}", exception,
exception.getMessage()
);
}
catch (IOException exception)
{
throw new KeyManagerException(
"Unable to write key to keystore : {0}", exception,
exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"Security provider does not support required key store algorithm: {0}", exception,
exception.getMessage()
);
}
catch (CertificateException exception)
{
throw new KeyManagerException(
"Cannot store certificate: {0}", exception,
exception.getMessage()
);
}
finally
{
if (bout != null)
{
try
{
bout.flush();
bout.close();
}
catch (IOException exception)
{
securityLog.warn(
"Failed to close file output stream to keystore : {0}", exception,
exception.getMessage()
);
}
}
}
}
/**
* Loads a key store from the given input stream or creates a new instance in case of a
* null input stream. Configured key storage type and security provider instance are used
* to load/create the keystore.
*
* @param file
* file to load the key store from
*
* @param password
* password to access the key store
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
private void loadKeyStore(File file, char[] password) throws ConfigurationException,
KeyManagerException
{
// This is basically just a convenience method to actual implementation
// in loadKeyStore(InputStream, char[])...
if (file == null)
{
throw new KeyManagerException("Implementation Error: null file descriptor.");
}
try
{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
loadKeyStore(in, password);
}
catch (FileNotFoundException exception)
{
throw new KeyManagerException(
"Keystore file ''{0}'' could not be created or opened : {1}", exception,
resolveFilePath(file), exception.getMessage()
);
}
catch (SecurityException exception)
{
throw new KeyManagerException(
"Security manager has denied access to keystore file ''{0}'' : {1}", exception,
resolveFilePath(file), exception.getMessage()
);
}
}
/**
* Loads a key store from the given input stream or creates a new instance in case of a
* null input stream. Configured key storage type and security provider instance are used
* to load/create the keystore.
*
* @param in
* input stream to key store file (or null to create a new one)
*
* @param password
* shared secret (a password) used for protecting access to the key store
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
private void loadKeyStore(InputStream in, char[] password) throws ConfigurationException,
KeyManagerException
{
try
{
if (provider == null)
{
// Use system installed security provider...
keystore = KeyStore.getInstance(storage.getStorageName());
}
else
{
keystore = KeyStore.getInstance(storage.getStorageName(), provider);
}
keystore.load(in, password);
}
catch (KeyStoreException exception)
{
// NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested
// NoSuchAlgorithmException. This is the behavior for both SUN default provider
// in Java 6 and BouncyCastle.
if (exception.getCause() != null && exception.getCause() instanceof NoSuchAlgorithmException)
{
String usedProviders;
if (provider == null)
{
usedProviders = Arrays.toString(Security.getProviders());
}
else
{
usedProviders = provider.getName();
}
throw new ConfigurationException(
"The security provider(s) '{0}' do not support keystore type '{1}' : {2}", exception,
usedProviders, storage.name(), exception.getMessage()
);
}
throw new KeyManagerException(
"Cannot load keystore: {0}", exception,
exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
// If part of the keystore load() the algorithm to verify the keystore contents cannot
// be found...
throw new KeyManagerException(
"Required keystore verification algorithm not found: {0}", exception,
exception.getMessage()
);
}
catch (CertificateException exception)
{
// Can happen if any of the certificates in the store cannot be loaded...
throw new KeyManagerException(
"Can't load keystore: {0}", exception,
exception.getMessage()
);
}
catch (IOException exception)
{
// If there's an I/O problem, or if keystore has been corrupted, or if password is missing
// if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException)
// // The Java 6 javadoc claims that an incorrect password can be detected by having
// // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't
// // seem to be the case or is not working... incorrect password is reported as an
// // IOException just like other I/O errors with no root causes as far as I'm able to
// // tell. So leaving this out for now
// // [JPL]
// throw new PasswordException(
// "Cannot recover keys from keystore (was the provided password correct?) : {0}",
// e.getMessage(), e
// TODO : this error would be improved by reporting file location and keystore type..
throw new KeyManagerException(
"I/O Error: Cannot load keystore: {0}", exception,
exception.getMessage()
);
}
}
/**
* File utility to print file path.
*
* @param file
* file path to print
*
* @return resolves to an absolute file path if allowed by the security manager, if not
* returns the file path as defined in the file object parameter
*/
private String resolveFilePath(File file)
{
try
{
return file.getAbsolutePath();
}
catch (SecurityException e)
{
return file.getPath();
}
}
/**
* Convenience class to hold keystore entry and its protection parameter as single entity in
* collections.
*/
private static class KeyStoreEntry
{
private KeyStore.Entry entry;
private KeyStore.ProtectionParameter protectionParameter;
private KeyStoreEntry(KeyStore.Entry entry, KeyStore.ProtectionParameter param)
{
this.entry = entry;
this.protectionParameter = param;
}
}
/**
* Exception type for the public API of this class to indicate errors.
*/
public static class KeyManagerException extends OpenRemoteException
{
protected KeyManagerException(String msg)
{
super(msg);
}
protected KeyManagerException(String msg, Throwable cause, Object... params)
{
super(msg, cause, params);
}
}
/**
* Specific subclass of KeyManagerException that indicates a security configuration issue.
*/
public static class ConfigurationException extends KeyManagerException
{
protected ConfigurationException(String msg, Throwable cause, Object... params)
{
super(msg, cause, params);
}
}
} |
package ui.components;
import javafx.scene.input.KeyCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Optional;
import java.util.function.IntConsumer;
/**
* A very specialized ListView subclass that:
*
* - can be navigated with the arrow keys and Enter
* - supports an event for item selection
* - provides methods for retaining selection after its contents are changed
*
* It depends on the functionality of ScrollableListView to ensure that
* navigation scrolls the list properly. The Up, Down, and Enter key events
* should not be separately bound on it.
*
* An item is considered selected when:
*
* - it is highlighted with the arrow keys, but only when the Shift key is not down
* - Enter is pressed when it is highlighted
* - it is clicked
*/
public class NavigableListView<T> extends ScrollableListView<T> {
private static final Logger logger = LogManager.getLogger(NavigableListView.class.getName());
// Tracks the index of the list which should be currently selected
private Optional<Integer> selectedIndex = Optional.empty();
// Used for saving and restoring selection.
// selectedIndex should be used to get the currently-selected item, through the provided getter.
private Optional<T> lastSelectedItem = Optional.empty();
// Indicates that saveSelection was called, in the event that saveSelection itself fails
// (when nothing is selected, both should be no-ops)
private boolean saveSelectionCalled = false;
private IntConsumer onItemSelected = i -> {};
public NavigableListView() {
setupKeyEvents();
setupMouseEvents();
}
/**
* Should be called before making changes to the item list of this list view if
* it's important that selection is retained after.
*/
public void saveSelection() {
if (getSelectionModel().getSelectedItem() != null) {
lastSelectedItem = Optional.of(getSelectionModel().getSelectedItem());
}
saveSelectionCalled = true;
}
public void restoreSelection() {
if (!lastSelectedItem.isPresent()) {
if (!saveSelectionCalled) {
throw new IllegalStateException("saveSelection must be called before restoreSelection");
} else {
saveSelectionCalled = false;
return; // No-op
}
}
saveSelectionCalled = false;
// Find index of previously-selected item
int index = -1;
int i = 0;
for (T item : getItems()) {
if (item.equals(lastSelectedItem.get())) {
index = i;
break;
}
i++;
}
if (index == -1) {
// The item disappeared
if (getItems().size() == 0) {
selectedIndex = Optional.empty();
}
// Otherwis do nothing; selection will be resolved on its own
} else {
// Select that item
getSelectionModel().clearAndSelect(index);
selectedIndex = Optional.of(index);
// Do not trigger event
}
}
private void setupMouseEvents() {
setOnMouseClicked(e -> {
int currentlySelected = getSelectionModel().getSelectedIndex();
// The currently-selected index is sometimes -1 when an issue is clicked.
// When this happens we ignore this event.
if (currentlySelected != -1) {
selectedIndex = Optional.of(currentlySelected);
logger.info("Mouse click on issue " + selectedIndex.get());
onItemSelected.accept(selectedIndex.get());
}
});
}
private void setupKeyEvents() {
setOnKeyPressed(e -> {
if (e.isControlDown()){
return;
}
switch (e.getCode()) {
case UP:
case T:
case DOWN:
case V:
e.consume();
handleUpDownKeys(e.getCode() == KeyCode.DOWN || e.getCode() == KeyCode.V);
assert selectedIndex.isPresent() : "handleUpDownKeys doesn't set selectedIndex!";
if (!e.isShiftDown()) {
logger.info("Arrow key navigation to issue " + selectedIndex.get());
onItemSelected.accept(selectedIndex.get());
}
break;
case ENTER:
e.consume();
if (selectedIndex.isPresent()) {
logger.info("Enter key selection on issue " + selectedIndex.get());
onItemSelected.accept(selectedIndex.get());
}
break;
default:
break;
}
});
}
private void handleUpDownKeys(boolean isDownKey) {
// Nothing is selected or the list is empty; do nothing
if (!selectedIndex.isPresent()) return;
if (getItems().size() == 0) return;
// Compute new index and clamp it within range
int newIndex = selectedIndex.get() + (isDownKey ? 1 : -1);
newIndex = Math.min(Math.max(0, newIndex), getItems().size()-1);
// Update selection state and our selection model
getSelectionModel().clearAndSelect(newIndex);
selectedIndex = Optional.of(newIndex);
// Ensure that the newly-selected item is in view
scrollAndShow(newIndex);
}
public void setOnItemSelected(IntConsumer callback) {
onItemSelected = callback;
}
public void selectFirstItem(){
requestFocus();
if (getItems().size() == 0) return;
getSelectionModel().clearAndSelect(0);
scrollAndShow(0);
selectedIndex = Optional.of(0);
onItemSelected.accept(selectedIndex.get());
}
public Optional<T> getSelectedItem() {
return selectedIndex.map(getItems()::get);
}
} |
package com.xiaojinzi.componentdemo;
import android.app.Application;
import com.google.gson.Gson;
import com.xiaojinzi.component.Component;
import com.xiaojinzi.component.Config;
import com.xiaojinzi.component.impl.application.ModuleManager;
import com.xiaojinzi.component.support.LogUtil;
import com.xiaojinzi.component.support.RxErrorIgnoreUtil;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
long startTime = System.currentTimeMillis();
Component.init(
BuildConfig.DEBUG,
Config.with(this)
.defaultScheme("router")
// , true,
.useRouteRepeatCheckInterceptor(true)
// 1000 ,
.routeRepeatCheckDuration(1000)
// Application Context
.tipWhenUseApplication(true)
// , Gradle
.optimizeInit(true)
// , optimizeInit(true)
.autoRegisterModule(true)
// demo , ,
.objectToJsonConverter(obj -> new Gson().toJson(obj))
.build()
);
long endTime = System.currentTimeMillis();
LogUtil.log("
RxErrorIgnoreUtil.ignoreError();
if (BuildConfig.DEBUG) {
ModuleManager.getInstance().check();
}
}
} |
package org.perl6.nqp.sixmodel.reprs;
import java.util.List;
import java.util.ArrayList;
import com.sun.jna.Structure;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.perl6.nqp.sixmodel.REPR;
import org.perl6.nqp.sixmodel.SerializationReader;
import org.perl6.nqp.sixmodel.SixModelObject;
import org.perl6.nqp.sixmodel.STable;
import org.perl6.nqp.sixmodel.StorageSpec;
import org.perl6.nqp.sixmodel.TypeObject;
import org.perl6.nqp.sixmodel.reprs.CStructREPRData.AttrInfo;
import org.perl6.nqp.sixmodel.reprs.NativeCall.ArgType;
import org.perl6.nqp.runtime.ExceptionHandling;
import org.perl6.nqp.runtime.ThreadContext;
public class CStruct extends REPR {
public SixModelObject type_object_for(ThreadContext tc, SixModelObject HOW) {
STable st = new STable(this, HOW);
SixModelObject obj = new TypeObject();
obj.st = st;
st.WHAT = obj;
return st.WHAT;
}
public void compose(ThreadContext tc, STable st, SixModelObject repr_info_hash) {
SixModelObject repr_info = repr_info_hash.at_key_boxed(tc, "attribute");
CStructREPRData repr_data = new CStructREPRData();
long mroLength = repr_info.elems(tc);
List<AttrInfo> attrInfos = new ArrayList<AttrInfo>();
for (long i = mroLength - 1; i >= 0; i
SixModelObject entry = repr_info.at_pos_boxed(tc, i);
SixModelObject attrs = entry.at_pos_boxed(tc, 1);
long parents = entry.at_pos_boxed(tc, 2).elems(tc);
if (parents <= 1) {
long numAttrs = attrs.elems(tc);
for (long j = 0; j < numAttrs; j++) {
SixModelObject attrHash = attrs.at_pos_boxed(tc, j);
AttrInfo info = new AttrInfo();
info.name = attrHash.at_key_boxed(tc, "name").get_str(tc);
info.type = attrHash.at_key_boxed(tc, "type");
StorageSpec spec = info.type.st.REPR.get_storage_spec(tc, info.type.st);
info.bits = spec.bits;
repr_data.fieldTypes.put(info.name, info);
if (info.type == null) {
ExceptionHandling.dieInternal(tc, "CStruct representation requires the types of all attributes to be specified");
}
attrInfos.add(info);
}
}
else {
ExceptionHandling.dieInternal(tc, "CStruct representation does not support multiple inheritance");
}
}
/* XXX: We could generate the structure class lazily the first time we
* allocate an object, rather than upfront. Not sure if that's
* necessary though. */
st.REPRData = repr_data;
generateStructClass(tc, st, attrInfos);
}
public SixModelObject allocate(ThreadContext tc, STable st) {
/* TODO: Die if someone tries to allocate a CStruct before it's been
* composed. */
CStructInstance obj = new CStructInstance();
CStructREPRData repr_data = (CStructREPRData) st.REPRData;
obj.st = st;
try {
obj.storage = (Structure) repr_data.structureClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return obj;
}
public SixModelObject deserialize_stub(ThreadContext tc, STable st) {
/* This REPR can't be serialized. */
ExceptionHandling.dieInternal(tc, "Can't deserialize_stub a CStruct object.");
return null;
}
public void deserialize_finish(ThreadContext tc, STable st, SerializationReader reader, SixModelObject obj) {
ExceptionHandling.dieInternal(tc, "Can't deserialize_finish a CStruct object.");
}
private static long typeId = 0;
private void generateStructClass(ThreadContext tc, STable st, List<AttrInfo> fields) {
CStructREPRData reprData = (CStructREPRData) st.REPRData;
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
String className = "__CStruct__" + typeId++;
int attributes = fields.size();
// public $className extends com.sun.jna.Structure implements com.sun.jna.Structure.ByReference { ... }
cw.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null,
"com/sun/jna/Structure", new String[]{"com/sun/jna/Structure$ByReference"});
// private static List<String> fieldOrder;
FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, "fieldOrder", "Ljava/util/List;",
"Ljava.util.List<Ljava.lang.String;>;", null);
fv.visitEnd();
for (AttrInfo info: fields) {
fv = cw.visitField(Opcodes.ACC_PUBLIC, info.name, typeDescriptor(tc, info), null, null);
fv.visitEnd();
}
// static { fieldOrder = new ArrayList(); fieldOrder.add(field1); ... }
MethodVisitor staticVisitor = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
staticVisitor.visitCode();
staticVisitor.visitTypeInsn(Opcodes.NEW, "java/util/ArrayList"); // Construct new object.
staticVisitor.visitInsn(Opcodes.DUP);
staticVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V"); // Invoke the constructor.
staticVisitor.visitFieldInsn(Opcodes.PUTSTATIC, className, "fieldOrder", "Ljava/util/List;");
for (int i = 0; i < attributes; i++) {
staticVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, "fieldOrder", "Ljava/util/List;");
staticVisitor.visitLdcInsn(fields.get(i).name);
staticVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z");
staticVisitor.visitInsn(Opcodes.POP);
}
staticVisitor.visitInsn(Opcodes.RETURN);
staticVisitor.visitMaxs(2, 0);
staticVisitor.visitEnd();
// public List<String> getFieldOrder() { return fieldOrder; }
MethodVisitor gfoVisitor = cw.visitMethod(Opcodes.ACC_PUBLIC, "getFieldOrder", "()Ljava/util/List;", "()Ljava/util/List<Ljava/lang/String;>;", null);
gfoVisitor.visitCode();
gfoVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, "fieldOrder", "Ljava/util/List;");
gfoVisitor.visitInsn(Opcodes.ARETURN);
gfoVisitor.visitMaxs(1, 1);
gfoVisitor.visitEnd();
// Add nullary constructor calling superclass.
MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitCode();
constructor.visitVarInsn(Opcodes.ALOAD, 0);
constructor.visitMethodInsn(Opcodes.INVOKESPECIAL,
"com/sun/jna/Structure", "<init>", "()V");
constructor.visitInsn(Opcodes.RETURN);
constructor.visitMaxs(1, 1);
constructor.visitEnd();
cw.visitEnd();
byte[] compiled = cw.toByteArray();
reprData.structureClass = tc.gc.byteClassLoader.defineClass(className, compiled);
}
private String typeDescriptor(ThreadContext tc, AttrInfo info) {
REPR repr = info.type.st.REPR;
StorageSpec spec = repr.get_storage_spec(tc, info.type.st);
info.bits = spec.bits;
if (spec.inlineable == StorageSpec.INLINED && spec.boxed_primitive == StorageSpec.BP_INT) {
if (spec.bits == 8) {
info.argType = ArgType.CHAR;
return "B";
}
else if (spec.bits == 16) {
info.argType = ArgType.SHORT;
return "S";
}
else if (spec.bits == 32) {
info.argType = ArgType.INT;
return "I";
}
else if (spec.bits == 64) {
info.argType = ArgType.LONG;
return "J";
}
else {
ExceptionHandling.dieInternal(tc, "CStruct representation only handles 8, 16, 32 and 64 bit ints");
return null;
}
}
else if (spec.inlineable == StorageSpec.INLINED && spec.boxed_primitive == StorageSpec.BP_NUM) {
if (spec.bits == 32) {
info.argType = ArgType.FLOAT;
return "F";
}
else if (spec.bits == 64) {
info.argType = ArgType.DOUBLE;
return "D";
}
else {
ExceptionHandling.dieInternal(tc, "CStruct representation only handles 32 and 64 bit nums");
return null;
}
}
else if ((spec.can_box & StorageSpec.CAN_BOX_STR) != 0) {
info.argType = ArgType.UTF8STR;
return "Ljava/lang/String;";
}
else if (repr instanceof CArray) {
info.argType = ArgType.CARRAY;
return "Lcom/sun/jna/Pointer;";
}
else if (repr instanceof CPointer) {
info.argType = ArgType.CPOINTER;
return "Lcom/sun/jna/Pointer;";
}
else if (repr instanceof CStruct) {
info.argType = ArgType.CSTRUCT;
Class c = ((CStructREPRData) info.type.st.REPRData).structureClass;
/* When we hit a struct in an attribute that is not composed yet, we most likely
* have hit a struct of our own kind. */
if (c == null)
return "L__CStruct__" + typeId + ";";
return Type.getDescriptor(c);
}
else {
ExceptionHandling.dieInternal(tc, "CStruct representation only handles int, num, CArray, CPointer and CStruct");
return null;
}
}
} |
package org.openremote.security;
import org.openremote.base.exception.IncorrectImplementationException;
import org.openremote.base.exception.OpenRemoteException;
import org.openremote.logging.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Arrays;
/**
* This is an abstract base class for managing and storing key material. It is useful for
* both generating keys (and associated certificates if desired) as well as optionally
* persisting keys and key certificates on filesystem using secure keystores. <p>
*
* This abstract implementation contains several operations that the subclasses may or may not
* choose to expose as part of their public API. If a subclass wants to expose a method
* implementation as part of public API, it should create a public method that invokes one of
* the protected methods in this class. Some of the method implementations in this class may
* be unnecessarily generic to expose in API as-is, and therefore it may make sense to create
* a more use-case specific method signatures in each subclass. For examples of protected
* methods, see {@link #save(java.net.URI, char[])}, {@link #load(java.net.URI, char[])},
* {@link #add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)},
* {@link #remove(String)}. <p>
*
* For examples of subclasses that may expose parts of this class protected API, see
* {@link PasswordManager}, {@link PrivateKeyManager} classes.
*
* @see #save(java.net.URI, char[])
* @see #load(java.net.URI, char[])
* @see #add(String, java.security.KeyStore.Entry, java.security.KeyStore.ProtectionParameter)
* @see #remove(String)
* @see PasswordManager
* @see PrivateKeyManager
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public abstract class KeyManager
{
/**
* This is the default key storage type used if nothing else is specified. <p>
*
* Note that the default storage format PKCS12 can only be used as an asymmetric public and
* private key and a key certificate storage but not for other (symmetric) keys. For the latter,
* other provider-specific storage types must be used. <p>
*
* Default: {@value}
*/
public final static Storage DEFAULT_KEYSTORE_STORAGE = Storage.PKCS12;
/**
* The default security provider used by this instance. Note that can contain a null value
* if loading of the security provider fails. A null value should indicate using the system
* installed security providers in their preferred order rather than this explicit security
* provider. <p>
*
* Default: {@value}
*/
public final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC;
/**
* If no key-specific password is set for stored keys, use this default empty password instead.
* Note, most keystore implementations don't allow passing a null password protection parameters
* for keys, and some (e.g. BouncyCastle UBER) do not allow empty passwords (empty char arrays)
* either.
*/
public static final char[] EMPTY_KEY_PASSWORD = new char[] { '0' };
/**
* ASN.1 OID for NSA / NIST standard curve P-521. This is equivalent to SEC 2 prime curve
* "secp521r1". OID = {@value}
*/
public final static String ASN_OID_STD_CURVE_NSA_NIST_P521 = "1.3.132.0.35";
/**
* ASN.1 OID for NSA / NIST standard curve P-384. This is equivalent to SEC 2 prime curve
* "secp384r1". OID = {@value}
*/
public final static String ASN_OID_STD_CURVE_NSA_NIST_P384 = "1.3.132.0.34";
/**
* ASN.1 OID for NSA / NIST standard curve P-256. This is equivalent to SEC 2 prime curve
* "secp256r1" and ANSI X9.62 "prime256v1". OID = {@value}
*/
public final static String ASN_OID_STD_CURVE_NSA_NIST_P256 = "1.2.840.10045.3.1.7";
/**
* RSA key size : {@value} <p>
*
* This is recommended asymmetric RSA key size for classified, secret data, as per NSA Suite B.
*/
public final static int DEFAULT_RSA_KEY_SIZE = 3072;
/**
* Public exponent value used in RSA algorithm (increase impacts performance): {@value}
*
* @see java.security.spec.RSAKeyGenParameterSpec#F4
*/
public final static BigInteger DEFAULT_RSA_PUBLIC_EXPONENT = RSAKeyGenParameterSpec.F4;
/**
* Default logger for the security package.
*/
protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT);
/**
* The key storage type used by this instance.
*/
private Storage storage = DEFAULT_KEYSTORE_STORAGE;
/**
* The security provider used by this instance. <p>
*
* Note that may contain a null reference in which case implementation should delegate to the
* JVM installed security providers in their preferred use order.
*/
private Provider provider = DEFAULT_SECURITY_PROVIDER.getProviderInstance();
/**
* Reference to the internal keystore instance that is used to persist the key entries in
* this key manager.
*/
private KeyStore keystore = null;
/**
* Creates a new key manager instance with a {@link #DEFAULT_KEYSTORE_STORAGE default} key
* storage format using {@link #DEFAULT_SECURITY_PROVIDER default} security provider.
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager() throws ConfigurationException, KeyManagerException
{
this(DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance());
}
/**
* This constructor allows the subclasses to specify both the key storage format and explicit
* security provider to use with this instance. The key storage format and security provider
* given as arguments will be used instead of the default values for this instance. <p>
*
* Note that the security provider parameter allows a null value. This indicates that the
* appropriate security provider should be searched from the JVM installed security providers
* in their preferred order.
*
*
* @param storage
* key storage format to use with this instance
*
* @param provider
* The explicit security provider to use with the key storage of this instance. If a
* null value is specified, the implementations should opt to delegate the selection
* of a security provider to the JVMs installed security provider implementations.
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(Storage storage, Provider provider)
throws ConfigurationException, KeyManagerException
{
init(storage, provider);
loadKeyStore((InputStream) null, null);
}
/**
* This constructor will load an existing keystore into memory. It expects the keystore
* to be in default key storage format as specified in {@link #DEFAULT_KEYSTORE_STORAGE}. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password) throws ConfigurationException,
KeyManagerException
{
this(
keyStoreFile, password,
DEFAULT_KEYSTORE_STORAGE,
DEFAULT_SECURITY_PROVIDER.getProviderInstance()
);
}
/**
* This constructor will load an existing keystore into memory. It allows the subclasses to
* specify the expected key storage format used by the keystore file. The storage format
* must be supported by the {@link #DEFAULT_SECURITY_PROVIDER} implementation. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
* @param storage
* key storage format to use with this instance
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password, Storage storage)
throws ConfigurationException, KeyManagerException
{
this(keyStoreFile, password, storage, storage.getSecurityProvider());
}
/**
* This constructor will load an existing keystore into memory. It allows the subclasses to
* specify both the expected key storage format and explicit security provider to be used
* when the keystore is loaded. <p>
*
* Note that the security provider parameter allows a null value. This indicates that the
* appropriate security provider should be searched from the JVM installed security providers
* in their preferred order. <p>
*
* The URI to a keystore file must use a 'file' scheme.
*
*
* @param keyStoreFile
* a file URI pointing to a keystore file that should be loaded into this key
* manager
*
* @param password
* a master password to access the keystore file
*
* @param storage
* key storage format to use with this instance
*
* @param provider
* The explicit security provider to use with the key storage of this instance. If a
* null value is specified, the implementations should opt to delegate the selection
* of a security provider to the JVMs installed security provider implementations.
*
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if creating the keystore fails
*/
protected KeyManager(URI keyStoreFile, char[] password, Storage storage, Provider provider)
throws ConfigurationException, KeyManagerException
{
this(storage, provider);
load(keyStoreFile, password);
}
/**
* Indicates if this key manager contains a key with a given alias.
*
* @param keyAlias
* key alias to check
*
* @return true if a key is associated with a given alias in this key manager; false
* otherwise
*/
public boolean contains(String keyAlias)
{
try
{
return keystore.containsAlias(keyAlias);
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to retrieve key info for alias '{0}' : {1}", exception,
keyAlias, exception.getMessage()
);
return false;
}
}
/**
* Returns the number of keys currently managed in this key manager.
*
* @return number of keys in this key manager
*/
public int size()
{
try
{
return keystore.size();
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to retrieve keystore size : {0}", exception,
exception.getMessage()
);
return -1;
}
}
/**
* Initialization method used by constructors to initialize this instance. Should not be
* invoked outside of a constructor. <p>
*
* @param storage
* The keystore storage type to use with this instance.
*
* @param provider
* The security provider to use with this instance. Can be null in which case
* the implementations should delegate to the JVM installed security providers
* in their preferred use order.
*/
protected void init(Storage storage, Provider provider)
{
if (storage == null)
{
throw new IllegalArgumentException("Implementation Error: null storage type");
}
this.provider = provider;
this.storage = storage;
}
/**
* Stores the keys in this key manager in a secure key store format. This implementation generates
* a file-based, persistent key store which can be shared with other applications and processes.
* <p>
* IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array
* as soon as it is no longer needed. This prevents passwords from lingering
* in JVM memory pool any longer than is necessary. Use the
* {@link #clearPassword(char[])} method for this purpose.
*
* @param uri
* The location of the file where the key store should be persisted. Must be
* an URI with file scheme.
*
* @param password
* A secret password used to access the keystore contents. NOTE: the character
* array should be set to zero values after this method call completes, via
* {@link #clearPassword(char[])} method.
*
* @see #clearPassword(char[])
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
protected void save(URI uri, char[] password) throws ConfigurationException,
KeyManagerException
{
if (uri == null)
{
throw new KeyManagerException("Save failed due to null URI.");
}
try
{
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uri)));
// Persist...
save(keystore, out, password);
}
catch (FileNotFoundException exception)
{
throw new KeyManagerException(
"File ''{0}'' cannot be created or opened : {1}", exception,
resolveFilePath(new File(uri)), exception.getMessage()
);
}
catch (SecurityException exception)
{
throw new KeyManagerException(
"Security manager has denied access to file ''{0}'' : {1}", exception,
resolveFilePath(new File(uri)), exception.getMessage()
);
}
}
/**
* Loads existing, persisted key store contents into this instance. Any previous keys in this
* key manager instance are overridden. <p>
*
* IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array
* as soon as it is no longer needed. This prevents passwords from lingering
* in JVM memory pool any longer than is necessary. Use the
* {@link #clearPassword(char[])} method for this purpose.
*
* @param uri
* URI with file scheme pointing to the file system location of the keystore
* to load
*
* @param keystorePassword
* The password to access the keystore. Note that the subclasses invoking this
* method are responsible for resetting the password character array after use.
*
* @see #clearPassword(char[])
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading the keystore fails
*/
protected void load(URI uri, char[] keystorePassword) throws KeyManagerException
{
if (uri == null)
{
throw new KeyManagerException("Implementation Error: null file URI.");
}
if (exists(uri))
{
loadKeyStore(new File(uri), keystorePassword);
}
}
/**
* Adds a key entry to this instance. Use {@link #save(URI, char[])} to persist
* if desired.
*
* @param keyAlias
* A lookup name of the key entry to be added.
*
* @param entry
* Key entry to be added. Note that accepted entry types depend on the
* keystore storage format.
*
* @param param
* Protection parameters for the key entry. A null value is accepted for
* trusted certificate entries, for other type of key entries a null value
* is converted to an empty password character array.
*/
protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param)
throws KeyManagerException
{
if (keyAlias == null || keyAlias.equals(""))
{
throw new KeyManagerException(
"Implementation Error: null or empty key alias is not allowed."
);
}
if (entry == null)
{
throw new KeyManagerException(
"Implementation Error: null keystore entry is not allowed."
);
}
// Key stores appear to behave differently with regards to key entries depending what
// types of entries are stored (and possibly differing between store implementations too).
// E.g. private keys may have a strict requirement for a key protection where public
// certificates may not allow protection parameters at all.
// Doing some special handling here depending what type of entry is being stored:
// - if a null protection parameter is provided, it is converted to an empty password
// protection unless the null protection parameter is for a trusted certificate
// entry in which case it is accepted.
if (param == null)
{
param = new KeyStore.PasswordProtection(EMPTY_KEY_PASSWORD);
}
if (entry instanceof KeyStore.TrustedCertificateEntry)
{
param = null;
}
try
{
keystore.setEntry(keyAlias, entry, param);
}
catch (KeyStoreException exception)
{
throw new KeyManagerException(
"Failed to add key '{0}' to key store : {1}", exception,
keyAlias, exception.getMessage());
}
}
/**
* Removes a key entry from this instance. Use {@link #save(URI, char[])} to persist
* if desired.
*
* @param keyAlias
* A lookup name of the key entry to be removed.
*
* @return true if key was removed, false otherwise
*/
protected boolean remove(String keyAlias)
{
try
{
keystore.deleteEntry(keyAlias);
return true;
}
catch (KeyStoreException exception)
{
securityLog.error(
"Unable to remove key alias '{0}' : {1}", exception,
keyAlias, exception.getMessage()
);
return false;
}
}
/**
* Retrieves a key from underlying key storage.
*
* @param alias
* Key alias of the key to retrieve.
*
* @param protection
* Protection parameter to retrieve the key.
*
* @return a key store entry, or null if it was not found
*
* @throws KeyManagerException
* if the key could not be retrieved, due to incorrect protection parameters,
* unsupported algorithm or other reasons
*/
protected KeyStore.Entry retrieveKey(String alias, KeyStore.ProtectionParameter protection)
throws KeyManagerException
{
try
{
return keystore.getEntry(alias, protection);
}
catch (KeyStoreException exception)
{
throw new IncorrectImplementationException(
"Implementation Error: password manager has not been initialized.", exception
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"Configuration error. Required key storage algorithm is not available: {0}", exception,
exception.getMessage()
);
}
catch (UnrecoverableKeyException exception)
{
throw new KeyManagerException(
"Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " +
"protection password: {1}", exception,
alias, exception.getMessage()
);
}
catch (UnrecoverableEntryException exception)
{
throw new KeyManagerException(
"Password with alias ''{0}'' could not be retrieved, possibly due to incorrect " +
"protection password: {1}", exception,
alias, exception.getMessage()
);
}
}
/**
* A convenience method to retrieve a certificate (rather than a private or secret key)
* from the underlying keystore.
*
* @param alias
* Certificate alias to retrieve.
*
* @return A certificate, or null if not found
*/
protected Certificate getCertificate(String alias)
{
try
{
return keystore.getCertificate(alias);
}
catch (KeyStoreException exception)
{
// This exception may happen if keystore is not initialized/loaded when asking for
// a certificate -- since we initialize the keystore instance as part of the constructor
// it should always be present. Therefore this exception should only occur in case of
// an implementation error.
throw new IncorrectImplementationException(
"Could not retrieve certificate '{0}': {1}", exception,
alias, exception.getMessage()
);
}
}
/**
* Generates a new asymmetric key pair using the given algorithm.
*
* @param keyAlgo
* algorithm for the key generator
*
* @return generated key pair
*
* @throws KeyManagerException
* in case any errors in key generation
*/
protected KeyPair generateKey(AsymmetricKeyAlgorithm keyAlgo) throws KeyManagerException
{
try
{
KeyPairGenerator keyGen;
if (provider == null)
{
keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName());
}
else
{
keyGen = KeyPairGenerator.getInstance(keyAlgo.getAlgorithmName(), provider);
}
keyGen.initialize(keyAlgo.algorithmSpec);
return keyGen.generateKeyPair();
}
catch (InvalidAlgorithmParameterException exception)
{
throw new KeyManagerException(
"Invalid algorithm parameter in {0} : {1}", exception,
keyAlgo, exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"No security provider found for {0} : {1}", exception,
keyAlgo, exception.getMessage()
);
}
}
/**
* Returns the key storage type used by this key manager.
*
* @return key storage type
*/
protected Storage getStorageType()
{
return storage;
}
/**
* Checks if key store exists at given file URI.
*
* @param uri
* the file URI to check
*
* @return true if file exists, false otherwise
*
* @throws KeyManagerException
* if security manager has denied access to file information
*/
protected boolean exists(URI uri) throws KeyManagerException
{
File file = new File(uri);
try
{
return file.exists();
}
catch (SecurityException exception)
{
String path = resolveFilePath(file);
throw new KeyManagerException(
"Security manager has prevented access to file ''{0}'' : {1}", exception,
path, exception.getMessage()
);
}
}
/**
* Clears the given password character array with zero values.
*
* @param password
* password character array to erase
*/
protected void clearPassword(char[] password)
{
if (password != null)
{
for (int i = 0; i < password.length; ++i)
{
password[i] = 0;
}
}
}
/**
* Clears the given password byte array with zero values.
*
* @param password
* password byte array to erase
*/
protected void clearPassword(byte[] password)
{
if (password != null)
{
for (int i = 0; i< password.length; ++i)
{
password[i] = 0;
}
}
}
/**
* Stores the key entries of this key manager into a keystore. The keystore is saved to the given
* output stream. The keystore can be an existing, loaded keystore or a new, empty one.
*
* @param keystore
* keystore to add keys from this key manager to
*
* @param out
* the output stream for the keystore (can be used for persisting the keystore to disk)
*
* @param password
* password to access the keystore
*
* @throws KeyManagerException
* if the save operation fails
*/
private void save(KeyStore keystore, OutputStream out, char[] password)
throws KeyManagerException
{
if (password == null || password.length == 0)
{
throw new KeyManagerException(
"Null or empty password. Keystore must be protected with a password."
);
}
BufferedOutputStream bout = new BufferedOutputStream(out);
try
{
keystore.store(bout, password);
}
catch (KeyStoreException exception)
{
throw new KeyManagerException(
"Storing the key pair failed : {0}", exception,
exception.getMessage()
);
}
catch (IOException exception)
{
throw new KeyManagerException(
"Unable to write key to keystore : {0}", exception,
exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
throw new KeyManagerException(
"Security provider does not support required key store algorithm: {0}", exception,
exception.getMessage()
);
}
catch (CertificateException exception)
{
throw new KeyManagerException(
"Cannot store certificate: {0}", exception,
exception.getMessage()
);
}
finally
{
if (bout != null)
{
try
{
bout.flush();
bout.close();
}
catch (IOException exception)
{
securityLog.warn(
"Failed to close file output stream to keystore : {0}", exception,
exception.getMessage()
);
}
}
}
}
/**
* Loads a key store from the given input stream or creates a new instance in case of a
* null input stream. Configured key storage type and security provider instance are used
* to load/create the keystore.
*
* @param file
* file to load the key store from
*
* @param password
* password to access the key store
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
private void loadKeyStore(File file, char[] password) throws ConfigurationException,
KeyManagerException
{
// This is basically just a convenience method to actual implementation
// in loadKeyStore(InputStream, char[])...
if (file == null)
{
throw new KeyManagerException("Implementation Error: null file descriptor.");
}
try
{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
loadKeyStore(in, password);
}
catch (FileNotFoundException exception)
{
throw new KeyManagerException(
"Keystore file ''{0}'' could not be created or opened : {1}", exception,
resolveFilePath(file), exception.getMessage()
);
}
catch (SecurityException exception)
{
throw new KeyManagerException(
"Security manager has denied access to keystore file ''{0}'' : {1}", exception,
resolveFilePath(file), exception.getMessage()
);
}
}
/**
* Loads a key store from the given input stream or creates a new instance in case of a
* null input stream. Configured key storage type and security provider instance are used
* to load/create the keystore.
*
* @param in
* input stream to key store file (or null to create a new one)
*
* @param password
* shared secret (a password) used for protecting access to the key store
*
* @throws ConfigurationException
* if the configured security provider(s) do not contain implementation for the
* required keystore type
*
* @throws KeyManagerException
* if loading or creating the keystore fails
*/
private void loadKeyStore(InputStream in, char[] password) throws ConfigurationException,
KeyManagerException
{
try
{
if (provider == null)
{
// Use system installed security provider...
keystore = KeyStore.getInstance(storage.getStorageName());
}
else
{
keystore = KeyStore.getInstance(storage.getStorageName(), provider);
}
keystore.load(in, password);
}
catch (KeyStoreException exception)
{
// NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested
// NoSuchAlgorithmException. This is the behavior for both SUN default provider
// in Java 6 and BouncyCastle.
if (exception.getCause() != null && exception.getCause() instanceof NoSuchAlgorithmException)
{
String usedProviders;
if (provider == null)
{
usedProviders = Arrays.toString(Security.getProviders());
}
else
{
usedProviders = provider.getName();
}
throw new ConfigurationException(
"The security provider(s) '{0}' do not support keystore type '{1}' : {2}", exception,
usedProviders, storage.name(), exception.getMessage()
);
}
throw new KeyManagerException(
"Cannot load keystore: {0}", exception,
exception.getMessage()
);
}
catch (NoSuchAlgorithmException exception)
{
// If part of the keystore load() the algorithm to verify the keystore contents cannot
// be found...
throw new KeyManagerException(
"Required keystore verification algorithm not found: {0}", exception,
exception.getMessage()
);
}
catch (CertificateException exception)
{
// Can happen if any of the certificates in the store cannot be loaded...
throw new KeyManagerException(
"Can't load keystore: {0}", exception,
exception.getMessage()
);
}
catch (IOException exception)
{
// If there's an I/O problem, or if keystore has been corrupted, or if password is missing
// if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException)
// // The Java 6 javadoc claims that an incorrect password can be detected by having
// // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't
// // seem to be the case or is not working... incorrect password is reported as an
// // IOException just like other I/O errors with no root causes as far as I'm able to
// // tell. So leaving this out for now
// // [JPL]
// throw new PasswordException(
// "Cannot recover keys from keystore (was the provided password correct?) : {0}",
// e.getMessage(), e
// TODO : this error would be improved by reporting file location and keystore type..
throw new KeyManagerException(
"I/O Error: Cannot load keystore: {0}", exception,
exception.getMessage()
);
}
}
/**
* File utility to print file path.
*
* @param file
* file path to print
*
* @return resolves to an absolute file path if allowed by the security manager, if not
* returns the file path as defined in the file object parameter
*/
private String resolveFilePath(File file)
{
try
{
return file.getAbsolutePath();
}
catch (SecurityException e)
{
return file.getPath();
}
}
public enum Storage
{
/**
* PKCS #12 format. Used for storing asymmetric key pairs and X.509 public key certificates.
* Standardized format.
*/
PKCS12,
JCEKS,
/**
* BouncyCastle keystore format which is roughly equivalent to Sun's 'JKS' keystore format
* and implementation, and therefore can be used with the standard Java SDK 'keytool'. <p>
*
* This format is resistant to tampering but not resistant to inspection, therefore in
* typical cases the {@link #UBER} storage format is recommended.
*/
BKS(SecurityProvider.BC),
/**
* Recommended BouncyCastle keystore format. Requires password verification and is
* resistant to inspection and tampering.
*/
UBER(SecurityProvider.BC);
/**
* Reference to the security provider with the implementation of the storage. Can be null
* if no specific provider is used (relying on already installed security providers in the
* JVM).
*/
private SecurityProvider provider = null;
/**
* Constructs a new storage instance without specific security provider.
*/
private Storage()
{
// no op
}
/**
* Constructs a new storage instance linked to a specific security provider.
*
* @param provider
* security provider
*/
private Storage(SecurityProvider provider)
{
this.provider = provider;
}
public String getStorageName()
{
return name();
}
/**
* Returns the security provider instance associated with this storage implementation. Can
* return a null if no specific security provider has been associated with the storage
* instance.
*
* @return security provider instance associated with the storage instance or null if
* no specific provider is used
*/
public Provider getSecurityProvider()
{
return (provider == null)
? null
: provider.getProviderInstance();
}
@Override public String toString()
{
return getStorageName();
}
}
public enum AsymmetricKeyAlgorithm
{
EC(
new ECGenParameterSpec(ASN_OID_STD_CURVE_NSA_NIST_P521),
KeySigner.DEFAULT_EC_SIGNATURE_ALGORITHM
),
RSA(
new RSAKeyGenParameterSpec(DEFAULT_RSA_KEY_SIZE, DEFAULT_RSA_PUBLIC_EXPONENT),
KeySigner.DEFAULT_RSA_SIGNATURE_ALGORITHM
);
/**
* Key generator algorithm configuration parameters.
*/
private AlgorithmParameterSpec algorithmSpec;
/**
* A default signature algorithm associated with this asymmetric key algorithm.
*/
private KeySigner.SignatureAlgorithm defaultSignatureAlgorithm;
/**
* Constructs a new asymmetric key algorithm enum.
*
* @param spec
* algorithm parameters
*
* @param defaultSignatureAlgorithm
* a corresponding default public key signature algorithm to associate with this
* asymmetric key algorithm
*/
private AsymmetricKeyAlgorithm(AlgorithmParameterSpec spec,
KeySigner.SignatureAlgorithm defaultSignatureAlgorithm)
{
this.algorithmSpec = spec;
this.defaultSignatureAlgorithm = defaultSignatureAlgorithm;
}
public String getAlgorithmName()
{
return name();
}
/**
* Returns a default public key signature algorithm that should be used with this asymmetric
* key algorithm.
*
* @return a public key signature algorithm associated with this asymmetric key algorithm
*/
public KeySigner.SignatureAlgorithm getDefaultSignatureAlgorithm()
{
return defaultSignatureAlgorithm;
}
@Override public String toString()
{
return getAlgorithmName();
}
}
/**
* Exception type for the public API of this class to indicate errors.
*/
public static class KeyManagerException extends OpenRemoteException
{
protected KeyManagerException(String msg)
{
super(msg);
}
protected KeyManagerException(String msg, Throwable cause, Object... params)
{
super(msg, cause, params);
}
}
/**
* Specific subclass of KeyManagerException that indicates a security configuration issue.
*/
public static class ConfigurationException extends KeyManagerException
{
protected ConfigurationException(String msg, Throwable cause, Object... params)
{
super(msg, cause, params);
}
}
} |
package ee.ria.DigiDoc.android;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;
import com.google.android.gms.common.util.CollectionUtils;
import com.google.android.gms.tasks.Task;
import com.google.common.collect.ImmutableList;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.firebase.crashlytics.internal.common.CommonUtils;
import java.lang.ref.WeakReference;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import javax.inject.Singleton;
import ee.ria.DigiDoc.R;
import ee.ria.DigiDoc.android.crypto.create.CryptoCreateScreen;
import ee.ria.DigiDoc.android.main.home.HomeScreen;
import ee.ria.DigiDoc.android.main.settings.SettingsDataStore;
import ee.ria.DigiDoc.android.main.sharing.SharingScreen;
import ee.ria.DigiDoc.android.signature.create.SignatureCreateScreen;
import ee.ria.DigiDoc.android.utils.IntentUtils;
import ee.ria.DigiDoc.android.utils.SecureUtil;
import ee.ria.DigiDoc.android.utils.files.FileStream;
import ee.ria.DigiDoc.android.utils.navigator.Navigator;
import ee.ria.DigiDoc.android.utils.navigator.Screen;
import ee.ria.DigiDoc.android.utils.widget.ErrorDialog;
import ee.ria.DigiDoc.common.FileUtil;
import timber.log.Timber;
public final class Activity extends AppCompatActivity {
private Navigator navigator;
private RootScreenFactory rootScreenFactory;
private SettingsDataStore settingsDataStore;
private static WeakReference<Context> mContext;
public SettingsDataStore getSettingsDataStore() {
return settingsDataStore;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
handleRootedDevice();
setTheme(R.style.Theme_Application);
setTitle(""); // ACCESSIBILITY: prevents application name read during each activity launch
super.onCreate(savedInstanceState);
// Prevent screen recording
SecureUtil.markAsSecure(getWindow());
handleCrashOnPreviousExecution();
Intent intent = sanitizeIntent(getIntent());
if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction())) && intent.getType() != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(intent.getAction());
handleIncomingFiles(intent);
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(intent.getAction())) {
getIntent().setAction(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
restartAppWithIntent(intent);
} else if (Intent.ACTION_GET_CONTENT.equals(intent.getAction())) {
rootScreenFactory.intent(intent);
}
else {
// Avoid blank screen on language change
if (savedInstanceState != null) {
restartAppWithIntent(intent);
}
rootScreenFactory.intent(intent);
}
mContext = new WeakReference<>(this);
initializeApplicationFileTypesAssociation();
navigator.onCreate(this, findViewById(android.R.id.content), savedInstanceState);
}
private void handleRootedDevice() {
if (CommonUtils.isRooted(getApplicationContext())) {
ErrorDialog errorDialog = new ErrorDialog(this);
errorDialog.setMessage(getResources().getString(R.string.rooted_device));
errorDialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), (dialog, which) -> dialog.cancel());
errorDialog.show();
}
}
private void handleCrashOnPreviousExecution() {
if (FirebaseCrashlytics.getInstance().didCrashOnPreviousExecution()) {
if (settingsDataStore.getAlwaysSendCrashReport()) {
sendUnsentCrashReports();
return;
}
Dialog crashReportDialog = new Dialog(this);
SecureUtil.markAsSecure(crashReportDialog.getWindow());
crashReportDialog.setContentView(R.layout.crash_report_dialog);
Button sendButton = crashReportDialog.findViewById(R.id.sendButton);
sendButton.setOnClickListener(v -> {
sendUnsentCrashReports();
crashReportDialog.dismiss();
});
Button alwaysSendButton = crashReportDialog.findViewById(R.id.alwaysSendButton);
alwaysSendButton.setOnClickListener(v -> {
settingsDataStore.setAlwaysSendCrashReport(true);
sendUnsentCrashReports();
crashReportDialog.dismiss();
});
Button dontSendButton = crashReportDialog.findViewById(R.id.dontSendButton);
dontSendButton.setOnClickListener(v -> {
crashReportDialog.dismiss();
});
crashReportDialog.show();
}
}
private void sendUnsentCrashReports() {
Task<Boolean> task = FirebaseCrashlytics.getInstance().checkForUnsentReports();
task.addOnSuccessListener(hasUnsentReports -> {
if (hasUnsentReports) {
FirebaseCrashlytics.getInstance().sendUnsentReports();
} else {
FirebaseCrashlytics.getInstance().deleteUnsentReports();
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void restartAppWithIntent(Intent intent) {
finish();
startActivity(intent);
overridePendingTransition (0, 0);
}
private void handleIncomingFiles(Intent intent) {
try {
intent.setDataAndType(intent.getData(), "*/*");
rootScreenFactory.intent(intent);
} catch (ActivityNotFoundException e) {
Timber.e(e, "Handling incoming file intent");
}
}
private Intent sanitizeIntent(Intent intent) {
if (intent.getDataString() != null) {
intent.setData(Uri.parse(FileUtil.sanitizeString(intent.getDataString(), '_')));
}
if (intent.getExtras() != null && !(intent.getExtras().containsKey(Intent.EXTRA_REFERRER) &&
intent.getExtras().get(Intent.EXTRA_REFERRER).equals(R.string.application_name))) {
intent.replaceExtras(new Bundle());
}
return intent;
}
private void initializeApplicationFileTypesAssociation() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isOpenAllTypesEnabled = sharedPreferences.getBoolean(getString(R.string.main_settings_open_all_filetypes_key), true);
PackageManager pm = getApplicationContext().getPackageManager();
ComponentName openAllTypesComponent = new ComponentName(getPackageName(), getClass().getName() + ".OPEN_ALL_FILE_TYPES");
ComponentName openCustomTypesComponent = new ComponentName(getPackageName(), getClass().getName() + ".OPEN_CUSTOM_TYPES");
if (isOpenAllTypesEnabled) {
pm.setComponentEnabledSetting(openAllTypesComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(openCustomTypesComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
} else {
pm.setComponentEnabledSetting(openCustomTypesComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(openAllTypesComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}
@Override
protected void attachBaseContext(Context newBase) {
Application.ApplicationComponent component = Application.component(newBase);
navigator = component.navigator();
rootScreenFactory = component.rootScreenFactory();
settingsDataStore = component.settingsDataStore();
super.attachBaseContext(component.localeService().attachBaseContext(newBase));
}
@Override
public void onBackPressed() {
if (!navigator.onBackPressed()) {
super.onBackPressed();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
navigator.onActivityResult(requestCode, resultCode, data);
}
public static WeakReference<Context> getContext() {
return mContext;
}
@Singleton
static final class RootScreenFactory implements Callable<Screen> {
@Nullable private Intent intent;
@Inject RootScreenFactory() {}
void intent(Intent intent) {
this.intent = intent;
}
@Override
public Screen call() {
if ((intent.getAction() != null && Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction())) && intent.getType() != null) {
return chooseScreen(intent);
} else if (intent.getAction() != null && Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction()) && intent.getType() != null) {
return SignatureCreateScreen.create(intent);
} else if (intent.getAction() != null && Intent.ACTION_GET_CONTENT.equals(intent.getAction())) {
return SharingScreen.create();
}
return HomeScreen.create(intent);
}
private Screen chooseScreen(Intent intent) {
ImmutableList<FileStream> fileStreams = IntentUtils.parseGetContentIntent(getContext().get().getContentResolver(), intent);
if (!CollectionUtils.isEmpty(fileStreams) && fileStreams.size() == 1) {
String fileName = fileStreams.get(0).displayName();
String extension = fileName.substring(fileName.lastIndexOf("."));
if (".cdoc".equalsIgnoreCase(extension)) {
return CryptoCreateScreen.open(intent);
}
}
return SignatureCreateScreen.create(intent);
}
}
} |
package jp.blanktar.ruumusic;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
import android.support.annotation.NonNull;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.media.MediaPlayer;
import android.os.Handler;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.app.PendingIntent;
import android.os.Build;
public class RuuService extends Service {
private File path;
private MediaPlayer player;
private String repeatMode = "off";
private boolean shuffleMode = false;
private boolean ready = false;
private List<File> playlist;
private int currentIndex;
private File currentDir;
@Override
public IBinder onBind(Intent intent) {
throw null;
}
@Override
public void onCreate() {
player = new MediaPlayer();
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
repeatMode = preference.getString("repeat_mode", "off");
shuffleMode = preference.getBoolean("shuffle_mode", false);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (repeatMode.equals("one")) {
player.pause();
play();
} else {
if (playlist == null || currentIndex + 1 >= playlist.size() && repeatMode.equals("off")) {
pause();
} else {
if (shuffleMode) {
shufflePlay();
} else {
play(playlist.get((currentIndex + 1) % playlist.size()));
}
}
}
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
player.reset();
File realName = FileTypeUtil.detectRealName(path);
Intent sendIntent = new Intent();
sendIntent.setAction("RUU_FAILED_OPEN");
sendIntent.putExtra("path", (realName==null ? path : realName).getPath());
getBaseContext().sendBroadcast(sendIntent);
return true;
}
});
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null) {
switch (intent.getAction()) {
case "RUU_PLAY":
play(intent.getStringExtra("path"));
break;
case "RUU_PAUSE":
pause();
break;
case "RUU_SEEK":
seek(intent.getIntExtra("newtime", -1));
break;
case "RUU_REPEAT":
setRepeatMode(intent.getStringExtra("mode"));
break;
case "RUU_SHUFFLE":
setShuffleMode(intent.getBooleanExtra("mode", false));
break;
case "RUU_PING":
sendStatus();
break;
case "RUU_NEXT":
next();
break;
case "RUU_PREV":
prev();
break;
case "RUU_ROOT_CHANGE":
updateRoot();
break;
}
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
removePlayingNotification();
}
private void sendStatus() {
Intent sendIntent = new Intent();
sendIntent.setAction("RUU_STATUS");
if(path != null) {
sendIntent.putExtra("path", path.getPath());
}
sendIntent.putExtra("repeat", repeatMode);
sendIntent.putExtra("shuffle", shuffleMode);
if(ready) {
sendIntent.putExtra("playing", player.isPlaying());
sendIntent.putExtra("duration", player.getDuration());
sendIntent.putExtra("current", player.getCurrentPosition());
sendIntent.putExtra("basetime", System.currentTimeMillis() - player.getCurrentPosition());
}
getBaseContext().sendBroadcast(sendIntent);
}
private Notification makeNotification() {
int playpause_icon = player.isPlaying() ? R.drawable.ic_pause : R.drawable.ic_play_arrow;
String playpause_text = player.isPlaying() ? "pause" : "play";
PendingIntent playpause_pi = PendingIntent.getService(this, 0, (new Intent(this, RuuService.class)).setAction(player.isPlaying() ? "RUU_PAUSE" : "RUU_PLAY"), 0);
PendingIntent prev_pi = PendingIntent.getService(this, 0, (new Intent(this, RuuService.class)).setAction("RUU_PREV"), 0);
PendingIntent next_pi = PendingIntent.getService(this, 0, (new Intent(this, RuuService.class)).setAction("RUU_NEXT"), 0);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
return new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_play_notification)
.setColor(0xff333333)
.setTicker(path.getName())
.setContentTitle(path.getName())
.setContentText(FileTypeUtil.getPathFromRoot(this, path.getParentFile()))
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MIN)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.addAction(R.drawable.ic_skip_previous, "prev", prev_pi)
.addAction(playpause_icon, playpause_text, playpause_pi)
.addAction(R.drawable.ic_skip_next, "next", next_pi)
.build();
}
private void updatePlayingNotification(){
if(!player.isPlaying()) {
return;
}
startForeground(1, makeNotification());
}
private void removePlayingNotification() {
if(player.isPlaying()) {
return;
}
stopForeground(true);
if(Build.VERSION.SDK_INT >= 16) {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(1, makeNotification());
}
}
private void updateRoot() {
if(player.isPlaying()) {
updatePlayingNotification();
}else {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
}
}
private void play() {
if(path != null) {
player.start();
sendStatus();
updatePlayingNotification();
}
}
private void play(String path) {
if(path == null) {
play();
return;
}
play(new File(path));
}
private void play(@NonNull File path) {
if(this.path != null && this.path.equals(path)) {
player.pause();
player.seekTo(0);
play();
return;
}
ready = false;
player.reset();
this.path = path;
File realName = FileTypeUtil.detectRealName(path);
if(realName == null) {
Intent sendIntent = new Intent();
sendIntent.setAction("RUU_NOT_FOUND");
sendIntent.putExtra("path", path.getPath());
getBaseContext().sendBroadcast(sendIntent);
}else {
try {
player.setDataSource(realName.getPath());
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
ready = true;
play();
}
});
player.prepareAsync();
} catch (IOException e) {
Intent sendIntent = new Intent();
sendIntent.setAction("RUU_FAILED_OPEN");
sendIntent.putExtra("path", realName.getPath());
getBaseContext().sendBroadcast(sendIntent);
}
}
File newparent = path.getParentFile();
if(currentDir == null || !currentDir.equals(newparent)) {
currentDir = newparent;
playlist = FileTypeUtil.getMusics(currentDir);
if(shuffleMode) {
shuffleList();
}else {
Collections.sort(playlist);
currentIndex = Arrays.binarySearch(playlist.toArray(), path);
}
}else {
currentIndex = playlist.indexOf(path);
}
}
private void shuffleList() {
if(playlist != null) {
Collections.shuffle(playlist);
Collections.swap(playlist, 0, playlist.indexOf(path));
currentIndex = 0;
}
}
private void shufflePlay() {
if(playlist != null) {
do {
Collections.shuffle(playlist);
} while (playlist.get(0).equals(path));
currentIndex = 0;
play(playlist.get(0));
}
}
private void pause() {
player.pause();
sendStatus();
removePlayingNotification();
}
private void seek(int newtime) {
if(0 <= newtime && newtime <= player.getDuration()) {
player.seekTo(newtime);
sendStatus();
}
}
private void setRepeatMode(@NonNull String mode) {
if(mode.equals("off") || mode.equals("loop") || mode.equals("one")) {
repeatMode = mode;
sendStatus();
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("repeat_mode", repeatMode)
.apply();
}
}
private void setShuffleMode(boolean mode) {
if(playlist != null) {
if (!shuffleMode && mode) {
shuffleList();
}
if (shuffleMode && !mode) {
Collections.sort(playlist);
currentIndex = Arrays.binarySearch(playlist.toArray(), path);
}
}
shuffleMode = mode;
sendStatus();
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean("shuffle_mode", shuffleMode)
.apply();
}
private void next() {
if(playlist != null) {
if (currentIndex + 1 < playlist.size()) {
play(playlist.get(currentIndex + 1));
} else if (repeatMode.equals("loop")) {
if (shuffleMode) {
shufflePlay();
} else {
play(playlist.get(0));
}
} else {
showToast(getString(R.string.last_of_directory));
}
}
}
private void prev() {
if(playlist != null) {
if (currentIndex > 0) {
play(playlist.get(currentIndex - 1));
} else if (repeatMode.equals("loop")) {
if (shuffleMode) {
shufflePlay();
} else {
play(playlist.get(playlist.size() - 1));
}
} else {
showToast(getString(R.string.first_of_directory));
}
}
}
private void showToast(@NonNull final String message) {
final Handler handler = new Handler();
(new Thread(new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RuuService.this, message, Toast.LENGTH_LONG).show();
}
});
}
})).start();
}
} |
package org.swingeasy;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Locale;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JTextField;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;
/**
* @author Jurgen
*/
public class EListFilterComponent<T> extends ELabeledTextFieldButtonComponent implements TextFilterator<EListRecord<T>> {
private static final long serialVersionUID = -8699648472825404199L;
protected EList<T> eList;
protected EListI<T> sList;
protected EventList<EListRecord<T>> tmprecords;
protected TextComponentMatcherEditor<EListRecord<T>> filter;
public EListFilterComponent(EventList<EListRecord<T>> records) {
this.createComponent();
this.filter = new TextComponentMatcherEditor<EListRecord<T>>(JTextField.class.cast(this.getInput()), this, false);
this.tmprecords = new FilterList<EListRecord<T>>(records, this.filter);
}
/**
*
* @see org.swingeasy.EComponentPopupMenu.ReadableComponent#copy(java.awt.event.ActionEvent)
*/
@Override
public void copy(ActionEvent e) {
// TODO implement
}
/**
*
* @see org.swingeasy.ELabeledTextFieldButtonComponent#doAction()
*/
@Override
protected void doAction() {
this.filter.setFilterText(new String[] { JTextField.class.cast(this.getInput()).getText() });
}
/**
*
* @see org.swingeasy.ELabeledTextFieldButtonComponent#getAction()
*/
@Override
protected String getAction() {
return "filter";
}
/**
*
* @see ca.odell.glazedlists.TextFilterator#getFilterStrings(java.util.List, java.lang.Object)
*/
@Override
public void getFilterStrings(List<String> baseList, EListRecord<T> element) {
if (element != null) {
baseList.add(element.getStringValue());
}
}
/**
*
* @see org.swingeasy.ELabeledTextFieldButtonComponent#getIcon()
*/
@Override
protected Icon getIcon() {
return Resources.getImageResource("magnifier.png");
}
/**
*
* @see org.swingeasy.HasParentComponent#getParentComponent()
*/
@Override
public JComponent getParentComponent() {
return this;
}
protected EventList<EListRecord<T>> grabRecords() {
EventList<EListRecord<T>> _records = this.tmprecords;
this.tmprecords = null;
return _records;
}
/**
* @see ca.odell.glazedlists.swing.TextComponentMatcherEditor#isLive()
*/
public boolean isLive() {
return this.filter.isLive();
}
protected void setList(EList<T> eList) {
this.eList = eList;
this.sList = eList.stsi();
}
/**
* @see ca.odell.glazedlists.swing.TextComponentMatcherEditor#setLive(boolean)
*/
public void setLive(boolean live) {
this.filter.setLive(live);
}
/**
*
* @see java.awt.Component#setLocale(java.util.Locale)
*/
@Override
public void setLocale(Locale l) {
super.setLocale(l);
this.getButton().setToolTipText(Messages.getString(l, "EList.FilterComponent.filter"));//$NON-NLS-1$
this.getLabel().setText(Messages.getString(l, "EList.FilterComponent.filter") + ": ");//$NON-NLS-1$ //$NON-NLS-2$
}
} |
package org.teamstbf.yats.ui;
import java.util.logging.Logger;
import org.teamstbf.yats.commons.core.LogsCenter;
import org.teamstbf.yats.commons.events.ui.EventPanelSelectionChangedEvent;
import org.teamstbf.yats.commons.util.FxViewUtil;
import org.teamstbf.yats.model.item.ReadOnlyEvent;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
/**
* Panel containing the list of persons.
*/
public class TaskListPanel extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(TaskListPanel.class);
private static final String FXML = "PersonListPanel.fxml";
@FXML
private ListView<ReadOnlyEvent> personListView;
public TaskListPanel(AnchorPane eventListPlaceholder, ObservableList<ReadOnlyEvent> observableList) {
super(FXML);
setConnections(observableList);
addToPlaceholder(eventListPlaceholder);
}
private void setConnections(ObservableList<ReadOnlyEvent> observableList) {
personListView.setItems(observableList);
personListView.setCellFactory(listView -> new PersonListViewCell());
setEventHandlerForSelectionChangeEvent();
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
placeHolderPane.getChildren().add(getRoot());
}
private void setEventHandlerForSelectionChangeEvent() {
personListView.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
logger.fine("Selection in task list panel changed to : '" + newValue + "'");
raise(new EventPanelSelectionChangedEvent(newValue));
}
});
}
public void scrollTo(int index) {
Platform.runLater(() -> {
personListView.scrollTo(index);
personListView.getSelectionModel().clearAndSelect(index);
});
}
class PersonListViewCell extends ListCell<ReadOnlyEvent> {
@Override
protected void updateItem(ReadOnlyEvent person, boolean empty) {
super.updateItem(person, empty);
if (empty || person == null) {
setGraphic(null);
setText(null);
} else {
setGraphic(new TaskCard(person, getIndex() + 1).getRoot());
}
}
}
} |
package org.testng.internal;
import org.testng.IClass;
import org.testng.IRetryAnalyzer;
import org.testng.ITestClass;
import org.testng.ITestNGMethod;
import org.testng.annotations.ITestOrConfiguration;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.thread.IAtomicInteger;
import org.testng.internal.thread.ThreadUtil;
import org.testng.xml.XmlTest;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Superclass to represent both @Test and @Configuration methods.
*/
public abstract class BaseTestMethod implements ITestNGMethod {
private static final long serialVersionUID = -2666032602580652173L;
/**
* The test class on which the test method was found. Note that this is not
* necessarily the declaring class.
*/
protected ITestClass m_testClass;
protected final transient Class<?> m_methodClass;
protected final transient ConstructorOrMethod m_method;
protected String m_id = "";
protected long m_date = -1;
protected final transient IAnnotationFinder m_annotationFinder;
protected String[] m_groups = {};
protected String[] m_groupsDependedUpon = {};
protected String[] m_methodsDependedUpon = {};
protected String[] m_beforeGroups = {};
protected String[] m_afterGroups = {};
private boolean m_isAlwaysRun;
private boolean m_enabled;
private final String m_methodName;
// If a depended group is not found
private String m_missingGroup;
private String m_description = null;
protected IAtomicInteger m_currentInvocationCount = ThreadUtil.createAtomicInteger(0);
private int m_parameterInvocationCount = 1;
private IRetryAnalyzer m_retryAnalyzer = null;
private boolean m_skipFailedInvocations = true;
private long m_invocationTimeOut = 0L;
private List<Integer> m_invocationNumbers = Lists.newArrayList();
private List<Integer> m_failedInvocationNumbers = Lists.newArrayList();
/**
* {@inheritDoc}
*/
private long m_timeOut = 0;
private boolean m_ignoreMissingDependencies;
private int m_priority;
private XmlTest m_xmlTest;
private Object m_instance;
/**
* Constructs a <code>BaseTestMethod</code> TODO cquezel JavaDoc.
*
* @param method
* @param annotationFinder
* @param instance
*/
public BaseTestMethod(Method method, IAnnotationFinder annotationFinder, Object instance) {
this(new ConstructorOrMethod(method), annotationFinder, instance);
}
public BaseTestMethod(ConstructorOrMethod com, IAnnotationFinder annotationFinder,
Object instance) {
m_methodClass = com.getDeclaringClass();
m_method = com;
m_methodName = com.getName();
m_annotationFinder = annotationFinder;
m_instance = instance;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAlwaysRun() {
return m_isAlwaysRun;
}
/**
* TODO cquezel JavaDoc.
*
* @param alwaysRun
*/
protected void setAlwaysRun(boolean alwaysRun) {
m_isAlwaysRun = alwaysRun;
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getRealClass() {
return m_methodClass;
}
/**
* {@inheritDoc}
*/
@Override
public ITestClass getTestClass() {
return m_testClass;
}
/**
* {@inheritDoc}
*/
@Override
public void setTestClass(ITestClass tc) {
assert null != tc;
if (! tc.getRealClass().equals(m_method.getDeclaringClass())) {
assert m_method.getDeclaringClass().isAssignableFrom(tc.getRealClass()) :
"\nMISMATCH : " + tc.getRealClass() + " " + m_method.getDeclaringClass();
}
m_testClass = tc;
}
/**
* TODO cquezel JavaDoc.
*
* @param o
* @return
*/
@Override
public int compareTo(Object o) {
int result = -2;
Class<?> thisClass = getRealClass();
Class<?> otherClass = ((ITestNGMethod) o).getRealClass();
if (thisClass.isAssignableFrom(otherClass)) {
result = -1;
} else if (otherClass.isAssignableFrom(thisClass)) {
result = 1;
} else if (equals(o)) {
result = 0;
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public Method getMethod() {
return m_method.getMethod();
}
/**
* {@inheritDoc}
*/
@Override
public String getMethodName() {
return m_methodName;
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getInstances() {
return new Object[] { getInstance() };
}
@Override
public Object getInstance() {
return m_instance;
}
/**
* {@inheritDoc}
*/
@Override
public long[] getInstanceHashCodes() {
return m_testClass.getInstanceHashCodes();
}
/**
* {@inheritDoc}
* @return the addition of groups defined on the class and on this method.
*/
@Override
public String[] getGroups() {
return m_groups;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getGroupsDependedUpon() {
return m_groupsDependedUpon;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getMethodsDependedUpon() {
return m_methodsDependedUpon;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTest() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBeforeSuiteConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAfterSuiteConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBeforeTestConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAfterTestConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBeforeGroupsConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAfterGroupsConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBeforeClassConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAfterClassConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isBeforeMethodConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAfterMethodConfiguration() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public long getTimeOut() {
long result = m_timeOut != 0 ? m_timeOut : (m_xmlTest != null ? m_xmlTest.getTimeOut(0) : 0);
return result;
}
@Override
public void setTimeOut(long timeOut) {
m_timeOut = timeOut;
}
/**
* {@inheritDoc}
* @return the number of times this method needs to be invoked.
*/
@Override
public int getInvocationCount() {
return 1;
}
/**
* No-op.
*/
@Override
public void setInvocationCount(int counter) {
}
/**
* {@inheritDoc} Default value for successPercentage.
*/
@Override
public int getSuccessPercentage() {
return 100;
}
/**
* {@inheritDoc}
*/
@Override
public String getId() {
return m_id;
}
/**
* {@inheritDoc}
*/
@Override
public void setId(String id) {
m_id = id;
}
/**
* {@inheritDoc}
* @return Returns the date.
*/
@Override
public long getDate() {
return m_date;
}
/**
* {@inheritDoc}
* @param date The date to set.
*/
@Override
public void setDate(long date) {
m_date = date;
}
/**
* {@inheritDoc}
*/
@Override
public boolean canRunFromClass(IClass testClass) {
return m_methodClass.isAssignableFrom(testClass.getRealClass());
}
/**
* {@inheritDoc} Compares two BaseTestMethod using the test class then the associated
* Java Method.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BaseTestMethod other = (BaseTestMethod) obj;
boolean isEqual = m_testClass == null ? other.m_testClass == null
: other.m_testClass != null &&
m_testClass.getRealClass().equals(other.m_testClass.getRealClass())
&& m_instance == other.getInstance();
return isEqual && getConstructorOrMethod().equals(other.getConstructorOrMethod());
}
/**
* {@inheritDoc} This implementation returns the associated Java Method's hash code.
* @Return the associated Java Method's hash code.
*/
@Override
public int hashCode() {
return m_method.hashCode();
}
/**
* TODO cquezel JavaDoc.
*
* @param annotationClass
*/
protected void initGroups(Class<?> annotationClass) {
// Init groups
{
ITestOrConfiguration annotation =
(ITestOrConfiguration) getAnnotationFinder().findAnnotation(getMethod(),
annotationClass);
ITestOrConfiguration classAnnotation =
(ITestOrConfiguration) getAnnotationFinder().findAnnotation(getMethod().getDeclaringClass(),
annotationClass);
setGroups(getStringArray(null != annotation ? annotation.getGroups() : null,
null != classAnnotation ? classAnnotation.getGroups() : null));
}
// Init groups depended upon
{
ITestOrConfiguration annotation =
(ITestOrConfiguration) getAnnotationFinder().findAnnotation(getMethod(),
annotationClass);
ITestOrConfiguration classAnnotation =
(ITestOrConfiguration) getAnnotationFinder().findAnnotation(getMethod().getDeclaringClass(),
annotationClass);
setGroupsDependedUpon(
getStringArray(null != annotation ? annotation.getDependsOnGroups() : null,
null != classAnnotation ? classAnnotation.getDependsOnGroups() : null));
String[] methodsDependedUpon =
getStringArray(null != annotation ? annotation.getDependsOnMethods() : null,
null != classAnnotation ? classAnnotation.getDependsOnMethods() : null);
// Qualify these methods if they don't have a package
for (int i = 0; i < methodsDependedUpon.length; i++) {
String m = methodsDependedUpon[i];
if (m.indexOf(".") < 0) {
m = MethodHelper.calculateMethodCanonicalName(m_methodClass, methodsDependedUpon[i]);
methodsDependedUpon[i] = m != null ? m : methodsDependedUpon[i];
}
}
setMethodsDependedUpon(methodsDependedUpon);
}
}
/**
* TODO cquezel JavaDoc.
*
* @return
*/
protected IAnnotationFinder getAnnotationFinder() {
return m_annotationFinder;
}
/**
* TODO cquezel JavaDoc.
*
* @return
*/
protected IClass getIClass() {
return m_testClass;
}
/**
* TODO cquezel JavaDoc.
*
* @return
*/
protected String getSignature() {
String classLong = m_method.getDeclaringClass().getName();
String cls = classLong.substring(classLong.lastIndexOf(".") + 1);
StringBuffer result = new StringBuffer(cls + "." + m_method.getName() + "(");
int i = 0;
for (Class<?> p : m_method.getParameterTypes()) {
if (i++ > 0) {
result.append(", ");
}
result.append(p.getName());
}
result.append(")");
result.append("[pri:" + getPriority() + ", instance:" + m_instance + "]");
return result.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return getSignature();
}
/**
* TODO cquezel JavaDoc.
*
* @param methodArray
* @param classArray
* @return
*/
protected String[] getStringArray(String[] methodArray, String[] classArray) {
Map<String, String> vResult = Maps.newHashMap();
if (null != methodArray) {
for (String m : methodArray) {
vResult.put(m, m);
}
}
if (null != classArray) {
for (String m : classArray) {
vResult.put(m, m);
}
}
return vResult.values().toArray(new String[vResult.size()]);
}
protected void setGroups(String[] groups) {
m_groups = groups;
}
protected void setGroupsDependedUpon(String[] groups) {
m_groupsDependedUpon = groups;
}
protected void setMethodsDependedUpon(String[] methods) {
m_methodsDependedUpon = methods;
}
/**
* {@inheritDoc}
*/
@Override
public void addMethodDependedUpon(String method) {
String[] newMethods = new String[m_methodsDependedUpon.length + 1];
newMethods[0] = method;
for (int i =1; i < newMethods.length; i++) {
newMethods[i] = m_methodsDependedUpon[i - 1];
}
m_methodsDependedUpon = newMethods;
}
private static void ppp(String s) {
System.out.println("[BaseTestMethod] " + s);
}
/** Compares two ITestNGMethod by date. */
public static final Comparator<?> DATE_COMPARATOR = new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
try {
ITestNGMethod m1 = (ITestNGMethod) o1;
ITestNGMethod m2 = (ITestNGMethod) o2;
return (int) (m1.getDate() - m2.getDate());
}
catch(Exception ex) {
return 0; // TODO CQ document this logic
}
}
};
/**
* {@inheritDoc}
*/
@Override
public String getMissingGroup() {
return m_missingGroup;
}
/**
* {@inheritDoc}
*/
@Override
public void setMissingGroup(String group) {
m_missingGroup = group;
}
/**
* {@inheritDoc}
*/
@Override
public int getThreadPoolSize() {
return 0;
}
/**
* No-op.
* @param threadPoolSize
*/
@Override
public void setThreadPoolSize(int threadPoolSize) {
}
/**
* TODO cquezel JavaDoc.
*
* @param description
*/
public void setDescription(String description) {
m_description = description;
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return m_description;
}
public void setEnabled(boolean enabled) {
m_enabled = enabled;
}
@Override
public boolean getEnabled() {
return m_enabled;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getBeforeGroups() {
return m_beforeGroups;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getAfterGroups() {
return m_afterGroups;
}
@Override
public void incrementCurrentInvocationCount() {
m_currentInvocationCount.incrementAndGet();
}
@Override
public int getCurrentInvocationCount() {
return m_currentInvocationCount.get();
}
@Override
public void setParameterInvocationCount(int n) {
m_parameterInvocationCount = n;
}
@Override
public int getParameterInvocationCount() {
return m_parameterInvocationCount;
}
@Override
public abstract ITestNGMethod clone();
@Override
public IRetryAnalyzer getRetryAnalyzer() {
return m_retryAnalyzer;
}
@Override
public void setRetryAnalyzer(IRetryAnalyzer retryAnalyzer) {
m_retryAnalyzer = retryAnalyzer;
}
@Override
public boolean skipFailedInvocations() {
return m_skipFailedInvocations;
}
@Override
public void setSkipFailedInvocations(boolean s) {
m_skipFailedInvocations = s;
}
public void setInvocationTimeOut(long timeOut) {
m_invocationTimeOut = timeOut;
}
@Override
public long getInvocationTimeOut() {
return m_invocationTimeOut;
}
@Override
public boolean ignoreMissingDependencies() {
return m_ignoreMissingDependencies;
}
@Override
public void setIgnoreMissingDependencies(boolean i) {
m_ignoreMissingDependencies = i;
}
@Override
public List<Integer> getInvocationNumbers() {
return m_invocationNumbers;
}
@Override
public void setInvocationNumbers(List<Integer> numbers) {
m_invocationNumbers = numbers;
}
@Override
public List<Integer> getFailedInvocationNumbers() {
return m_failedInvocationNumbers;
}
@Override
public void addFailedInvocationNumber(int number) {
m_failedInvocationNumbers.add(number);
}
@Override
public int getPriority() {
return m_priority;
}
@Override
public void setPriority(int priority) {
m_priority = priority;
}
@Override
public XmlTest getXmlTest() {
return m_xmlTest;
}
public void setXmlTest(XmlTest xmlTest) {
m_xmlTest = xmlTest;
}
@Override
public ConstructorOrMethod getConstructorOrMethod() {
return m_method;
}
} |
package org.unidle.config;
import de.bripkens.gravatar.DefaultImage;
import de.bripkens.gravatar.Gravatar;
import de.bripkens.gravatar.Rating;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
import org.unidle.service.LocationService;
import org.unidle.web.BuildTimestampInterceptor;
import org.unidle.web.LocationHandlerMethodArgumentResolver;
import java.util.List;
@ComponentScan("org.unidle.controller")
@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Value("${unidle.build.timestamp}")
private String buildTimestamp;
@Value("${unidle.gravatar.https}")
private boolean gravatarHttps;
@Value("${unidle.gravatar.rating}")
private Rating gravatarRating;
@Value("${unidle.gravatar.size}")
private int gravatarSize;
@Value("${unidle.gravatar.defaultImage}")
private DefaultImage gravatarStandardDefaultImages;
@Autowired
private LocationService locationService;
@Value("${unidle.resource.cachePeriod}")
private int resourceCachePeriod;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Override
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(locationHandlerMethodArgumentResolver());
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(buildTimestampInterceptor());
}
@Bean
public HandlerInterceptor buildTimestampInterceptor() {
return new BuildTimestampInterceptor(buildTimestamp);
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) { |
package permafrost.tundra.data;
import com.wm.app.b2b.server.ServiceException;
import com.wm.data.IData;
import com.wm.data.IDataCursor;
import com.wm.data.IDataFactory;
import com.wm.data.IDataPortable;
import com.wm.data.IDataUtil;
import com.wm.util.Table;
import com.wm.util.coder.IDataCodable;
import com.wm.util.coder.ValuesCodable;
import permafrost.tundra.flow.ConditionEvaluator;
import permafrost.tundra.flow.variable.SubstitutionHelper;
import permafrost.tundra.lang.ArrayHelper;
import permafrost.tundra.lang.ObjectHelper;
import permafrost.tundra.lang.StringHelper;
import permafrost.tundra.time.DateTimeHelper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A collection of convenience methods for working with IData objects.
*/
public final class IDataHelper {
/**
* Disallow instantiation of this class.
*/
private IDataHelper() {}
/**
* Returns all the keys in the given IData document.
*
* @param document An IData document to retrieve the keys from.
* @return The list of keys present in the given IData document.
*/
public static String[] getKeys(IData document) {
return getKeys(document, (Pattern)null);
}
/**
* Returns the keys that match the given regular expression pattern in the given IData document.
*
* @param document An IData document to retrieve the keys from.
* @param patternString A regular expression pattern which the returned set of keys must match.
* @return The list of keys present in the given IData document that match the given regular expression pattern.
*/
public static String[] getKeys(IData document, String patternString) {
return getKeys(document, patternString == null ? null : Pattern.compile(patternString));
}
/**
* Returns the keys that match the given regular expression pattern in the given IData document.
*
* @param document An IData document to retrieve the keys from.
* @param pattern A regular expression pattern which the returned set of keys must match.
* @return The list of keys present in the given IData document that match the given regular expression pattern.
*/
public static String[] getKeys(IData document, Pattern pattern) {
java.util.List<String> keys = new java.util.ArrayList<String>(size(document));
for (Map.Entry<String, Object> entry : IDataMap.of(document)) {
String key = entry.getKey();
if (pattern == null) {
keys.add(key);
} else {
Matcher matcher = pattern.matcher(key);
if (matcher.matches()) keys.add(key);
}
}
return keys.toArray(new String[keys.size()]);
}
/**
* Returns all the top-level values from the given document.
*
* @param document An IData document from which to return all values.
* @return The list of top-level values present in the given IData document.
*/
public static Object[] getValues(IData document) {
List<Object> values = new ArrayList<Object>(size(document));
for (Map.Entry<String, Object> entry : IDataMap.of(document)) {
values.add(entry.getValue());
}
return ArrayHelper.normalize(values);
}
/**
* Returns all leaf values from the given document.
*
* @param document The document to getLeafValues.
* @return All leaf values recursively collected from the given document and its children.
*/
public static Object[] getLeafValues(IData document) {
return getLeafValues(document, new Class[0]);
}
/**
* Returns all leaf values that are instances of the given classes from the given document.
*
* @param document The document to getLeafValues.
* @param classes List of classes the returned values must be instances of.
* @return All leaf values recursively collected from the given document and its children.
*/
public static Object[] getLeafValues(IData document, Class... classes) {
Object[] values = ArrayHelper.normalize(getLeafValues(new ArrayList<Object>(), document, classes).toArray());
if (values != null && values.length > 0) {
return values;
} else {
return null;
}
}
/**
* Returns all leaf values from the given document list.
*
* @param array The document list to getLeafValues.
* @return All leaf values recursively collected from the given document list and its children.
*/
public static Object[] getLeafValues(IData[] array) {
return getLeafValues(array, new Class[0]);
}
/**
* Returns all leaf values that are instances of the given classes from the given document list.
*
* @param array The document list to getLeafValues.
* @param classes List of classes the returned values must be instances of.
* @return All leaf values recursively collected from the given document list and its children.
*/
public static Object[] getLeafValues(IData[] array, Class... classes) {
Object[] values = ArrayHelper.normalize(getLeafValues(new ArrayList<Object>(), array, classes).toArray());
if (values != null && values.length > 0) {
return values;
} else {
return null;
}
}
/**
* Determine if IData leaves/children should be recursed.
*
* @param classes The list of classes the leaves are required to be instances of.
* @return True if IData leaves should be recursed.
*/
private static boolean recurseIDataLeaves(Class ... classes) {
boolean recurse = true;
// if one of the requested classes is an IData compatible class, then we shouldn't recurse IData documents
if (classes != null && classes.length > 0) {
for (Class klass : classes) {
if (klass != null && (klass == IData.class || klass == IDataCodable.class || klass == IDataPortable.class || klass == ValuesCodable.class)) {
recurse = false;
break;
}
}
}
return recurse;
}
/**
* Returns all leaf values that are instances of the given classes from the given top-level IData.
*
* @param values The list to add the flattened values to.
* @param value The IData to getLeafValues.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, IData value, Class... classes) {
return getLeafValues(values, value, recurseIDataLeaves(classes), classes);
}
/**
* Returns all leaf values that are instances of the given classes from the given IData[].
*
* @param values The list to add the flattened values to.
* @param value The IData[] to getLeafValues.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, IData[] value, Class... classes) {
return getLeafValues(values, value, recurseIDataLeaves(classes), classes);
}
/**
* Returns all leaf values that are instances of the given classes from the given IData.
*
* @param values The list to add the flattened values to.
* @param value The IData to getLeafValues.
* @param recurse If true, all IData objects will be recursed to construct the list of leaf values.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, IData value, boolean recurse, Class... classes) {
for (Map.Entry<String, Object> entry : IDataMap.of(value)) {
values = getLeafValues(values, entry.getValue(), recurse, classes);
}
return values;
}
/**
* Returns all leaf values that are instances of the given classes from the given IData[].
*
* @param values The list to add the flattened values to.
* @param value The IData[] to getLeafValues.
* @param recurse If true, all IData objects will be recursed to construct the list of leaf values.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, IData[] value, boolean recurse, Class... classes) {
for (IData item : value) {
values = getLeafValues(values, item, recurse, classes);
}
return values;
}
/**
* Returns all leaf values that are instances of the given classes from the given Object[][].
*
* @param values The list to add the flattened values to.
* @param value The Object[][] to getLeafValues.
* @param recurse If true, all IData objects will be recursed to construct the list of leaf values.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, Object[][] value, boolean recurse, Class... classes) {
for (Object[] array : value) {
values = getLeafValues(values, array, recurse, classes);
}
return values;
}
/**
* Returns all leaf values that are instances of the given classes from the given Object[].
*
* @param values The list to add the flattened values to.
* @param value The Object[] to getLeafValues.
* @param recurse If true, all IData objects will be recursed to construct the list of leaf values.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, Object[] value, boolean recurse, Class... classes) {
for (Object item : value) {
values = getLeafValues(values, item, recurse, classes);
}
return values;
}
/**
* Returns all leaf values that are instances of the given classes from the given Object.
*
* @param values The list to add the flattened values to.
* @param value The Object to getLeafValues.
* @param recurse If true, all IData objects will be recursed to construct the list of leaf values.
* @param classes List of classes the returned values must be instances of.
* @return The list of flattened values.
*/
private static List<Object> getLeafValues(List<Object> values, Object value, boolean recurse, Class... classes) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
values = getLeafValues(values, toIDataArray(value), recurse, classes);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = toIData(value);
if (recurse) {
values = getLeafValues(values, toIData(value), recurse, classes);
} else {
values.add(value);
}
} else if (value instanceof Object[][]) {
values = getLeafValues(values, (Object[][])value, recurse, classes);
} else if (value instanceof Object[]) {
values = getLeafValues(values, (Object[])value, recurse, classes);
} else {
if (classes == null || classes.length == 0) {
values.add(value);
} else {
for (Class klass : classes) {
if (klass != null && klass.isInstance(value)) {
values.add(value);
break;
}
}
}
}
return values;
}
/**
* Merges multiple IData documents into a single new IData document.
*
* @param documents One or more IData documents to be merged.
* @return A new IData document containing the keys and values from all merged input documents.
*/
public static IData merge(IData... documents) {
IData output = IDataFactory.create();
if (documents != null) {
for (IData document : documents) {
if (document != null) {
IDataUtil.merge(document, output);
}
}
}
return output;
}
/**
* Merges multiple IData documents into a single new IData document.
*
* @param recurse If true, a recursive merge is performed.
* @param documents One or more IData documents to be merged.
* @return A new IData document containing the keys and values from all merged input documents.
*/
public static IData merge(boolean recurse, IData... documents) {
IData output = IDataFactory.create();
if (documents != null) {
for (IData document : documents) {
if (document != null) {
IDataCursor documentCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
try {
while(documentCursor.next()) {
String key = documentCursor.getKey();
Object value = documentCursor.getValue();
Object existingValue = IDataUtil.get(outputCursor, key);
if (value != null) {
if (recurse &&
(value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) &&
(existingValue instanceof IData || existingValue instanceof IDataCodable || existingValue instanceof IDataPortable || existingValue instanceof ValuesCodable)) {
IDataUtil.put(outputCursor, key, merge(recurse, toIData(existingValue), toIData(value)));
} else {
IDataUtil.put(outputCursor, key, value);
}
}
}
} finally {
documentCursor.destroy();
outputCursor.destroy();
}
}
}
}
return output;
}
/**
* Returns the number of top-level key value pairs in the given IData document.
*
* @param document An IData document.
* @return The number of key value pairs in the given IData document.
*/
public static int size(IData document) {
int size = 0;
if (document != null) {
IDataCursor cursor = document.getCursor();
size = IDataUtil.size(cursor);
cursor.destroy();
}
return size;
}
/**
* Returns the number of occurrences of the given key in the given IData document.
*
* @param document An IData document.
* @param key The key whose occurrences are to be counted.
* @return The number of occurrences of the given key in the given IData document.
*/
public static int size(IData document, String key) {
return size(document, key, false);
}
/**
* Returns the number of occurrences of the given key in the given IData document.
*
* @param document An IData document.
* @param key The key whose occurrences are to be counted.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The number of occurrences of the given key in the given IData document.
*/
public static int size(IData document, String key, boolean literal) {
int size = 0;
if (document != null && key != null) {
IDataCursor cursor = document.getCursor();
if (cursor.first(key)) {
size++;
while (cursor.next(key)) size++;
} else if (IDataKey.isFullyQualified(key, literal)) {
size = size(document, IDataKey.of(key, literal));
}
cursor.destroy();
}
return size;
}
/**
* Returns the number of occurrences of the given fully-qualified key in the given IData document.
*
* @param document An IData document.
* @param key The parsed fully-qualified key whose occurrences are to be counted.
* @return The number of occurrences of the given parsed fully-qualified key in the given IData document.
*/
private static int size(IData document, IDataKey key) {
int size = 0;
if (document != null && key != null && key.size() > 0) {
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
size = size(ArrayHelper.get(toIDataArray(IDataUtil.get(cursor, keyPart.getKey())), keyPart.getIndex()), key);
} else if (keyPart.hasKeyIndex()) {
size = size(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key);
} else {
size = size(toIData(IDataUtil.get(cursor, keyPart.getKey())), key);
}
} else {
if (keyPart.hasArrayIndex()) {
Object[] array = IDataUtil.getObjectArray(cursor, keyPart.getKey());
if (array != null && array.length > keyPart.getIndex()) {
size = 1;
}
} else if (keyPart.hasKeyIndex()) {
size = size(document, keyPart.getKey(), keyPart.getIndex());
} else {
while (cursor.next(keyPart.getKey())) size++;
}
}
cursor.destroy();
}
return size;
}
/**
* Returns the number of occurrences of the given nth key in the given IData document.
*
* @param document An IData document.
* @param key The key whose occurrence is to be counted.
* @param n The nth occurrence to be counted.
* @return The number of occurrences of the given nth key in the given IData document.
*/
private static int size(IData document, String key, int n) {
int size = 0;
if (document != null && key != null && n >= 0) {
int i = 0;
IDataCursor cursor = document.getCursor();
while (cursor.next(key) && i++ < n) ;
if (i > n) size = 1;
cursor.destroy();
}
return size;
}
/**
* Returns true if the given key exists in the given IData document.
*
* @param document An IData document.
* @param key The key to check the existence of.
* @return True if the given key exists in the given IData document.
*/
public static boolean exists(IData document, String key) {
return exists(document, key, false);
}
/**
* Returns true if the given key exists in the given IData document.
*
* @param document An IData document.
* @param key The key to check the existence of.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return True if the given key exists in the given IData document.
*/
public static boolean exists(IData document, String key, boolean literal) {
return size(document, key, literal) > 0;
}
/**
* Removes the given key from the given IData document, returning the associated value if one exists.
*
* @param document The document to remove the key from.
* @param key The key to remove.
* @return The value that was associated with the given key.
*/
public static Object remove(IData document, String key) {
return remove(document, key, false);
}
/**
* Removes the given key from the given IData document, returning the associated value if one exists.
*
* @param document The document to remove the key from.
* @param key The key to remove.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The value that was associated with the given key.
*/
public static Object remove(IData document, String key, boolean literal) {
Object value = get(document, key, literal);
drop(document, key, literal);
return value;
}
/**
* Removes all occurrences of the given key from the given IData document, returning the associated values if there
* were any.
*
* @param document The document to remove the key from.
* @param key The key to remove.
* @return The values that were associated with the given key.
*/
public static Object[] removeAll(IData document, String key) {
return removeAll(document, key, false);
}
/**
* Removes all occurrences of the given key from the given IData document, returning the associated values if there
* were any.
*
* @param document The document to remove the key from.
* @param key The key to remove.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The values that were associated with the given key.
*/
public static Object[] removeAll(IData document, String key, boolean literal) {
Object[] value = getAsArray(document, key, literal);
dropAll(document, key, literal);
return value;
}
/**
* Returns a recursive clone of the given IData document.
*
* @param document An IData document to be duplicated.
* @return A new IData document which is a copy of the given IData document.
*/
public static IData duplicate(IData document) {
return duplicate(document, true);
}
/**
* Returns a clone of the given IData document.
*
* @param document An IData document to be duplicated.
* @param recurse When true, nested IData documents and IData[] document lists will also be duplicated.
* @return A new IData document which is a copy of the given IData document.
*/
public static IData duplicate(IData document, boolean recurse) {
IData output = null;
try {
if (document != null) {
if (recurse) {
output = IDataUtil.deepClone(document);
} else {
output = IDataUtil.clone(document);
}
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return output;
}
/**
* Removes the value with the given key from the given IData document.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value to be removed from the given IData
* document.
* @return The given IData document.
*/
public static IData drop(IData document, String key) {
return drop(document, key, false);
}
/**
* Removes the value with the given key from the given IData document.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value to be removed from the given IData
* document.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The given IData document.
*/
public static IData drop(IData document, String key, boolean literal) {
if (document != null && key != null) {
IDataCursor cursor = document.getCursor();
if (cursor.first(key)) {
cursor.delete();
} else if (IDataKey.isFullyQualified(key, literal)) {
drop(document, IDataKey.of(key, literal));
}
cursor.destroy();
}
return document;
}
/**
* Removes the value with the given key from the given IData document.
*
* @param document An IData document.
* @param key A fully-qualified key identifying the value to be removed from the given IData document.
* @return The given IData document.
*/
private static IData drop(IData document, IDataKey key) {
if (document != null && key != null && key.size() > 0) {
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
drop(ArrayHelper.get(toIDataArray(IDataUtil.get(cursor, keyPart.getKey())), keyPart.getIndex()), key);
} else if (keyPart.hasKeyIndex()) {
drop(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key);
} else {
Object value = IDataUtil.get(cursor, keyPart.getKey());
IData[] array = toIDataArray(value);
if (array != null) {
// if we are referencing an IData[], drop the key from all items in the array
for (IData item : array) {
drop(item, key.clone());
}
} else {
drop(toIData(value), key);
}
}
} else {
if (keyPart.hasArrayIndex()) {
IDataUtil.put(cursor, keyPart.getKey(), ArrayHelper.drop(IDataUtil.getObjectArray(cursor, keyPart.getKey()), keyPart.getIndex()));
} else if (keyPart.hasKeyIndex()) {
drop(document, keyPart.getKey(), keyPart.getIndex());
} else {
IDataUtil.remove(cursor, keyPart.getKey());
}
}
cursor.destroy();
}
return document;
}
/**
* Removes the element with the given nth key from the given IData document.
*
* @param document The IData document to remove the key value pair from.
* @param key The key to be removed.
* @param n Determines which occurrence of the key to remove.
*/
private static void drop(IData document, String key, int n) {
if (document == null || key == null || n < 0) return;
int i = 0;
IDataCursor cursor = document.getCursor();
while (cursor.next(key) && i++ < n) ;
if (i > n) cursor.delete();
cursor.destroy();
}
/**
* Removes all occurrences of the given key from the given IData document.
*
* @param document The IData document to remove the key from.
* @param key The key to be removed.
* @return The given IData document, to allow for method chaining.
*/
public static IData dropAll(IData document, String key) {
return dropAll(document, key, false);
}
/**
* Removes all occurrences of the given key from the given IData document.
*
* @param document The IData document to remove the key from.
* @param key The key to be removed.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The given IData document, to allow for method chaining.
*/
public static IData dropAll(IData document, String key, boolean literal) {
if (document != null && key != null) {
IDataCursor cursor = document.getCursor();
if (cursor.next(key)) {
do {
cursor.delete();
} while (cursor.next(key));
} else if (IDataKey.isFullyQualified(key, literal)) {
dropAll(document, IDataKey.of(key, literal));
}
cursor.destroy();
}
return document;
}
/**
* Removes all occurrences of the given key from the given IData document.
*
* @param document An IData document.
* @param key A fully-qualified key identifying the values to be removed from the given IData document.
* @return The given IData document.
*/
private static IData dropAll(IData document, IDataKey key) {
if (document != null && key != null && key.size() > 0) {
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
dropAll(ArrayHelper.get(toIDataArray(IDataUtil.get(cursor, keyPart.getKey())), keyPart.getIndex()), key);
} else if (keyPart.hasKeyIndex()) {
dropAll(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key);
} else {
dropAll(toIData(IDataUtil.get(cursor, keyPart.getKey())), key);
}
} else {
if (keyPart.hasArrayIndex()) {
IDataUtil.put(cursor, keyPart.getKey(), ArrayHelper.drop(IDataUtil.getObjectArray(cursor, keyPart.getKey()), keyPart.getIndex()));
} else if (keyPart.hasKeyIndex()) {
drop(document, keyPart.getKey(), keyPart.getIndex());
} else {
while (cursor.next(keyPart.getKey())) {
cursor.delete();
}
}
}
cursor.destroy();
}
return document;
}
/**
* Renames a key from source to target within the given IData document.
*
* @param document An IData document.
* @param source A simple or fully-qualified key identifying the value in the given IData document to be renamed.
* @param target The new simple or fully-qualified key for the renamed value.
* @return The given IData document.
*/
public static IData rename(IData document, String source, String target) {
return rename(document, source, target, false);
}
/**
* Renames a key from source to target within the given IData document.
*
* @param document An IData document.
* @param source A simple or fully-qualified key identifying the value in the given IData document to be renamed.
* @param target The new simple or fully-qualified key for the renamed value.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The given IData document.
*/
public static IData rename(IData document, String source, String target, boolean literal) {
if (document != null && source != null && target != null && !source.equals(target)) {
document = copy(document, source, target, literal);
document = drop(document, source, literal);
}
return document;
}
/**
* Copies a value from source key to target key within the given IData document.
*
* @param document An IData document.
* @param source A simple or fully-qualified key identifying the value in the given IData document to be copied.
* @param target A simple or fully-qualified key the source value will be copied to.
* @return The given IData document.
*/
public static IData copy(IData document, String source, String target) {
return copy(document, source, target, false);
}
/**
* Copies a value from source key to target key within the given IData document.
*
* @param document An IData document.
* @param source A simple or fully-qualified key identifying the value in the given IData document to be copied.
* @param target A simple or fully-qualified key the source value will be copied to.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The given IData document.
*/
public static IData copy(IData document, String source, String target, boolean literal) {
if (document != null && source != null && target != null && !source.equals(target)) {
document = put(document, target, get(document, source, literal), literal);
}
return document;
}
/**
* Amends the given IData document with the key value pairs specified in the amendments IData document.
*
* @param document The IData document to be amended.
* @param amendments The list of key value pairs to amend the document with.
* @param scope The scope against which to resolve variable substitution statements.
* @return The amended IData document.
*/
public static IData amend(IData document, IData[] amendments, IData scope) throws ServiceException {
if (amendments == null) return document;
IData output = duplicate(document);
for (int i = 0; i < amendments.length; i++) {
if (amendments[i] != null) {
IDataCursor cursor = amendments[i].getCursor();
String key = IDataUtil.getString(cursor, "key");
String value = IDataUtil.getString(cursor, "value");
String condition = IDataUtil.getString(cursor, "condition");
cursor.destroy();
key = SubstitutionHelper.substitute(key, scope);
value = SubstitutionHelper.substitute(value, scope);
if ((condition == null) || ConditionEvaluator.evaluate(condition, scope)) {
output = IDataHelper.put(output, key, value);
}
}
}
return output;
}
/**
* Trims all string values, then converts empty strings to nulls, then compacts by removing all null values.
*
* @param document An IData document to be squeezed.
* @param recurse Whether to also squeeze embedded IData and IData[] objects.
* @return A new IData document that is the given IData squeezed.
*/
public static IData squeeze(IData document, boolean recurse) {
if (document == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
while (inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value instanceof String) {
value = StringHelper.squeeze((String)value, false);
} else if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
IData[] array = toIDataArray(value);
if (recurse) {
value = squeeze(array, recurse);
} else {
if (array != null && array.length == 0) {
value = null;
} else {
value = array;
}
}
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
IData data = toIData(value);
if (recurse) {
value = squeeze(data, recurse);
} else {
if (size(data) == 0) {
value = null;
} else {
value = data;
}
}
} else if (value instanceof Object[][]) {
value = ArrayHelper.squeeze((Object[][])value);
} else if (value instanceof Object[]) {
value = ArrayHelper.squeeze((Object[])value);
}
if (value != null) outputCursor.insertAfter(key, value);
}
inputCursor.destroy();
outputCursor.destroy();
return size(output) == 0 ? null : output;
}
/**
* Returns a new IData[] with all empty and null items removed.
*
* @param array An IData[] to be squeezed.
* @param recurse Whether to also squeeze embedded IData and IData[] objects.
* @return A new IData[] that is the given IData[] squeezed.
*/
public static IData[] squeeze(IData[] array, boolean recurse) {
if (array == null) return null;
List<IData> list = new ArrayList<IData>(array.length);
for (IData document : array) {
document = squeeze(document, recurse);
if (document != null) list.add(document);
}
array = list.toArray(new IData[list.size()]);
return array.length == 0 ? null : array;
}
/**
* Converts all strings that only contain whitespace characters to null.
*
* @param document An IData document to be nullified.
* @param recurse Whether to also nullify embedded IData and IData[] objects.
* @return A new IData document that is the given IData nullified.
*/
public static IData nullify(IData document, boolean recurse) {
if (document == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
while (inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value instanceof String) {
value = StringHelper.nullify((String)value);
} else if (recurse) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
value = nullify(toIDataArray(value), recurse);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = nullify(toIData(value), recurse);
}
}
outputCursor.insertAfter(key, value);
}
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Converts all strings that only contain whitespace characters to null.
*
* @param input An IData[] to be nullified.
* @param recurse Whether to also nullify embedded IData and IData[] objects.
* @return A new IData[] that is the given IData[] nullify.
*/
public static IData[] nullify(IData[] input, boolean recurse) {
if (input == null) return null;
IData[] output = new IData[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = nullify(input[i], recurse);
}
return output;
}
public static String join(IData document) {
return join(document, true);
}
public static String join(IData document, boolean includeNulls) {
return join(document, null, null, null, includeNulls);
}
public static String join(IData document, String itemSeparator, String listSeparator, String valueSeparator) {
return join(document, itemSeparator, listSeparator, valueSeparator, true);
}
public static String join(IData document, String itemSeparator, String listSeparator, String valueSeparator, boolean includeNulls) {
if (document == null) return null;
if (itemSeparator == null) itemSeparator = ", ";
if (listSeparator == null) listSeparator = ", ";
if (valueSeparator == null) valueSeparator = ": ";
boolean itemSeparatorRequired = false;
IDataCursor cursor = document.getCursor();
StringBuilder builder = new StringBuilder();
while (cursor.next()) {
String key = cursor.getKey();
Object value = cursor.getValue();
boolean includeItem = includeNulls || value != null;
if (itemSeparatorRequired && includeItem) builder.append(itemSeparator);
if (includeItem) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
value = "[" + join(toIDataArray(value), itemSeparator, listSeparator, valueSeparator, includeNulls) + "]";
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = "{" + join(toIData(value), itemSeparator, listSeparator, valueSeparator, includeNulls) + "}";
} else if (value instanceof Object[][]) {
value = "[" + ArrayHelper.join(ArrayHelper.toStringTable((Object[][])value), listSeparator, includeNulls) + "]";
} else if (value instanceof Object[]) {
value = "[" + ArrayHelper.join(ArrayHelper.toStringArray((Object[])value), listSeparator, includeNulls) + "]";
}
builder.append(key);
builder.append(valueSeparator);
builder.append(ObjectHelper.stringify(value));
itemSeparatorRequired = true;
}
}
cursor.destroy();
return builder.toString();
}
public static String join(IData[] array) {
return join(array, null, null, null, true);
}
public static String join(IData[] array, String itemSeparator, String listSeparator, String valueSeparator) {
return join(array, itemSeparator, listSeparator, valueSeparator, true);
}
public static String join(IData[] array, String itemSeparator, String listSeparator, String valueSeparator, boolean includeNulls) {
if (array == null) return null;
if (itemSeparator == null) itemSeparator = ", ";
if (listSeparator == null) listSeparator = ", ";
if (valueSeparator == null) valueSeparator = ": ";
StringBuilder builder = new StringBuilder();
boolean separatorRequired = false;
for(IData item : array) {
boolean includeItem = includeNulls || item != null;
if (separatorRequired && includeItem) builder.append(listSeparator);
if (includeItem) {
builder.append("{");
builder.append(join(item, itemSeparator, listSeparator, valueSeparator, includeNulls));
builder.append("}");
separatorRequired = true;
}
}
return builder.toString();
}
/**
* Converts all non-string values to strings, except for IData and IData[] compatible objects.
*
* @param document The IData document to stringify.
* @param recurse Whether embedded IData and IData[] objects should also be stringified recursively.
* @return The stringified IData document.
*/
public static IData stringify(IData document, boolean recurse) {
if (document == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
while (inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value instanceof String || value instanceof String[] || value instanceof String[][]) {
// do nothing, value is already a string
} else if (recurse && (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[])) {
value = stringify(toIDataArray(value), recurse);
} else if (recurse && (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable)) {
value = stringify(toIData(value), recurse);
} else if (value instanceof Object[][]) {
value = ArrayHelper.toStringTable((Object[][]) value);
} else if (value instanceof Object[]) {
value = ArrayHelper.toStringArray((Object[])value);
} else if (value instanceof Calendar) {
value = DateTimeHelper.emit((Calendar)value);
} else if (value instanceof Date) {
value = DateTimeHelper.emit((Date)value);
} else if (value != null){
value = value.toString();
}
outputCursor.insertAfter(key, value);
}
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Converts all non-string values to strings, except for IData and IData[] compatible objects.
*
* @param array The IData[] to stringify.
* @param recurse Whether to stringify embedded IData and IData[] objects recursively.
* @return The stringified IData[].
*/
public static IData[] stringify(IData[] array, boolean recurse) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = stringify(array[i], recurse);
}
return output;
}
/**
* Converts all null values to empty strings.
*
* @param document The IData document to blankify.
* @param recurse Whether embedded IData and IData[] objects should be recursively blankified.
* @return The blankified IData.
*/
public static IData blankify(IData document, boolean recurse) {
if (document == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
while (inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value == null) {
value = "";
} else if (recurse && (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[])) {
value = blankify(toIDataArray(value), recurse);
} else if (recurse && (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable)) {
value = blankify(toIData(value), recurse);
}
outputCursor.insertAfter(key, value);
}
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Converts all null values to empty strings.
*
* @param array The IData[] to blankify.
* @param recurse Whether embedded IData and IData[] objects should be recursively blankified.
* @return The blankified IData[].
*/
public static IData[] blankify(IData[] array, boolean recurse) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = blankify(array[i], recurse);
}
return output;
}
/**
* Converts the value associated with the given key to an array in the given IData document.
*
* @param document An IData document.
* @param key The key whose associated value is to be converted to an array.
* @return The given IData with the given key's value converted to an array.
*/
public static IData arrayify(IData document, String key) {
if (exists(document, key)) {
Object[] value = getAsArray(document, key);
dropAll(document, key);
put(document, key, value);
}
return document;
}
/**
* Removes all null values from the given IData document.
*
* @param document The IData document to be compacted.
* @param recurse Whether embedded IData and IData[] objects should be recursively compacted.
* @return The compacted IData.
*/
public static IData compact(IData document, boolean recurse) {
if (document == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = document.getCursor();
IDataCursor outputCursor = output.getCursor();
while (inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value != null) {
if (recurse) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
value = compact(toIDataArray(value), recurse);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = compact(toIData(value), recurse);
} else if (value instanceof Object[][]) {
value = ArrayHelper.compact((Object[][])value);
} else if (value instanceof Object[]) {
value = ArrayHelper.compact((Object[])value);
}
}
}
if (value != null) IDataUtil.put(outputCursor, key, value);
}
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Removes all null values from the given IData[].
*
* @param array The IData[] to be compacted.
* @param recurse Whether embedded IData and IData[] objects should be recursively compacted.
* @return The compacted IData[].
*/
public static IData[] compact(IData[] array, boolean recurse) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = compact(array[i], recurse);
}
return ArrayHelper.compact(output);
}
/**
* Normalizes the given Object.
*
* @param value An Object to be normalized.
* @return A new normalized version of the given Object.
*/
private static Object normalize(Object value) {
if (value instanceof IData[]) {
value = normalize((IData[])value);
} else if (value instanceof Table) {
value = normalize((Table)value);
} else if (value instanceof IDataCodable[]) {
value = normalize((IDataCodable[])value);
} else if (value instanceof IDataPortable[]) {
value = normalize((IDataPortable[])value);
} else if (value instanceof ValuesCodable[]) {
value = normalize((ValuesCodable[])value);
} else if (value instanceof Collection) {
value = normalize((Collection)value);
} else if (value instanceof Map[]) {
value = normalize((Map[]) value);
} else if (value instanceof IData) {
value = normalize((IData)value);
} else if (value instanceof IDataCodable) {
value = normalize((IDataCodable)value);
} else if (value instanceof IDataPortable) {
value = normalize((IDataPortable)value);
} else if (value instanceof ValuesCodable) {
value = normalize((ValuesCodable)value);
} else if (value instanceof Map) {
value = normalize((Map)value);
}
return value;
}
/**
* Normalizes the given Object[].
*
* @param array The Object[] to be normalized.
* @return Normalized version of the Object[].
*/
private static Object[] normalize(Object[] array) {
return (Object[])normalize((Object)ArrayHelper.normalize(array));
}
/**
* Returns a new IData document, where all nested IData and IData[] objects are implemented with the same class, and
* all fully-qualified keys are replaced with their representative nested structure.
*
* @param document An IData document to be normalized.
* @return A new normalized version of the given IData document.
*/
public static IData normalize(IData document) {
if (document == null) return null;
IData output = IDataFactory.create();
for (Map.Entry<String, Object> entry : IDataMap.of(document)) {
String key = entry.getKey();
Object value = normalize(entry.getValue());
if (IDataKey.isFullyQualified(key)) {
// normalize fully-qualified keys by using IDataHelper.put() rather than IDataUtil.put()
put(output, entry.getKey(), value);
} else {
// support multiple occurrences of same key by using IDataCursor.insertAfter()
IDataCursor outputCursor = output.getCursor();
outputCursor.insertAfter(key, value);
outputCursor.destroy();
}
}
return output;
}
/**
* Converts a java.util.Map to an IData object.
*
* @param map A java.util.Map to be converted to an IData object.
* @return An IData representation of the given java.util.Map object.
*/
private static IData normalize(Map map) {
return normalize(toIData(map));
}
/**
* Normalizes a java.util.Collection to an Object[].
*
* @param collection A java.util.Collection to be converted to an Object[].
* @return An Object[] representation of the given java.util.Collection object.
*/
private static Object[] normalize(Collection collection) {
return normalize(ArrayHelper.toArray(collection));
}
/**
* Normalizes an IDataCodable object to an IData representation.
*
* @param document An IDataCodable object to be normalized.
* @return An IData representation for the given IDataCodable object.
*/
public static IData normalize(IDataCodable document) {
return normalize(toIData(document));
}
/**
* Normalizes an IDataCodable[] where all items are converted to IData documents implemented with the same class,
* and all fully-qualified keys are replaced with their representative nested structure.
*
* @param array An IDataCodable[] list to be normalized.
* @return A new normalized IData[] version of the given IDataCodable[] list.
*/
public static IData[] normalize(IDataCodable[] array) {
return normalize(toIDataArray(array));
}
/**
* Normalizes an IDataPortable object to an IData representation.
*
* @param document An IDataPortable object to be normalized.
* @return An IData representation for the given IDataPortable object.
*/
public static IData normalize(IDataPortable document) {
return normalize(toIData(document));
}
/**
* Normalizes an IDataPortable[] where all items are converted to IData documents implemented with the same class,
* and all fully-qualified keys are replaced with their representative nested structure.
*
* @param array An IDataPortable[] list to be normalized.
* @return A new normalized IData[] version of the given IDataPortable[] list.
*/
public static IData[] normalize(IDataPortable[] array) {
return normalize(toIDataArray(array));
}
/**
* Normalizes an ValuesCodable object to an IData representation.
*
* @param document An ValuesCodable object to be normalized.
* @return An IData representation for the given ValuesCodable object.
*/
public static IData normalize(ValuesCodable document) {
return normalize(toIData(document));
}
/**
* Normalizes an ValuesCodable[] where all items are converted to IData documents implemented with the same class,
* and all fully-qualified keys are replaced with their representative nested structure.
*
* @param array An ValuesCodable[] list to be normalized.
* @return A new normalized IData[] version of the given ValuesCodable[] list.
*/
public static IData[] normalize(ValuesCodable[] array) {
return normalize(toIDataArray(array));
}
/**
* Normalizes an IData[] where all IData objects are implemented with the same class, and all fully-qualified keys
* are replaced with their representative nested structure.
*
* @param array An IData[] document list to be normalized.
* @return A new normalized version of the given IData[] document list.
*/
public static IData[] normalize(IData[] array) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = normalize(array[i]);
}
return output;
}
/**
* Normalizes a com.wm.util.Table object to an IData[] representation.
*
* @param table A com.wm.util.Table object to be normalized.
* @return An IData[] representation of the given com.wm.util.Table object.
*/
public static IData[] normalize(Table table) {
return normalize(toIDataArray(table));
}
/**
* Normalizes a Map[] object to an IData[] representation.
*
* @param array A Map[] object to be normalized.
* @return An IData[] representation of the given Map[] object.
*/
public static IData[] normalize(Map[] array) {
return normalize(toIDataArray(array));
}
/**
* Removes all key value pairs from the given IData document.
*
* @param document An IData document to be cleared.
*/
public static void clear(IData document) {
clear(document, (String)null);
}
/**
* Removes all key value pairs from the given IData document except those with a specified key.
*
* @param document An IData document to be cleared.
* @param keysToBePreserved List of simple or fully-qualified keys identifying items that should not be removed.
*/
public static void clear(IData document, String... keysToBePreserved) {
if (document == null) return;
IData saved = IDataFactory.create();
if (keysToBePreserved != null) {
for (String key : keysToBePreserved) {
if (key != null) put(saved, key, get(document, key), false, false);
}
}
IDataCursor cursor = document.getCursor();
cursor.first();
while (cursor.delete());
cursor.destroy();
if (keysToBePreserved != null) IDataUtil.merge(saved, document);
}
/**
* Returns the value associated with the given key as a one-dimensional array; if the value is a
* multi-dimensional array it is first flattened.
*
* @param document The IData document which contains the values to be flattened.
* @param keys One or more fully-qualified keys identifying the values to be flattened.
* @return A one-dimensional flattened array containing the values associated with the given keys.
*/
public static Object[] flatten(IData document, String... keys) {
return flatten(document, false, keys);
}
/**
* Returns the value associated with the given key as a one-dimensional array; if the value is a
* multi-dimensional array it is first flattened.
*
* @param document The IData document which contains the values to be flattened.
* @param includeNulls If true null values will be included in the returned array.
* @param keys One or more fully-qualified keys identifying the values to be flattened.
* @return A one-dimensional flattened array containing the values associated with the given keys.
*/
public static Object[] flatten(IData document, boolean includeNulls, String... keys) {
if (document == null || keys == null) return null;
ArrayList<Object> list = new ArrayList<Object>();
for (String key : keys) {
Object value = get(document, key);
if (value instanceof Object[]) {
ArrayHelper.flatten((Object[])value, list, includeNulls);
} else if (includeNulls || value != null) {
list.add(value);
}
}
return list.size() == 0 ? null : ArrayHelper.normalize(list);
}
/**
* Returns the value associated with the given key from the given IData document.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @return The value associated with the given key in the given IData document.
*/
public static Object get(IData document, String key) {
return get(null, document, key);
}
/**
* Returns the value associated with the given key from the given scope (if relative) or pipeline (if absolute).
*
* @param pipeline The pipeline, required if the key is an absolute path.
* @param scope An IData document used to scope the key if it is relative.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @return The value associated with the given key in the given IData document.
*/
public static Object get(IData pipeline, IData scope, String key) {
return get(pipeline, scope, key, false);
}
/**
* Returns the value associated with the given key from the given IData document.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The value associated with the given key in the given IData document.
*/
public static Object get(IData document, String key, boolean literal) {
return get(null, document, key, literal);
}
/**
* Returns the value associated with the given key from the given IData document, or if null the specified default
* value.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param defaultValue A default value to be returned if the existing value associated with the given key is null.
* @return Either the value associated with the given key in the given IData document, or the given
* defaultValue if null.
*/
public static Object get(IData document, String key, Object defaultValue) {
return get(document, key, defaultValue, false);
}
/**
* Returns the value associated with the given key from the given scope (if relative) or pipeline (if absolute).
*
* @param pipeline The pipeline, required if the key is an absolute path.
* @param scope An IData document used to scope the key if it is relative.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param defaultValue A default value to be returned if the existing value associated with the given key is null.
* @return Either the value associated with the given key in the given IData document, or the given
* defaultValue if null.
*/
public static Object get(IData pipeline, IData scope, String key, Object defaultValue) {
return get(pipeline, scope, key, defaultValue, false);
}
/**
* Returns the value associated with the given key from the given IData document, or if null the specified default
* value.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param defaultValue A default value to be returned if the existing value associated with the given key is null.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a
* fully-qualified key.
* @return Either the value associated with the given key in the given IData document, or the given
* defaultValue if null.
*/
public static Object get(IData document, String key, Object defaultValue, boolean literal) {
return get(null, document, key, defaultValue, literal);
}
/**
* Returns the value associated with the given key from the given IData document, or if null the specified default
* value.
*
* @param pipeline An IData document against which absolute variables are resolved.
* @param scope An IData document against which relative variables are resolved.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param defaultValue A default value to be returned if the existing value associated with the given key is null.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a
* fully-qualified key.
* @return Either the value associated with the given key in the given IData document, or the given
* defaultValue if null.
*/
public static Object get(IData pipeline, IData scope, String key, Object defaultValue, boolean literal) {
Object value = get(pipeline, scope, key, literal);
if (value == null) value = defaultValue;
return value;
}
/**
* Returns the value associated with the given key from the given scope (if relative) or pipeline (if absolute).
*
* @param pipeline The pipeline, required if the key is an absolute path.
* @param scope An IData document used to scope the key if it is relative.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The value associated with the given key in the given IData document.
*/
public static Object get(IData pipeline, IData scope, String key, boolean literal) {
if (key == null) return null;
Object value = null;
if (scope != null) {
// try finding a value that matches the literal key, and if not found try finding a value
// associated with the leaf key if the key is considered fully-qualified
IDataCursor cursor = scope.getCursor();
if (cursor.first(key)) {
value = cursor.getValue();
} else if (pipeline != null && IDataKey.isAbsolute(key, literal)) {
value = get(null, pipeline, key.substring(1), literal);
} else if (scope != null && IDataKey.isFullyQualified(key, literal)) {
value = get(scope, IDataKey.of(key, literal));
}
cursor.destroy();
} else if (pipeline != null && IDataKey.isAbsolute(key, literal)) {
value = get(null, pipeline, key.substring(1), literal);
}
return value;
}
/**
* Returns the value associated with the given fully-qualified key from the given IData document.
*
* @param document An IData document.
* @param key A fully-qualified key identifying the value in the given IData document to be returned.
* @return The value associated with the given key in the given IData document.
*/
private static Object get(IData document, IDataKey key) {
Object value = null;
if (document != null && key != null && key.size() > 0) {
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
value = get(ArrayHelper.get(toIDataArray(IDataUtil.get(cursor, keyPart.getKey())), keyPart.getIndex()), key);
} else if (keyPart.hasKeyIndex()) {
value = get(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key);
} else {
Object object = IDataUtil.get(cursor, keyPart.getKey());
IData parent = toIData(object);
if (parent != null) {
value = get(parent, key);
} else {
IData[] array = toIDataArray(object);
if (array != null) {
List<Object> values = new ArrayList<Object>(array.length);
// if we are referencing an IData[], create a new array of values from the individual values in each IData
for (IData item : array) {
values.add(get(item, key.clone()));
}
value = ArrayHelper.normalize(values);
}
}
}
} else {
if (keyPart.hasArrayIndex()) {
value = IDataUtil.get(cursor, keyPart.getKey());
if (value != null) {
if (value instanceof Object[] || value instanceof Table) {
Object[] array = value instanceof Object[] ? (Object[])value : ((Table)value).getValues();
value = ArrayHelper.get(array, keyPart.getIndex());
} else {
value = null;
}
}
} else if (keyPart.hasKeyIndex()) {
value = get(document, keyPart.getKey(), keyPart.getIndex());
} else {
value = IDataUtil.get(cursor, keyPart.getKey());
}
}
cursor.destroy();
}
return value;
}
/**
* Returns the nth value associated with the given key.
*
* @param document The IData document to return the value from.
* @param key The key whose associated value is to be returned.
* @param n Determines which occurrence of the key to return the value for.
* @return The value associated with the nth occurrence of the given key in the given IData document.
*/
private static Object get(IData document, String key, int n) {
if (document == null || key == null || n < 0) return null;
Object value = null;
int i = 0;
IDataCursor cursor = document.getCursor();
while (cursor.next(key) && i++ < n) ;
if (i > n) value = cursor.getValue();
cursor.destroy();
return value;
}
/**
* Returns the value associated with the given key from the given IData document as an array.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @return The value associated with the given key in the given IData document as an array.
*/
public static Object[] getAsArray(IData document, String key) {
return getAsArray(document, key, false);
}
/**
* Returns the value associated with the given key from the given IData document as an array.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value in the given IData document to be
* returned.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The value associated with the given key in the given IData document as an array.
*/
public static Object[] getAsArray(IData document, String key, boolean literal) {
if (document == null || key == null) return null;
Object[] output = null;
IDataCursor cursor = document.getCursor();
// try finding a value that matches the literal key, and if not found try finding a value
// associated with the leaf key if the key is considered fully-qualified
if (cursor.next(key)) {
List<Object> list = new ArrayList<Object>();
do {
list.addAll(ObjectHelper.listify(cursor.getValue()));
} while (cursor.next(key));
output = ArrayHelper.toArray(list);
} else if (IDataKey.isFullyQualified(key, literal)) {
output = getAsArray(document, IDataKey.of(key, literal));
}
cursor.destroy();
return output;
}
/**
* Returns the value associated with the given fully-qualified key from the given IData document as an array.
*
* @param document An IData document.
* @param key A fully-qualified key identifying the value in the given IData document to be returned.
* @return The value associated with the given key in the given IData document as an array.
*/
private static Object[] getAsArray(IData document, IDataKey key) {
Object[] output = null;
if (document != null && key != null && key.size() > 0) {
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
output = getAsArray(ArrayHelper.get(toIDataArray(IDataUtil.get(cursor, keyPart.getKey())), keyPart.getIndex()), key);
} else if (keyPart.hasKeyIndex()) {
output = getAsArray(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key);
} else {
output = getAsArray(IDataUtil.getIData(cursor, keyPart.getKey()), key);
}
} else {
List<Object> list = new ArrayList<Object>();
if (keyPart.hasArrayIndex()) {
Object value = IDataUtil.get(cursor, keyPart.getKey());
if (value != null) {
if (value instanceof Object[] || value instanceof Table) {
Object[] array = value instanceof Object[] ? (Object[])value : ((Table)value).getValues();
value = ArrayHelper.get(array, keyPart.getIndex());
} else {
value = null;
}
}
list.addAll(ObjectHelper.listify(value));
} else if (keyPart.hasKeyIndex()) {
list.addAll(ObjectHelper.listify(get(document, keyPart.getKey(), keyPart.getIndex())));
} else {
while (cursor.next(keyPart.getKey())) {
list.addAll(ObjectHelper.listify(cursor.getValue()));
}
}
output = ArrayHelper.toArray(list);
}
cursor.destroy();
}
return output;
}
/**
* Sets the value associated with the given key in the given IData document. Note that this method mutates the given
* IData document in place.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value to be set.
* @param value The value to be set.
* @return The input IData document with the value set.
*/
public static IData put(IData document, String key, Object value) {
return put(document, key, value, false);
}
/**
* Sets the value associated with the given key in the given IData document. Note that this method mutates the given
* IData document in place.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value to be set.
* @param value The value to be set.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a fully-qualified
* key.
* @return The input IData document with the value set.
*/
public static IData put(IData document, String key, Object value, boolean literal) {
return put(document, key, value, literal, true);
}
/**
* Sets the value associated with the given key in the given IData document. Note that this method mutates the given
* IData document in place.
*
* @param document An IData document.
* @param key A simple or fully-qualified key identifying the value to be set.
* @param value The value to be set.
* @param literal If true, the key will be treated as a literal key, rather than potentially as a
* fully-qualified key.
* @param includeNull When true the value is set even when null, otherwise the value is only set when it is not
* null.
* @return The input IData document with the value set.
*/
public static IData put(IData document, String key, Object value, boolean literal, boolean includeNull) {
return put(document, IDataKey.of(key, literal), value, includeNull);
}
/**
* Sets the value associated with the given key in the given IData document. Note that this method mutates the given
* IData document in place.
*
* @param document An IData document.
* @param key A fully-qualified key identifying the value to be set.
* @param value The value to be set.
* @param includeNull When true the value is set even when null, otherwise the value is only set when it is
* not null.
* @return The input IData document with the value set.
*/
private static IData put(IData document, IDataKey key, Object value, boolean includeNull) {
if (!includeNull && value == null) return document;
if (key != null && key.size() > 0) {
if (document == null) document = IDataFactory.create();
IDataCursor cursor = document.getCursor();
IDataKey.Part keyPart = key.remove();
if (key.size() > 0) {
if (keyPart.hasArrayIndex()) {
IData[] array = IDataUtil.getIDataArray(cursor, keyPart.getKey());
IData child = null;
try {
child = ArrayHelper.get(array, keyPart.getIndex());
} catch(ArrayIndexOutOfBoundsException ex) {
// ignore exception
}
value = ArrayHelper.put(array, put(child, key, value, includeNull), keyPart.getIndex(), IData.class);
} else if (keyPart.hasKeyIndex()) {
value = put(toIData(get(document, keyPart.getKey(), keyPart.getIndex())), key, value, includeNull);
} else {
value = put(IDataUtil.getIData(cursor, keyPart.getKey()), key, value, includeNull);
}
} else if (keyPart.hasArrayIndex()) {
Class klass = Object.class;
if (value != null) {
if (value instanceof String) {
klass = String.class;
} else if (value instanceof IData) {
klass = IData.class;
}
}
value = ArrayHelper.put(IDataUtil.getObjectArray(cursor, keyPart.getKey()), value, keyPart.getIndex(), klass);
}
if (keyPart.hasKeyIndex()) {
put(document, keyPart.getKey(), keyPart.getIndex(), value);
} else {
IDataUtil.put(cursor, keyPart.getKey(), value);
}
cursor.destroy();
}
return document;
}
/**
* Sets the value associated with the given nth key in the given IData document. Note that this method mutates the
* given IData document in place.
*
* @param document The IData document to set the key's associated value in.
* @param key The key whose value is to be set.
* @param n Determines which occurrence of the key to set the value for.
* @param value The value to be set.
* @return The IData document with the given nth key set to the given value.
*/
private static IData put(IData document, String key, int n, Object value) {
if (document == null || key == null || n < 0) return null;
IDataCursor cursor = document.getCursor();
for (int i = 0; i < n; i++) {
if (!cursor.next(key)) cursor.insertAfter(key, null);
}
cursor.insertAfter(key, value);
cursor.destroy();
return document;
}
/**
* Converts the given object to a Map object, if possible.
*
* @param object The object to be converted.
* @return A Map representation of the given object if its type is compatible (IData, IDataCodable,
* IDataPortable, ValuesCodable), otherwise null.
*/
private static Map<String, Object> toMap(Object object) {
if (object == null) return null;
Map<String, Object> output = null;
if (object instanceof IData) {
output = toMap((IData)object);
} else if (object instanceof IDataCodable) {
output = toMap((IDataCodable)object);
} else if (object instanceof IDataPortable) {
output = toMap((IDataPortable)object);
} else if (object instanceof ValuesCodable) {
output = toMap((ValuesCodable)object);
}
return output;
}
/**
* Converts an IData object to a Map object.
*
* @param document An IData object to be converted.
* @return A Map representation of the given IData object.
*/
public static Map<String, Object> toMap(IData document) {
if (document == null) return null;
IDataCursor cursor = document.getCursor();
int size = IDataUtil.size(cursor);
cursor.destroy();
Map<String, Object> output = new java.util.LinkedHashMap<String, Object>(size);
for (Map.Entry<String, Object> entry : IDataMap.of(document)) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
value = toList(value);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = toMap(value);
}
output.put(key, value);
}
cursor.destroy();
return output;
}
/**
* Converts an IDataCodable object to a Map object.
*
* @param document An IDataCodable object to be converted.
* @return A Map representation of the given IDataCodable object.
*/
public static Map<String, Object> toMap(IDataCodable document) {
return toMap(toIData(document));
}
/**
* Converts an IDataPortable object to a Map object.
*
* @param document An IDataPortable object to be converted.
* @return A Map representation of the given IDataPortable object.
*/
public static Map<String, Object> toMap(IDataPortable document) {
return toMap(toIData(document));
}
/**
* Converts an ValuesCodable object to a Map object.
*
* @param document An ValuesCodable object to be converted.
* @return A Map representation of the given ValuesCodable object.
*/
public static Map<String, Object> toMap(ValuesCodable document) {
return toMap(toIData(document));
}
/**
* Converts an object to a List object, if possible.
*
* @param object An object to be converted.
* @return A List representation of the given object, if the object was a compatible type (IData[],
* Table, IDataCodable[], IDataPortable[], ValuesCodable[]), otherwise null.
*/
private static List<Map<String, Object>> toList(Object object) {
if (object == null) return null;
List<Map<String, Object>> output = null;
if (object instanceof IData[]) {
output = toList((IData[])object);
} else if (object instanceof Table) {
output = toList((Table)object);
} else if (object instanceof IDataCodable[]) {
output = toList((IDataCodable[])object);
} else if (object instanceof IDataPortable[]) {
output = toList((IDataPortable[])object);
} else if (object instanceof ValuesCodable[]) {
output = toList((ValuesCodable[])object);
}
return output;
}
/**
* Converts an IData[] object to a List object.
*
* @param array An IData[] object to be converted.
* @return A List representation of the given IData[] object.
*/
public static List<Map<String, Object>> toList(IData[] array) {
if (array == null) return null;
List<Map<String, Object>> output = new java.util.ArrayList<Map<String, Object>>(array.length);
for (IData item : array) {
output.add(toMap(item));
}
return output;
}
/**
* Converts a Table object to a List object.
*
* @param table An Table object to be converted.
* @return A List representation of the given Table object.
*/
public static List<Map<String, Object>> toList(Table table) {
return toList(toIDataArray(table));
}
/**
* Converts an IDataCodable[] object to a List object.
*
* @param array An IDataCodable[] object to be converted.
* @return A List representation of the given IDataCodable[] object.
*/
public static List<Map<String, Object>> toList(IDataCodable[] array) {
return toList(toIDataArray(array));
}
/**
* Converts an IDataPortable[] object to a List object.
*
* @param array An IDataPortable[] object to be converted.
* @return A List representation of the given IDataPortable[] object.
*/
public static List<Map<String, Object>> toList(IDataPortable[] array) {
return toList(toIDataArray(array));
}
/**
* Converts an ValuesCodable[] object to a java.util.List object.
*
* @param array An ValuesCodable[] object to be converted.
* @return A List representation of the given ValuesCodable[] object.
*/
public static List<Map<String, Object>> toList(ValuesCodable[] array) {
return toList(toIDataArray(array));
}
/**
* Returns an IData representation of the given object, if possible.
*
* @param object The object to convert.
* @return An IData representing the given object if its type is compatible (IData, IDataCodable,
* IDataPortable, ValuesCodable), otherwise null.
*/
public static IData toIData(Object object) {
if (object == null) return null;
IData output = null;
if (object instanceof IData) {
output = (IData)object;
} else if (object instanceof IDataCodable) {
output = toIData((IDataCodable)object);
} else if (object instanceof IDataPortable) {
output = toIData((IDataPortable)object);
} else if (object instanceof ValuesCodable) {
output = toIData((ValuesCodable)object);
} else if (object instanceof Map) {
output = toIData((Map)object);
}
return output;
}
/**
* Returns an IData representation of the given IDataCodable object.
*
* @param document The IDataCodable object to be converted to an IData object.
* @return An IData representation of the give IDataCodable object.
*/
public static IData toIData(IDataCodable document) {
if (document == null) return null;
return document.getIData();
}
/**
* Returns an IData representation of the given IDataPortable object.
*
* @param document The IDataPortable object to be converted to an IData object.
* @return An IData representation of the give IDataPortable object.
*/
public static IData toIData(IDataPortable document) {
if (document == null) return null;
return document.getAsData();
}
/**
* Returns an IData representation of the given ValuesCodable object.
*
* @param document The ValuesCodable object to be converted to an IData object.
* @return An IData representation of the give ValuesCodable object.
*/
public static IData toIData(ValuesCodable document) {
if (document == null) return null;
return document.getValues();
}
/**
* Returns an IData representation of the given Map.
*
* @param map The Map to be converted.
* @return An IData representation of the given map.
*/
public static IData toIData(Map map) {
if (map == null) return null;
IData output = IDataFactory.create();
IDataCursor cursor = output.getCursor();
for (Object key : map.keySet()) {
if (key != null) {
put(output, key.toString(), normalize(map.get(key)), true);
}
}
cursor.destroy();
return output;
}
/**
* Returns an IData[] representation of the given object, if possible.
*
* @param object The Table object to be converted to an IData[] object.
* @return An IData[] representation of the give object if the object was a compatible type (IData[],
* Table, IDataCodable[], IDataPortable[], ValuesCodable[]), otherwise null.
*/
public static IData[] toIDataArray(Object object) {
if (object == null) return null;
IData[] output = null;
if (object instanceof IData[]) {
output = (IData[])object;
} else if (object instanceof Table) {
output = toIDataArray((Table)object);
} else if (object instanceof IDataCodable[]) {
output = toIDataArray((IDataCodable[])object);
} else if (object instanceof IDataPortable[]) {
output = toIDataArray((IDataPortable[])object);
} else if (object instanceof ValuesCodable[]) {
output = toIDataArray((ValuesCodable[])object);
} else if (object instanceof Map[]) {
output = toIDataArray((Map[])object);
}
return output;
}
/**
* Returns an IData[] representation of the given Table object.
*
* @param table The Table object to be converted to an IData[] object.
* @return An IData[] representation of the give Table object.
*/
public static IData[] toIDataArray(Table table) {
if (table == null) return null;
return table.getValues();
}
/**
* Returns an IData[] representation of the given IDataCodable[] object.
*
* @param array The IDataCodable[] object to be converted to an IData[] object.
* @return An IData[] representation of the give IDataCodable[] object.
*/
public static IData[] toIDataArray(IDataCodable[] array) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = toIData(array[i]);
}
return output;
}
/**
* Returns an IData[] representation of the given IDataPortable[] object.
*
* @param array The IDataPortable[] object to be converted to an IData[] object.
* @return An IData[] representation of the give IDataPortable[] object.
*/
public static IData[] toIDataArray(IDataPortable[] array) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = toIData(array[i]);
}
return output;
}
/**
* Returns an IData[] representation of the given ValuesCodable[] object.
*
* @param array The ValuesCodable[] object to be converted to an IData[] object.
* @return An IData[] representation of the give ValuesCodable[] object.
*/
public static IData[] toIDataArray(ValuesCodable[] array) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = toIData(array[i]);
}
return output;
}
/**
* Returns an IData[] representation of the given Map[] object.
*
* @param array The Map[] object to be converted to an IData[] object.
* @return An IData[] representation of the give Map[] object.
*/
public static IData[] toIDataArray(Map[] array) {
if (array == null) return null;
IData[] output = new IData[array.length];
for (int i = 0; i < array.length; i++) {
output[i] = toIData(array[i]);
}
return output;
}
/**
* Returns the union set of keys present in every item in the given IData[] document list.
*
* @param array An IData[] to retrieve the union set of keys from.
* @return The union set of keys from the given IData[].
*/
public static String[] getKeys(IData[] array) {
return getKeys(array, (Pattern)null);
}
/**
* Returns the union set of keys present in every item in the given IData[] document list that match the given
* regular expression pattern.
*
* @param array An IData[] to retrieve the union set of keys from.
* @param patternString A regular expression pattern the returned keys must match.
* @return The union set of keys from the given IData[].
*/
public static String[] getKeys(IData[] array, String patternString) {
return getKeys(array, patternString == null ? null : Pattern.compile(patternString));
}
/**
* Returns the union set of keys present in every item in the given IData[] document list that match the given
* regular expression pattern.
*
* @param array An IData[] to retrieve the union set of keys from.
* @param pattern A regular expression pattern the returned keys must match.
* @return The union set of keys from the given IData[].
*/
public static String[] getKeys(IData[] array, Pattern pattern) {
java.util.Set<String> keys = new java.util.LinkedHashSet<String>();
if (array != null) {
for (IData document : array) {
if (document != null) {
for (Map.Entry<String, Object> entry : IDataMap.of(document)) {
String key = entry.getKey();
if (pattern == null) {
keys.add(key);
} else {
Matcher matcher = pattern.matcher(key);
if (matcher.matches()) keys.add(key);
}
}
}
}
}
return keys.toArray(new String[keys.size()]);
}
/**
* Converts an IData document to an IData[] document list with each item representing each key value tuple from the
* given document.
*
* @param document An IData document to pivot.
* @param recurse Whether to recursively pivot embedded IData objects.
* @return The given IData document pivoted.
*/
public static IData[] pivot(IData document, boolean recurse) {
if (document == null) return null;
IDataCursor cursor = document.getCursor();
List<IData> pivot = new ArrayList<IData>();
while (cursor.next()) {
String key = cursor.getKey();
Object value = cursor.getValue();
if (recurse && value != null) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
IData[] array = toIDataArray(value);
if (array != null) {
List<IData[]> list = new ArrayList<IData[]>(array.length);
for (int i = 0; i < array.length; i++) {
list.add(pivot(array[i], recurse));
}
value = list.toArray(new IData[0][0]);
}
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = pivot(toIData(value), recurse);
}
}
IData item = IDataFactory.create();
IDataCursor ic = item.getCursor();
IDataUtil.put(ic, "key", key);
IDataUtil.put(ic, "value", value);
ic.destroy();
pivot.add(item);
}
return pivot.toArray(new IData[pivot.size()]);
}
/**
* Returns an IData document where the keys are the values associated with given pivot key from the given IData[]
* document list, and the values are the IData[] document list items associated with each pivot key.
*
* @param array The IData[] to be pivoted.
* @param delimiter The delimiter to use when building a compound key.
* @param pivotKeys The keys to pivot on.
* @return The IData document representing the pivoted IData[].
*/
public static IData pivot(IData[] array, String delimiter, String... pivotKeys) {
if (array == null || pivotKeys == null || pivotKeys.length == 0) return null;
if (delimiter == null) delimiter = "/";
IData output = IDataFactory.create();
outer:
for (IData item : array) {
if (item != null) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < pivotKeys.length; i++) {
Object value = get(item, pivotKeys[i]);
if (value == null) {
continue outer;
} else {
buffer.append(value.toString());
}
if (i < (pivotKeys.length - 1)) buffer.append(delimiter);
}
String key = buffer.toString();
if (get(output, key) == null) put(output, key, item);
}
}
return output;
}
/**
* Returns a new IData document containing all denormalized items from the given input IData document.
*
* Array items are denormalized to individual items in the output IData document with their keys suffixed
* with "[n]" where n is the item's array index.
*
* Items in nested IData documents are denormalized to items included directly in the output IData document
* with their keys prefixed with the associated fully-qualified nested path.
*
* @param input An IData document to be denormalized.
* @return The denormalized IData document.
*/
public static IData denormalize(IData input) {
if (input == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = input.getCursor();
IDataCursor outputCursor = output.getCursor();
denormalize(inputCursor, outputCursor, null);
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Inserts each item of the given input IDataCursor to the end of the given output IDataCursor with the keys
* denormalized to a fully-qualified key.
*
* @param inputCursor The cursor to source items to be denormalized from.
* @param outputCursor The cursor to insert the denormalized items into.
* @param path The original path to the IData document being denormalized from the inputCursor, or null.
*/
private static void denormalize(IDataCursor inputCursor, IDataCursor outputCursor, String path) {
if (inputCursor == null || outputCursor == null) return;
while(inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
denormalize(toIDataArray(value), outputCursor, path == null ? key : path + "/" + key);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
IData child = toIData(value);
IDataCursor childCursor = child.getCursor();
denormalize(childCursor, outputCursor, path == null ? key : path + "/" + key);
childCursor.destroy();
} else if (value instanceof Object[][]) {
denormalize((Object[][])value, outputCursor, path == null ? key : path + "/" + key);
} else if (value instanceof Object[]) {
denormalize((Object[])value, outputCursor, path == null ? key : path + "/" + key);
} else {
outputCursor.insertAfter(path == null ? key : path + "/" + key, value);
}
}
inputCursor.destroy();
outputCursor.destroy();
}
/**
* Inserts each item of the given array to the end of the given IDataCursor with the given
* key suffixed with "[n]" where n is the item's array index.
*
* @param array An array to be denormalized into the given IDataCursor.
* @param outputCursor The cursor to insert the denormalized array items into.
* @param key The original key associated with this array in the IData document being denormalized.
*/
private static void denormalize(IData[] array, IDataCursor outputCursor, String key) {
if (array == null || array.length == 0 || outputCursor == null || key == null) return;
for (int i = 0; i < array.length; i++) {
IData child = array[i];
if (child != null) {
IDataCursor inputCursor = child.getCursor();
denormalize(inputCursor, outputCursor, key + "[" + i + "]");
inputCursor.destroy();
}
}
}
/**
* Inserts each item of the given two dimensional array to the end of the given IDataCursor with the given
* key suffixed with "[n][m]" where n and m are the item's array indexes.
*
* @param array An array to be denormalized into the given IDataCursor.
* @param outputCursor The cursor to insert the denormalized array items into.
* @param key The original key associated with this array in the IData document being denormalized.
*/
private static void denormalize(Object[][] array, IDataCursor outputCursor, String key) {
if (array == null || array.length == 0 || outputCursor == null || key == null) return;
for (int i = 0; i < array.length; i++) {
denormalize(array[i], outputCursor, key + "[" + i + "]");
}
}
/**
* Inserts each item of the given array to the end of the given IDataCursor with the given
* key suffixed with "[n]" where n is the item's array index.
*
* @param array An array to be denormalized into the given IDataCursor.
* @param outputCursor The cursor to insert the denormalized array items into.
* @param key The original key associated with this array in the IData document being denormalized.
*/
private static void denormalize(Object[] array, IDataCursor outputCursor, String key) {
if (array == null || array.length == 0 || outputCursor == null || key == null) return;
for (int i = 0; i < array.length; i++) {
outputCursor.insertAfter(key + "[" + i + "]", array[i]);
}
outputCursor.destroy();
}
/**
* Sorts the given IData document by its keys in natural ascending order.
*
* @param document An IData document to be sorted by its keys.
* @return A new IData document which is duplicate of the given input IData document but with its keys
* sorted in natural ascending order.
*/
public static IData sort(IData document) {
return sort(document, true);
}
/**
* Sorts the given IData document by its keys in natural ascending order.
*
* @param document An IData document to be sorted by its keys.
* @param recurse A boolean which when true will also recursively sort nested IData document and IData[] document
* lists.
* @return A new IData document which is duplicate of the given input IData document but with its keys
* sorted in natural ascending order.
*/
public static IData sort(IData document, boolean recurse) {
return sort(document, recurse, false);
}
/**
* Sorts the given IData document by its keys in natural ascending or descending order.
*
* @param document An IData document to be sorted by its keys.
* @param recurse A boolean which when true will also recursively sort nested IData document and IData[]
* document lists.
* @param descending Whether to sort in descending or ascending order.
* @return A new IData document which is duplicate of the given input IData document but with its keys
* sorted in natural ascending order.
*/
public static IData sort(IData document, boolean recurse, boolean descending) {
if (document == null) return null;
String[] keys = ArrayHelper.sort(getKeys(document), descending);
IData output = IDataFactory.create();
IDataCursor ic = document.getCursor();
IDataCursor oc = output.getCursor();
for (int i = 0; i < keys.length; i++) {
boolean result;
if (i > 0 && keys[i].equals(keys[i - 1])) {
result = ic.next(keys[i]);
} else {
result = ic.first(keys[i]);
}
if (result) {
Object value = ic.getValue();
if (recurse) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
IData[] array = toIDataArray(value);
for (int j = 0; j < array.length; j++) {
array[j] = sort(array[j], recurse);
}
value = array;
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = sort(toIData(value), recurse);
}
}
oc.insertAfter(keys[i], value);
}
}
ic.destroy();
oc.destroy();
return output;
}
/**
* Returns a new IData[] array with all elements sorted in ascending order by the values associated with the given
* key.
*
* @param array An IData[] array to be sorted.
* @param key The key to use to sort the array.
* @return A new IData[] array sorted by the given key.
*/
public static IData[] sort(IData[] array, String key) {
return sort(array, key, true);
}
/**
* Returns a new IData[] array with all elements sorted in either ascending or descending order by the values
* associated with the given key.
*
* @param array An IData[] array to be sorted.
* @param key The key to use to sort the array.
* @param ascending When true, the array will be sorted in ascending order, otherwise it will be sorted in
* descending order.
* @return A new IData[] array sorted by the given key.
*/
public static IData[] sort(IData[] array, String key, boolean ascending) {
String[] keys = null;
if (key != null) {
keys = new String[1];
keys[0] = key;
}
return sort(array, keys, ascending);
}
/**
* Returns a new IData[] array with all elements sorted in ascending order by the values associated with the given
* keys.
*
* @param array An IData[] array to be sorted.
* @param keys The list of keys in order of precedence to use to sort the array.
* @return A new IData[] array sorted by the given keys.
*/
public static IData[] sort(IData[] array, String[] keys) {
return sort(array, keys, true);
}
/**
* Returns a new IData[] array with all elements sorted in either ascending or descending order by the values
* associated with the given keys.
*
* @param array An IData[] array to be sorted.
* @param keys The list of keys in order of precedence to use to sort the array.
* @param ascending When true, the array will be sorted in ascending order, otherwise it will be sorted in
* descending order.
* @return A new IData[] array sorted by the given keys.
*/
public static IData[] sort(IData[] array, String[] keys, boolean ascending) {
if (array == null || array.length < 2 || keys == null || keys.length == 0) return array;
IDataComparisonCriterion[] criteria = new IDataComparisonCriterion[keys.length];
for (int i = 0; i < keys.length; i++) {
criteria[i] = new IDataComparisonCriterion(keys[i], !ascending);
}
return sort(array, criteria);
}
/**
* Returns a new IData[] array with all elements sorted according to the specified criteria.
*
* @param array An IData[] array to be sorted.
* @param criteria One or more sort criteria.
* @return A new IData[] array sorted by the given criteria.
*/
public static IData[] sort(IData[] array, IDataComparisonCriterion... criteria) {
if (array == null) return null;
if (criteria != null && criteria.length > 0) {
array = ArrayHelper.sort(array, new CriteriaBasedIDataComparator(criteria));
} else {
array = Arrays.copyOf(array, array.length);
}
return array;
}
/**
* Returns a new IData[] array with all elements sorted according to the specified criteria.
*
* @param array An IData[] array to be sorted.
* @param criteria One or more sort criteria specified as an IData[].
* @return A new IData[] array sorted by the given criteria.
*/
public static IData[] sort(IData[] array, IData[] criteria) {
return sort(array, IDataComparisonCriterion.of(criteria));
}
/**
* Returns a new IData[] array with all elements sorted according to the specified criteria.
*
* @param array An IData[] array to be sorted.
* @param comparator An IDataComparator object used to determine element ordering.
* @return A new IData[] array sorted by the given criteria.
*/
public static IData[] sort(IData[] array, IDataComparator comparator) {
if (array == null) return null;
return ArrayHelper.sort(array, comparator);
}
/**
* Returns the values associated with the given key from each item in the given IData[] document list.
*
* @param array An IData[] array to return values from.
* @param key A fully-qualified key identifying the values to return.
* @param defaultValue The default value returned if the key does not exist.
* @return The values associated with the given key from each IData item in the given array.
*/
public static Object[] getValues(IData[] array, String key, Object defaultValue) {
if (array == null || key == null) return null;
List<Object> list = new ArrayList<Object>(array.length);
for (IData item : array) {
list.add(get(item, key, defaultValue));
}
return ArrayHelper.normalize(list);
}
/**
* Converts all the keys in the given IData document to lower case.
*
* @param input The IData whose keys are to be converted to lower case.
* @return The given IData duplicated with all keys converted to lower case.
*/
public static IData keysToLowerCase(IData input) {
return keysToLowerCase(input, true);
}
/**
* Converts all the keys in the given IData document to lower case.
*
* @param input The IData whose keys are to be converted to lower case.
* @param recurse Whether child IData and IData[] objects should also have their keys converted to lower case.
* @return The given IData duplicated with all keys converted to lower case.
*/
public static IData keysToLowerCase(IData input, boolean recurse) {
if (input == null) return null;
IData output = IDataFactory.create();
IDataCursor inputCursor = input.getCursor();
IDataCursor outputCursor = output.getCursor();
while(inputCursor.next()) {
String key = inputCursor.getKey();
Object value = inputCursor.getValue();
if (recurse) {
if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) {
value = keysToLowerCase(toIDataArray(value), recurse);
} else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) {
value = keysToLowerCase(toIData(value), recurse);
}
}
outputCursor.insertAfter(key.toLowerCase(), value);
}
inputCursor.destroy();
outputCursor.destroy();
return output;
}
/**
* Converts all the keys in the given IData[] document list to lower case.
*
* @param input The IData[] whose keys are to be converted to lower case.
* @return The given IData[] duplicated with all keys converted to lower case.
*/
public static IData[] keysToLowerCase(IData[] input) {
return keysToLowerCase(input, true);
}
/**
* Converts all the keys in the given IData[] document list to lower case.
*
* @param input The IData[] whose keys are to be converted to lower case.
* @param recurse Whether child IData and IData[] objects should also have their keys converted to lower case.
* @return The given IData[] duplicated with all keys converted to lower case.
*/
public static IData[] keysToLowerCase(IData[] input, boolean recurse) {
if (input == null) return null;
IData[] output = new IData[input.length];
for (int i = 0; i < input.length; i++) {
output[i] = keysToLowerCase(input[i], recurse);
}
return output;
}
/**
* Groups the given IData[] by the given keys.
*
* @param array The IData[] to be grouped.
* @param keys The keys to group items by.
* @return The grouped IData[].
*/
public static IData[] group(IData[] array, String... keys) {
Map<CompoundKey, List<IData>> groups = group(array, IDataComparisonCriterion.of(keys));
List<IData> result;
if (groups.size() == 0) {
result = new ArrayList<IData>(1);
IData document = IDataFactory.create();
IDataCursor cursor = document.getCursor();
IDataUtil.put(cursor, "group", IDataFactory.create());
IDataUtil.put(cursor, "items", array);
cursor.destroy();
result.add(document);
} else {
result = new ArrayList<IData>(groups.size());
for (Map.Entry<CompoundKey, List<IData>> entry : groups.entrySet()) {
CompoundKey key = entry.getKey();
List<IData> items = entry.getValue();
IData group = IDataFactory.create();
IDataCursor cursor = group.getCursor();
IDataUtil.put(cursor, "group", key.getIData());
IDataUtil.put(cursor, "items", items.toArray(new IData[items.size()]));
cursor.destroy();
result.add(group);
}
}
return result.toArray(new IData[result.size()]);
}
/**
* Performs a multi-level grouping of the given IData[] by the given criteria.
*
* @param array The IData[] to be grouped.
* @param criteria The multi-level grouping criteria.
* @return The grouped IData[].
*/
public static IData[] group(IData[] array, IData criteria) {
if (array == null) return null;
List<IData> result;
if (criteria == null) {
result = new ArrayList<IData>(1);
IData document = IDataFactory.create();
IDataCursor cursor = document.getCursor();
IDataUtil.put(cursor, "by", IDataFactory.create());
IDataUtil.put(cursor, "items", array);
cursor.destroy();
result.add(document);
} else {
IDataCursor criteriaCursor = criteria.getCursor();
IData[] by = IDataUtil.getIDataArray(criteriaCursor, "by");
IData then = IDataUtil.getIData(criteriaCursor, "then");
criteriaCursor.destroy();
Map<CompoundKey, List<IData>> groups = group(array, IDataComparisonCriterion.of(by));
result = new ArrayList<IData>(groups.size());
for (Map.Entry<CompoundKey, List<IData>> entry : groups.entrySet()) {
CompoundKey key = entry.getKey();
List<IData> value = entry.getValue();
IData[] items = value.toArray(new IData[value.size()]);
IData group = IDataFactory.create();
IDataCursor cursor = group.getCursor();
IDataUtil.put(cursor, "by", key.getIData());
IDataUtil.put(cursor, "items", items);
if (then != null) IDataUtil.put(cursor, "then", group(items, then));
cursor.destroy();
result.add(group);
}
}
return result.toArray(new IData[result.size()]);
}
/**
* Groups the given IData[] by the given keys.
*
* @param array The IData[] to be grouped.
* @param criteria The criteria to group items by.
* @return A Map containing the groups and their items.
*/
public static Map<CompoundKey, List<IData>> group(IData[] array, IDataComparisonCriterion[] criteria) {
Map<CompoundKey, List<IData>> groups = new TreeMap<CompoundKey, List<IData>>();
if (array != null && criteria != null || criteria.length == 0) {
for (IData item : array) {
if (item != null) {
CompoundKey key = new CompoundKey(criteria, item);
List<IData> list = groups.get(key);
if (list == null) {
list = new ArrayList<IData>();
groups.put(key, list);
}
list.add(item);
}
}
}
return groups;
}
/**
* Returns a new IData[] document list that only contains unique IData objects from the input IData[] document
* list.
*
* @param array The IData[] document list to find the unique set of.
* @return A new IData[] document list only containing the first occurrence of each IData containing a
* distinct set of values.
*/
public static IData[] unique(IData[] array) {
return unique(array, (String[])null);
}
/**
* Returns a new IData[] document list that only contains unique IData objects from the input IData[] document list,
* where uniqueness is determined by the values associated with the given list of keys.
*
* @param array The IData[] document list to find the unique set of.
* @param keys The keys whose associated values will be used to determine uniqueness. If not specified, all keys
* will be used to determine uniqueness.
* @return A new IData[] document list only containing the first occurrence of each IData containing a distinct
* set of values associated with the given list of keys.
*/
public static IData[] unique(IData[] array, String... keys) {
IData[] output = null;
if (array != null) {
if (array.length <= 1) {
output = Arrays.copyOf(array, array.length);
} else {
if (keys == null || keys.length == 0) keys = getKeys(array);
Map<CompoundKey, IData> set = new TreeMap<CompoundKey, IData>();
for (IData item : array) {
if (item != null) {
CompoundKey key = new CompoundKey(keys, item);
if (!set.containsKey(key)) set.put(key, item);
}
}
output = set.values().toArray(new IData[set.size()]);
}
}
return output;
}
/**
* Represents a compound key which can be used for grouping IData documents together.
*/
private static class CompoundKey implements Comparable<CompoundKey>, IDataCodable {
/**
* The comparator used for comparison with other compound keys.
*/
private CriteriaBasedIDataComparator comparator;
/**
* The IData document containing the values referenced by the compound key.
*/
private IData document;
/**
* Constructs a new compound key for the given list of keys and their associated values from the given IData
* document.
*
* @param keys The keys which together form this compound key.
* @param document The IData document containing the values associated with the given keys.
*/
public CompoundKey(String[] keys, IData document) {
this(new CriteriaBasedIDataComparator(IDataComparisonCriterion.of(keys)), document);
}
/**
* Constructs a new compound key for the given comparison criteria and their associated values from the given
* IData document.
*
* @param criteria The comparison criteria which together form this compound key.
* @param document The IData document containing the values associated with the given keys.
*/
public CompoundKey(IDataComparisonCriterion[] criteria, IData document) {
this(new CriteriaBasedIDataComparator(criteria), document);
}
/**
* Constructs a new compound key for the given comparison criteria and their associated values from the given
* IData document.
*
* @param criteria The comparison criteria which together form this compound key.
* @param document The IData document containing the values associated with the given keys.
*/
public CompoundKey(List<IDataComparisonCriterion> criteria, IData document) {
this(new CriteriaBasedIDataComparator(criteria), document);
}
/**
* Constructs a new compound key for the given comparison criteria and their associated values from the given
* IData document.
*
* @param comparator The comparator used for comparison with other compound keys.
* @param document The IData document containing the values associated with the given keys.
*/
private CompoundKey(CriteriaBasedIDataComparator comparator, IData document) {
if (comparator == null) throw new NullPointerException("comparator must not be null");
if (document == null) throw new NullPointerException("document must not be null");
this.comparator = comparator;
this.document = document;
}
/**
* Returns the IData document containing the values used by this compound key.
*
* @return The IData document containing the values used by this compound key.
*/
public IData getDocument() {
return this.document;
}
/**
* Sets the IData document containing the values used for comparison by this compound key.
*
* @param document The IData document containing the values to be used for comparison by this compound key.
*/
public void setDocument(IData document) {
if (document == null) throw new NullPointerException("document must not be null");
this.document = document;
}
/**
* Returns the comparator used for comparisons by this compound key.
*
* @return The comparator used for comparisons by this compound key.
*/
public CriteriaBasedIDataComparator getComparator() {
return this.comparator;
}
/**
* Sets the comparator to be used by this compound key in comparisons.
*
* @param comparator The comparator to be used by this compound key in comparisons.
*/
public void setComparator(CriteriaBasedIDataComparator comparator) {
this.comparator = comparator;
}
/**
* Returns an IData representation of this compound key.
*
* @return An IData representation of this compound key.
*/
public IData getIData() {
IData output = IDataFactory.create();
for (IDataComparisonCriterion criterion : comparator.getCriteria()) {
IDataHelper.put(output, criterion.getKey(), IDataHelper.get(document, criterion.getKey()));
}
return output;
}
/**
* This method is not implemented.
*
* @param document Not used.
* @throws UnsupportedOperationException as this method is not implemented.
*/
public void setIData(IData document) {
throw new UnsupportedOperationException("method not implemented");
}
/**
* Compares this compound key with another compound key.
*
* @param other The other key to be compared with.
* @return 0 if the two keys are equal, less than 0 if this key is less than the other key,
* greater than 0 if this key is greater than the other key.
*/
public int compareTo(CompoundKey other) {
if (other == null) return 1;
return comparator.compare(this.document, other.getIData());
}
/**
* Returns true if this object is equal to the other object.
*
* @param other The object to compare for equality with.
* @return True if this object is equal to the other object.
*/
public boolean equals(Object other) {
boolean result = false;
if (other instanceof CompoundKey) {
result = this.compareTo((CompoundKey)other) == 0;
}
return result;
}
}
} |
package prm4j.indexing.realtime;
import java.util.Arrays;
import prm4j.api.Event;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.staticdata.ChainData;
/**
* Holds a set of {@link BaseMonitor}s.
*/
public class MonitorSet {
/**
* Initial capacity of the set.
*/
protected static final int DEFAULT_CAPACITY = 16;
/**
* Number of contained monitors
*/
private int size = 0;
/**
* Stores the monitors
*/
private NodeRef[] monitorSet;
public MonitorSet() {
monitorSet = new NodeRef[DEFAULT_CAPACITY];
}
/**
* Adds a monitor to the monitor set.
*
* @param monitor
*/
public void add(NodeRef monitor) {
monitorSet[size++] = monitor;
ensureCapacity();
}
/**
* Enlarge the capacity if we run out of space.
*/
private void ensureCapacity() {
if (size >= monitorSet.length) {
int capacity = (monitorSet.length * 3) / 2 + 1;
monitorSet = Arrays.copyOf(monitorSet, capacity);
}
}
/**
* Updates all alive monitors in this monitor set by processing the given event. All monitors in the set are tested,
* if they have reached the end of their lifetime. In this case, they are removed from the monitor set. A monitor
* has reached the end of its lifetime if is already terminated, or if some bindings, necessary to reach an
* accepting state, have already expired.
*
* @param event
* the current event
*/
public void processEvent(Event event) {
int deadPartitionStart = 0;
for (int i = 0; i < size; i++) {
final NodeRef nodeRef = monitorSet[i];
final BaseMonitor monitor = nodeRef.monitor;
// check if the monitor was already gc'ed by the NodeManager
if (nodeRef.monitor == null) {
continue;
}
// check if the monitor was terminated by some other operation
if (nodeRef.monitor.isTerminated()) {
nodeRef.monitor = null;
continue;
}
// if the monitor is still alive after processing, its reference is copied into the alive partition
if (monitor.process(event)) {
monitorSet[deadPartitionStart++] = nodeRef;
}
}
// nullify the dead partition
for (int i = deadPartitionStart; i < size; i++) {
monitorSet[i] = null;
}
size = deadPartitionStart;
}
/**
* Creates new nodes and bindings by trying to 'join' the current event bindings with all bindings in this monitor
* set. All monitors in the set are tested, if they have reached the end of their lifetime. In this case, they are
* removed from the monitor set. A monitor has reached the end of its lifetime if is already terminated, or if some
* bindings, necessary to reach an accepting state, have already expired.
*
* @param nodeStore
* access to all nodes
* @param event
* the current event
* @param joinableBindings
* a special copy of the event bindings as an 'expanded' array containing gaps to prepare the join (aka
* 'merge') with the bindings in the compatible monitor
* @param someBindingsAreKnown
* <code>true</code>, if some bindings have been seen already
* @param tmax
* the latest 'seeing' time of all bindings in joinableBindings
* @param copyPattern
* used to copy a number of bindings from the compatible monitor
*/
public void join(NodeStore nodeStore, Event event, final LowLevelBinding[] joinableBindings,
boolean someBindingsAreKnown, long tmax, int[] copyPattern) {
// create initial copy of the joinable; will gets cloned again if this one is used in a monitor
LowLevelBinding[] joinable = joinableBindings.clone();
// post-loop invariant: all monitors up to monitorSet[deadPartitionStart] are not dead
int deadPartitionStart = 0;
// iterate over all compatible nodes
for (int i = 0; i < size; i++) {
// this monitor holds some bindings we would like to copy to our joined bindings
final NodeRef compatibleNodeRef = monitorSet[i];
final BaseMonitor compatibleMonitor = compatibleNodeRef.monitor;
// test if some of the bindings had been used already after the compatible monitor was created.
if (someBindingsAreKnown && compatibleMonitor.getCreationTime() < tmax) {
// => the binding was not yet enabled => current event is not part of an accepting trace continued from
// this monitor => the joined monitor would never reach accepting state
deadPartitionStart++; // this monitor may be still alive, we just avoid joining with it
continue;
}
final LowLevelBinding[] compatibleBindings = compatibleMonitor.getLowLevelBindings();
// test if lifetime of monitor is already over
if (compatibleBindings == null) {
continue; // don't increment the deadPartitionStart => this monitor will be removed from the set
}
// copy some compatible bindings to our joinable
createJoin(joinable, compatibleBindings, copyPattern); // 67 - 71
// retrieve the node associated with the joined binding
final Node lastNode = nodeStore.getOrCreateNode(joinable);
// due to multiple joining phases, it can happen that the node already has a monitor
if (lastNode.getMonitor() == null) {
// inlined 'DefineTo' // 73
final BaseMonitor monitor = compatibleMonitor.copy(joinable); // 102-105
// process and test if monitor is still alive
if (monitor.process(event)) { // 103
// this monitor is alive, so copy its reference to the alive partition
monitorSet[deadPartitionStart++] = compatibleNodeRef;
}
lastNode.setMonitor(monitor); // 106
// normal chain phase: connect necessary less informative instances so the joined binding will gets some
// updates (or be used in join phase itself as compatible monitor)
for (ChainData chainData : lastNode.getMetaNode().getChainDataArray()) {
nodeStore.getOrCreateNode(joinable, chainData.getNodeMask())
.getMonitorSet(chainData.getMonitorSetId()).add(lastNode.getNodeRef());
}
// copy got used => clone again
joinable = joinableBindings.clone();
}
}
// remove all dead monitors from the monitor set by nullifying the 'dead partition'
for (int i = deadPartitionStart; i < size; i++) {
monitorSet[i] = null;
}
size = deadPartitionStart;
}
/**
* Merges the joiningBindings into the joinableBindings.
*
* @param joinableBindings
* special expanded array representation of the current event bindings
* @param joiningBindings
* compatible bindings from which some bindings will get copied
* @param copyPattern
* encodes which binding from joiningBindings gets copied to which location in joinableBindings
*/
private static void createJoin(LowLevelBinding[] joinableBindings, LowLevelBinding[] joiningBindings,
int[] copyPattern) {
for (int j = 0; j < copyPattern.length; j += 2) {
// copy from j to j+1
joinableBindings[copyPattern[j + 1]] = joiningBindings[copyPattern[j]];
}
}
/**
* DIAGNOSTIC: Searches the set linearly if monitor is contained, testing for object identity.
*
* @param monitor
* @return <code>true</code> if monitor is contained
*/
public boolean contains(BaseMonitor monitor) {
for (int i = 0; i < size; i++) {
if (monitorSet[i].monitor == monitor) {
return true;
}
}
return false;
}
/**
* Returns the number of monitors contained in the monitor set. It is unknown if the monitors are alive or dead.
*
* @return number of contained monitors
*/
public int getSize() {
return size;
}
/**
* Returns the array representation of this monitor set up to the full also containing any null values.
*/
@Override
public String toString() {
return Arrays.toString(monitorSet);
}
} |
package redis.clients.jedis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.util.JedisByteHashMap;
import redis.clients.util.SafeEncoder;
public final class BuilderFactory {
public static final Builder<Double> DOUBLE = new Builder<Double>() {
@Override
public Double build(Object data) {
String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString);
}
@Override
public String toString() {
return "double";
}
};
public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {
@Override
public Boolean build(Object data) {
return ((Long) data) == 1;
}
@Override
public String toString() {
return "boolean";
}
};
public static final Builder<byte[]> BYTE_ARRAY = new Builder<byte[]>() {
@Override
public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1
}
@Override
public String toString() {
return "byte[]";
}
};
public static final Builder<Long> LONG = new Builder<Long>() {
@Override
public Long build(Object data) {
return (Long) data;
}
@Override
public String toString() {
return "long";
}
};
public static final Builder<String> STRING = new Builder<String>() {
@Override
public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data);
}
@Override
public String toString() {
return "string";
}
};
public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {
@Override
@SuppressWarnings("unchecked")
public List<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@Override
public String toString() {
return "List<String>";
}
};
public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {
@Override
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<String, String> hash = new HashMap<String, String>(flatHash.size()/2, 1);
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()));
}
return hash;
}
@Override
public String toString() {
return "Map<String, String>";
}
};
public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() {
@Override
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>(flatHash.size()/2, 1);
final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next()));
}
return hash;
}
@Override
public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>";
}
};
public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
@Override
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size(), 1);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@Override
public String toString() {
return "Set<String>";
}
};
public static final Builder<List<byte[]>> BYTE_ARRAY_LIST = new Builder<List<byte[]>>() {
@Override
@SuppressWarnings("unchecked")
public List<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
return l;
}
@Override
public String toString() {
return "List<byte[]>";
}
};
public static final Builder<Set<byte[]>> BYTE_ARRAY_ZSET = new Builder<Set<byte[]>>() {
@Override
@SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(barray);
}
}
return result;
}
@Override
public String toString() {
return "ZSet<byte[]>";
}
};
public static final Builder<Map<byte[], byte[]>> BYTE_ARRAY_MAP = new Builder<Map<byte[], byte[]>>() {
@Override
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next());
}
return hash;
}
@Override
public String toString() {
return "Map<byte[], byte[]>";
}
};
public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {
@Override
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size(), 1);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@Override
public String toString() {
return "ZSet<String>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET = new Builder<Set<Tuple>>() {
@Override
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size()/2, 1);
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()), Double.valueOf(SafeEncoder
.encode(iterator.next()))));
}
return result;
}
@Override
public String toString() {
return "ZSet<Tuple>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET_BINARY = new Builder<Set<Tuple>>() {
@Override
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size()/2, 1);
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
}
@Override
public String toString() {
return "ZSet<Tuple>";
}
};
public static final Builder<Object> EVAL_RESULT = new Builder<Object>() {
@Override
public Object build(Object data) {
return evalResult(data);
}
@Override
public String toString() {
return "Eval<Object>";
}
private Object evalResult(Object result) {
if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result);
if (result instanceof List<?>) {
List<?> list = (List<?>) result;
List<Object> listResult = new ArrayList<Object>(list.size());
for (Object bin : list) {
listResult.add(evalResult(bin));
}
return listResult;
}
return result;
}
};
public static final Builder<Object> EVAL_BINARY_RESULT = new Builder<Object>() {
@Override
public Object build(Object data) {
return evalResult(data);
}
@Override
public String toString() {
return "Eval<Object>";
}
private Object evalResult(Object result) {
if (result instanceof List<?>) {
List<?> list = (List<?>) result;
List<Object> listResult = new ArrayList<Object>(list.size());
for (Object bin : list) {
listResult.add(evalResult(bin));
}
return listResult;
}
return result;
}
};
public static final Builder<List<GeoCoordinate>> GEO_COORDINATE_LIST = new Builder<List<GeoCoordinate>>() {
@Override
public List<GeoCoordinate> build(Object data) {
if (null == data) {
return null;
}
return interpretGeoposResult((List<Object>) data);
}
@Override
public String toString() {
return "List<GeoCoordinate>";
}
private List<GeoCoordinate> interpretGeoposResult(List<Object> responses) {
List<GeoCoordinate> responseCoordinate = new ArrayList<GeoCoordinate>(responses.size());
for (Object response : responses) {
if (response == null) {
responseCoordinate.add(null);
} else {
List<Object> respList = (List<Object>) response;
GeoCoordinate coord = new GeoCoordinate(Double.parseDouble(SafeEncoder
.encode((byte[]) respList.get(0))), Double.parseDouble(SafeEncoder
.encode((byte[]) respList.get(1))));
responseCoordinate.add(coord);
}
}
return responseCoordinate;
}
};
public static final Builder<List<GeoRadiusResponse>> GEORADIUS_WITH_PARAMS_RESULT = new Builder<List<GeoRadiusResponse>>() {
@Override
public List<GeoRadiusResponse> build(Object data) {
if (data == null) {
return null;
}
List<Object> objectList = (List<Object>) data;
List<GeoRadiusResponse> responses = new ArrayList<GeoRadiusResponse>(objectList.size());
if (objectList.isEmpty()) {
return responses;
}
if (objectList.get(0) instanceof List<?>) {
// list of members with additional informations
GeoRadiusResponse resp;
for (Object obj : objectList) {
List<Object> informations = (List<Object>) obj;
resp = new GeoRadiusResponse((byte[]) informations.get(0));
int size = informations.size();
for (int idx = 1; idx < size; idx++) {
Object info = informations.get(idx);
if (info instanceof List<?>) {
// coordinate
List<Object> coord = (List<Object>) info;
resp.setCoordinate(new GeoCoordinate(DOUBLE.build(coord.get(0)),
DOUBLE.build(coord.get(1))));
} else {
// distance
resp.setDistance(DOUBLE.build(info));
}
}
responses.add(resp);
}
} else {
// list of members
for (Object obj : objectList) {
responses.add(new GeoRadiusResponse((byte[]) obj));
}
}
return responses;
}
private Double convertByteArrayToDouble(Object obj) {
return Double.valueOf(SafeEncoder.encode((byte[]) obj));
}
@Override
public String toString() {
return "GeoRadiusWithParamsResult";
}
};
public static final Builder<List<Module>> MODULE_LIST = new Builder<List<Module>>() {
@Override
public List<Module> build(Object data) {
if (data == null) {
return null;
}
List<List<Object>> objectList = (List<List<Object>>) data;
List<Module> responses = new ArrayList<Module>(objectList.size());
if (objectList.isEmpty()) {
return responses;
}
for (List<Object> moduleResp: objectList) {
Module m = new Module(SafeEncoder.encode((byte[]) moduleResp.get(1)), ((Long) moduleResp.get(3)).intValue());
responses.add(m);
}
return responses;
}
@Override
public String toString() {
return "List<Module>";
}
};
public static final Builder<List<Long>> LONG_LIST = new Builder<List<Long>>() {
@Override
@SuppressWarnings("unchecked")
public List<Long> build(Object data) {
if (null == data) {
return null;
}
return (List<Long>) data;
}
@Override
public String toString() {
return "List<Long>";
}
};
private BuilderFactory() {
throw new InstantiationError( "Must not instantiate this class" );
}
} |
package imj2.tools;
import static imj2.tools.MultiresolutionSegmentationTest.getColorGradient;
import static imj2.tools.TiledParticleSegmentationTest.XYW.xyw;
import static java.awt.Color.BLACK;
import static java.awt.Color.RED;
import static java.awt.Color.WHITE;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.util.Arrays.sort;
import static java.util.Collections.nCopies;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import imj.IntList;
import imj2.tools.Image2DComponent.Painter;
import imj2.tools.RegionShrinkingTest.AutoMouseAdapter;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import net.sourceforge.aprog.tools.Tools;
import org.junit.Test;
/**
* @author codistmonk (creation 2014-02-23)
*/
public final class TiledParticleSegmentationTest {
/**
* {@value}.
*/
public static final int NORTH = 0;
/**
* {@value}.
*/
public static final int WEST = 1;
/**
* {@value}.
*/
public static final int EAST = 2;
/**
* {@value}.
*/
public static final int SOUTH = 3;
@Test
public final void test() {
final int quantizationAlgorithm = 1;
final boolean fillSegments = false;
final Color regionSeparationColor = Color.GREEN;
final Color segmentSeparationColor = null;
final Color segmentLocatorColor = null;
final int algo0Q = 6;
final int algo1Q = 2;
final SimpleImageView imageView = new SimpleImageView();
new AutoMouseAdapter(imageView.getImageHolder()) {
private int cellSize = 7;
private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() {
private final Canvas segmentation;
{
this.segmentation = new Canvas();
imageView.getPainters().add(this);
}
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
final BufferedImage image = imageView.getImage();
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
this.segmentation.setFormat(imageWidth, imageHeight, BufferedImage.TYPE_BYTE_GRAY);
this.segmentation.clear(BLACK);
final int s = getCellSize();
final int horizontalTileCount = (imageWidth + s - 1) / s + 1;
final int verticalTileCount = (imageHeight + s - 1) / s + 1;
final int[] northXs = new int[horizontalTileCount * verticalTileCount];
final int[] westYs = new int[horizontalTileCount * verticalTileCount];
for (int tileY = 0; tileY + 2 < imageHeight; tileY += s) {
final int tileLastY = imageHeight <= tileY + s + 2 ? imageHeight - 1 : min(imageHeight - 1, tileY + s);
for (int tileX = 0; tileX + 2 < imageWidth; tileX += s) {
final int tileLastX = imageWidth <= tileX + s + 2 ? imageWidth - 1 : min(imageWidth - 1, tileX + s);
final int northY = tileY;
final int westX = tileX;
final int eastX = tileLastX;
final int southY = tileLastY;
final int northX = findMaximumGradientX(image, northY, westX + 1, eastX - 1);
final int westY = findMaximumGradientY(image, westX, northY + 1, southY - 1);
final int eastY = findMaximumGradientY(image, eastX, northY + 1, southY - 1);
final int southX = findMaximumGradientX(image, southY, westX + 1, eastX - 1);
final int tileIndex = tileY / s * horizontalTileCount + tileX / s;
northXs[tileIndex] = northX;
northXs[tileIndex + horizontalTileCount] = southX;
westYs[tileIndex] = westY;
westYs[tileIndex + 1] = eastY;
this.segmentation.getGraphics().setColor(WHITE);
this.segmentation.getGraphics().drawLine(northX, northY, southX, southY);
this.segmentation.getGraphics().drawLine(westX, westY, eastX, eastY);
}
}
final BufferedImage segmentationMask = this.segmentation.getImage();
if (segmentSeparationColor != null) {
for (int y = 0; y < imageHeight; ++y) {
for (int x = 0; x < imageWidth; ++x) {
if ((segmentationMask.getRGB(x, y) & 0x00FFFFFF) != 0) {
imageView.getBufferImage().setRGB(x, y, segmentSeparationColor.getRGB());
}
}
}
}
{
final List<Color> colors = new ArrayList<Color>(nCopies(horizontalTileCount * verticalTileCount, Color.BLACK));
for (int tileY = 0; tileY < imageHeight; tileY += s) {
for (int tileX = 0; tileX < imageWidth; tileX += s) {
final Color[] color = { Color.YELLOW };
new ComputeMeanColor(image, color).process(segmentationMask, tileX, tileY);
colors.set(tileY / s * horizontalTileCount + tileX / s , color[0]);
}
}
debugPrint(colors.size(), horizontalTileCount, verticalTileCount);
{
final int colorCount = colors.size();
final Color[] sortedColors = colors.toArray(new Color[0]);
final int[] redPrototypes = new int[min(algo1Q, colorCount)];
final int[] greenPrototypes = redPrototypes.clone();
final int[] bluePrototypes = redPrototypes.clone();
debugPrint(colorCount);
if (algo1Q < colorCount) {
sort(sortedColors, COLOR_RED_COMPARATOR);
computePrototypes(sortedColors, 16, algo1Q, redPrototypes);
sort(sortedColors, COLOR_GREEN_COMPARATOR);
computePrototypes(sortedColors, 8, algo1Q, greenPrototypes);
sort(sortedColors, COLOR_BLUE_COMPARATOR);
computePrototypes(sortedColors, 8, algo1Q, bluePrototypes);
}
debugPrint(Arrays.toString(redPrototypes));
debugPrint(Arrays.toString(greenPrototypes));
debugPrint(Arrays.toString(bluePrototypes));
final List<Color> quantizedColors = new ArrayList<Color>(colorCount);
final Set<Color> uniqueQuantizedColors = new HashSet<Color>();
for (final Color color : colors) {
final Color quantizedColor;
if (quantizationAlgorithm == 0) {
quantizedColor = quantize(color, algo0Q);
} else {
quantizedColor = quantize(color, redPrototypes, greenPrototypes, bluePrototypes);
}
quantizedColors.add(quantizedColor);
uniqueQuantizedColors.add(quantizedColor);
}
final BufferedImage labels = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
for (int tileY = s, tileRowIndex = tileY / s; tileY < imageHeight; tileY += s, ++tileRowIndex) {
for (int tileX = s, tileColumnIndex = tileX / s; tileX < imageWidth; tileX += s, ++tileColumnIndex) {
final int tileIndex = tileRowIndex * horizontalTileCount + tileColumnIndex;
final int rgb = quantizedColors.get(tileIndex).getRGB();
new SegmentProcessor() {
@Override
protected final void pixel(final int pixel, final int x, final int y) {
labels.setRGB(x, y, rgb);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 3483091181451079097L;
}.process(segmentationMask, tileX, tileY);
}
}
for (int tileY = 0; tileY + 2 < imageHeight; tileY += s) {
final int tileLastY = imageHeight <= tileY + s + 2 ? imageHeight - 1 : min(imageHeight - 1, tileY + s);
for (int tileX = 0; tileX + 2 < imageWidth; tileX += s) {
final int tileLastX = imageWidth <= tileX + s + 2 ? imageWidth - 1 : min(imageWidth - 1, tileX + s);
final int rgb = labels.getRGB(tileX, tileY);
if (fillSegments) {
new SegmentProcessor() {
@Override
protected final void pixel(final int pixel, final int x, final int y) {
imageView.getBuffer().getImage().setRGB(x, y, rgb);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -1650602767179074395L;
}.process(segmentationMask, tileX, tileY);
}
if (segmentLocatorColor != null) {
g.setColor(segmentLocatorColor);
g.drawOval(tileX - 1, tileY - 1, 2, 2);
}
if (regionSeparationColor != null) {
final int northY = tileY;
final int westX = tileX;
final int eastX = tileLastX;
final int southY = tileLastY;
final int tileIndex = tileY / s * horizontalTileCount + tileX / s;
final int northX = northXs[tileIndex];
final int westY = westYs[tileIndex];
final int southX = northXs[tileIndex + horizontalTileCount];
final int eastY = westYs[tileIndex + 1];
final XYW intersection = intersection(xyw(northX, northY), xyw(southX, southY), xyw(westX, westY), xyw(eastX, eastY));
final int intersectionX = intersection.getUnscaledX();
final int intersectionY = intersection.getUnscaledY();
g.setColor(regionSeparationColor);
if (rgb != labels.getRGB(tileLastX, tileY)) {
g.drawLine(northX, northY, intersectionX, intersectionY);
}
if (rgb != labels.getRGB(tileX, tileLastY)) {
g.drawLine(westX, westY, intersectionX, intersectionY);
}
if (labels.getRGB(tileX, tileLastY) != labels.getRGB(tileLastX, tileLastY)) {
g.drawLine(intersectionX, intersectionY, southX, southY);
}
if (labels.getRGB(tileLastX, tileY) != labels.getRGB(tileLastX, tileLastY)) {
g.drawLine(intersectionX, intersectionY, eastX, eastY);
}
}
}
}
debugPrint(uniqueQuantizedColors.size(), uniqueQuantizedColors);
}
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = -8170474943200742892L;
};
public final int getCellSize() {
return this.cellSize;
}
@Override
protected final void cleanup() {
imageView.getPainters().remove(this.painter);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -6497489818537320168L;
};
show(imageView, this.getClass().getSimpleName(), true);
}
public static final XYW intersection(final XYW line1Point1, final XYW line1Point2, final XYW line2Point1, final XYW line2Point2) {
final XYW line1 = line1Point1.cross(line1Point2);
final XYW line2 = line2Point1.cross(line2Point2);
assert line1.dot(line1Point1) == 0;
assert line1.dot(line1Point2) == 0;
assert line2.dot(line2Point1) == 0;
assert line2.dot(line2Point2) == 0;
return line1.cross(line2);
}
public static final Color quantize(final Color color, final int q) {
final int quantizationMask = ((((~0) << q) & 0xFF) * 0x00010101) | 0xFF000000;
return new Color(color.getRGB() & quantizationMask);
}
public static final Color quantize(final Color color,
final int[] redPrototypes, final int[] greenPrototypes, final int[] bluePrototypes) {
return new Color(
getNearestNeighbor(color.getRed(), redPrototypes),
getNearestNeighbor(color.getGreen(), greenPrototypes),
getNearestNeighbor(color.getBlue(), bluePrototypes));
}
public static final int getNearestNeighbor(final int value, final int[] prototypes) {
int result = value;
int nearestDistance = Integer.MAX_VALUE;
for (final int prototype : prototypes) {
final int distance = abs(value - prototype);
if (distance < nearestDistance) {
nearestDistance = distance;
result = prototype;
}
}
return result;
}
public static final void computePrototypes(final Color[] sortedColors, final int channelOffset,
final int q, final int[] prototypes) {
final int colorCount = sortedColors.length;
final int chunkSize = (colorCount + q - 1) / q;
for (int chunkIndex = 0, prototypeIndex = 0; chunkIndex < colorCount; chunkIndex += chunkSize, ++prototypeIndex) {
final int nextChunkIndex = min(chunkIndex + chunkSize, colorCount);
for (int colorIndex = chunkIndex; colorIndex < nextChunkIndex; ++colorIndex) {
prototypes[prototypeIndex] += (sortedColors[colorIndex].getRGB() >> channelOffset) & 0xFF;
}
final int actualChunkSize = nextChunkIndex - chunkIndex;
if (1 < actualChunkSize) {
prototypes[prototypeIndex] /= actualChunkSize;
}
}
}
public static final Comparator<Color> COLOR_RED_COMPARATOR = new Comparator<Color>() {
@Override
public final int compare(final Color color1, final Color color2) {
return color1.getRed() - color2.getRed();
}
};
public static final Comparator<Color> COLOR_GREEN_COMPARATOR = new Comparator<Color>() {
@Override
public final int compare(final Color color1, final Color color2) {
return color1.getGreen() - color2.getGreen();
}
};
public static final Comparator<Color> COLOR_BLUE_COMPARATOR = new Comparator<Color>() {
@Override
public final int compare(final Color color1, final Color color2) {
return color1.getBlue() - color2.getBlue();
}
};
public static final int findMaximumGradientX(final BufferedImage image, final int y, final int firstX, final int lastX) {
int maximumGradient = 0;
int result = (firstX + lastX) / 2;
for (int x = firstX; x <= lastX; ++x) {
final int gradient = getColorGradient(image, x, y);
if (maximumGradient < gradient) {
maximumGradient = gradient;
result = x;
}
}
return result;
}
public static final int findMaximumGradientY(final BufferedImage image, final int x, final int firstY, final int lastY) {
int maximumGradient = 0;
int result = (firstY + lastY) / 2;
for (int y = firstY; y <= lastY; ++y) {
final int gradient = getColorGradient(image, x, y);
if (maximumGradient < gradient) {
maximumGradient = gradient;
result = y;
}
}
return result;
}
/**
* @author codistmonk (creation 2014-02-24)
*/
public static final class ComputeMeanColor extends SegmentProcessor {
private final BufferedImage image;
private final Color[] color;
private int red = 0;
private int green = 0;
private int blue = 0;
public ComputeMeanColor(final BufferedImage image, final Color[] color) {
this.image = image;
this.color = color;
}
@Override
protected final void pixel(final int pixel, final int x, final int y) {
final int rgb = this.image.getRGB(x, y);
this.red += (rgb >> 16) & 0xFF;
this.green += (rgb >> 8) & 0xFF;
this.blue += (rgb >> 0) & 0xFF;
}
@Override
protected final void afterPixels() {
final int pixelCount = this.getPixelCount();
if (0 < pixelCount) {
this.red = (this.red / pixelCount) << 16;
this.green = (this.green / pixelCount) << 8;
this.blue = (this.blue / pixelCount) << 0;
}
this.color[0] = new Color(this.red | this.green | this.blue);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 8855412064679395641L;
}
/**
* @author codistmonk (creation 2014-02-24)
*/
public static abstract class SegmentProcessor implements Serializable {
private int pixelCount;
public final SegmentProcessor process(final BufferedImage segmentation, final int tileX, final int tileY) {
final IntList todo = new IntList();
final int w = segmentation.getWidth();
final int h = segmentation.getHeight();
final BitSet done = new BitSet(w * h);
this.pixelCount = 0;
todo.add(tileY * w + tileX);
this.beforePixels();
while (!todo.isEmpty()) {
final int pixel = todo.remove(0);
final int x = pixel % w;
final int y = pixel / w;
++this.pixelCount;
done.set(pixel);
this.pixel(pixel, x, y);
if (0 < y && !done.get(pixel - w) && (segmentation.getRGB(x, y - 1) & 0x00FFFFFF) == 0) {
todo.add(pixel - w);
}
if (0 < x && !done.get(pixel - 1) && (segmentation.getRGB(x - 1, y) & 0x00FFFFFF) == 0) {
todo.add(pixel - 1);
}
if (x + 1 < w && !done.get(pixel + 1) && (segmentation.getRGB(x + 1, y) & 0x00FFFFFF) == 0) {
todo.add(pixel + 1);
}
if (y + 1 < h && !done.get(pixel + w) && (segmentation.getRGB(x, y + 1) & 0x00FFFFFF) == 0) {
todo.add(pixel + w);
}
}
this.afterPixels();
return this;
}
public final int getPixelCount() {
return this.pixelCount;
}
protected void beforePixels() {
// NOP
}
protected abstract void pixel(int pixel, int x, int y);
protected void afterPixels() {
// NOP
}
/**
* {@value}.
*/
private static final long serialVersionUID = -5860299062780405885L;
}
/**
* @author codistmonk (creation 2014-02-25)
*/
public static final class XYW implements Serializable {
private final int x;
private final int y;
private final int w;
public XYW(final int x, final int y, final int w) {
this.x = x;
this.y = y;
this.w = w;
}
public final int getX() {
return this.x;
}
public final int getY() {
return this.y;
}
public final int getW() {
return this.w;
}
public final int getUnscaledX() {
return this.getX() / this.getW();
}
public final int getUnscaledY() {
return this.getY() / this.getW();
}
public final int dot(final XYW that) {
return this.getX() * that.getX() + this.getY() * that.getY() + this.getW() * that.getW();
}
public final XYW cross(final XYW that) {
return new XYW(
det(this.getY(), this.getW(), that.getY(), that.getW()),
det(this.getW(), this.getX(), that.getW(), that.getX()),
det(this.getX(), this.getY(), that.getX(), that.getY()));
}
@Override
public final String toString() {
return "[" + this.getX() + " " + this.getY() + " " + this.getW() + "]";
}
/**
* {@value}.
*/
private static final long serialVersionUID = -3326572044424114312L;
public static final int det(final int a, final int b, final int c, final int d) {
return a * d - b * c;
}
public static final XYW xyw(final int x, final int y) {
return new XYW(x, y, 1);
}
}
} |
package io.lumify.storm.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateUtil {
public static Date extractDateFromJSON(JSONObject json) {
if (json == null) {
return null;
}
try {
JSONArray streamsJson = json.getJSONArray("streams");
for (int i = 0; i < streamsJson.length(); i++) {
try {
JSONObject streamsIndexJson = streamsJson.getJSONObject(i);
JSONObject tagsJson = streamsIndexJson.getJSONObject("tags");
String creationTime = tagsJson.getString("creation_time");
System.out.println(creationTime);
Date date = parseDateString(creationTime);
if (date != null) {
return date;
}
} catch (JSONException e) {
//Could not find "creation_time" name on this pathway. Keep searching.
}
}
} catch (Exception e) {
System.out.println("Could not retrieve a \"geoLocation\" value from the JSON object.");
e.printStackTrace();
}
try {
JSONObject formatObject = json.getJSONObject("format");
JSONObject tagsObject = formatObject.getJSONObject("tags");
String creationTime = tagsObject.getString("creation_time");
System.out.println(creationTime);
Date date = parseDateString(creationTime);
if (date != null) {
return date;
}
} catch (Exception e) {
//Could not find "creation_time" name on this pathway. Keep searching.
}
return null;
}
private static Date parseDateString(String dateString) {
if (dateString.length() < 9) {
return null;
}
Integer year = Integer.parseInt(dateString.substring(0, 4));
Integer month = Integer.parseInt(dateString.substring(5,7));
Integer day = Integer.parseInt(dateString.substring(8,10));
Integer hour = null;
Integer min = null;
try {
hour = Integer.parseInt(dateString.substring(11, 13));
min = Integer.parseInt(dateString.substring(14, 16));
} catch (Exception e){
//No action required.
}
Integer sec = null;
try {
sec = Integer.parseInt(dateString.substring(17, 19));
} catch (Exception e){
//No action required.
}
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.clear();
if(year != null && month != null && day != null){
if(hour != null && min != null && sec != null){
cal.set(year,month,day,hour,min,sec);
} else if (hour != null && min != null){
cal.set(year,month,day,hour,min);
} else {
cal.set(year, month, day);
}
Date date = cal.getTime();
return date;
} else {
return null;
}
}
} |
package remark.client.controls;
import elemental.html.ButtonElement;
import webmattr.event.MouseEventHandler;
import webmattr.react.*;
import javax.inject.Inject;
import javax.inject.Singleton;
import static webmattr.dom.DOM.button;
import static webmattr.dom.DOM.span;
@Singleton
public class LaddaButton extends Component<LaddaButton.Props, LaddaButton.State> {
private final Ref<ButtonElement> refBtn = Ref.make();
private final Ref<Ladda> refLadda = Ref.make();
@Inject
public LaddaButton() {
}
// Lifecycle
@Override
protected void componentDidMount(ReactComponent<Props, State> $this) {
super.componentDidMount($this);
refBtn.get($this, btnEl -> {
refLadda.set($this, Ladda.create(btnEl));
});
}
// Render
@Override
protected State initState(ReactComponent<Props, State> $this, Props props, State state) {
state.status = props.status != null ? props.status : LaddaStatus.DEFAULT;
return super.initState($this, props, state);
}
@Override
protected ReactElement render(ReactComponent<Props, State> $this, Props props, State state) {
refLadda.get($this, laddaEl -> {
switch (state.status) {
case DEFAULT:
laddaEl.stop();
break;
case SPINNING:
laddaEl.start();
break;
}
// laddaEl.setProgress(props.progress);
});
return button($ -> $
.className("btn ladda-button" + " " + props.className)
.type(props.type)
.onClick(event -> {
if (props.onClick != null) {
props.onClick.handle(event);
}
})
.ref(refBtn)
.set("data-style", props.style != null ? props.style.value : LaddaStyle.ZOOM_IN.value)
.set("data-size", props.spinnerSize != null ? props.spinnerSize.value : null),
span($ -> $.className("ladda-label"),
props.children
)
);
}
// Props
public enum LaddaStatus {
DEFAULT,
SPINNING
}
// State
public enum LaddaStyle {
EXPAND_LEFT("expand-left"),
EXPAND_RIGHT("expand-right"),
EXPAND_UP("expand-up"),
EXPAND_DOWN("expand-down"),
ZOOM_IN("zoom-in"),
ZOOM_OUT("zoom-out"),
SLIDE_LEFT("slide-left"),
SLIDE_RIGHT("slide-right"),
SLIDE_UP("slide-up"),
SLIDE_DOWN("slide-down"),
CONTRACT("contract");
public String value;
LaddaStyle(String value) {
this.value = value;
}
}
// Settings
public enum SpinnerSize {
XS("xs"),
S("s"),
L("l");
public String value;
SpinnerSize(String value) {
this.value = value;
}
}
public static class Props extends BaseProps {
public String className;
public String type;
public MouseEventHandler onClick;
public LaddaStatus status;
public double progress; // (0.0 - 1.0)
public LaddaStyle style;
public SpinnerSize spinnerSize;
@Inject
public Props() {
}
public Props className(String className) {
this.className = className;
return this;
}
public Props type(String type) {
this.type = type;
return this;
}
public Props onClick(MouseEventHandler onClick) {
this.onClick = onClick;
return this;
}
public Props status(LaddaStatus status) {
this.status = status;
return this;
}
public Props progress(double progress) {
this.progress = progress;
return this;
}
public Props style(LaddaStyle style) {
this.style = style;
return this;
}
public Props spinnerSize(SpinnerSize spinnerSize) {
this.spinnerSize = spinnerSize;
return this;
}
}
public static class State {
LaddaStatus status;
@Inject
public State() {
}
}
} |
package meizhuo.org.lightmeeting.app;
import java.io.Serializable;
import meizhuo.org.lightmeeting.R;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.Optional;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public abstract class BaseActivity extends FragmentActivity {
@Optional @InjectView(R.id.tv_app_title) TextView tv_title;
@Optional @InjectView(R.id.iv_app_icon_back) ImageView iv_app_icon_back;
protected void onCreate(Bundle savedInstanceState, int layoutId) {
super.onCreate(savedInstanceState);
setContentView(layoutId);
ButterKnife.inject(this);
setAppTitle(getResources().getString(R.string.app_name));
setDisplayBackIcon(true);
}
public void setAppTitle(String title) {
if (tv_title != null) {
tv_title.setText(title);
}
}
public void setDisplayBackIcon(boolean display) {
if(display){
if ( iv_app_icon_back != null) {
iv_app_icon_back.setVisibility(View.VISIBLE);
}
}else{
if ( iv_app_icon_back != null) {
iv_app_icon_back.setVisibility(View.INVISIBLE);
}
}
}
/**
*
* Class<?> cls Activity
*
* @param cls
*/
public void openActivity(Class<?> cls) {
this.startActivity(new Intent(this, cls));
}
/**
* intentActivity
*
* @param intent
*/
public void openActivity(Intent intent) {
this.startActivity(intent);
}
/**
* ToasttoastString content
*
* @param content
* content of your want to Toast
*/
public void toast(String content) {
Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
}
/**
* Activity
*/
public void closeActivity() {
this.finish();
}
/**
* ActivityContext
*
* @return
*/
public Context getContext() {
return this;
}
/**
*
*
* @param content
*/
public void debug(String content) {
Log.i("debug", this.getClass().getName() + ":" + content);
}
/**
* Get intent extra
*
* @param name
* @return serializable
*/
@SuppressWarnings("unchecked") protected <V extends Serializable> V getSerializableExtra(
final String name) {
return (V) getIntent().getSerializableExtra(name);
}
/**
* Get intent extra
*
* @param name
* @return int -1 if not exist!
*/
protected int getIntExtra(final String name) {
return getIntent().getIntExtra(name, -1);
}
/**
* Get intent extra
*
* @param name
* @return string
*/
protected String getStringExtra(final String name) {
return getIntent().getStringExtra(name);
}
/**
* Get intent extra
*
* @param name
* @return string array
*/
protected String[] getStringArrayExtra(final String name) {
return getIntent().getStringArrayExtra(name);
}
@Override protected void onDestroy() {
super.onDestroy();
}
@Override protected void onPause() {
super.onPause();
}
@Override protected void onStop() {
super.onStop();
}
@Override protected void onResume() {
super.onResume();
}
@Optional @OnClick(R.id.btn_app_back) public void back() {
if (this.findViewById(R.id.tv_app_title).getVisibility() != View.INVISIBLE) {
closeActivity();
}
}
protected abstract void initData();
protected abstract void initLayout();
} |
package ru.org.linux.spring.dao;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ru.org.linux.site.*;
import ru.org.linux.spring.AddMessageRequest;
import ru.org.linux.util.LorHttpUtils;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
@Repository
public class MessageDao {
private static final Log logger = LogFactory.getLog(MessageDao.class);
@Autowired
private GroupDao groupDao;
@Autowired
private PollDao pollDao;
@Autowired
private TagDao tagDao;
private static final String queryMessage = "SELECT " +
"postdate, topics.id as msgid, userid, topics.title, " +
"topics.groupid as guid, topics.url, topics.linktext, ua_id, " +
"groups.title as gtitle, urlname, vote, havelink, section, topics.sticky, topics.postip, " +
"postdate<(CURRENT_TIMESTAMP-sections.expire) as expired, deleted, lastmod, commitby, " +
"commitdate, topics.stat1, postscore, topics.moderate, message, notop,bbcode, " +
"topics.resolved, restrict_comments, minor " +
"FROM topics " +
"INNER JOIN groups ON (groups.id=topics.groupid) " +
"INNER JOIN sections ON (sections.id=groups.section) " +
"INNER JOIN msgbase ON (msgbase.id=topics.id) " +
"WHERE topics.id=?";
private static final String updateDeleteMessage = "UPDATE topics SET deleted='t',sticky='f' WHERE id=?";
private static final String updateDeleteInfo = "INSERT INTO del_info (msgid, delby, reason, deldate) values(?,?,?, CURRENT_TIMESTAMP)";
private static final String queryEditInfo = "SELECT * FROM edit_info WHERE msgid=? ORDER BY id DESC";
private static final String queryTags = "SELECT tags_values.value FROM tags, tags_values WHERE tags.msgid=? AND tags_values.id=tags.tagid ORDER BY value";
private static final String updateUndeleteMessage = "UPDATE topics SET deleted='f' WHERE id=?";
private static final String updateUneleteInfo = "DELETE FROM del_info WHERE msgid=?";
private static final String queryOnlyMessage = "SELECT message FROM msgbase WHERE id=?";
private static final String queryTopicsIdByTime = "SELECT id FROM topics WHERE postdate>=? AND postdate<?";
public static final String queryTimeFirstTopic = "SELECT min(postdate) FROM topics WHERE postdate!='epoch'::timestamp";
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedJdbcTemplate;
private SimpleJdbcInsert editInsert;
@Autowired
private UserDao userDao;
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
editInsert =
new SimpleJdbcInsert(dataSource)
.withTableName("edit_info")
.usingColumns("msgid", "editor", "oldmessage", "oldtitle", "oldtags", "oldlinktext", "oldurl");
}
public Timestamp getTimeFirstTopic() {
return jdbcTemplate.queryForObject(queryTimeFirstTopic, Timestamp.class);
}
public String getMessage(Message message) {
return jdbcTemplate.queryForObject(queryOnlyMessage, String.class, message.getId());
}
public Message getById(int id) throws MessageNotFoundException {
Message message;
try {
message = jdbcTemplate.queryForObject(queryMessage, new RowMapper<Message>() {
@Override
public Message mapRow(ResultSet resultSet, int i) throws SQLException {
return new Message(resultSet);
}
}, id);
} catch (EmptyResultDataAccessException exception) {
throw new MessageNotFoundException(id);
}
return message;
}
public List<Integer> getMessageForMonth(int year, int month){
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
Timestamp ts_start = new Timestamp(calendar.getTimeInMillis());
calendar.add(Calendar.MONTH, 1);
Timestamp ts_end = new Timestamp(calendar.getTimeInMillis());
return jdbcTemplate.query(queryTopicsIdByTime, new RowMapper<Integer>() {
@Override
public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getInt("id");
}
}, ts_start, ts_end);
}
public List<EditInfoDTO> getEditInfo(int id) {
final List<EditInfoDTO> editInfoDTOs = new ArrayList<EditInfoDTO>();
jdbcTemplate.query(queryEditInfo, new RowCallbackHandler() {
@Override
public void processRow(ResultSet resultSet) throws SQLException {
EditInfoDTO editInfoDTO = new EditInfoDTO();
editInfoDTO.setId(resultSet.getInt("id"));
editInfoDTO.setMsgid(resultSet.getInt("msgid"));
editInfoDTO.setEditor(resultSet.getInt("editor"));
editInfoDTO.setOldmessage(resultSet.getString("oldmessage"));
editInfoDTO.setEditdate(resultSet.getTimestamp("editdate"));
editInfoDTO.setOldtitle(resultSet.getString("oldtitle"));
editInfoDTO.setOldtags(resultSet.getString("oldtags"));
editInfoDTOs.add(editInfoDTO);
}
}, id);
return editInfoDTOs;
}
public ImmutableList<String> getTags(Message message) {
final ImmutableList.Builder<String> tags = ImmutableList.builder();
jdbcTemplate.query(queryTags, new RowCallbackHandler() {
@Override
public void processRow(ResultSet resultSet) throws SQLException {
tags.add(resultSet.getString("value"));
}
}, message.getId());
return tags.build();
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void deleteWithBonus(Message message, User user, String reason, int bonus) throws UserErrorException {
String finalReason = reason;
jdbcTemplate.update(updateDeleteMessage, message.getId());
if (user.canModerate() && bonus!=0 && user.getId()!=message.getUid()) {
if (bonus>20 || bonus<0) {
throw new UserErrorException("Некорректное значение bonus");
}
userDao.changeScore(message.getUid(), -bonus);
finalReason += " ("+bonus+ ')';
}
jdbcTemplate.update(updateDeleteInfo, message.getId(), user.getId(), finalReason);
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void undelete(Message message) {
jdbcTemplate.update(updateUndeleteMessage, message.getId());
jdbcTemplate.update(updateUneleteInfo, message.getId());
}
private int allocateMsgid() {
return jdbcTemplate.queryForInt("select nextval('s_msgid') as msgid");
}
// call in @Transactional environment
public int saveNewMessage(final Message msg, Template tmpl, final HttpServletRequest request, Screenshot scrn, final User user)
throws IOException, ScriptErrorException {
final Group group = groupDao.getGroup(msg.getGroupId());
final int msgid = allocateMsgid();
String url = msg.getUrl();
String linktext = msg.getLinktext();
if (group.isImagePostAllowed()) {
if (scrn == null) {
throw new ScriptErrorException("scrn==null!?");
}
Screenshot screenshot = scrn.moveTo(tmpl.getObjectConfig().getHTMLPathPrefix() + "/gallery", Integer.toString(msgid));
url = "gallery/" + screenshot.getMainFile().getName();
linktext = "gallery/" + screenshot.getIconFile().getName();
}
final String finalUrl = url;
final String finalLinktext = linktext;
jdbcTemplate.execute(
"INSERT INTO topics (groupid, userid, title, url, moderate, postdate, id, linktext, deleted, ua_id, postip) VALUES (?, ?, ?, ?, 'f', CURRENT_TIMESTAMP, ?, ?, 'f', create_user_agent(?),?::inet)",
new PreparedStatementCallback<String>() {
@Override
public String doInPreparedStatement(PreparedStatement pst) throws SQLException, DataAccessException {
pst.setInt(1, group.getId());
pst.setInt(2, user.getId());
pst.setString(3, msg.getTitle());
pst.setString(4, finalUrl);
pst.setInt(5, msgid);
pst.setString(6, finalLinktext);
pst.setString(7, request.getHeader("User-Agent"));
pst.setString(8, msg.getPostIP());
pst.executeUpdate();
return null;
}
}
);
// insert message text
jdbcTemplate.update(
"INSERT INTO msgbase (id, message, bbcode) values (?,?, ?)",
msgid, msg.getMessage(), msg.isLorcode()
);
String logmessage = "Написана тема " + msgid + ' ' + LorHttpUtils.getRequestIP(request);
logger.info(logmessage);
return msgid;
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public int addMessage(HttpServletRequest request, AddMessageRequest form, Template tmpl, Group group, User user, Screenshot scrn, Message previewMsg) throws IOException, ScriptErrorException, UserErrorException {
final int msgid = saveNewMessage(
previewMsg,
tmpl,
request,
scrn,
user
);
if (group.isPollPostAllowed()) {
pollDao.createPoll(Arrays.asList(form.getPoll()), form.isMultiSelect(), msgid);
}
if (form.getTags() != null) {
final List<String> tags = TagDao.parseTags(form.getTags());
tagDao.updateTags(msgid, tags);
tagDao.updateCounters(Collections.<String>emptyList(), tags);
}
return msgid;
}
private boolean updateMessage(Message oldMsg, Message msg, User editor, List<String> newTags) {
List<String> oldTags = tagDao.getMessageTags(msg.getId());
EditInfoDTO editInfo = new EditInfoDTO();
editInfo.setMsgid(msg.getId());
editInfo.setEditor(editor.getId());
boolean modified = false;
if (!oldMsg.getMessage().equals(msg.getMessage())) {
editInfo.setOldmessage(oldMsg.getMessage());
modified = true;
namedJdbcTemplate.update(
"UPDATE msgbase SET message=:message WHERE id=:msgid",
ImmutableMap.of("message", msg.getMessage(), "msgid", msg.getId())
);
}
if (!oldMsg.getTitle().equals(msg.getTitle())) {
modified = true;
editInfo.setOldtitle(oldMsg.getTitle());
namedJdbcTemplate.update(
"UPDATE topics SET title=:title WHERE id=:id",
ImmutableMap.of("title", msg.getTitle(), "id", msg.getId())
);
}
if (!equalStrings(oldMsg.getLinktext(), msg.getLinktext())) {
modified = true;
editInfo.setOldlinktext(oldMsg.getLinktext());
namedJdbcTemplate.update(
"UPDATE topics SET linktext=:linktext WHERE id=:id",
ImmutableMap.of("linktext", msg.getLinktext(), "id", msg.getId())
);
}
if (!equalStrings(oldMsg.getUrl(), msg.getUrl())) {
modified = true;
editInfo.setOldurl(oldMsg.getUrl());
namedJdbcTemplate.update(
"UPDATE topics SET url=:url WHERE id=:id",
ImmutableMap.of("url", msg.getUrl(), "id", msg.getId())
);
}
if (newTags != null) {
boolean modifiedTags = tagDao.updateTags(msg.getId(), newTags);
if (modifiedTags) {
editInfo.setOldtags(TagDao.toString(oldTags));
tagDao.updateCounters(oldTags, newTags);
modified = true;
}
}
if (oldMsg.isMinor() != msg.isMinor()) {
namedJdbcTemplate.update("UPDATE topics SET minor=:minor WHERE id=:id",
ImmutableMap.of("minor", msg.isMinor(), "id", msg.getId()));
modified = true;
}
if (modified) {
editInsert.execute(new BeanPropertySqlParameterSource(editInfo));
}
return modified;
}
private static boolean equalStrings(String s1, String s2) {
if (Strings.isNullOrEmpty(s1)) {
return Strings.isNullOrEmpty(s2);
}
return s1.equals(s2);
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public boolean updateAndCommit(
Message newMsg,
Message message,
User user,
List<String> newTags,
boolean commit,
Integer changeGroupId,
int bonus
) {
boolean modified = updateMessage(message, newMsg, user, newTags);
if (commit) {
if (changeGroupId != null) {
if (message.getGroupId() != changeGroupId) {
jdbcTemplate.update("UPDATE topics SET groupid=? WHERE id=?", changeGroupId, message.getId());
jdbcTemplate.update("UPDATE groups SET stat4=stat4+1 WHERE id=? or id=?", message.getGroupId(), changeGroupId);
}
}
commit(message, user, bonus);
}
if (modified) {
logger.info("сообщение " + message.getId() + " исправлено " + user.getNick());
}
return modified;
}
private void commit(Message msg, User commiter, int bonus) {
if (bonus < 0 || bonus > 20) {
throw new IllegalStateException("Неверное значение bonus");
}
jdbcTemplate.update(
"UPDATE topics SET moderate='t', commitby=?, commitdate='now' WHERE id=?",
commiter.getId(),
msg.getId()
);
User author;
try {
author = userDao.getUser(msg.getUid());
} catch (UserNotFoundException e) {
throw new RuntimeException(e);
}
userDao.changeScore(author.getId(), bonus);
}
public void uncommit(Message msg) {
jdbcTemplate.update("UPDATE topics SET moderate='f',commitby=NULL,commitdate=NULL WHERE id=?", msg.getId());
}
public Message getPreviousMessage(Message message) {
int scrollMode = Section.getScrollMode(message.getSectionId());
List<Integer> res;
switch (scrollMode) {
case Section.SCROLL_SECTION:
res = jdbcTemplate.queryForList(
"SELECT topics.id as msgid FROM topics WHERE topics.commitdate=(SELECT max(commitdate) FROM topics, groups, sections WHERE sections.id=groups.section AND topics.commitdate<? AND topics.groupid=groups.id AND groups.section=? AND (topics.moderate OR NOT sections.moderate) AND NOT deleted)",
Integer.class,
message.getCommitDate(),
message.getSectionId()
);
break;
case Section.SCROLL_GROUP:
res = jdbcTemplate.queryForList(
"SELECT max(topics.id) as msgid FROM topics, groups, sections WHERE sections.id=groups.section AND topics.id<? AND topics.groupid=? AND topics.groupid=groups.id AND (topics.moderate OR NOT sections.moderate) AND NOT deleted",
Integer.class,
message.getMessageId(),
message.getGroupId()
);
break;
case Section.SCROLL_NOSCROLL:
default:
return null;
}
try {
if (res.isEmpty() || res.get(0)==null) {
return null;
}
int prevMsgid = res.get(0);
return getById(prevMsgid);
} catch (MessageNotFoundException e) {
throw new RuntimeException(e);
}
}
public Message getNextMessage(Message message) {
int scrollMode = Section.getScrollMode(message.getSectionId());
List<Integer> res;
switch (scrollMode) {
case Section.SCROLL_SECTION:
res = jdbcTemplate.queryForList(
"SELECT topics.id as msgid FROM topics WHERE topics.commitdate=(SELECT min(commitdate) FROM topics, groups, sections WHERE sections.id=groups.section AND topics.commitdate>? AND topics.groupid=groups.id AND groups.section=? AND (topics.moderate OR NOT sections.moderate) AND NOT deleted)",
Integer.class,
message.getCommitDate(),
message.getSectionId()
);
break;
case Section.SCROLL_GROUP:
res = jdbcTemplate.queryForList(
"SELECT min(topics.id) as msgid FROM topics, groups, sections WHERE sections.id=groups.section AND topics.id>? AND topics.groupid=? AND topics.groupid=groups.id AND (topics.moderate OR NOT sections.moderate) AND NOT deleted",
Integer.class,
message.getId(),
message.getGroupId()
);
break;
case Section.SCROLL_NOSCROLL:
default:
return null;
}
try {
if (res.isEmpty() || res.get(0)==null) {
return null;
}
int nextMsgid = res.get(0);
return getById(nextMsgid);
} catch (MessageNotFoundException e) {
throw new RuntimeException(e);
}
}
public List<EditInfoDTO> loadEditInfo(int msgid) {
List<EditInfoDTO> list = jdbcTemplate.query(
"SELECT * FROM edit_info WHERE msgid=? ORDER BY id DESC",
BeanPropertyRowMapper.newInstance(EditInfoDTO.class),
msgid
);
return ImmutableList.copyOf(list);
}
public void resolveMessage(int msgid, boolean b) {
jdbcTemplate.update(
"UPDATE topics SET resolved=?,lastmod=lastmod+'1 second'::interval WHERE id=?",
b,
msgid
);
}
public void setTopicOptions(Message msg, int postscore, boolean sticky, boolean notop, boolean minor) {
jdbcTemplate.update(
"UPDATE topics SET postscore=?, sticky=?, notop=?, lastmod=CURRENT_TIMESTAMP,minor=? WHERE id=?",
postscore,
sticky,
notop,
minor,
msg.getId()
);
}
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public void moveTopic(Message msg, Group newGrp, User moveBy) {
String url = msg.getUrl();
jdbcTemplate.update("UPDATE topics SET groupid=?,lastmod=CURRENT_TIMESTAMP WHERE id=?", newGrp.getId(), msg.getId());
if (!newGrp.isLinksAllowed() && !newGrp.isImagePostAllowed()) {
jdbcTemplate.update("UPDATE topics SET linktext=null, url=null WHERE id=?", msg.getId());
String title = msg.getGroupTitle();
String linktext = msg.getLinktext();
/* if url is not null, update the topic text */
String link;
if (!Strings.isNullOrEmpty(url)) {
if (msg.isLorcode()) {
link = "\n[url=" + url + ']' + linktext + "[/url]\n";
} else {
link = "<br><a href=\"" + url + "\">" + linktext + "</a>\n<br>\n";
}
} else {
link = "";
}
String add;
if (msg.isLorcode()) {
add = '\n' + link + "\n[i]Перемещено " + moveBy.getNick() + " из " + title + "[/i]\n";
} else {
add = '\n' + link + "<br><i>Перемещено " + moveBy.getNick() + " из " + title + "</i>\n";
}
jdbcTemplate.update("UPDATE msgbase SET message=message||? WHERE id=?", add, msg.getId());
}
if (!newGrp.isModerated()) {
ImmutableList<String> oldTags = tagDao.getMessageTags(msg.getId());
tagDao.updateTags(msg.getId(), ImmutableList.<String>of());
tagDao.updateCounters(oldTags, Collections.<String>emptyList());
}
}
} |
package seedu.emeraldo.model.task;
import seedu.emeraldo.commons.exceptions.IllegalValueException;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.regex.Matcher;
/**
* Represents a Task's date and time in Emeraldo.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class DateTime {
//@@author A0139749L
private static final String MESSAGE_KEYWORD_FROM_CONSTRAINTS = "Invalid format! It should be "
+ "'from DD/MM/YYYY, HH:MM to DD/MM/YYYY, HH:MM'\n"
+ "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n"
+ "Accepted time formats: 14:20 | 14.20 | 1420 | 2.20pm | 2:20pm\n"
+ "Type 'help' to see the full list of accepted formats in the user guide";
private static final String MESSAGE_KEYWORD_BY_CONSTRAINTS = "Invalid format! It should be "
+ "'by DD/MM/YYYY, HH:MM'\n"
+ "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n"
+ "Accepted time formats: 14:20 | 14.20 | 1420 | 2.20pm | 2:20pm\n"
+ "Type 'help' to see the full list of accepted formats in the user guide";
private static final String MESSAGE_KEYWORD_ON_CONSTRAINTS = "Invalid format! It should be "
+ "'on DD/MM/YYYY'\n"
+ "Accepted date formats: 4/03/2016 | 4/03/16 | 4-03-16 | 4 March 16 | 4/03 | 4 Mar\n"
+ "Type 'help' to see the full list of accepted formats in the user guide";
public static final String MESSAGE_DATETIME_CONSTRAINTS = "Command format is invalid! "
+ "It must be one of the following (type 'help' to see all accepted formats):\n"
+ "Keyword 'on' : on DD/MM/YYYY\n"
+ "Keyword 'by' : by DD/MM/YYYY, HH:MM\n"
+ "Keyword 'from' and 'to' : from DD/MM/YYYY, HH:MM to DD/MM/YYYY, HH:MM";
public final String value;
public String context;
public String overdueContext;
public String eventContext;
public String valueFormatted;
public LocalDate valueDate;
public LocalTime valueTime;
public LocalDate valueDateEnd;
public LocalTime valueTimeEnd;
public LocalDate completedValueDate = null;
public LocalTime completedValueTime = null;
public DateTime(String dateTime) throws IllegalValueException, DateTimeException{
assert dateTime != null;
final Matcher matcher = DateTimeParser.DATETIME_VALIDATION_REGEX.matcher(dateTime);
if (!dateTime.isEmpty() && !matcher.matches()) {
throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS);
}
if(dateTime.isEmpty()){
this.valueDate = null;
this.valueTime = null;
this.valueDateEnd = null;
this.valueTimeEnd = null;
this.value = "";
this.valueFormatted = "Anytime";
this.context = "";
this.overdueContext = "";
this.eventContext = "";
} else {
final String preKeyword = matcher.group("preKeyword").trim();
if(preKeyword.equals("on")){
if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword))
throw new IllegalValueException(MESSAGE_KEYWORD_ON_CONSTRAINTS);
this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword);
this.context = setContext(valueDate, null);
this.overdueContext = setOverdueContext(valueDate, null);
this.eventContext = "";
this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + context;
this.valueTime = null;
this.valueDateEnd = null;
this.valueTimeEnd = null;
}else if(preKeyword.equals("by")){
if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword))
throw new IllegalValueException(MESSAGE_KEYWORD_BY_CONSTRAINTS);
this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword);
this.valueTime = DateTimeParser.valueTimeFormatter(matcher, preKeyword);
this.context = setContext(valueDate, valueTime);
this.overdueContext = setOverdueContext(valueDate, valueTime);
this.eventContext = "";
this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + context;
this.valueDateEnd = null;
this.valueTimeEnd = null;
}else{
if(!isValidFormatFor_GivenKeyword(dateTime, preKeyword))
throw new IllegalValueException(MESSAGE_KEYWORD_FROM_CONSTRAINTS);
final String aftKeyword = matcher.group("aftKeyword").trim();
this.valueDate = DateTimeParser.valueDateFormatter(matcher, preKeyword);
this.valueTime = DateTimeParser.valueTimeFormatter(matcher, preKeyword);
this.context = setContext(valueDate, valueTime);
this.valueDateEnd = DateTimeParser.valueDateFormatter(matcher, aftKeyword);
this.valueTimeEnd = DateTimeParser.valueTimeFormatter(matcher, aftKeyword);
this.overdueContext = setOverdueContext(valueDateEnd, valueTimeEnd);
this.eventContext = setEventContext(valueDate, valueTime, valueDateEnd, valueTimeEnd);
this.valueFormatted = DateTimeParser.valueFormatter(matcher, preKeyword) + " "
+ DateTimeParser.valueFormatter(matcher, aftKeyword) + context + eventContext;
}
this.value = dateTime;
}
}
private boolean isValidFormatFor_GivenKeyword(String dateTime, String keyword){
switch(keyword){
case "on":
return dateTime.matches(DateTimeParser.ON_KEYWORD_VALIDATION_REGEX);
case "by":
return dateTime.matches(DateTimeParser.BY_KEYWORD_VALIDATION_REGEX);
case "from":
return dateTime.matches(DateTimeParser.FROM_KEYWORD_VALIDATION_REGEX);
default:
return false;
}
}
//@@author A0142290N
public void setCompletedDateTime() throws IllegalValueException{
this.completedValueDate = LocalDate.now();
this.completedValueTime = LocalTime.now();
this.valueFormatted = "Completed on " + DateTimeParser.valueDateCompletedFormatter(completedValueDate)
+ " at " + DateTimeParser.valueTimeCompletedFormatter(completedValueTime);
}
public String setContext(LocalDate valueDate, LocalTime valueTime) {
String context = "";
Boolean timeIsNow = valueTime != null && valueTime.getHour() == LocalTime.now().getHour() && valueTime.getMinute() == LocalTime.now().getMinute();
Boolean dayIsToday = valueDate.isEqual(LocalDate.now());
Boolean timeIsLater = valueTime != null && valueTime.isAfter(LocalTime.now());
Boolean noTimeSpecified = valueTime == null;
Boolean dayIsTomorrow = valueDate.minusDays(1).isEqual(LocalDate.now());
Boolean dayIsBeforeToday = valueDate.isBefore(LocalDate.now());
String stringHours = "";
//For tasks due today, now
if (dayIsToday && timeIsNow)
context = "(Today; Now)";
//For tasks that is due today, after current time
else if (dayIsToday && timeIsLater){
stringHours = Long.toString(LocalTime.now().until(valueTime, ChronoUnit.HOURS));
context = " (Today; in " + stringHours + " hours) ";
}
//For tasks due today at unspecified times
else if (dayIsToday && noTimeSpecified)
context = " (Today)";
//For tasks due tomorrow
else if (dayIsTomorrow)
context = " (Tomorrow)";
else if (dayIsBeforeToday)
context = "";
else
context = "";
return context;
}
public String setOverdueContext(LocalDate valueDate, LocalTime valueTime) {
String overdueContext = "";
Boolean dayIsBeforeToday = valueDate.isBefore(LocalDate.now());
Boolean dayIsToday = valueDate.isEqual(LocalDate.now());
Boolean dayIsAfterToday = valueDate.isEqual(LocalDate.now());
Boolean timeIsBeforeNow = valueTime != null && valueTime.isBefore(LocalTime.now());
//For tasks due before today
if (dayIsBeforeToday){
int monthsDue = valueDate.until(LocalDate.now()).getMonths();
int yearsDue = valueDate.until(LocalDate.now()).getYears();
int daysDue = valueDate.until(LocalDate.now()).getDays();
String stringDaysDue = Integer.toString(daysDue);
String stringMonthsDue = Integer.toString(monthsDue);
String stringYearsDue = Integer.toString(yearsDue);
String periodDue = "";
if (monthsDue > 0 && yearsDue > 0)
periodDue = stringYearsDue + " years, " + stringMonthsDue + " months and " + stringDaysDue + " days";
else if (monthsDue > 0 && yearsDue == 0)
periodDue = stringMonthsDue + " months and " + stringDaysDue + " days ";
else if (monthsDue == 0 && yearsDue == 0){
if (daysDue == 1)
periodDue = valueDate.until(LocalDate.now()).getDays() + " day";
else
periodDue = valueDate.until(LocalDate.now()).getDays() + " days";
}
else
periodDue = "";
overdueContext = "Overdue by " + periodDue;
}
//For tasks that is due today, at or before current time
else if (dayIsToday && timeIsBeforeNow) {
String stringHoursDue = Long.toString(valueTime.until(LocalTime.now(), ChronoUnit.HOURS));
String periodDue = stringHoursDue + " hours ";
overdueContext = "Due just now, " + periodDue + "ago";
}
else if (dayIsAfterToday) {
overdueContext = "";
}
return overdueContext;
}
public String setEventContext(LocalDate valueDate, LocalTime valueTime, LocalDate valueDateEnd, LocalTime valueTimeEnd) {
String eventContext = "";
LocalDateTime valueDateTime = LocalDateTime.of(valueDate, valueTime);
LocalDateTime valueDateTimeEnd = LocalDateTime.of(valueDateEnd, valueTimeEnd);
Boolean duringEventTime = valueDateTime.isBefore(LocalDateTime.now()) && valueDateTimeEnd.isAfter(LocalDateTime.now());
if (duringEventTime)
eventContext = " (Today; Now)";
else
eventContext = "";
return eventContext;
}
public String getOverdueContext(){
return overdueContext;
}
public String getEventContext(){
return eventContext;
}
@Override
public String toString() {
return valueFormatted;
}
//@@author
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DateTime // instanceof handles nulls
&& this.valueFormatted.equals(((DateTime) other).valueFormatted)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
} |
package ttaomae.connectn.gui;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPaneBuilder;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.GridPaneBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import ttaomae.connectn.AlphaBetaPlayer;
import ttaomae.connectn.Board;
import ttaomae.connectn.BoardListener;
import ttaomae.connectn.GameManager;
import ttaomae.connectn.Piece;
import ttaomae.connectn.Player;
/**
* A panel for a Connect-N game. Provides an interface for selecting the height,
* width, and win condition; whether the players are human or computer; and for
* starting and reseting games. Also contains a display for messages to the
* user.
*
* @author Todd Taomae
*/
public class ConnectNPanel extends GridPane implements BoardListener
{
private static final String START_MESSAGE = "Click \"Start\" to start a new game.";
private static final String BLACK_TURN = "BLACK's turn.";
private static final String RED_TURN = "RED's turn.";
private static final String BLACK_WIN = "BLACK Wins!";
private static final String RED_WIN = "RED Wins!";
private static final String DRAW = "Draw!";
private static final int BOARD_WIDTH = 440;
private static final int BOARD_HEIGHT = 380;
private Label title;
private Board board;
private BoardPanel boardPanel;
private GameManager gameManager;
private Thread gameManagerThread;
private Slider heightSlider;
private Slider widthSlider;
private Slider winConditionSlider;
private PlayerSelectPanel playerOne;
private PlayerSelectPanel playerTwo;
private Button startButton;
private boolean running;
private Label displayMessage;
/**
* Constructs a new ConnectNPanel. The range of heights is 2 to 12, the
* range of widths is 2 to 14, and the range of win conditions is 2 to 14.
*/
public ConnectNPanel()
{
this.running = false;
this.title = new Label();
// set up height slider
this.heightSlider = new Slider(2, 12, 6);
this.heightSlider.setOrientation(Orientation.VERTICAL);
this.heightSlider.setMajorTickUnit(2.0);
this.heightSlider.setMinorTickCount(1);
this.heightSlider.setShowTickMarks(true);
this.heightSlider.setShowTickLabels(true);
this.heightSlider.setSnapToTicks(true);
this.heightSlider.setMaxHeight(BOARD_HEIGHT);
// set up width slider
this.widthSlider = new Slider(2, 14, 7);
this.widthSlider.setMajorTickUnit(2.0);
this.widthSlider.setMinorTickCount(1);
this.widthSlider.setShowTickMarks(true);
this.widthSlider.setShowTickLabels(true);
this.widthSlider.setSnapToTicks(true);
this.widthSlider.setMaxWidth(BOARD_WIDTH);
// set up win condition slider
this.winConditionSlider = new Slider(2, 14, 4);
this.winConditionSlider.setMajorTickUnit(2.0);
this.winConditionSlider.setMinorTickCount(1);
this.winConditionSlider.setShowTickMarks(true);
this.winConditionSlider.setShowTickLabels(true);
this.winConditionSlider.setSnapToTicks(true);
this.winConditionSlider.setMaxWidth(BOARD_WIDTH);
// set up start button
this.startButton = new Button("Start");
this.startButton.setFont(Font.font("Sans Serif", 12));
this.title = new Label();
this.title.setFont(Font.font("Serif", FontWeight.BOLD, 30));
this.displayMessage = new Label(START_MESSAGE);
this.playerOne = new PlayerSelectPanel(2, 10, 1, true);
this.playerOne.setMaxWidth(BOARD_WIDTH / 2);
this.playerTwo = new PlayerSelectPanel(2, 10, 2, false);
this.playerTwo.setMaxWidth(BOARD_WIDTH / 2);
// set up handlers and listeners
this.startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e)
{
if (ConnectNPanel.this.running) {
ConnectNPanel.this.resetGame();
ConnectNPanel.this.startButton.setText("Start");
ConnectNPanel.this.running = false;
}
else {
ConnectNPanel.this.startGame();
ConnectNPanel.this.startButton.setText("Reset");
ConnectNPanel.this.running = true;
}
}
});
this.heightSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val)
{
ConnectNPanel.this.checkWinConditionSlider();
if (!ConnectNPanel.this.running) {
ConnectNPanel.this.resetBoard();
}
}
});
this.widthSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val)
{
ConnectNPanel.this.checkWinConditionSlider();
if (!ConnectNPanel.this.running) {
ConnectNPanel.this.resetBoard();
}
}
});
this.winConditionSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val)
{
ConnectNPanel.this.checkWinConditionSlider();
if (!ConnectNPanel.this.running) {
ConnectNPanel.this.resetBoard();
}
}
});
this.boardPanel = new BoardPanel(BOARD_WIDTH, BOARD_WIDTH, new Board());
this.resetBoard();
// this.setGridLinesVisible(true);
this.setHgap(10);
this.setVgap(10);
this.setPadding(new Insets(10, 10, 10, 10));
this.add(this.title, 1, 0);
this.add(this.winConditionSlider, 1, 1);
this.add(this.heightSlider, 0, 2);
this.add(this.boardPanel, 1, 2);
this.add(this.widthSlider, 1, 3);
this.add(BorderPaneBuilder.create().left(this.playerOne)
.right(this.playerTwo)
.build(),
1, 4);
GridPane bottomRow = GridPaneBuilder.create().hgap(20.0).build();
bottomRow.add(this.startButton, 0, 0);
bottomRow.add(this.displayMessage, 1, 0);
this.add(bottomRow, 1, 5);
}
/**
* Starts a game based on this ConnectNPanel's current settings.
*/
private void startGame()
{
Player p1;
Player p2;
if (this.playerOne.isHuman()) {
p1 = new MousePlayer(this.boardPanel);
}
else {
p1 = new AlphaBetaPlayer(this.playerOne.getCpuDifficulty());
}
if (this.playerTwo.isHuman()) {
p2 = new MousePlayer(this.boardPanel);
}
else {
p2 = new AlphaBetaPlayer(this.playerTwo.getCpuDifficulty());
}
this.gameManager = new GameManager(this.board, p1, p2);
this.displayMessage.setText(BLACK_TURN);
this.gameManagerThread = new Thread(this.gameManager, "Game Manager");
this.gameManagerThread.start();
}
/**
* Ends the current game and resets the board.
*/
private void resetGame()
{
this.gameManager.stop();
this.gameManagerThread.interrupt();
this.resetBoard();
}
/**
* Resets the board to match the current settings.
*/
private void resetBoard()
{
this.title.setText("Connect " + ((int) this.winConditionSlider.getValue()));
this.board = new Board((int) this.heightSlider.getValue(),
(int) this.widthSlider.getValue(),
(int) this.winConditionSlider.getValue());
this.board.addBoardListener(this);
this.boardPanel.setBoard(this.board);
this.displayMessage.setText(START_MESSAGE);
}
/**
* Checks that the win condition slider is valid and sets it to a valid
* range if it is not.
*/
private void checkWinConditionSlider()
{
int height = (int) this.heightSlider.getValue();
int width = (int) this.widthSlider.getValue();
int winCondition = (int) this.winConditionSlider.getValue();
if (winCondition > Math.max(height, width)) {
this.winConditionSlider.setValue(Math.max(height, width));
}
}
/**
* Updates the display message whenever necessary.
*/
@Override
public void boardChanged()
{
switch (this.board.getWinner()) {
case NONE:
if (this.board.getNextPiece() == Piece.BLACK) {
this.updateMessage(BLACK_TURN);
}
else if (this.board.getNextPiece() == Piece.RED) {
this.updateMessage(RED_TURN);
}
break;
case BLACK:
this.updateMessage(BLACK_WIN);
break;
case RED:
this.updateMessage(RED_WIN);
break;
case DRAW:
this.updateMessage(DRAW);
break;
}
}
/**
* Sets the display to the specified message.
*
* @param message the message to update to
*/
public void updateMessage(final String message)
{
javafx.application.Platform.runLater(new Runnable() {
@Override
public void run()
{
ConnectNPanel.this.displayMessage.setText(message);
}
});
}
} |
package mu.nu.nullpo.tool.airankstool;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import org.apache.log4j.Logger;
import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.GroupLayout.ParallelGroup;
import mu.nu.nullpo.util.CustomProperties;
public class AIRanksTool extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
/** Log */
static final Logger log = Logger.getLogger(AIRanksTool.class);
/** Default language file */
public static CustomProperties propLangDefault;
/** Primary language file */
public static CustomProperties propLang; |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.colar.netbeans.fan.indexer;
import fan.sys.Buf;
import fan.sys.FanObj;
import fan.sys.Pod;
import fan.sys.Slot;
import fan.sys.Type;
import fanx.fcode.FConst;
import fanx.fcode.FField;
import fanx.fcode.FMethod;
import fanx.fcode.FMethodVar;
import fanx.fcode.FPod;
import fanx.fcode.FSlot;
import fanx.fcode.FStore;
import fanx.fcode.FType;
import fanx.fcode.FTypeRef;
import java.io.File;import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.regex.Pattern;
import net.colar.netbeans.fan.FanParserTask;
import net.colar.netbeans.fan.FanUtilities;
import net.colar.netbeans.fan.NBFanParser;
//import net.colar.netbeans.fan.ast.FanAstField;
//import net.colar.netbeans.fan.ast.FanAstMethod;
import net.colar.netbeans.fan.indexer.model.FanDocUsing;
import net.colar.netbeans.fan.scope.FanAstScopeVarBase;
import net.colar.netbeans.fan.scope.FanAstScopeVarBase.ModifEnum;
//import net.colar.netbeans.fan.ast.FanTypeScope;
import net.colar.netbeans.fan.indexer.model.FanDocument;
import net.colar.netbeans.fan.indexer.model.FanMethodParam;
import net.colar.netbeans.fan.indexer.model.FanSlot;
import net.colar.netbeans.fan.indexer.model.FanType;
import net.colar.netbeans.fan.indexer.model.FanTypeInheritance;
import net.colar.netbeans.fan.parboiled.AstNode;
import net.colar.netbeans.fan.parboiled.FanLexAstUtils;
import net.colar.netbeans.fan.platform.FanPlatform;
import net.colar.netbeans.fan.scope.FanAstScopeVarBase.VarKind;
import net.colar.netbeans.fan.scope.FanMethodScopeVar;
import net.colar.netbeans.fan.scope.FanScopeMethodParam;
import net.colar.netbeans.fan.scope.FanTypeScopeVar;
import net.colar.netbeans.fan.types.FanResolvedType;
import net.jot.logger.JOTLoggerLocation;
import net.jot.persistance.JOTSQLCondition;
import net.jot.persistance.builders.JOTQueryBuilder;
import org.netbeans.modules.parsing.api.Snapshot;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.modules.parsing.spi.Parser.Result;
import org.netbeans.modules.parsing.spi.indexing.Context;
import org.netbeans.modules.parsing.spi.indexing.CustomIndexer;
import org.netbeans.modules.parsing.spi.indexing.Indexable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileAttributeEvent;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileRenameEvent;
import org.openide.filesystems.FileUtil;
//import org.netbeans.modules.java.source.indexing.JavaBinaryIndexer;
/**
* This indexer is backed by a DB(H2 database)
* This class does all the Index updates(write)
* Use FanIndexQyery to search it.
*
* Index all the documents:
* fan/fwt sources
* fantom distro pods/libs
* jdk libs ?
* @author tcolar
*/
public class FanIndexer extends CustomIndexer implements FileChangeListener
{
public static final String UNRESOLVED_TYPE = "!!UNRESOLVED!!";
private final static Pattern CLOSURECLASS = Pattern.compile(".*?\\$\\d+\\z");
static JOTLoggerLocation log = new JOTLoggerLocation(FanIndexer.class);
private final FanIndexerThread indexerThread;
public static volatile boolean shutdown = false;
//TODO: will that work or should they all be in the same fifo stack
Hashtable<String, Long> fanSrcToBeIndexed = new Hashtable<String, Long>();
Hashtable<String, Long> fanPodsToBeIndexed = new Hashtable<String, Long>();
Hashtable<String, Long> toBeDeleted = new Hashtable<String, Long>();
private FanJarsIndexer jarsIndexer;
private boolean alreadyWarned;
private MainIndexer mainIndexer;
public FanIndexer()
{
super();
indexerThread = new FanIndexerThread();
indexerThread.start();
}
synchronized void warnIfNecessary()
{
if (!alreadyWarned)
{
alreadyWarned = true;
NotifyDescriptor desc = new NotifyDescriptor.Message("Initial Fantom/Java API Indexing just started\nThis might take a while and use a lot of CPU (once).\nSome features such as completion will not be available until it's completed.", NotifyDescriptor.WARNING_MESSAGE);
DialogDisplayer.getDefault().notify(desc);
}
}
/**
* Rerun whole indexing (called on FAN_HOME change, see FanPlatform)
* @param backgroundJava
*/
public void indexAll(boolean backgroundJava)
{
mainIndexer = new MainIndexer(backgroundJava);
mainIndexer.start();
if (!backgroundJava)
{
mainIndexer.waitFor();
}
}
public FanJarsIndexer getJarsIndexer()
{
return jarsIndexer;
}
@Override
protected void index(Iterable<? extends Indexable> iterable, Context context)
{
for (Indexable indexable : iterable)
{
requestIndexing(indexable.getURL().getPath());
}
}
public void requestDelete(String path)
{
toBeDeleted.put(path, new Date().getTime());
}
/**
* all Fantom indexing should be requested through here (no direct call to index()
* for threading safety
* @param path
*/
public void requestIndexing(String path)
{
if( ! FanPlatform.isConfigured())
return;
boolean isPod = path.toLowerCase().endsWith(".pod");
FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(new File(path)));
if (fo.getNameExt().equalsIgnoreCase("sys.pod"))
{
warnIfNecessary();
}
if (isPod)
{
fanPodsToBeIndexed.put(path, new Date().getTime());
} else if (isAllowedIndexing(fo))
{
fanSrcToBeIndexed.put(path, new Date().getTime());
}
}
// TODO: It would be MUCH faster to just parse what we need (types/slots)
// Might need a separte ANTLR grammar though.
private void indexSrc(String path)
{
if (!FanPlatform.isConfigured())
{
log.info("Platform not ready to index: " + path);
return;
}
if (!isAllowedIndexing(FileUtil.toFileObject(FileUtil.normalizeFile(new File(path)))))
{
log.info("Skipping: " + path);
return;
}
long then = new Date().getTime();
log.info("Indexing requested for: " + path);
// Get a snaphost of the source
File f = new File(path);
FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(f));
Source source = Source.create(fo);
Snapshot snapshot = source.createSnapshot();
// Parse the snaphot
NBFanParser parser = new NBFanParser();
try
{
parser.parse(snapshot, true);
} catch (Throwable e)
{
log.exception("Parsing failed for: " + path, e);
return;
}
Result result = parser.getResult();
long now = new Date().getTime();
log.debug("Indexing - parsing done in " + (now - then) + " ms for: " + path);
// Index the parsed doc
indexSrc(path, result);
now = new Date().getTime();
log.debug("Indexing completed in " + (now - then) + " ms for: " + path);
}
private void indexSrc(String path, Result parserResult)
{
log.debug("Indexing parsed result for : " + path);
FanParserTask fanResult = (FanParserTask) parserResult;
indexSrcDoc(path, fanResult.getRootScope());
}
/**
* Index the document in the DB, using the root scope.
* @param doc
* @param indexable
* @param rootScope
*/
private void indexSrcDoc(String path, AstNode rootScope)
{
FanDocument doc = null;
try
{
if (rootScope != null)
{
// create / update the doument
doc = FanDocument.findOrCreateOne(null, path);
doc.setPath(path);
doc.setTstamp(0L);
doc.setIsSource(true);
doc.save();
// Update the "using" / try to be smart as to not delete / recreate all everytime.
Vector<FanDocUsing> usings = FanDocUsing.findAllForDoc(null, doc.getId());
Vector<FanType> types = FanType.findAllForDoc(null, doc.getId());
Collection<FanAstScopeVarBase> vars = rootScope.getLocalScopeVars().values();
Vector<String> addedUsings = new Vector<String>();
for (FanAstScopeVarBase var : vars)
{
if (var.getKind() == FanAstScopeVarBase.VarKind.IMPORT || var.getKind() == FanAstScopeVarBase.VarKind.IMPORT_JAVA)
{
FanResolvedType type = var.getType();
String sig = type.getAsTypedType();
int foundIdx = -1;
for (int i = 0; i != usings.size(); i++)
{
FanDocUsing using = usings.get(i);
if (using.getType().equals(sig))
{
foundIdx = i;
break;
}
}
if (foundIdx != -1)
{
// already in there, leave it alone
usings.remove(foundIdx);
} else
{
// there can be duplicates because of the way rootscope usings works
if (!addedUsings.contains(sig))
{
addedUsings.add(sig);
// new one, creating it
FanDocUsing using = new FanDocUsing();
using.setDocumentId(doc.getId());
using.setType(sig);
using.save();
}
}
}
// types
if (var instanceof FanTypeScopeVar)
{
FanTypeScopeVar typeScope = (FanTypeScopeVar) var;
JOTSQLCondition cond = new JOTSQLCondition("qualifiedName", JOTSQLCondition.IS_EQUAL, typeScope.getQName());
FanType dbType = (FanType) JOTQueryBuilder.selectQuery(null, FanType.class).where(cond).findOrCreateOne();
if (!dbType.isNew())
{
for (int i = 0; i != types.size(); i++)
{
FanType t = types.get(i);
if (t.getId() == dbType.getId())
{
types.remove(i);
break;
}
}
}
dbType.setSrcDocId(doc.getId());
dbType.setKind(typeScope.getKind().value());
dbType.setIsAbstract(typeScope.hasModifier(FanAstScopeVarBase.ModifEnum.ABSTRACT));
dbType.setIsConst(typeScope.hasModifier(FanAstScopeVarBase.ModifEnum.CONST));
dbType.setIsFinal(typeScope.hasModifier(FanAstScopeVarBase.ModifEnum.FINAL));
dbType.setQualifiedName(typeScope.getQName());
dbType.setSimpleName(typeScope.getName());
dbType.setPod(rootScope.getRoot().getPod());
dbType.setProtection(typeScope.getProtection());
dbType.setIsFromSource(true);
dbType.save();
// Try to reuse existing db entries.
Vector<FanTypeInheritance> currentInh = FanTypeInheritance.findAllForMainType(null, typeScope.getQName());
for (FanResolvedType item : typeScope.getInheritedItems())
{
String mainType = typeScope.getQName();
String inhType = item.isResolved() ? item.getDbType().getQualifiedName() : item.getAsTypedType();
FanTypeInheritance inh = null;
for (int i = 0; i != currentInh.size(); i++)
{
FanTypeInheritance cur = currentInh.get(i);
if (cur.getMainType().equals(mainType) && cur.getInheritedType().equals(inhType))
{
inh = cur;
currentInh.remove(i);
break;
}
}
if (inh == null)
{
// new one, creating it
inh = new FanTypeInheritance();
}
inh.setMainType(mainType);
inh.setInheritedType(inhType);
inh.save();
}
// old inherited types
for (FanTypeInheritance oldInh : currentInh)
{
//System.out.println("inh delete " + oldInh.getInheritedType() + "::" + oldInh.getMainType());
oldInh.delete();
}
// Slots
// Try to reuse existing db entries.
Vector<FanSlot> currentSlots = FanSlot.findAllForType(dbType.getId());
Collection<FanAstScopeVarBase> localVars = FanLexAstUtils.getScopeNode(typeScope.getNode()).getLocalScopeVars().values();
for (FanAstScopeVarBase slot : localVars)
{
if (slot.getKind() == VarKind.CTOR || slot.getKind() == VarKind.FIELD || slot.getKind() == VarKind.METHOD)
{
JOTSQLCondition cond2 = new JOTSQLCondition("typeId", JOTSQLCondition.IS_EQUAL, dbType.getId());
JOTSQLCondition cond3 = new JOTSQLCondition("name", JOTSQLCondition.IS_EQUAL, slot.getName());
FanSlot dbSlot = (FanSlot) JOTQueryBuilder.selectQuery(null, FanSlot.class).where(cond2).where(cond3).findOrCreateOne();
if (!dbSlot.isNew())
{
for (int i = 0; i != currentSlots.size(); i++)
{
FanSlot s = currentSlots.get(i);
if (s.getId() == dbSlot.getId())
{
currentSlots.remove(i);
break;
}
}
}
dbSlot.setTypeId(dbType.getId());
dbSlot.setSlotKind(slot.getKind().value());
FanResolvedType slotType = slot.getType();
dbSlot.setReturnedType(slotType.toTypeSig(true));
dbSlot.setName(slot.getName());
dbSlot.setIsAbstract(slot.hasModifier(ModifEnum.ABSTRACT));
dbSlot.setIsNative(slot.hasModifier(ModifEnum.NATIVE));
dbSlot.setIsOverride(slot.hasModifier(ModifEnum.OVERRIDE));
dbSlot.setIsStatic(slot.hasModifier(ModifEnum.STATIC));
dbSlot.setIsVirtual(slot.hasModifier(ModifEnum.VIRTUAL));
dbSlot.setIsConst(slot.hasModifier(ModifEnum.CONST));
dbSlot.setProtection(slot.getProtection());
dbSlot.save();
// deal with parameters of method/ctor
if (slot instanceof FanMethodScopeVar)
{
FanMethodScopeVar method = (FanMethodScopeVar) slot;
Hashtable<String, FanScopeMethodParam> parameters = method.getParameters();
// Try to reuse existing db entries.
Vector<FanMethodParam> currentParams = dbSlot.getAllParameters();
for (String paramName : parameters.keySet())
{
FanScopeMethodParam paramResult = parameters.get(paramName);
JOTSQLCondition cond4 = new JOTSQLCondition("slotId", JOTSQLCondition.IS_EQUAL, dbSlot.getId());
JOTSQLCondition cond5 = new JOTSQLCondition("paramIndex", JOTSQLCondition.IS_EQUAL, paramResult.getOrder());
FanMethodParam dbParam = (FanMethodParam) JOTQueryBuilder.selectQuery(null, FanMethodParam.class).where(cond4).where(cond5).findOrCreateOne();
if (!dbParam.isNew())
{
for (int i = 0; i != currentParams.size(); i++)
{
FanMethodParam p = currentParams.get(i);
if (p.getId() == dbParam.getId())
{
currentParams.remove(i);
break;
}
}
}
dbParam.setSlotId(dbSlot.getId());
dbParam.setName(paramName);
String pType = pType = paramResult.getType().toTypeSig(true);
dbParam.setQualifiedType(pType);
dbParam.setParamIndex(paramResult.getOrder());
dbParam.setHasDefault(paramResult.hasDefaultValue());
dbParam.save();
} // end param loop
// Whatever param wasn't removed from the vector is not needed anymore.
for (FanMethodParam param : currentParams)
{
param.delete();
}
}
}
} // end slot loop
// Whatever slot wasn't removed from the vector is not needed anymore.
for (FanSlot s : currentSlots)
{
s.delete();
}
}
} // end type if
// all went well, set the tstamp - mark as good
doc.setTstamp(new Date().getTime());
doc.save();
// remove old usings
for (FanDocUsing using : usings)
{
using.delete();
}
// remove old types
for (FanType t : types)
{
//System.out.println("type delete " + t.getQualifiedName());
t.delete();
}
}
} catch (Exception e)
{
log.exception("Indexing Failed for: " + path, e);
try
{
// remove the incomplete doc ... wil try again next time.
if (doc != null)
{
doc.delete();
}
} catch (Exception e2)
{
log.exception("Indexing 'rollback' failed for: " + path, e);
}
}
}
public static boolean checkIfNeedsReindexing(String path, long tstamp)
{
JOTSQLCondition cond = new JOTSQLCondition("path", JOTSQLCondition.IS_EQUAL, path);
try
{
FanDocument doc = (FanDocument) JOTQueryBuilder.selectQuery(null, FanDocument.class).where(cond).findOne();
if (doc != null)
{
long indexedTime = doc.getTstamp();
if (indexedTime >= tstamp)
{
return false;
}
}
} catch (Exception e)
{
log.exception("FanDocument search exception", e);
}
return true;
}
public void indexFantomPods(boolean runInBackground)
{
if (!FanPlatform.isConfigured())
{
return;
}
try
{
String podsDir = FanPlatform.getInstance().getPodsDir();
File f = new File(podsDir);
// listen to changes in pod folder
FileUtil.addRecursiveListener(this, f);
// index the pods if not up to date
File[] pods = f.listFiles();
for (File pod : pods)
{
String path = pod.getAbsolutePath();
if (checkIfNeedsReindexing(path, pod.lastModified()))
{
requestIndexing(path);
}
}
} catch (Throwable t)
{
log.exception("Pod indexing thread error", t);
}
if (!runInBackground)
{
while (!(shutdown || fanPodsToBeIndexed.isEmpty()))
{
try
{
Thread.sleep(100);
Thread.yield();
} catch (Exception e)
{
log.exception("waiting for pods indexign to complete", e);
}
}
}
}
private void indexPod(String pod)
{
if (pod.toLowerCase().endsWith(".pod"))
{
FanDocument doc = null;
try
{
//ZipFile zpod = new ZipFile(pod);
FPod fpod = new FPod(null, FStore.makeZip(new File(pod)));
fpod.readFully();
log.info("Indexing pod: " + pod);
// Create the document
doc = FanDocument.findOrCreateOne(null, pod);
doc.setPath(pod);
doc.setTstamp(0L);
doc.setIsSource(false);
doc.save();
Vector<FanType> types = FanType.findAllForDoc(null, doc.getId());
for (FType type : fpod.types)
{
FTypeRef typeRef = type.pod.typeRef(type.self);
String sig = typeRef.signature;
int flags = type.flags;
// Skipping "internal" classes - closures and the likes
// synthetic means generated by compiler
if (hasFlag(flags, FConst.Synthetic) || CLOSURECLASS.matcher(typeRef.typeName).matches())
{
continue;
}
log.debug("Indexing Pod Type: " + sig);
JOTSQLCondition cond = new JOTSQLCondition("qualifiedName", JOTSQLCondition.IS_EQUAL, sig);
FanType dbType = (FanType) JOTQueryBuilder.selectQuery(null, FanType.class).where(cond).findOrCreateOne();
if (!dbType.isNew())
{
for (int i = 0; i != types.size(); i++)
{
FanType t = types.get(i);
if (t.getId() == dbType.getId())
{
types.remove(i);
break;
}
}
}
dbType.setBinDocId(doc.getId());
dbType.setKind(getKind(type));
dbType.setIsAbstract(hasFlag(flags,
FConst.Abstract));
dbType.setIsConst(hasFlag(flags, FConst.Const));
dbType.setIsFinal(hasFlag(flags, FConst.Final));
dbType.setQualifiedName(sig);
dbType.setSimpleName(typeRef.typeName);
dbType.setPod(typeRef.podName);
dbType.setProtection(getProtection(type.flags));
dbType.setIsFromSource(
false);
dbType.save();
// Slots
// Try to reuse existing db entries.
Vector<FanSlot> currentSlots = FanSlot.findAllForType(dbType.getId());
Vector<FSlot> slots = new Vector<FSlot>();
slots.addAll(Arrays.asList(type.fields));
// It's a bit odd but type.methods has the fields in as well
// I guess because Fan creates "internal" field getter/setters ?
for (FMethod m : type.methods)
{
boolean isField = false;
for (FSlot s : slots)
{
if (s.name.equals(m.name))
{
isField = true;
}
}
if (!isField)
{
slots.add(m);
}
}
for (FSlot slot : slots)
{
// determine kind of slot
VarKind kind = VarKind.FIELD;
String retType = null;
if (slot instanceof FField)
{
retType = type.pod.typeRef(((FField) slot).type).signature;
} else if (slot instanceof FMethod)
{
if (hasFlag(slot.flags, FConst.Ctor))
{
// This returns Void -> retType = type.pod.typeRef(((FMethod) slot).ret);
retType = "sys::This";
kind = VarKind.CTOR;
} else
{
retType = type.pod.typeRef(((FMethod) slot).ret).signature;
kind = VarKind.METHOD;
}
} else
{
throw new RuntimeException("Unexpected Slot kind: " + slot.getClass().getName());
}
JOTSQLCondition cond2 = new JOTSQLCondition("typeId", JOTSQLCondition.IS_EQUAL, dbType.getId());
JOTSQLCondition cond3 = new JOTSQLCondition("name", JOTSQLCondition.IS_EQUAL, slot.name);
FanSlot dbSlot = (FanSlot) JOTQueryBuilder.selectQuery(null, FanSlot.class).where(cond2).where(cond3).findOrCreateOne();
if (!dbSlot.isNew())
{
for (int i = 0; i != currentSlots.size(); i++)
{
FanSlot s = currentSlots.get(i);
if (s.getId() == dbSlot.getId())
{
currentSlots.remove(i);
break;
}
}
}
dbSlot.setTypeId(dbType.getId());
dbSlot.setSlotKind(kind.value());
dbSlot.setReturnedType(retType);
dbSlot.setName(slot.name);
dbSlot.setIsAbstract(hasFlag(slot.flags, FConst.Abstract));
dbSlot.setIsNative(hasFlag(slot.flags, FConst.Native));
dbSlot.setIsOverride(hasFlag(slot.flags, FConst.Override));
dbSlot.setIsStatic(hasFlag(slot.flags, FConst.Static));
dbSlot.setIsVirtual(hasFlag(slot.flags, FConst.Virtual));
dbSlot.setIsConst(hasFlag(slot.flags, FConst.Const));
dbSlot.setProtection(getProtection(slot.flags));
dbSlot.save();
// deal with parameters of method/ctor
if (slot instanceof FMethod)
{
FMethod method = (FMethod) slot;
FMethodVar[] parameters = method.params();
// Try to reuse existing db entries.
Vector<FanMethodParam> currentParams = dbSlot.getAllParameters();
int paramIndex = 0;
for (FMethodVar param : parameters)
{
JOTSQLCondition cond4 = new JOTSQLCondition("slotId", JOTSQLCondition.IS_EQUAL, dbSlot.getId());
JOTSQLCondition cond5 = new JOTSQLCondition("paramIndex", JOTSQLCondition.IS_EQUAL, paramIndex);
FanMethodParam dbParam = (FanMethodParam) JOTQueryBuilder.selectQuery(null, FanMethodParam.class).where(cond4).where(cond5).findOrCreateOne();
if (!dbParam.isNew())
{
for (int i = 0; i != currentParams.size(); i++)
{
FanMethodParam p = currentParams.get(i);
if (p.getId() == dbParam.getId())
{
currentParams.remove(i);
break;
}
}
}
FTypeRef tRef = type.pod.typeRef(param.type);
String signature = tRef.signature;
// Temp Workaround for Fantom bug 1056
// http://fantom.org/sidewalk/topic/1056#c7687
if (dbSlot.getName().equals("with") && dbType.getQualifiedName().equals("sys::Obj"))
{
signature = "|sys::This->sys::Void|";
}
// end workaround
dbParam.setSlotId(dbSlot.getId());
dbParam.setName(param.name);
dbParam.setQualifiedType(signature);
dbParam.setHasDefault(param.def != null);
dbParam.setParamIndex(paramIndex);
dbParam.save();
paramIndex++;
} // end param loop
// Whatever param wasn't removed from the vector is not needed anymore.
for (FanMethodParam param : currentParams)
{
param.delete();
}
}
} // end slot loop
// Whatever slot wasn't removed from the vector is not needed anymore.
for (FanSlot s : currentSlots)
{
s.delete();
}
// Deal with Inheritance
Vector<FTypeRef> inhTypes = new Vector<FTypeRef>();
if (type.base >= 0 && type.base != 65535) // 65535 seem to eb value for a type with no base (Obj?)
{
inhTypes.add(type.pod.typeRef(type.base));
}
for (int t : type.mixins)
{
inhTypes.add(type.pod.typeRef(t));
}
// Try to reuse existing db entries.
Vector<FanTypeInheritance> currentInh = FanTypeInheritance.findAllForMainType(null, typeRef.signature);
for (FTypeRef item : inhTypes)
{
String mainType = typeRef.signature;
String inhType = item.signature;
if (inhType.equals("sys::Obj")
|| inhType.equals("sys::Enum"))
{
// Those types are implied, no need to pollute the DB
continue;
}
int foundIdx = -1;
for (int i = 0; i != currentInh.size(); i++)
{
FanTypeInheritance cur = currentInh.get(i);
if (cur.getMainType().equals(mainType) && cur.getInheritedType().equals(inhType))
{
foundIdx = i;
break;
}
}
if (foundIdx != -1)
{
// already in there, leave it alone
currentInh.remove(foundIdx);
} else
{
// new one, creating it
FanTypeInheritance inh = new FanTypeInheritance();
inh.setMainType(mainType);
inh.setInheritedType(inhType);
inh.save();
//System.out.println("saving inh: " + inh.getMainType() + " " + inh.getInheritedType() + " " + inh.getId());
}
} // end inh
// Whatever wasn't removed from the vector is not needed anymore.
for (FanTypeInheritance inh : currentInh)
{
inh.delete();
}
// allow for quicker exit on shutdown
if (shutdown)
{
break;
}
} // end type
// all went well, set the tstamp - mark as good
doc.setTstamp(new Date().getTime());
doc.save();
for (FanType t : types)
{
t.delete();
}
} catch (Exception e)
{
log.exception("Indexing failed for: " + pod, e);
try
{
// remove broken entry, will try again next time
if (doc != null)
{
doc.delete();
}
} catch (Exception e2)
{
log.exception("Indexing 'rollback' failed for: " + pod, e);
}
}
}
}
private int getKind(FType type)
{
if (hasFlag(type.flags, FConst.Mixin))
{
return FanAstScopeVarBase.VarKind.TYPE_MIXIN.value();
}
if (hasFlag(type.flags, FConst.Enum))
{
return FanAstScopeVarBase.VarKind.TYPE_ENUM.value();
} // class is default
return FanAstScopeVarBase.VarKind.TYPE_CLASS.value();
}
private boolean hasFlag(int flags, int flag)
{
return (flags & flag) != 0;
}
public static void shutdown()
{
FanJarsIndexer.shutdown();
shutdown = true;
}
private int getProtection(int flags)
{
if (hasFlag(flags, FConst.Private))
{
return ModifEnum.PRIVATE.value();
}
if (hasFlag(flags, FConst.Protected))
{
return ModifEnum.PROTECTED.value();
}
if (hasFlag(flags, FConst.Internal))
{
return ModifEnum.INTERNAL.value();
} // default is public
return ModifEnum.PUBLIC.value();
}
/**
* Index a fantom source folder recursively
* @param root
* @param nb - nb of files parsed
* @return
*/
public int indexSrcFolder(FileObject root, int nb)
{
if (!FanPlatform.isConfigured())
{
return 0;
}
if (!isAllowedIndexing(root))
{
return nb;
}
FileObject[] children = root.getChildren();
for (FileObject child : children)
{
if (child.isFolder())
{
//recurse
nb = indexSrcFolder(child, nb);
} else
{
if (child.hasExt("fan") || child.hasExt("fwt"))
{
if (FanIndexer.checkIfNeedsReindexing(child.getPath(), child.lastModified().getTime()))
{
log.info("ReIndexing: " + root);
nb++;
requestIndexing(child.getPath());
}
}
}
}
return nb;
}
public static String getPodDoc(String podName)
{
if (!FanPlatform.isConfigured())
{
return null;
}
Pod pod = null;
try
{
pod = Pod.find(podName);
} catch (RuntimeException e)
{
log.debug("Pod doc not found for " + podName);
}
if (pod != null)
{
return fanDocToHtml((String) pod.meta().get("pod.summary"));
}
return null;
}
public static String getSlotDoc(FanSlot slot)
{
FanType type = FanType.findByID(slot.getTypeId());
if (type != null)
{
String sig = type.getQualifiedName() + "." + slot.getName();
try
{
Slot fslot = Slot.find(sig);
if (fslot != null)
{
return fanDocToHtml(fslot.doc());
}
} catch (Throwable t)
{
// Fantom runtime exception if type ! found
log.debug(t.toString());
}
}
return null;
}
public static String getDoc(FanType type)
{
if (!FanPlatform.isConfigured())
{
return null;
}
try
{
Pod pod = Pod.find(type.getPod());
Type t = pod.type(type.getSimpleName());
if (t != null)
{
return fanDocToHtml(t.doc());
}
} catch (RuntimeException e)
{
log.debug("Type doc not found for " + type);
}
return null;
}
/**
* Parse Fandoc text into HTML using fan's builtin parser.
* @param fandoc
* @return
*/
public static String fanDocToHtml(String fandoc)
{
if (fandoc == null)
{
return null;
}
if (!FanPlatform.isConfigured())
{
return fandoc;
}
String html = fandoc;
try
{
FanObj parser = (FanObj) Type.find("fandoc::FandocParser").make();
FanObj doc = (FanObj) parser.typeof().method("parseStr").call(parser, fandoc);
Buf buf = Buf.make();
FanObj writer = (FanObj) Type.find("fandoc::HtmlDocWriter").method("make").call(buf.out());
doc.typeof().method("write").call(doc, writer);
html = buf.flip().readAllStr();
} catch (Exception e)
{
e.printStackTrace();
} //System.out.println("Html doc: "+html);
return html;
}
@SuppressWarnings("unchecked")
private void cleanupOldDocs()
{
try
{
Vector<FanDocument> docs = (Vector<FanDocument>) JOTQueryBuilder.selectQuery(null, FanDocument.class).find().getAllResults();
for (FanDocument doc : docs)
{
String path = doc.getPath();
if (!new File(path).exists())
{
log.info("Removing entries for removed document: " + path);
doc.delete();
}
}
} catch (Exception e)
{
log.exception("Error deleting outdated docs", e);
}
}
/*********************************************************************
* Indexer Thread class
* All indexing request should go through here to avoid issues.
*/
class FanIndexerThread extends Thread implements Runnable
{
@Override
public void run()
{
while (!shutdown)
{
try
{
Thread.yield();
sleep(100);
} catch (Exception e)
{
}
// to be deleted
Enumeration<String> tbd = toBeDeleted.keys();
{
while (tbd.hasMoreElements())
{
if (shutdown)
{
return;
}
String path = tbd.nextElement();
FanDocument doc = FanDocument.findByPath(path);
try
{
if (doc != null)
{
doc.delete();
}
} catch (Exception e)
{
log.exception("Error deleting doc", e);
}
}
}
// always do binaries first
do
{
// Usig keys() since it uses a "snapshot"
// no concurrentmodif error
// also nextElement() should be safe since we only remove elements from within here
// elems can be added outside ... but that should be fine.
Enumeration<String> it = fanPodsToBeIndexed.keys();
while (it.hasMoreElements())
{
if (shutdown)
{
return;
}
String path = it.nextElement();
Long l = fanPodsToBeIndexed.get(path);
long now = new Date().getTime();
if (l!=null && l.longValue() < now - 1000)
{
fanPodsToBeIndexed.remove(path);
indexPod(path);
}
}
} while (!fanPodsToBeIndexed.isEmpty());
// then do the sources
Enumeration<String> it = fanSrcToBeIndexed.keys();
while (it.hasMoreElements())
{
if (shutdown)
{
return;
}
String path = it.nextElement();
Long l = fanSrcToBeIndexed.get(path);
// Hasn't changed in a couple seconds
long now = new Date().getTime();
if (path!=null && l!=null && l.longValue() < now - 2000)
{
fanSrcToBeIndexed.remove(path);
indexSrc(path);
}
}
}
}
}
class MainIndexer extends Thread implements Runnable
{
volatile boolean done = false;
private final boolean bg;
public MainIndexer(boolean backgroundJava)
{
super();
this.bg = backgroundJava;
}
@Override
public void run()
{
done = false;
alreadyWarned = false;
// cleanup old docs
cleanupOldDocs();
// start the indexing thread
// index Fantom libs right aways
long then = new Date().getTime();
// index first existing pods
// we want to wait for pods, since we want them done first (there might be pods without sources)
indexFantomPods(false);
// then index from source
indexSrcFolder(FanPlatform.getInstance().getFanSrcHome(), 0);
long now = new Date().getTime();
log.info("Fantom Pod Parsing completed in " + (now - then) + " ms.");
// sources indexes will be called through scanStarted()
jarsIndexer = new FanJarsIndexer();
// Do this one in the background (might take a while and not needed for everyone)
jarsIndexer.indexJars(bg);
done = true;
}
public void waitFor()
{
while (!done && !shutdown)
{
try
{
sleep(250);
yield();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public static boolean isAllowedIndexing(FileObject srcFile)
{
/*if ( ! FanPlatform.getInstance(false).isConfigured())
{
return true;
}
boolean skip = FileUtil.isParentOf(FanPlatform.getInstance().getFanSrcHome(), srcFile);
return ! skip;*/
return true;
}
} |
package net.wurstclient.features.mods;
import net.minecraft.block.material.Material;
import net.wurstclient.compatibility.WBlock;
import net.wurstclient.events.listeners.UpdateListener;
@Mod.Info(
description = "Automatically mines a block as soon as you look at it.",
name = "AutoMine",
tags = "AutoBreak, auto mine, auto break",
help = "Mods/AutoMine")
@Mod.Bypasses
public final class AutoMineMod extends Mod implements UpdateListener
{
@Override
public void onEnable()
{
wurst.events.add(UpdateListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(UpdateListener.class, this);
// release attack key
mc.gameSettings.keyBindAttack.pressed = false;
}
@Override
public void onUpdate()
{
// check hitResult
if(mc.objectMouseOver == null
|| mc.objectMouseOver.getBlockPos() == null)
return;
// if attack key is down but nothing happens, release it for one tick
if(mc.gameSettings.keyBindAttack.pressed
&& !mc.playerController.getIsHittingBlock())
{
mc.gameSettings.keyBindAttack.pressed = false;
return;
}
// press attack key if looking at block
mc.gameSettings.keyBindAttack.pressed = WBlock
.getMaterial(mc.objectMouseOver.getBlockPos()) != Material.AIR;
}
} |
package org.biojava.bio.dist;
import java.util.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.bio.symbol.*;
/**
* Provides an N'th order distribution.
*
* @author Samiul Hasan
* @author Matthew Pocock
*/
public class NthOrderDistribution extends AbstractDistribution implements Serializable {
private CrossProductAlphabet alphabet;
private Alphabet firstA;
private Alphabet lastA;
private Map dists;
private Distribution nullModel;
protected WeigthForwarder weightForwarder = null;
protected void generateChangeSupport(ChangeType ct) {
super.generateChangeSupport(ct);
if(
( (ct == null) || (ct == Distribution.WEIGHTS) ) &&
weightForwarder == null
) {
weightForwarder = new WeigthForwarder(this, changeSupport);
for(Iterator i = dists.values().iterator(); i.hasNext(); ) {
Distribution dist = (Distribution) i.next();
dist.addChangeListener(weightForwarder, Distribution.WEIGHTS);
}
}
}
public NthOrderDistribution(CrossProductAlphabet alpha, DistributionFactory df)
throws IllegalAlphabetException {
this.alphabet = alpha;
List aList = alpha.getAlphabets();
int lb1 = aList.size() - 1;
if(aList.size() == 2) {
this.firstA = (Alphabet) aList.get(0);
} else {
this.firstA = AlphabetManager.getCrossProductAlphabet(aList.subList(0, lb1));
}
this.lastA = (Alphabet) aList.get(lb1);
this.dists = new HashMap();
this.nullModel = new UniformNullModel();
for(Iterator i = ((FiniteAlphabet) firstA).iterator(); i.hasNext(); ) {
Symbol si = (Symbol) i.next();
dists.put(si, df.createDistribution(lastA));
}
}
public void setDistribution(Symbol sym, Distribution dist)
throws IllegalSymbolException, IllegalAlphabetException {
firstA.validate(sym);
if(dist.getAlphabet() != lastA) {
throw new IllegalAlphabetException(
"The distribution must be over " + lastA +
", not " + dist.getAlphabet()
);
}
Distribution old = (Distribution) dists.get(sym);
if( (old != null) && (weightForwarder != null) ) {
old.removeChangeListener(weightForwarder);
}
if(weightForwarder != null) {
dist.addChangeListener(weightForwarder);
}
dists.put(sym, dist);
}
public Distribution getDistribution(Symbol sym)
throws IllegalSymbolException {
Distribution d = (Distribution) dists.get(sym);
if(d == null) {
firstA.validate(sym);
}
return d;
}
public Alphabet getAlphabet() {
return alphabet;
}
public double getWeight(Symbol sym) throws IllegalSymbolException {
if(sym instanceof AtomicSymbol) {
CrossProductSymbol cps = (CrossProductSymbol) sym;
List symL = cps.getSymbols();
int lb1 = symL.size() - 1;
Symbol firstS;
if(symL.size() == 2) {
firstS = (Symbol) symL.get(0);
} else {
firstS = ((CrossProductAlphabet) firstA).getSymbol(symL.subList(0, lb1));
}
Distribution dist = getDistribution(firstS);
return dist.getWeight((Symbol) symL.get(lb1));
} else {
return getAmbiguityWeight(sym);
}
}
public void setNullModel(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException {
if(nullModel == null) {
throw new NullPointerException(
"The null model must not be null." +
" The apropreate null-model is a UniformDistribution instance."
);
}
if(nullModel.getAlphabet() != getAlphabet()) {
throw new IllegalAlphabetException(
"Could not use distribution " + nullModel +
" as its alphabet is " + nullModel.getAlphabet().getName() +
" and this distribution's alphabet is " + getAlphabet().getName()
);
}
this.nullModel = nullModel;
}
public Distribution getNullModel() {
return this.nullModel;
}
public void registerWithTrainer(DistributionTrainerContext dtc) {
for(Iterator i = dists.values().iterator(); i.hasNext(); ) {
dtc.registerDistribution((Distribution) i.next());
}
dtc.registerTrainer(this, new IgnoreCountsTrainer() {
public void addCount(
DistributionTrainerContext dtc,
Symbol sym,
double count
) throws IllegalSymbolException {
CrossProductSymbol cps = (CrossProductSymbol) sym;
List symL = cps.getSymbols();
int lb1 = symL.size() - 1;
Symbol firstS;
if(lb1 == 1) {
firstS = (Symbol) symL.get(0);
} else {
firstS = ((CrossProductAlphabet) firstA).getSymbol(symL.subList(0, lb1));
}
Distribution dist = getDistribution(firstS);
dtc.addCount(dist, (Symbol) symL.get(lb1), count);
}
});
}
private class UniformNullModel extends AbstractDistribution {
private Distribution nullModel = new UniformDistribution((FiniteAlphabet) lastA);
public Alphabet getAlphabet() {
return NthOrderDistribution.this.getAlphabet();
}
public double getWeight(Symbol sym)
throws IllegalSymbolException {
CrossProductSymbol cps = (CrossProductSymbol) sym;
List symL = cps.getSymbols();
int lb1 = symL.size() - 1;
return nullModel.getWeight((Symbol) symL.get(lb1));
}
public Distribution getNullModel() {
return this;
}
public void setNullModel(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException {
throw new ChangeVetoException(
"Can't set the null model for NthOrderDistribution.UniformNullModel"
);
}
}
private class WeigthForwarder extends ChangeAdapter {
public WeigthForwarder(Object source, ChangeSupport cs) {
super(source, cs);
}
protected ChangeEvent generateEvent(ChangeEvent ce) {
if(ce.getType() == Distribution.WEIGHTS) {
return new ChangeEvent(
getSource(),
Distribution.WEIGHTS,
ce
);
}
return null;
}
}
} |
package org.biojava.bio.symbol;
import java.util.Set;
import org.biojava.bio.symbol.Symbol;
import org.biojava.bio.dist.Distribution;
/**
* an object to return statistics about
* the frequency of the wobble base
* in a set of synonymous codons.
*
* @author David Huen
* @since 1.3
*/
public interface WobbleDistribution
{
/**
* returns the residue encoded by this WobbleDistribution
*/
public Symbol getResidue();
/**
* returns Set containing the nonWobbleBases that
* occur in codons that encode this residue
*/
public Set getNonWobbleBases();
/**
* returns the frequency with which
* synonymous codons start with a
* specified pair of bases.
*/
public Distribution getFrequencyOfNonWobbleBases();
/**
* returns the frequency of a specific
* wobble base in a set of synonymous
* codons that start with the same two
* bases. (sums to one over this set).
*/
public Distribution getWobbleFrequency(Symbol nonWobbleBases);
} |
package org.bootstrapjsp.tags.core.misc;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
import org.bootstrapjsp.dialect.Html;
import org.bootstrapjsp.tags.html.Div;
import org.tldgen.annotations.Attribute;
import org.tldgen.annotations.BodyContent;
import org.tldgen.annotations.Tag;
/**
* Easily center a page's contents by wrapping its contents in a <container>.
* Containers set width at various media query breakpoints to match the grid
* system.
* <p>
* Note that, due to padding and fixed widths, containers are not nestable, and
* will throw an error if nested.
* </p>
* <p>
* <dl>
* <dt><b>Example</b></dt>
* <dd><b:container fluid="true">... </b:container></dd>
* <dt><b>Output</b></dt>
* <dd><div class="container-fluid">... </div></dd>
* </dl>
* </p>
*/
@Tag(bodyContent=BodyContent.SCRIPTLESS,dynamicAttributes=true)
public class Container extends Div {
private boolean fluid = false;
public Container() {
super();
}
@Override
public void doTag() throws JspException, IOException {
super.setAttribute(Html.CLASS_ATTRIBUTE, this.fluid ? "container-fluid" : "container");
super.doTag();
}
@Override
public void setParent(JspTag parent) {
if (parent instanceof Container) {
throw new IllegalArgumentException("Bootstrap containers may not be nested");
}
super.setParent(parent);
}
/**
* Makes the container fluid.
*/
@Attribute(rtexprvalue=true)
public void setFluid(boolean fluid) {
this.fluid = fluid;
}
} |
// $Id: CoordGmsImpl.java,v 1.11 2004/09/06 13:48:59 belaban Exp $
package org.jgroups.protocols.pbcast;
import org.jgroups.*;
import org.jgroups.util.Promise;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Vector;
/**
* Coordinator role of the Group MemberShip (GMS) protocol. Accepts JOIN and LEAVE requests and emits view changes
* accordingly.
* @author Bela Ban
*/
public class CoordGmsImpl extends GmsImpl {
boolean merging=false;
Promise leave_promise=null;
MergeTask merge_task=new MergeTask();
Vector merge_rsps=new Vector(11);
// for MERGE_REQ/MERGE_RSP correlation, contains MergeData elements
Serializable merge_id=null;
public CoordGmsImpl(GMS g) {
gms=g;
}
public void join(Address mbr) {
wrongMethod("join");
}
/** The coordinator itself wants to leave the group */
public void leave(Address mbr) {
if(mbr == null) {
if(log.isErrorEnabled()) log.error("member's address is null !");
return;
}
if(leave_promise == null)
leave_promise=new Promise();
else
leave_promise.reset();
if(mbr.equals(gms.local_addr))
leaving=true;
handleLeave(mbr, false); // regular leave
}
public void handleJoinResponse(JoinRsp join_rsp) {
wrongMethod("handleJoinResponse");
}
public void handleLeaveResponse() {
wrongMethod("handleLeaveResponse");
}
public void suspect(Address mbr) {
handleSuspect(mbr);
}
public void unsuspect(Address mbr) {
}
/**
* Invoked upon receiving a MERGE event from the MERGE layer. Starts the merge protocol.
* See description of protocol in DESIGN.
* @param other_coords A list of coordinators (including myself) found by MERGE protocol
*/
public void merge(Vector other_coords) {
Membership tmp;
Address leader=null;
if(merging) {
if(log.isWarnEnabled()) log.warn("merge already in progress, discarded MERGE event");
return;
}
if(other_coords == null) {
if(log.isWarnEnabled()) log.warn("list of other coordinators is null. Will not start merge.");
return;
}
if(other_coords.size() <= 1) {
if(log.isErrorEnabled()) log.error("number of coordinators found is "
+ other_coords.size() + "; will not perform merge");
return;
}
/* Establish deterministic order, so that coords can elect leader */
tmp=new Membership(other_coords);
tmp.sort();
leader=(Address)tmp.elementAt(0);
if(log.isDebugEnabled()) log.debug("coordinators in merge protocol are: " + tmp);
if(leader.equals(gms.local_addr)) {
if(log.isDebugEnabled()) log.debug("I (" + leader + ") will be the leader. Starting the merge task");
startMergeTask(other_coords);
}
}
/**
* Get the view and digest and send back both (MergeData) in the form of a MERGE_RSP to the sender.
* If a merge is already in progress, send back a MergeData with the merge_rejected field set to true.
*/
public void handleMergeRequest(Address sender, Object merge_id) {
Digest digest;
View view;
if(sender == null) {
if(log.isErrorEnabled()) log.error("sender == null; cannot send back a response");
return;
}
if(merging) {
if(log.isErrorEnabled()) log.error("merge already in progress");
sendMergeRejectedResponse(sender);
return;
}
merging=true;
this.merge_id=(Serializable)merge_id;
if(log.isDebugEnabled()) log.debug("sender=" + sender + ", merge_id=" + merge_id);
digest=gms.getDigest();
view=new View(gms.view_id.copy(), gms.members.getMembers());
sendMergeResponse(sender, view, digest);
}
MergeData getMergeResponse(Address sender, Object merge_id) {
Digest digest;
View view;
MergeData retval;
if(sender == null) {
if(log.isErrorEnabled()) log.error("sender == null; cannot send back a response");
return null;
}
if(merging) {
if(log.isErrorEnabled()) log.error("merge already in progress");
retval=new MergeData(sender, null, null);
retval.merge_rejected=true;
return retval;
}
merging=true;
this.merge_id=(Serializable)merge_id;
if(log.isDebugEnabled()) log.debug("sender=" + sender + ", merge_id=" + merge_id);
digest=gms.getDigest();
view=new View(gms.view_id.copy(), gms.members.getMembers());
retval=new MergeData(sender, view, digest);
retval.view=view;
retval.digest=digest;
return retval;
}
public void handleMergeResponse(MergeData data, Object merge_id) {
if(data == null) {
if(log.isErrorEnabled()) log.error("merge data is null");
return;
}
if(merge_id == null || this.merge_id == null) {
if(log.isErrorEnabled()) log.error("merge_id ("
+ merge_id
+ ") or this.merge_id ("
+ this.merge_id
+ ") == null (sender="
+ data.getSender()
+ ").");
return;
}
if(!this.merge_id.equals(merge_id)) {
if(log.isErrorEnabled()) log.error("this.merge_id ("
+ this.merge_id
+ ") is different from merge_id ("
+ merge_id
+ ')');
return;
}
synchronized(merge_rsps) {
if(!merge_rsps.contains(data)) {
merge_rsps.addElement(data);
merge_rsps.notifyAll();
}
}
}
/**
* If merge_id != this.merge_id --> discard
* Else cast the view/digest to all members of this group.
*/
public void handleMergeView(MergeData data, Object merge_id) {
if(merge_id == null
|| this.merge_id == null
|| !this.merge_id.equals(merge_id)) {
if(log.isErrorEnabled()) log.error("merge_ids don't match (or are null); merge view discarded");
return;
}
gms.castViewChange(data.view, data.digest);
merging=false;
merge_id=null;
}
public void handleMergeCancelled(Object merge_id) {
if(merge_id != null
&& this.merge_id != null
&& this.merge_id.equals(merge_id)) {
if(log.isDebugEnabled()) log.debug("merge was cancelled (merge_id=" + merge_id + ')');
this.merge_id=null;
merging=false;
}
}
/**
* Computes the new view (including the newly joined member) and get the digest from PBCAST.
* Returns both in the form of a JoinRsp
*/
public synchronized JoinRsp handleJoin(Address mbr) {
Vector new_mbrs=new Vector(1);
View v=null;
Digest d, tmp;
if(log.isDebugEnabled()) log.debug("mbr=" + mbr);
if(gms.local_addr.equals(mbr)) {
if(log.isErrorEnabled()) log.error("cannot join myself !");
return null;
}
if(gms.members.contains(mbr)) {
if(log.isErrorEnabled())
log.error("member " + mbr + " already present; returning existing view " + gms.members.getMembers());
return new JoinRsp(new View(gms.view_id, gms.members.getMembers()), gms.getDigest());
// already joined: return current digest and membership
}
new_mbrs.addElement(mbr);
tmp=gms.getDigest(); // get existing digest
if(tmp == null) {
if(log.isErrorEnabled()) log.error("received null digest from GET_DIGEST: will cause JOIN to fail");
return null;
}
if(log.isDebugEnabled()) log.debug("got digest=" + tmp);
d=new Digest(tmp.size() + 1);
// create a new digest, which contains 1 more member
d.add(tmp); // add the existing digest to the new one
d.add(mbr, 0, 0);
// ... and add the new member. it's first seqno will be 1
v=gms.getNextView(new_mbrs, null, null);
if(log.isDebugEnabled()) log.debug("joined member " + mbr + ", view is " + v);
return new JoinRsp(v, d);
}
/**
Exclude <code>mbr</code> from the membership. If <code>suspected</code> is true, then
this member crashed and therefore is forced to leave, otherwise it is leaving voluntarily.
*/
public synchronized void handleLeave(Address mbr, boolean suspected) {
Vector v=new Vector(1);
// contains either leaving mbrs or suspected mbrs
if(log.isDebugEnabled()) log.debug("mbr=" + mbr);
if(!gms.members.contains(mbr)) {
if(log.isErrorEnabled()) log.error("mbr " + mbr + " is not a member !");
return;
}
if(gms.view_id == null) {
// we're probably not the coord anymore (we just left ourselves), let someone else do it
// (client will retry when it doesn't get a response
if(log.isDebugEnabled())
log.debug("gms.view_id is null, I'm not the coordinator anymore (leaving=" + leaving +
"); the new coordinator will handle the leave request");
return;
}
sendLeaveResponse(mbr); // send an ack to the leaving member
v.addElement(mbr);
if(suspected)
gms.castViewChange(null, null, v);
else
gms.castViewChange(null, v, null);
}
void sendLeaveResponse(Address mbr) {
Message msg=new Message(mbr, null, null);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.LEAVE_RSP);
msg.putHeader(gms.getName(), hdr);
gms.passDown(new Event(Event.MSG, msg));
}
/**
* Called by the GMS when a VIEW is received.
* @param new_view The view to be installed
* @param digest If view is a MergeView, digest contains the seqno digest of all members and has to
* be set by GMS
*/
public void handleViewChange(View new_view, Digest digest) {
Vector mbrs=new_view.getMembers();
{
if(digest != null)
if(log.isDebugEnabled()) log.debug("view=" + new_view + ", digest=" + digest);
else
if(log.isDebugEnabled()) log.debug("view=" + new_view);
}
if(leaving && !mbrs.contains(gms.local_addr)) {
if(leave_promise != null) {
leave_promise.setResult(Boolean.TRUE);
}
return;
}
gms.installView(new_view, digest);
}
public void handleSuspect(Address mbr) {
if(mbr.equals(gms.local_addr)) {
if(log.isWarnEnabled()) log.warn("I am the coord and I'm being am suspected -- will probably leave shortly");
return;
}
handleLeave(mbr, true); // irregular leave - forced
}
public void stop() {
leaving=true;
merge_task.stop();
}
void startMergeTask(Vector coords) {
merge_task.start(coords);
}
void stopMergeTask() {
merge_task.stop();
}
/**
* Sends a MERGE_REQ to all coords and populates a list of MergeData (in merge_rsps). Returns after coords.size()
* response have been received, or timeout msecs have elapsed (whichever is first).<p>
* If a subgroup coordinator rejects the MERGE_REQ (e.g. because of participation in a different merge),
* <em>that member will be removed from coords !</em>
* @param coords A list of Addresses of subgroup coordinators (inluding myself)
* @param timeout Max number of msecs to wait for the merge responses from the subgroup coords
*/
void getMergeDataFromSubgroupCoordinators(Vector coords, long timeout) {
Message msg;
GMS.GmsHeader hdr;
Address coord;
long curr_time, time_to_wait=0, end_time;
int num_rsps_expected=0;
if(coords == null || coords.size() <= 1) {
if(log.isErrorEnabled()) log.error("coords == null or size <= 1");
return;
}
synchronized(merge_rsps) {
merge_rsps.removeAllElements();
if(log.isDebugEnabled()) log.debug("sending MERGE_REQ to " + coords);
for(int i=0; i < coords.size(); i++) {
coord=(Address)coords.elementAt(i);
if(gms.local_addr != null && gms.local_addr.equals(coord)) {
merge_rsps.add(getMergeResponse(gms.local_addr, merge_id));
continue;
}
msg=new Message(coord, null, null);
hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_REQ);
hdr.mbr=gms.local_addr;
hdr.merge_id=merge_id;
msg.putHeader(gms.getName(), hdr);
gms.passDown(new Event(Event.MSG, msg));
}
// wait until num_rsps_expected >= num_rsps or timeout elapsed
num_rsps_expected=coords.size();
curr_time=System.currentTimeMillis();
end_time=curr_time + timeout;
while(end_time > curr_time) {
time_to_wait=end_time - curr_time;
if(log.isDebugEnabled()) log.debug("waiting for "
+ time_to_wait
+ " msecs for merge responses");
if(merge_rsps.size() < num_rsps_expected) {
try {
merge_rsps.wait(time_to_wait);
}
catch(Exception ex) {
}
}
if(log.isDebugEnabled()) log.debug("num_rsps_expected=" + num_rsps_expected
+ ", actual responses=" + merge_rsps.size());
if(merge_rsps.size() >= num_rsps_expected)
break;
curr_time=System.currentTimeMillis();
}
}
}
/**
* Generates a unique merge id by taking the local address and the current time
*/
Serializable generateMergeId() {
return new ViewId(gms.local_addr, System.currentTimeMillis());
// we're (ab)using ViewId as a merge id
}
/**
* Merge all MergeData. All MergeData elements should be disjunct (both views and digests). However,
* this method is prepared to resolve duplicate entries (for the same member). Resolution strategy for
* views is to merge only 1 of the duplicate members. Resolution strategy for digests is to take the higher
* seqnos for duplicate digests.<p>
* After merging all members into a Membership and subsequent sorting, the first member of the sorted membership
* will be the new coordinator.
* @param v A list of MergeData items. Elements with merge_rejected=true were removed before. Is guaranteed
* not to be null and to contain at least 1 member.
*/
MergeData consolidateMergeData(Vector v) {
MergeData ret=null;
MergeData tmp_data;
long logical_time=0; // for new_vid
ViewId new_vid, tmp_vid;
MergeView new_view;
View tmp_view;
Membership new_mbrs=new Membership();
int num_mbrs=0;
Digest new_digest=null;
Address new_coord;
Vector subgroups=new Vector(11);
// contains a list of Views, each View is a subgroup
for(int i=0; i < v.size(); i++) {
tmp_data=(MergeData)v.elementAt(i);
if(log.isDebugEnabled()) log.debug("merge data is " + tmp_data);
tmp_view=tmp_data.getView();
if(tmp_view != null) {
tmp_vid=tmp_view.getVid();
if(tmp_vid != null) {
// compute the new view id (max of all vids +1)
logical_time=Math.max(logical_time, tmp_vid.getId());
}
}
// merge all membership lists into one (prevent duplicates)
new_mbrs.add(tmp_view.getMembers());
subgroups.addElement(tmp_view.clone());
}
// the new coordinator is the first member of the consolidated & sorted membership list
new_mbrs.sort();
num_mbrs=new_mbrs.size();
new_coord=num_mbrs > 0? (Address)new_mbrs.elementAt(0) : null;
if(new_coord == null) {
if(log.isErrorEnabled()) log.error("new_coord == null");
return null;
}
new_vid=new ViewId(new_coord, logical_time + 1);
// determine the new view
new_view=new MergeView(new_vid, new_mbrs.getMembers(), subgroups);
if(log.isDebugEnabled()) log.debug("new merged view will be " + new_view);
// determine the new digest
new_digest=consolidateDigests(v, num_mbrs);
if(new_digest == null) {
if(log.isErrorEnabled()) log.error("digest could not be consolidated");
return null;
}
if(log.isDebugEnabled()) log.debug("consolidated digest=" + new_digest);
ret=new MergeData(gms.local_addr, new_view, new_digest);
return ret;
}
/**
* Merge all digests into one. For each sender, the new value is min(low_seqno), max(high_seqno),
* max(high_seqno_seen)
*/
Digest consolidateDigests(Vector v, int num_mbrs) {
MergeData data;
Digest tmp_digest, retval=new Digest(num_mbrs);
for(int i=0; i < v.size(); i++) {
data=(MergeData)v.elementAt(i);
tmp_digest=data.getDigest();
if(tmp_digest == null) {
if(log.isErrorEnabled()) log.error("tmp_digest == null; skipping");
continue;
}
retval.merge(tmp_digest);
}
return retval;
}
/**
* Sends the new view and digest to all subgroup coordinors in coords. Each coord will in turn
* <ol>
* <li>cast the new view and digest to all the members of its subgroup (MergeView)
* <li>on reception of the view, if it is a MergeView, each member will set the digest and install
* the new view
* </ol>
*/
void sendMergeView(Vector coords, MergeData combined_merge_data) {
Message msg;
GMS.GmsHeader hdr;
Address coord;
View v;
Digest d;
if(coords == null || combined_merge_data == null)
return;
v=combined_merge_data.view;
d=combined_merge_data.digest;
if(v == null || d == null) {
if(log.isErrorEnabled()) log.error("view or digest is null, cannot send consolidated merge view/digest");
return;
}
for(int i=0; i < coords.size(); i++) {
coord=(Address)coords.elementAt(i);
msg=new Message(coord, null, null);
hdr=new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW);
hdr.view=v;
hdr.digest=d;
hdr.merge_id=merge_id;
msg.putHeader(gms.getName(), hdr);
gms.passDown(new Event(Event.MSG, msg));
}
}
/**
* Send back a response containing view and digest to sender
*/
void sendMergeResponse(Address sender, View view, Digest digest) {
Message msg=new Message(sender, null, null);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.merge_id=merge_id;
hdr.view=view;
hdr.digest=digest;
msg.putHeader(gms.getName(), hdr);
if(log.isDebugEnabled()) log.debug("response=" + hdr);
gms.passDown(new Event(Event.MSG, msg));
}
void sendMergeRejectedResponse(Address sender) {
Message msg=new Message(sender, null, null);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.merge_rejected=true;
hdr.merge_id=merge_id;
msg.putHeader(gms.getName(), hdr);
if(log.isDebugEnabled()) log.debug("response=" + hdr);
gms.passDown(new Event(Event.MSG, msg));
}
void sendMergeCancelledMessage(Vector coords, Serializable merge_id) {
Message msg;
GMS.GmsHeader hdr;
Address coord;
if(coords == null || merge_id == null) {
if(log.isErrorEnabled()) log.error("coords or merge_id == null");
return;
}
for(int i=0; i < coords.size(); i++) {
coord=(Address)coords.elementAt(i);
msg=new Message(coord, null, null);
hdr=new GMS.GmsHeader(GMS.GmsHeader.CANCEL_MERGE);
hdr.merge_id=merge_id;
msg.putHeader(gms.getName(), hdr);
gms.passDown(new Event(Event.MSG, msg));
}
}
/** Removed rejected merge requests from merge_rsps and coords */
void removeRejectedMergeRequests(Vector coords) {
MergeData data;
for(Iterator it=merge_rsps.iterator(); it.hasNext();) {
data=(MergeData)it.next();
if(data.merge_rejected) {
if(data.getSender() != null && coords != null)
coords.removeElement(data.getSender());
it.remove();
if(log.isDebugEnabled()) log.debug("removed element " + data);
}
}
}
/**
* Starts the merge protocol (only run by the merge leader). Essentially sends a MERGE_REQ to all
* coordinators of all subgroups found. Each coord receives its digest and view and returns it.
* The leader then computes the digest and view for the new group from the return values. Finally, it
* sends this merged view/digest to all subgroup coordinators; each coordinator will install it in their
* subgroup.
*/
private class MergeTask implements Runnable {
Thread t=null;
Vector coords=null; // list of subgroup coordinators to be contacted
public void start(Vector coords) {
if(t == null) {
this.coords=coords;
t=new Thread(this, "MergeTask thread");
t.setDaemon(true);
t.start();
}
}
public void stop() {
Thread tmp=t;
if(isRunning()) {
t=null;
tmp.interrupt();
}
t=null;
coords=null;
}
public boolean isRunning() {
return t != null && t.isAlive();
}
/**
* Runs the merge protocol as a leader
*/
public void run() {
MergeData combined_merge_data=null;
if(merging == true) {
if(log.isWarnEnabled()) log.warn("merge is already in progress, terminating");
return;
}
if(log.isDebugEnabled()) log.debug("merge task started");
try {
/* 1. Generate a merge_id that uniquely identifies the merge in progress */
merge_id=generateMergeId();
/* 2. Fetch the current Views/Digests from all subgroup coordinators */
getMergeDataFromSubgroupCoordinators(coords, gms.merge_timeout);
/* 3. Remove rejected MergeData elements from merge_rsp and coords (so we'll send the new view only
to members who accepted the merge request) */
removeRejectedMergeRequests(coords);
if(merge_rsps.size() <= 1) {
if(log.isWarnEnabled())
log.warn("merge responses from subgroup coordinators <= 1 (" + merge_rsps + "). Cancelling merge");
sendMergeCancelledMessage(coords, merge_id);
return;
}
/* 4. Combine all views and digests into 1 View/1 Digest */
combined_merge_data=consolidateMergeData(merge_rsps);
if(combined_merge_data == null) {
if(log.isErrorEnabled()) log.error("combined_merge_data == null");
sendMergeCancelledMessage(coords, merge_id);
return;
}
/* 5. Send the new View/Digest to all coordinators (including myself). On reception, they will
install the digest and view in all of their subgroup members */
sendMergeView(coords, combined_merge_data);
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error("exception=" + ex);
}
finally {
merging=false;
if(log.isDebugEnabled()) log.debug("merge task terminated");
t=null;
}
}
}
} |
/*
* $Id: IdentityManagerStatus.java,v 1.9 2008-01-30 00:52:53 tlipkis Exp $
*/
package org.lockss.protocol;
import java.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.lockss.daemon.status.*;
import org.lockss.config.*;
import org.lockss.poller.*;
import org.lockss.util.*;
public class IdentityManagerStatus
implements StatusAccessor, StatusAccessor.DebugOnly {
static Logger log=Logger.getLogger("IdentityManagerStatus");
private IdentityManager mgr;
private boolean includeV1 = false;
public IdentityManagerStatus(IdentityManager mgr) {
this.mgr = mgr;
try {
includeV1 = (mgr.getLocalPeerIdentity(Poll.V1_PROTOCOL) != null);
} catch (IllegalArgumentException e) {
// ignore
}
}
private static final List statusSortRules =
ListUtil.list(new StatusTable.SortRule("ip", true));
private static final List<ColumnDescriptor> statusColDescs =
ListUtil.list(
new ColumnDescriptor("ip", "Peer",
ColumnDescriptor.TYPE_STRING),
new ColumnDescriptor("lastMessage", "Last Message",
ColumnDescriptor.TYPE_DATE,
"Last time a message was received " +
"from this peer."),
new ColumnDescriptor("lastOp", "Message Type",
ColumnDescriptor.TYPE_STRING,
"Last message type that " +
"was sent from this peer."),
new ColumnDescriptor("origTot", "Messages",
ColumnDescriptor.TYPE_INT,
"Total number of messages received " +
"from this peer."),
new ColumnDescriptor("origLastPoller", "Last Poll",
ColumnDescriptor.TYPE_DATE,
"Last time that the local peer " +
"participated in a poll with this peer."),
new ColumnDescriptor("origLastVoter", "Last Vote",
ColumnDescriptor.TYPE_DATE,
"Last time that this peer " +
"participate as a voter in a poll " +
"called by the local peer."),
new ColumnDescriptor("origLastInvitation", "Last Invitation",
ColumnDescriptor.TYPE_DATE,
"Last time this peer was invited into " +
"a poll called by the local peer."),
new ColumnDescriptor("origTotalInvitations", "Invitations",
ColumnDescriptor.TYPE_INT,
"Total number of invitations sent to " +
"this peer by the local peer."),
new ColumnDescriptor("origPoller", "Polls Called",
ColumnDescriptor.TYPE_INT,
"Total number of polls called by " +
"this peer in which the local peer " +
"voted."),
new ColumnDescriptor("origVoter", "Votes Cast",
ColumnDescriptor.TYPE_INT,
"Total number of polls called by " +
"the local peer in which this peer " +
"voted."),
new ColumnDescriptor("pollsRejected", "Polls Rejected",
ColumnDescriptor.TYPE_INT,
"Total number of poll requests "
+ "rejected by this peer"),
new ColumnDescriptor("pollNak", "NAK Reason",
ColumnDescriptor.TYPE_INT,
"Reason for most recent poll request " +
"rejection, if any."),
new ColumnDescriptor("groups", "Groups",
ColumnDescriptor.TYPE_STRING)
);
public String getDisplayName() {
return "Peer Identities";
}
public void populateTable(StatusTable table) {
String key = table.getKey();
table.setColumnDescriptors(getColDescs(table));
table.setDefaultSortRules(statusSortRules);
table.setRows(getRows(key,
table.getOptions().get(StatusTable.OPTION_DEBUG_USER)));
table.setSummaryInfo(getSummaryInfo(key));
}
public boolean requiresKey() {
return false;
}
private List getColDescs(StatusTable table) {
boolean includeGroups =
table.getOptions().get(StatusTable.OPTION_DEBUG_USER);
List res = new ArrayList(statusColDescs.size());
for (ColumnDescriptor desc : statusColDescs) {
if (includeGroups ||
StringUtil.indexOfIgnoreCase(desc.getColumnName(), "group") < 0) {
res.add(desc);
}
}
return res;
}
private boolean isGroupMatch(PeerIdentityStatus status, List myGroups) {
Collection hisGroups = status.getGroups();
return hisGroups == null ||
CollectionUtils.containsAny(myGroups, hisGroups);
}
private List getRows(String key, boolean includeWrongGroup) {
List myGroups = ConfigManager.getPlatformGroupList();
List table = new ArrayList();
for (PeerIdentityStatus status : mgr.getPeerIdentityStatusList()) {
PeerIdentity pid = status.getPeerIdentity();
if (!pid.isLocalIdentity() &&
(includeWrongGroup || isGroupMatch(status, myGroups))) {
try {
if (includeV1 || pid.getPeerAddress().isStream()) {
table.add(makeRow(pid, status));
}
} catch (IdentityManager.MalformedIdentityKeyException e) {
log.error("Can't get peer status: " + pid, e);
}
}
}
return table;
}
private List getSummaryInfo(String key) {
List res = new ArrayList();
List<String> localIds = new ArrayList();
for (PeerIdentity pid : mgr.getLocalPeerIdentities()) {
localIds.add(pid.getIdString());
}
if (!localIds.isEmpty()) {
String idList = StringUtil.separatedString(localIds, ", ");
String label =
localIds.size() == 1 ? "Local Identity" : "Local Identities";
res.add(new StatusTable.SummaryInfo(label,
ColumnDescriptor.TYPE_STRING,
idList));
}
return res;
}
private Map makeRow(PeerIdentity pid, PeerIdentityStatus status) {
Map row = new HashMap();
row.put("ip", pid.getIdString());
row.put("lastMessage", new Long(status.getLastMessageTime()));
row.put("lastOp", getMessageType(status.getLastMessageOpCode()));
row.put("origTot", new Long(status.getTotalMessages()));
row.put("origPoller",
new Long(status.getTotalPollerPolls()));
row.put("origLastPoller",
new Long(status.getLastPollerTime()));
row.put("origVoter",
new Long(status.getTotalVoterPolls()));
row.put("origLastVoter",
new Long(status.getLastVoterTime()));
row.put("origLastInvitation",
new Long(status.getLastPollInvitationTime()));
row.put("origTotalInvitations",
new Long(status.getTotalPollInvitatioins()));
row.put("pollsRejected",
new Long(status.getTotalRejectedPolls()));
row.put("pollNak",
status.getLastPollNak());
row.put("groups",
status.getGroups());
return row;
}
private String getMessageType(int opcode) {
if (opcode >= V3LcapMessage.POLL_MESSAGES_BASE &&
opcode < (V3LcapMessage.POLL_MESSAGES.length +
V3LcapMessage.POLL_MESSAGES_BASE)) {
return V3LcapMessage.POLL_MESSAGES[opcode -
V3LcapMessage.POLL_MESSAGES_BASE]
+ " (" + opcode + ")";
} else {
return "n/a";
}
}
} |
package org.opencms.scheduler;
import org.opencms.configuration.I_CmsConfigurationParameterHandler;
import org.opencms.main.CmsContextInfo;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.util.CmsStringUtil;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.quartz.CronTrigger;
import org.quartz.Trigger;
public class CmsScheduledJobInfo implements I_CmsConfigurationParameterHandler {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsScheduledJobInfo.class);
/** Indicates if this job is currently active in the scheduler or not. */
private boolean m_active;
/** The name of the class to schedule. */
private String m_className;
/** The context information for the user to execute the job with. */
private CmsContextInfo m_context;
/** The cron expression for this scheduler job. */
private String m_cronExpression;
/** Indicates if the configuration of this job is finalized (frozen). */
private boolean m_frozen;
/** The id of this job. */
private String m_id;
/** Instance object of the scheduled job (only required when instance is re-used). */
private I_CmsScheduledJob m_jobInstance;
/** The name of the job (for information purposes). */
private String m_jobName;
/** The parameters used for this job entry. */
private SortedMap m_parameters;
/** Indicates if the job instance should be re-used if the job is run. */
private boolean m_reuseInstance;
/** The (cron) trigger used for scheduling this job. */
private Trigger m_trigger;
/**
* Default constructor.<p>
*/
public CmsScheduledJobInfo() {
m_reuseInstance = false;
m_frozen = false;
// parameters are stored in a tree map
m_parameters = new TreeMap();
// a job is active by default
m_active = true;
}
/**
* Constructor for creating a new job with all required parameters.<p>
*
* @param id the id of the job of <code>null</code> if a new id should be automatically generated
* @param jobName the display name of the job
* @param className the class name of the job, must be an instance of <code>{@link I_CmsScheduledJob}</code>
* @param context the OpenCms user context information to use when executing the job
* @param cronExpression the cron expression for scheduling the job
* @param reuseInstance indicates if the job class should be re-used
* @param active indicates if the job should be active in the scheduler
* @param parameters the job parameters
*/
public CmsScheduledJobInfo(
String id,
String jobName,
String className,
CmsContextInfo context,
String cronExpression,
boolean reuseInstance,
boolean active,
SortedMap parameters) {
m_frozen = false;
setId(id);
if (CmsStringUtil.isNotEmpty(jobName)) {
// job name is optional, if not present class name will be used
setJobName(jobName);
}
setClassName(className);
setContextInfo(context);
setCronExpression(cronExpression);
setReuseInstance(reuseInstance);
setActive(active);
setParameters(parameters);
}
/**
* @see org.opencms.configuration.I_CmsConfigurationParameterHandler#addConfigurationParameter(java.lang.String, java.lang.String)
*/
public void addConfigurationParameter(String paramName, String paramValue) {
checkFrozen();
// add the configured parameter
m_parameters.put(paramName, paramValue);
if (LOG.isDebugEnabled()) {
LOG.debug(org.opencms.configuration.Messages.get().key(
org.opencms.configuration.Messages.LOG_ADD_CONFIG_PARAM_3,
paramName,
paramValue,
this));
}
}
/**
* Clears the id of the job.<p>
*
* This is useful if you want to create a copy of a job without keeping the job id.
* Use <code>{@link CmsScheduledJobInfo#clone()}</code> first to create the copy,
* and then clear the id of the clone.<p>
*/
public void clearId() {
setId(null);
}
/**
* Creates a clone of this scheduled job.<p>
*
* The clone will not be active in the scheduler until it is scheduled
* with <code>{@link CmsScheduleManager#scheduleJob(org.opencms.file.CmsObject, CmsScheduledJobInfo)}</code>.
* The job id returned by <code>{@link #getId()}</code> will be the same.
* The <code>{@link #isActive()}</code> flag will be set to false.
* The clones job instance class will be the same
* if the <code>{@link #isReuseInstance()}</code> flag is set.<p>
*
* @see java.lang.Object#clone()
*/
public Object clone() {
CmsScheduledJobInfo result = new CmsScheduledJobInfo();
result.m_id = m_id;
result.m_active = false;
result.m_frozen = false;
result.m_className = m_className;
if (isReuseInstance()) {
result.m_jobInstance = m_jobInstance;
}
result.m_context = (CmsContextInfo)m_context.clone();
result.m_cronExpression = m_cronExpression;
result.m_jobName = m_jobName;
result.m_parameters = new TreeMap(m_parameters);
result.m_trigger = null;
return result;
}
/**
* Returns the name of the class to schedule.<p>
*
* @return the name of the class to schedule
*/
public String getClassName() {
return m_className;
}
/**
* @see org.opencms.configuration.I_CmsConfigurationParameterHandler#getConfiguration()
*/
public Map getConfiguration() {
// this configuration does not support parameters
if (LOG.isDebugEnabled()) {
LOG.debug(org.opencms.configuration.Messages.get().key(
org.opencms.configuration.Messages.LOG_GET_CONFIGURATION_1,
this));
}
return getParameters();
}
/**
* Returns the context information for the user executing the job.<p>
*
* @return the context information for the user executing the job
*/
public CmsContextInfo getContextInfo() {
return m_context;
}
/**
* Returns the cron expression for this job entry.<p>
*
* @return the cron expression for this job entry
*/
public String getCronExpression() {
return m_cronExpression;
}
/**
* Returns the next time at which this job will be executed, after the given time.<p>
*
* If this job will not be executed after the given time, <code>null</code> will be returned..<p>
*
* @param date the after which the next execution time should be calculated
* @return the next time at which this job will be executed, after the given time
*/
public Date getExecutionTimeAfter(Date date) {
if (!m_active || (m_trigger == null)) {
// if the job is not active, no time can be calculated
return null;
}
return m_trigger.getFireTimeAfter(date);
}
/**
* Returns the next time at which this job will be executed.<p>
*
* If the job will not execute again, <code>null</code> will be returned.<p>
*
* @return the next time at which this job will be executed
*/
public Date getExecutionTimeNext() {
if (!m_active || (m_trigger == null)) {
// if the job is not active, no time can be calculated
return null;
}
return m_trigger.getNextFireTime();
}
/**
* Returns the previous time at which this job will be executed.<p>
*
* If this job has not yet been executed, <code>null</code> will be returned.
*
* @return the previous time at which this job will be executed
*/
public Date getExecutionTimePrevious() {
if (!m_active || (m_trigger == null)) {
// if the job is not active, no time can be calculated
return null;
}
return m_trigger.getPreviousFireTime();
}
/**
* Returns the internal id of this job in the scheduler.<p>
*
* Can be used to remove this job from the scheduler with
* <code>{@link CmsScheduleManager#unscheduleJob(org.opencms.file.CmsObject, String)}</code>.<p>
*
* @return the internal id of this job in the scheduler
*/
public String getId() {
return m_id;
}
/**
* Returns an instance of the configured job class.<p>
*
* If any error occurs during class invocaion, the error
* is written to the OpenCms log and <code>null</code> is returned.<p>
*
* @return an instance of the configured job class, or null if an error occured
*/
public synchronized I_CmsScheduledJob getJobInstance() {
if (m_jobInstance != null) {
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().key(Messages.LOG_REUSING_INSTANCE_1, m_jobInstance.getClass().getName()));
}
// job instance already initialized
return m_jobInstance;
}
I_CmsScheduledJob job = null;
try {
// create an instance of the OpenCms job class
job = (I_CmsScheduledJob)Class.forName(getClassName()).newInstance();
} catch (ClassNotFoundException e) {
LOG.error(Messages.get().key(Messages.LOG_CLASS_NOT_FOUND_1, getClassName()), e);
} catch (IllegalAccessException e) {
LOG.error(Messages.get().key(Messages.LOG_ILLEGAL_ACCESS_0), e);
} catch (InstantiationException e) {
LOG.error(Messages.get().key(Messages.LOG_INSTANCE_GENERATION_0), e);
} catch (ClassCastException e) {
LOG.error(Messages.get().key(Messages.LOG_BAD_INTERFACE_0), e);
}
if (m_reuseInstance) {
// job instance must be re-used
m_jobInstance = job;
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().key(Messages.LOG_JOB_CREATED_1, getClassName()));
}
return job;
}
/**
* Returns the job name.<p>
*
* @return the job name
*/
public String getJobName() {
return m_jobName;
}
/**
* Returns the parameters.<p>
*
* @return the parameters
*/
public SortedMap getParameters() {
return m_parameters;
}
/**
* Finalizes (freezes) the configuration of this scheduler job entry.<p>
*
* After this job entry has been frozen, any attempt to change the
* configuration of this entry with one of the "set..." methods
* will lead to a <code>RuntimeException</code>.<p>
*
* @see org.opencms.configuration.I_CmsConfigurationParameterHandler#initConfiguration()
*/
public void initConfiguration() {
// simple default configuration does not need to be initialized
if (LOG.isDebugEnabled()) {
LOG.debug(org.opencms.configuration.Messages.get().key(
org.opencms.configuration.Messages.LOG_INIT_CONFIGURATION_1,
this));
}
setFrozen(true);
}
/**
* Returns <code>true</code> if this job is currently active in the scheduler.<p>
*
* @return <code>true</code> if this job is currently active in the scheduler
*/
public boolean isActive() {
return m_active;
}
/**
* Returns true if the job instance class is reused for this job.<p>
*
* @return true if the job instance class is reused for this job
*/
public boolean isReuseInstance() {
return m_reuseInstance;
}
/**
* Sets the active state of this job.<p>
*
* @param active the active state to set
*/
public void setActive(boolean active) {
checkFrozen();
m_active = active;
}
/**
* Sets the name of the class to schedule.<p>
*
* @param className the class name to set
*/
public void setClassName(String className) {
checkFrozen();
if (!CmsStringUtil.isValidJavaClassName(className)) {
throw new CmsIllegalArgumentException(
Messages.get().container(Messages.ERR_BAD_JOB_CLASS_NAME_1, className));
}
Class jobClass;
try {
jobClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_JOB_CLASS_NOT_FOUND_1,
className));
}
if (!I_CmsScheduledJob.class.isAssignableFrom(jobClass)) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_JOB_CLASS_BAD_INTERFACE_2,
className,
I_CmsScheduledJob.class.getName()));
}
m_className = className;
if (getJobName() == null) {
// initialize job name with class name as default
setJobName(className);
}
}
/**
* Sets the context information for the user executing the job.<p>
*
* This will also "freeze" the context information that is set.<p>
*
* @param contextInfo the context information for the user executing the job
*
* @see CmsContextInfo#freeze()
*/
public void setContextInfo(CmsContextInfo contextInfo) {
checkFrozen();
if (contextInfo == null) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_BAD_CONTEXT_INFO_0));
}
m_context = contextInfo;
}
/**
* Sets the cron expression for this job entry.<p>
*
* @param cronExpression the cron expression to set
*/
public void setCronExpression(String cronExpression) {
checkFrozen();
try {
// check if the cron expression is valid
new CronTrigger().setCronExpression(cronExpression);
} catch (Exception e) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_BAD_CRON_EXPRESSION_2,
getJobName(),
cronExpression));
}
m_cronExpression = cronExpression;
}
/**
* Sets the job name.<p>
*
* @param jobName the job name to set
*/
public void setJobName(String jobName) {
checkFrozen();
if (CmsStringUtil.isEmpty(jobName) || !jobName.trim().equals(jobName)) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_BAD_JOB_NAME_1, jobName));
}
m_jobName = jobName;
}
/**
* Sets the job parameters.<p>
*
* @param parameters the parameters to set
*/
public void setParameters(SortedMap parameters) {
checkFrozen();
if (parameters == null) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_BAD_JOB_PARAMS_0));
}
// make sure the parameters are a sorted map
m_parameters = new TreeMap(parameters);
}
/**
* Controls if the job instance class is reused for this job,
* of if a new instance is generated every time the job is run.<p>
*
* @param reuseInstance must be true if the job instance class is to be reused
*/
public void setReuseInstance(boolean reuseInstance) {
checkFrozen();
m_reuseInstance = reuseInstance;
}
/**
* Checks if this job info configuration is frozen.<p>
*
* @throws CmsRuntimeException in case the configuration is already frozen
*/
protected void checkFrozen() throws CmsRuntimeException {
if (m_frozen) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_JOB_INFO_FROZEN_1, getJobName()));
}
}
/**
* Returns the Quartz trigger used for scheduling this job.<p>
*
* This is an internal operation that should only by performed by the
* <code>{@link CmsScheduleManager}</code>, never by using this API directly.<p>
*
* @return the Quartz trigger used for scheduling this job
*/
protected Trigger getTrigger() {
return m_trigger;
}
/**
* Sets the "frozen" state of this job.<p>
*
* This is an internal operation to be used only by the <code>{@link CmsScheduleManager}</code>.<p>
*
* @param frozen the "frozen" state to set
*/
protected synchronized void setFrozen(boolean frozen) {
if (frozen && !m_frozen) {
// "freeze" the job configuration
m_parameters = Collections.unmodifiableSortedMap(m_parameters);
m_context.freeze();
m_frozen = true;
} else if (!frozen && m_frozen) {
// "unfreeze" the job configuration
m_parameters = new TreeMap(m_parameters);
m_frozen = false;
}
}
/**
* Sets the is used for scheduling this job.<p>
*
* This is an internal operation that should only by performed by the
* <code>{@link CmsScheduleManager}</code>, never by using this API directly.<p>
*
* @param id the id to set
*/
protected void setId(String id) {
checkFrozen();
m_id = id;
}
/**
* Sets the Quartz trigger used for scheduling this job.<p>
*
* This is an internal operation that should only by performed by the
* <code>{@link CmsScheduleManager}</code>, never by using this API directly.<p>
*
* @param trigger the Quartz trigger to set
*/
protected void setTrigger(Trigger trigger) {
checkFrozen();
m_trigger = trigger;
}
} |
package org.opencms.workplace;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertydefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceTypeXmlPage;
import org.opencms.file.I_CmsResourceType;
import org.opencms.i18n.CmsEncoder;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.OpenCms;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.RandomAccess;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
/**
* Provides methods for the properties dialog.<p>
*
* The following files use this class:
* <ul>
* <li>/jsp/dialogs/property_advanced_html
* </ul>
*
* @author Andreas Zahner (a.zahner@alkacon.com)
* @version $Revision: 1.3 $
*
* @since 5.1
*/
public class CmsPropertyAdvanced extends CmsTabDialog implements I_CmsDialogHandler {
/** The dialog type */
public static final String DIALOG_TYPE = "property";
/** Value for the action: show edit properties form */
public static final int ACTION_SHOW_EDIT = 100;
/** Value for the action: show define property form */
public static final int ACTION_SHOW_DEFINE = 200;
/** Value for the action: save edited properties */
public static final int ACTION_SAVE_EDIT = 300;
/** Value for the action: save defined property */
public static final int ACTION_SAVE_DEFINE = 400;
/** Constant for the "Define" button in the build button method */
public static final int BUTTON_DEFINE = 201;
/** Constant for the "Finish" button in the build button method */
public static final int BUTTON_FINISH = 202;
/** Request parameter value for the action: show edit properties form */
public static final String DIALOG_SHOW_EDIT = "edit";
/** Request parameter value for the action: show define property form */
public static final String DIALOG_SHOW_DEFINE = "define";
/** Request parameter value for the action: show information form */
public static final String DIALOG_SHOW_DEFAULT = "default";
/** Request parameter value for the action: save edited properties */
public static final String DIALOG_SAVE_EDIT = "saveedit";
/** Request parameter value for the action: save defined property */
public static final String DIALOG_SAVE_DEFINE = "savedefine";
/** Value for the dialog mode: new resource wizard */
public static final String MODE_WIZARD = "wizard";
/** Value for the dialog mode: new resource wizard with creation of index page for new folder */
public static final String MODE_WIZARD_CREATEINDEX = "wizardcreateindex";
/** Value for the dialog mode: new resource wizard with index page created in new folder */
public static final String MODE_WIZARD_INDEXCREATED = "wizardindexcreated";
/** Prefix for the input values */
public static final String PREFIX_VALUE = "value-";
/** Prefix for the hidden fields */
public static final String PREFIX_HIDDEN = "hidden-";
/** Prefix for the hidden structure value */
public static final String PREFIX_STRUCTURE = "structure-";
/** Prefix for the hidden resource value */
public static final String PREFIX_RESOURCE = "resource-";
/** Prefix for the use property checkboxes */
public static final String PREFIX_USEPROPERTY = "use-";
/** Request parameter name for the new property definition */
public static final String PARAM_DIALOGMODE = "dialogmode";
/** Request parameter name for the new property definition */
public static final String PARAM_NEWPROPERTY = "newproperty";
/** The URI to the standard property dialog */
public static final String URI_PROPERTY_DIALOG = C_PATH_DIALOGS + "property_advanced.html";
/** The URI to the customized property dialog */
public static final String URI_PROPERTY_CUSTOM_DIALOG = C_PATH_DIALOGS + "property_custom.html";
/** Request parameter members */
private String m_paramNewproperty;
private String m_paramUseTempfileProject;
private String m_paramDialogMode;
/** Helper object storing the current editable state of the resource */
private Boolean m_isEditable = null;
/** Helper to determine if the user switched the tab views of the dialog */
private boolean m_tabSwitched;
/**
* Default constructor needed for dialog handler implementation.<p>
*/
public CmsPropertyAdvanced() {
super(null);
}
/**
* Public constructor with JSP action element.<p>
*
* @param jsp an initialized JSP action element
*/
public CmsPropertyAdvanced(CmsJspActionElement jsp) {
super(jsp);
}
/**
* Public constructor with JSP variables.<p>
*
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
*/
public CmsPropertyAdvanced(PageContext context, HttpServletRequest req, HttpServletResponse res) {
this(new CmsJspActionElement(context, req, res));
}
/**
* @see org.opencms.workplace.I_CmsDialogHandler#getDialogUri(java.lang.String, CmsJspActionElement)
*/
public String getDialogUri(String resource, CmsJspActionElement jsp) {
try {
CmsResource res = jsp.getCmsObject().readFileHeader(resource);
if (res.getType() == CmsResourceTypeXmlPage.C_RESOURCE_TYPE_ID) {
// display special property dialog for xmlpage types
return C_PATH_WORKPLACE + "editors/dialogs/property.html";
}
String resTypeName = jsp.getCmsObject().getResourceType(res.getType()).getResourceTypeName();
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getEplorerTypeSetting(resTypeName);
if (settings.isPropertiesEnabled()) {
// special properties for this type enabled, display customized dialog
return URI_PROPERTY_CUSTOM_DIALOG;
}
} catch (CmsException e) {
// ignore this exception
}
return URI_PROPERTY_DIALOG;
}
/**
* @see org.opencms.workplace.I_CmsDialogHandler#getDialogHandler()
*/
public String getDialogHandler() {
return CmsDialogSelector.DIALOG_PROPERTY;
}
/**
* @see org.opencms.workplace.CmsTabDialog#getTabs()
*/
public List getTabs() {
ArrayList tabList = new ArrayList(2);
tabList.add(key("panel.properties.structure"));
tabList.add(key("panel.properties.resource"));
return tabList;
}
/**
* @see org.opencms.workplace.CmsTabDialog#getTabParameterOrder()
*/
public List getTabParameterOrder() {
ArrayList orderList = new ArrayList(5);
orderList.add("tabstr");
orderList.add("tabres");
return orderList;
}
/**
* Returns the value of the new property parameter,
* or null if this parameter was not provided.<p>
*
* The new property parameter stores the name of the
* new defined property.<p>
*
* @return the value of the new property parameter
*/
public String getParamNewproperty() {
return m_paramNewproperty;
}
/**
* Sets the value of the new property parameter.<p>
*
* @param value the value to set
*/
public void setParamNewproperty(String value) {
m_paramNewproperty = value;
}
/**
* Returns the value of the usetempfileproject parameter,
* or null if this parameter was not provided.<p>
*
* The usetempfileproject parameter stores if the file resides
* in the temp file project.<p>
*
* @return the value of the usetempfileproject parameter
*/
public String getParamUsetempfileproject() {
return m_paramUseTempfileProject;
}
/**
* Sets the value of the usetempfileproject parameter.<p>
*
* @param value the value to set
*/
public void setParamUsetempfileproject(String value) {
m_paramUseTempfileProject = value;
}
/**
* Returns the value of the dialogmode parameter,
* or null if this parameter was not provided.<p>
*
* The dialogmode parameter stores the different modes of the property dialog,
* e.g. for displaying other buttons in the new resource wizard.<p>
*
* @return the value of the usetempfileproject parameter
*/
public String getParamDialogmode() {
return m_paramDialogMode;
}
/**
* Sets the value of the dialogmode parameter.<p>
*
* @param value the value to set
*/
public void setParamDialogmode(String value) {
m_paramDialogMode = value;
}
/**
* Returns all possible properties for the current resource type.<p>
*
* @return all property definitions for te resource type
* @throws CmsException if something goes wrong
*/
public Vector getPropertyDefinitions() throws CmsException {
CmsResource res = getCms().readFileHeader(getParamResource());
I_CmsResourceType type = getCms().getResourceType(res.getType());
return getCms().readAllPropertydefinitions(type.getResourceTypeName());
}
/**
* @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
*/
protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
// fill the parameter values in the get/set methods
fillParamValues(request);
// get the active tab from request parameter or display first tab
getActiveTab();
// set the dialog type
setParamDialogtype(DIALOG_TYPE);
boolean isPopup = Boolean.valueOf(getParamIsPopup()).booleanValue();
// set the action for the JSP switch
if (DIALOG_SHOW_DEFINE.equals(getParamAction())) {
setAction(ACTION_SHOW_DEFINE);
setParamTitle(key("title.newpropertydef") + ": " + CmsResource.getName(getParamResource()));
} else if (DIALOG_SAVE_EDIT.equals(getParamAction())) {
if (isPopup) {
setAction(ACTION_CLOSEPOPUP_SAVE);
} else {
setAction(ACTION_SAVE_EDIT);
}
} else if (DIALOG_SAVE_DEFINE.equals(getParamAction())) {
setAction(ACTION_SAVE_DEFINE);
} else if (DIALOG_CANCEL.equals(getParamAction())) {
if (isPopup) {
setAction(ACTION_CLOSEPOPUP);
} else {
setAction(ACTION_CANCEL);
}
} else {
// set the default action: show edit form
setAction(ACTION_DEFAULT);
if (!isEditable()) {
setParamTitle(key("title.property") + ": " + CmsResource.getName(getParamResource()));
} else {
setParamTitle(key("title.editpropertyinfo") + ": " + CmsResource.getName(getParamResource()));
}
// check if the user switched a tab
m_tabSwitched = false;
if (DIALOG_SWITCHTAB.equals(getParamAction())) {
m_tabSwitched = true;
}
}
}
/**
* @see org.opencms.workplace.CmsDialog#dialogButtonsHtml(java.lang.StringBuffer, int, java.lang.String)
*/
protected void dialogButtonsHtml(StringBuffer result, int button, String attribute) {
attribute = appendDelimiter(attribute);
switch (button) {
case BUTTON_DEFINE :
result.append("<input name=\"define\" type=\"button\" value=\"");
result.append(key("button.newpropertydef"));
result.append("\" class=\"dialogbutton\"");
result.append(attribute);
result.append(">\n");
break;
case BUTTON_FINISH :
result.append("<input name=\"finish\" type=\"submit\" value=\"");
result.append(key("button.endwizard"));
result.append("\" class=\"dialogbutton\"");
result.append(attribute);
result.append(">\n");
break;
default :
super.dialogButtonsHtml(result, button, attribute);
}
}
/**
* Builds a button row with an "Ok", a "Cancel" and a "Define" button.<p>
*
* @return the button row
*/
public String dialogButtonsOkCancelDefine() {
if (isEditable()) {
int okButton = BUTTON_OK;
if (getParamDialogmode() != null && getParamDialogmode().startsWith(MODE_WIZARD)) {
// in wizard mode, display finish button instead of ok button
okButton = BUTTON_FINISH;
}
return dialogButtons(new int[] {okButton, BUTTON_CANCEL, BUTTON_DEFINE}, new String[] {null, null, "onclick=\"definePropertyForm();\""});
} else {
return dialogButtons(new int[] {BUTTON_CLOSE}, new String[] {null});
}
}
/**
* Creates the HTML String for the active properties overview of the current resource.<p>
*
* @return the HTML output String for active properties of the resource
*/
public String buildActivePropertiesList() {
StringBuffer retValue = new StringBuffer(256);
Vector propertyDef = new Vector();
try {
// get all property definitions
propertyDef = getPropertyDefinitions();
} catch (CmsException e) {
// ignore this exception
}
for (int i = 0; i < propertyDef.size(); i++) {
CmsPropertydefinition curProperty = (CmsPropertydefinition)propertyDef.elementAt(i);
retValue.append(CmsEncoder.escapeXml(curProperty.getName()));
if ((i+1) < propertyDef.size()) {
retValue.append("<br>");
}
}
return retValue.toString();
}
/**
* Creates the HTML String for the edit properties form.<p>
*
* @return the HTML output String for the edit properties form
*/
public String buildEditForm() {
StringBuffer retValue = new StringBuffer(1024);
// get currently active tab
int activeTab = getActiveTab();
// initialize "disabled" attribute for input fields
String disabled = "";
if (!isEditable()) {
disabled = " disabled=\"disabled\"";
}
// get all properties for the resource
Vector propertyDef = new Vector();
try {
propertyDef = getPropertyDefinitions();
} catch (CmsException e) {
// ignore
}
// check if we are in the online project
boolean onlineProject = false;
if (getCms().getRequestContext().currentProject().getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
onlineProject = true;
}
// check for presence of property definitions, should always be true
boolean present = false;
if (propertyDef.size() > 0) {
present = true;
}
if (present) {
// there are properties defined for this resource, build the form list
retValue.append("<table border=\"0\">\n");
retValue.append("<tr>\n");
retValue.append("\t<td class=\"textbold\">"+key("input.property")+"</td>\n");
retValue.append("\t<td class=\"textbold\">"+key("label.value")+"</td>\n");
retValue.append("\t<td class=\"textbold\" style=\"white-space: nowrap;\">"+key("input.usedproperty")+"</td>\n");
retValue.append("</tr>\n");
retValue.append("<tr><td colspan=\"3\"><span style=\"height: 6px;\"></span></td></tr>\n");
// get all used properties for the resource
Map activeProperties = null;
if (!m_tabSwitched) {
try {
activeProperties = CmsPropertyAdvanced.getPropertyMap(getCms().readPropertyObjects(getParamResource(), false));
} catch (CmsException e) {
activeProperties = new HashMap();
}
}
// show all possible properties for the resource
for (int i = 0; i < propertyDef.size(); i++) {
CmsPropertydefinition currentPropertyDef = (CmsPropertydefinition)propertyDef.elementAt(i);
String propName = CmsEncoder.escapeXml(currentPropertyDef.getName());
String propValue = "";
String valueStructure = "";
String valueResource = "";
if (m_tabSwitched) {
// switched the tab, get values from hidden fields
if (activeTab == 1) {
// structure form
propValue = getJsp().getRequest().getParameter(PREFIX_STRUCTURE + propName);
valueStructure = getJsp().getRequest().getParameter(PREFIX_STRUCTURE + propName);
if (onlineProject) {
// in online project, values from diabled fields are not posted
valueResource = getJsp().getRequest().getParameter(PREFIX_RESOURCE + propName);
} else {
valueResource = getJsp().getRequest().getParameter(PREFIX_VALUE + propName);
}
} else {
// resource form
propValue = getJsp().getRequest().getParameter(PREFIX_RESOURCE + propName);
if (onlineProject) {
// in online project, values from diabled fields are not posted
valueStructure = getJsp().getRequest().getParameter(PREFIX_STRUCTURE + propName);
} else {
valueStructure = getJsp().getRequest().getParameter(PREFIX_VALUE + propName);
}
valueResource = getJsp().getRequest().getParameter(PREFIX_RESOURCE + propName);
if (valueStructure != null && !"".equals(valueStructure.trim()) && valueStructure.equals(valueResource)) {
// the resource value was shown in the input field, set structure value to empty String
valueStructure = "";
}
}
} else {
// initial call of edit form, get property values from database
CmsProperty currentProperty = (CmsProperty)activeProperties.get(propName);
if (currentProperty == null) {
currentProperty = new CmsProperty();
}
if (activeTab == 1) {
// show the structure properties
propValue = currentProperty.getStructureValue();
} else {
// show the resource properties
propValue = currentProperty.getResourceValue();
}
valueStructure = currentProperty.getStructureValue();
valueResource = currentProperty.getResourceValue();
// check values for null
if (propValue == null) {
propValue = "";
}
if (valueStructure == null) {
valueStructure = "";
}
if (valueResource == null) {
valueResource = "";
}
}
// remove unnecessary blanks from values
propValue = propValue.trim();
valueStructure = valueStructure.trim();
valueResource = valueResource.trim();
retValue.append(buildPropertyRow(propName, CmsEncoder.escapeXml(propValue), CmsEncoder.escapeXml(valueStructure), CmsEncoder.escapeXml(valueResource), disabled, activeTab));
}
retValue.append("</table>");
} else {
// there are no properties defined for this resource, show nothing
retValue.append("no properties defined!");
}
return retValue.toString();
}
/**
* Builds the html for a single property entry row.<p>
*
* The output depends on the currently active tab (shared or individual properties)
* and on the values of the current property.<p>
*
* @param propName the name of the property
* @param propValue the displayed value of the property
* @param valueStructure the structure value of the property
* @param valueResource the resource value of the property
* @param disabled contains attribute String to disable the fields
* @param activeTab the number of the currently active dialog tab
* @return the html for a single property entry row
*/
private StringBuffer buildPropertyRow(String propName, String propValue, String valueStructure, String valueResource, String disabled, int activeTab) {
StringBuffer result = new StringBuffer(256);
String shownValue = propValue;
String inputAttrs = "class=\"maxwidth\"";
if (activeTab == 1) {
// in "shared properties" form, show resource value if no structure value is set
if ("".equals(valueStructure) && !"".equals(valueResource)) {
shownValue = valueResource;
inputAttrs = "class=\"dialogmarkedfield\"";
}
}
result.append("<tr>\n");
result.append("\t<td style=\"white-space: nowrap;\">"+propName);
if (activeTab == 1 && !"".equals(valueResource)) {
// mark properties with present resource value in "shared properties" form
result.append("<sup>+</sup>");
} else {
result.append(" ");
}
result.append("</td>\n");
result.append("\t<td class=\"maxwidth\">");
result.append("<input type=\"text\" value=\"" + shownValue + "\" ");
result.append(inputAttrs + " name=\""+PREFIX_VALUE+propName+"\" id=\""+PREFIX_VALUE+propName+"\"");
result.append(" onFocus=\"deleteResEntry('" + propName + "', '"+activeTab+"');\"");
result.append(" onBlur=\"checkResEntry('" + propName + "', '"+activeTab+"');\" onKeyup=\"checkValue('"+propName+"', '"+activeTab+"');\"" + disabled + ">");
result.append("<input type=\"hidden\" name=\""+PREFIX_STRUCTURE+propName+"\" id=\""+PREFIX_STRUCTURE+propName+"\" value=\""+valueStructure+"\">");
result.append("<input type=\"hidden\" name=\""+PREFIX_RESOURCE+propName+"\" id=\""+PREFIX_RESOURCE+propName+"\" value=\""+valueResource+"\"></td>\n");
result.append("\t<td class=\"textcenter\">");
if (!"".equals(propValue)) {
// show checkbox only for non empty value
String prefix = PREFIX_RESOURCE;
if (activeTab == 1) {
prefix = PREFIX_STRUCTURE;
}
result.append("<input type=\"checkbox\" name=\""+PREFIX_USEPROPERTY+propName+"\" id=\""+PREFIX_USEPROPERTY+propName+"\" value=\"true\"" + disabled);
result.append(" checked=\"checked\" onClick=\"toggleDelete('"+propName+"', '"+prefix+"', '"+activeTab+"');\">");
} else {
result.append(" ");
}
result.append("</td>\n");
result.append("</tr>\n");
return result;
}
/**
* Returns whether the properties are editable or not depending on the lock state of the resource and the current project.<p>
*
* @return true if properties are editable, otherwise false
*/
protected boolean isEditable() {
if (m_isEditable == null) {
if (getCms().getRequestContext().currentProject().getId() == I_CmsConstants.C_PROJECT_ONLINE_ID) {
// we are in the online project, no editing allowed
m_isEditable = new Boolean(false);
} else {
// we are in an offline project, check lock state
String resourceName = getParamResource();
CmsResource file = null;
CmsLock lock = null;
try {
file = getCms().readFileHeader(resourceName);
// check if resource is a folder
if (file.isFolder()) {
resourceName += "/";
}
} catch (CmsException e) {
// ignore this exception
}
try {
// get the lock for the resource
lock = getCms().getLock(resourceName);
} catch (CmsException e) {
lock = CmsLock.getNullLock();
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error getting lock state for resource " + resourceName, e);
}
}
if (!lock.isNullLock()) {
// determine if resource is editable...
if (lock.getType() != CmsLock.C_TYPE_SHARED_EXCLUSIVE && lock.getType() != CmsLock.C_TYPE_SHARED_INHERITED
&& lock.getUserId().equals(getCms().getRequestContext().currentUser().getId())) {
// lock is not shared and belongs to the current user
if (getCms().getRequestContext().currentProject().getId() == lock.getProjectId()
|| "true".equals(getParamUsetempfileproject())) {
// resource is locked in the current project or the tempfileproject is used
m_isEditable = new Boolean(true);
return m_isEditable.booleanValue();
}
}
} else if (OpenCms.getWorkplaceManager().autoLockResources()) {
m_isEditable = new Boolean(true);
return m_isEditable.booleanValue();
}
// lock is null or belongs to other user and/or project, properties are not editable
m_isEditable = new Boolean(false);
}
}
return m_isEditable.booleanValue();
}
/**
* Used to close the current JSP dialog.<p>
*
* This method overwrites the close dialog method in the super class,
* because in case a new folder is created, after this dialog a new xml page might be created.<p>
*
* It tries to include the URI stored in the workplace settings.
* This URI is determined by the frame name, which has to be set
* in the framename parameter.<p>
*
* @throws JspException if including an element fails
*/
public void actionCloseDialog() throws JspException {
if (getAction() == ACTION_SAVE_EDIT && MODE_WIZARD_CREATEINDEX.equals(getParamDialogmode())) {
// special case: a new xmlpage resource will be created in wizard mode after closing the dialog
String newFolder = getParamResource();
if (!newFolder.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
newFolder += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// set the current explorer resource to the new created folder
getSettings().setExplorerResource(newFolder);
String newUri = OpenCms.getWorkplaceManager().getEplorerTypeSetting(CmsResourceTypeXmlPage.C_RESOURCE_TYPE_NAME).getNewResourceUri();
newUri += "?" + PARAM_DIALOGMODE + "=" + MODE_WIZARD_CREATEINDEX;
try {
// redirect to new xmlpage dialog
sendCmsRedirect(C_PATH_DIALOGS + newUri);
return;
} catch (Exception e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error redirecting to new xmlpage dialog " + C_PATH_DIALOGS + newUri);
}
}
} else if (getAction() == ACTION_SAVE_EDIT && MODE_WIZARD.equals(getParamDialogmode())) {
// set request attribute to reload the folder tree after creating a folder in wizard mode
try {
CmsResource res = getCms().readFileHeader(getParamResource());
if (res.isFolder()) {
List folderList = new ArrayList(1);
folderList.add(CmsResource.getParentFolder(getParamResource()));
getJsp().getRequest().setAttribute(C_REQUEST_ATTRIBUTE_RELOADTREE, folderList);
}
} catch (CmsException e) {
// ignore
}
} else if (MODE_WIZARD_INDEXCREATED.equals(getParamDialogmode())) {
// set request attribute to reload the folder tree after creating an xml page in a new created folder in wizard mode
getSettings().setExplorerResource(CmsResource.getParentFolder(CmsResource.getParentFolder(getParamResource())));
List folderList = new ArrayList(1);
folderList.add(CmsResource.getParentFolder(CmsResource.getParentFolder(getParamResource())));
getJsp().getRequest().setAttribute(C_REQUEST_ATTRIBUTE_RELOADTREE, folderList);
}
super.actionCloseDialog();
}
/**
* Deletes the current resource if the dialog is in wizard mode.<p>
*
* If the dialog is not in wizard mode, the resource is not deleted.<p>
*
* @throws JspException if including the error page fails
*/
public void actionDeleteResource() throws JspException {
if (getParamDialogmode() != null && getParamDialogmode().startsWith(MODE_WIZARD)) {
// only delete resource if dialog mode is a wizard mode
try {
getCms().deleteResource(getParamResource(), I_CmsConstants.C_DELETE_OPTION_PRESERVE_SIBLINGS);
} catch (CmsException e) {
// error deleting the resource, show error dialog
getJsp().getRequest().setAttribute(C_SESSION_WORKPLACE_CLASS, this);
setParamErrorstack(e.getStackTraceAsString());
setParamReasonSuggestion(getErrorSuggestionDefault());
getJsp().include(C_FILE_DIALOG_SCREEN_ERROR);
}
}
}
/**
* Performs the define property action, will be called by the JSP page.<p>
*
* @throws JspException if problems including sub-elements occur
*/
public void actionDefine() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(C_SESSION_WORKPLACE_CLASS, this);
try {
performDefineOperation();
// set the request parameters before returning to the overview
setParamAction(DIALOG_SHOW_DEFAULT);
setParamNewproperty(null);
sendCmsRedirect(getJsp().getRequestContext().getUri()+"?"+paramsAsRequest());
} catch (CmsException e) {
// error defining property, show error dialog
setParamErrorstack(e.getStackTraceAsString());
setParamMessage(key("error.message.newprop"));
setParamReasonSuggestion(getErrorSuggestionDefault());
getJsp().include(C_FILE_DIALOG_SCREEN_ERROR);
} catch (IOException exc) {
getJsp().include(C_FILE_EXPLORER_FILELIST);
}
}
/**
* Performs the definition of a new property.<p>
*
* @return true, if the new property was created, otherwise false
* @throws CmsException if creation is not successful
*/
private boolean performDefineOperation() throws CmsException {
boolean useTempfileProject = "true".equals(getParamUsetempfileproject());
try {
if (useTempfileProject) {
switchToTempProject();
}
CmsResource res = getCms().readFileHeader(getParamResource());
String newProperty = getParamNewproperty();
if (newProperty != null && !"".equals(newProperty.trim())) {
getCms().createPropertydefinition(newProperty, res.getType());
return true;
} else {
throw new CmsException("You entered an invalid property name", CmsException.C_BAD_NAME);
}
} finally {
if (useTempfileProject) {
switchToCurrentProject();
}
}
}
/**
* Performs the edit properties action, will be called by the JSP page.<p>
*
* @param request the HttpServletRequest
* @throws JspException if problems including sub-elements occur
*/
public void actionEdit(HttpServletRequest request) throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(C_SESSION_WORKPLACE_CLASS, this);
try {
if (isEditable()) {
performEditOperation(request);
}
} catch (CmsException e) {
// error editing property, show error dialog
setParamErrorstack(e.getStackTraceAsString());
setParamReasonSuggestion(getErrorSuggestionDefault());
getJsp().include(C_FILE_DIALOG_SCREEN_ERROR);
}
}
/**
* Performs the editing of the resources properties.<p>
*
* @param request the HttpServletRequest
* @return true, if the properties were successfully changed, otherwise false
* @throws CmsException if editing is not successful
*/
private boolean performEditOperation(HttpServletRequest request) throws CmsException {
Vector propertyDef = getPropertyDefinitions();
boolean useTempfileProject = "true".equals(getParamUsetempfileproject());
try {
if (useTempfileProject) {
switchToTempProject();
}
Map activeProperties = getPropertyMap(getCms().readPropertyObjects(getParamResource(), false));
int activeTab = getActiveTab();
List propertiesToWrite = new ArrayList();
// check all property definitions of the resource for new values
for (int i=0; i<propertyDef.size(); i++) {
CmsPropertydefinition curPropDef = (CmsPropertydefinition)propertyDef.elementAt(i);
String propName = CmsEncoder.escapeXml(curPropDef.getName());
String valueStructure = "";
String valueResource = "";
if (activeTab == 1) {
// get parameters from the structure tab
valueStructure = request.getParameter(PREFIX_VALUE + propName);
valueResource = request.getParameter(PREFIX_RESOURCE + propName);
if (valueStructure != null && !"".equals(valueStructure.trim()) && valueStructure.equals(valueResource)) {
// the resource value was shown/entered in input field, set structure value to empty String
valueStructure = "";
}
} else {
// get parameters from the resource tab
valueStructure = request.getParameter(PREFIX_STRUCTURE + propName);
valueResource = request.getParameter(PREFIX_VALUE + propName);
}
// check values for blanks and null
if (valueStructure != null) {
valueStructure = valueStructure.trim();
} else {
valueStructure = "";
}
if (valueResource != null) {
valueResource = valueResource.trim();
} else {
valueResource = "";
}
// create new CmsProperty object to store
CmsProperty newProperty = new CmsProperty();
newProperty.setKey(curPropDef.getName());
newProperty.setStructureValue(valueStructure);
newProperty.setResourceValue(valueResource);
// get the old property values
CmsProperty oldProperty = (CmsProperty)activeProperties.get(curPropDef.getName());
if (oldProperty == null) {
// property was not set, create new empty property object
oldProperty = new CmsProperty();
oldProperty.setKey(curPropDef.getName());
}
if (oldProperty.getStructureValue() == null) {
oldProperty.setStructureValue("");
}
if (oldProperty.getResourceValue() == null) {
oldProperty.setResourceValue("");
}
// check if saving the properties is necessary
if (!newProperty.equals(oldProperty)) {
// add property to list only if property values have changed
propertiesToWrite.add(newProperty);
}
}
if (propertiesToWrite.size() > 0) {
// lock resource if autolock is enabled
checkLock(getParamResource());
//write the new property values
getCms().writePropertyObjects(getParamResource(), propertiesToWrite);
}
} finally {
if (useTempfileProject) {
switchToCurrentProject();
}
}
return true;
}
/**
* Transforms a list of CmsProperty objects with structure and resource values into a map with
* CmsPropery object values keyed by property keys.<p>
*
* @param list a list of CmsProperty objects
* @return a map with CmsPropery object values keyed by property keys
*/
public static Map getPropertyMap(List list) {
Map result = null;
String key = null;
CmsProperty property = null;
if (list == null || list.size() == 0) {
return Collections.EMPTY_MAP;
}
result = (Map)new HashMap();
// choose the fastest method to iterate the list
if (list instanceof RandomAccess) {
for (int i = 0, n = list.size(); i < n; i++) {
property = (CmsProperty)list.get(i);
key = property.getKey();
result.put(key, property);
}
} else {
Iterator i = list.iterator();
while (i.hasNext()) {
property = (CmsProperty)i.next();
key = property.getKey();
result.put(key, property);
}
}
return result;
}
} |
package org.pentaho.ui.xul.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulContainer;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.dom.DocumentFactory;
import org.pentaho.ui.xul.dom.dom4j.DocumentDom4J;
import org.pentaho.ui.xul.dom.dom4j.ElementDom4J;
import org.pentaho.ui.xul.util.ResourceBundleTranslator;
public abstract class AbstractXulLoader implements XulLoader {
protected XulParser parser;
protected String rootDir = "/";
protected Object outerContext = null;
private static final Log logger = LogFactory.getLog(AbstractXulLoader.class);
private ResourceBundle mainBundle = null;
public AbstractXulLoader() throws XulException {
DocumentFactory.registerDOMClass(DocumentDom4J.class);
DocumentFactory.registerElementClass(ElementDom4J.class);
try {
parser = new XulParser();
} catch (Exception e) {
throw new XulException("Error getting XulParser Instance, probably a DOM Factory problem: " + e.getMessage(), e);
}
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.XulLoader#loadXul(org.w3c.dom.Document)
*/
public XulDomContainer loadXul(Document xulDocument) throws IllegalArgumentException, XulException {
try {
xulDocument = preProcess(xulDocument);
String processedDoc = performIncludeTranslations(xulDocument.asXML());
String localOutput = (mainBundle != null) ? ResourceBundleTranslator.translate(processedDoc, mainBundle)
: processedDoc;
SAXReader rdr = new SAXReader();
//localOutput = localOutput.replace("UTF-8", "ISO-8859-1");
// System.out.println(localOutput);
final Document doc = rdr.read(new StringReader(localOutput));
// System.out.println(doc.asXML());
XulDomContainer container = new XulWindowContainer(this);
container.setOuterContext(outerContext);
parser.setContainer(container);
parser.parseDocument(doc.getRootElement());
return container;
} catch (Exception e) {
throw new XulException(e);
}
}
public void setRootDir(String loc) {
if(!rootDir.equals("/")){ //lets only set this once
return;
}
if (loc.lastIndexOf("/") > 0 && loc.indexOf(".xul") > -1) { //exists and not first char
rootDir = loc.substring(0, loc.lastIndexOf("/") + 1);
} else {
rootDir = loc;
if (!(loc.lastIndexOf('/') == loc.length())) { //no trailing slash, add it
rootDir = rootDir + "/";
}
}
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.XulLoader#loadXulFragment(org.dom4j.Document)
*/
public XulDomContainer loadXulFragment(Document xulDocument) throws IllegalArgumentException, XulException {
XulDomContainer container = new XulFragmentContainer(this);
container.setOuterContext(outerContext);
parser.reset();
parser.setContainer(container);
parser.parseDocument(xulDocument.getRootElement());
return container;
}
public XulComponent createElement(String elementName) throws XulException {
return parser.getElement(elementName);
}
public XulDomContainer loadXul(String resource) throws IllegalArgumentException, XulException {
InputStream in = getClass().getClassLoader().getResourceAsStream(resource);
Document doc = getDocFromClasspath(resource);
setRootDir(resource);
ResourceBundle res;
try {
res = ResourceBundle.getBundle(resource.replace(".xul", ""));
} catch (MissingResourceException e) {
return loadXul(doc);
}
return loadXul(resource, res);
}
public XulDomContainer loadXul(String resource, ResourceBundle bundle) throws XulException {
final Document doc = getDocFromClasspath(resource);
setRootDir(resource);
mainBundle = bundle;
return this.loadXul(doc);
}
public XulDomContainer loadXulFragment(String resource) throws IllegalArgumentException, XulException {
Document doc = getDocFromClasspath(resource);
setRootDir(resource);
ResourceBundle res;
try {
res = ResourceBundle.getBundle(resource.replace(".xul", ""));
} catch (MissingResourceException e) {
return loadXulFragment(doc);
}
return loadXulFragment(resource, res);
}
public XulDomContainer loadXulFragment(String resource, ResourceBundle bundle) throws XulException {
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(resource);
String localOutput = ResourceBundleTranslator.translate(in, bundle);
SAXReader rdr = new SAXReader();
final Document doc = rdr.read(new StringReader(localOutput));
setRootDir(resource);
return this.loadXulFragment(doc);
} catch (DocumentException e) {
throw new XulException("Error parsing Xul Document", e);
} catch (IOException e) {
throw new XulException("Error loading Xul Document into Freemarker", e);
}
}
private List<String> includedSources = new ArrayList<String>();
private List<String> resourceBundles = new ArrayList<String>();
public String performIncludeTranslations(String input) throws XulException {
String output = input;
for (String includeSrc : includedSources) {
try {
ResourceBundle res = ResourceBundle.getBundle(includeSrc.replace(".xul", ""));
output = ResourceBundleTranslator.translate(output, res);
} catch (MissingResourceException e) {
continue;
} catch (IOException e) {
throw new XulException(e);
}
}
for (String resource : resourceBundles) {
logger.info("Processing Resource Bundle: " + resource);
try {
ResourceBundle res = ResourceBundle.getBundle(resource);
if (res == null) {
continue;
}
output = ResourceBundleTranslator.translate(output, res);
} catch (MissingResourceException e) {
continue;
} catch (IOException e) {
throw new XulException(e);
}
}
return output;
}
public void register(String tagName, String className) {
parser.registerHandler(tagName, className);
}
public String getRootDir() {
return this.rootDir;
}
public Document preProcess(Document srcDoc) throws XulException {
XPath xpath = new DefaultXPath("//pen:include");
HashMap uris = new HashMap();
uris.put("xul", "http:
uris.put("pen", "http:
xpath.setNamespaceURIs(uris);
List<Element> eles = xpath.selectNodes(srcDoc);
for (Element ele : eles) {
String src = "";
src = this.getRootDir() + ele.attributeValue("src");
String resourceBundle = ele.attributeValue("resource");
if (resourceBundle != null) {
resourceBundles.add(resourceBundle);
}
InputStream in = getClass().getClassLoader().getResourceAsStream(src);
if (in != null) {
logger.info("Adding include src: " + src);
includedSources.add(src);
} else {
//try fully qualified name
src = ele.attributeValue("src");
in = getClass().getClassLoader().getResourceAsStream(src);
if (in != null) {
includedSources.add(src);
logger.info("Adding include src: " + src);
} else {
logger.error("Could not resolve include: " + src);
}
}
final Document doc = getDocFromInputStream(in);
Element root = doc.getRootElement();
String ignoreRoot = ele.attributeValue("ignoreroot");
if (root.getName().equals("overlay")) {
processOverlay(root, ele.getDocument().getRootElement());
} else if (ignoreRoot == null || ignoreRoot.equalsIgnoreCase("false")) {
logger.info("Including entire file: " + src);
List contentOfParent = ele.getParent().content();
int index = contentOfParent.indexOf(ele);
contentOfParent.set(index, root);
//process any overlay children
List<Element> overlays = ele.elements();
for (Element overlay : overlays) {
logger.info("Processing overlay within include");
this.processOverlay(overlay.attributeValue("src"), srcDoc);
}
} else {
logger.info("Including children: " + src);
List contentOfParent = ele.getParent().content();
int index = contentOfParent.indexOf(ele);
contentOfParent.remove(index);
List children = root.elements();
for (int i = children.size() - 1; i >= 0; i
contentOfParent.add(index, children.get(i));
}
//process any overlay children
List<Element> overlays = ele.elements();
for (Element overlay : overlays) {
logger.info("Processing overlay within include");
this.processOverlay(overlay.attributeValue("src"), srcDoc);
}
}
}
return srcDoc;
}
private Document getDocFromInputStream(InputStream in) throws XulException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buf.append(line);
}
String upperedIdDoc = this.upperCaseIDAttrs(buf.toString());
SAXReader rdr = new SAXReader();
return rdr.read(new StringReader(upperedIdDoc));
} catch (Exception e) {
throw new XulException(e);
}
}
private Document getDocFromClasspath(String src) throws XulException {
InputStream in = getClass().getClassLoader().getResourceAsStream(this.getRootDir() + src);
if (in != null) {
return getDocFromInputStream(in);
} else {
//try fully qualified name
in = getClass().getClassLoader().getResourceAsStream(src);
if (in != null) {
return getDocFromInputStream(in);
} else {
throw new XulException("Can no locate Xul document [" + src + "]");
}
}
}
private void processOverlay(String overlaySrc, Document doc) {
try {
final Document overlayDoc = getDocFromClasspath(overlaySrc);
processOverlay(overlayDoc.getRootElement(), doc.getRootElement());
} catch (Exception e) {
logger.error("Could not load include overlay document: " + overlaySrc, e);
}
}
private void processOverlay(Element overlayEle, Element srcEle) {
for (Object child : overlayEle.elements()) {
Element overlay = (Element) child;
String overlayId = overlay.attributeValue("ID");
logger.info("Processing overlay\nID: " + overlayId);
Element sourceElement = srcEle.getDocument().elementByID(overlayId);
if (sourceElement == null) {
logger.error("Could not find corresponding element in src doc with id: " + overlayId);
continue;
}
logger.info("Found match in source doc:");
String removeElement = overlay.attributeValue("removeelement");
if (removeElement != null && removeElement.equalsIgnoreCase("true")) {
sourceElement.getParent().remove(sourceElement);
} else {
List attribs = overlay.attributes();
//merge in attributes
for(Object o : attribs){
Attribute atr = (Attribute) o;
sourceElement.addAttribute(atr.getName(), atr.getValue());
}
Document targetDocument = srcEle.getDocument();
//lets start out by just including everything
for (Object overlayChild : overlay.elements()) {
Element pluckedElement = (Element) overlay.content().remove(overlay.content().indexOf(overlayChild));
String insertBefore = pluckedElement.attributeValue("insertbefore");
String insertAfter = pluckedElement.attributeValue("insertafter");
String position = pluckedElement.attributeValue("position");
//determine position to place it
int positionToInsert = -1;
if(insertBefore != null){
Element insertBeforeTarget = sourceElement.elementByID(insertBefore);
positionToInsert = sourceElement.elements().indexOf(insertBeforeTarget);
} else if(insertAfter != null){
Element insertAfterTarget = sourceElement.elementByID(insertAfter);
positionToInsert = sourceElement.elements().indexOf(insertAfterTarget);
if(positionToInsert != -1){
positionToInsert++; //we want to be after that point;
}
} else if(position != null){
int pos = Integer.parseInt(position);
positionToInsert = (pos <= sourceElement.elements().size()) ? pos : -1;
}
if(positionToInsert == -1){
//default to last
positionToInsert = sourceElement.elements().size();
}
if(positionToInsert > sourceElement.elements().size()){
sourceElement.elements().add(pluckedElement);
} else {
sourceElement.elements().add(positionToInsert, pluckedElement);
}
logger.info("processed overlay child: " + ((Element) overlayChild).getName() + " : "
+ pluckedElement.getName());
}
}
}
}
private InputStream getInputStreamForSrc(String src){
InputStream in = getClass().getClassLoader().getResourceAsStream(this.getRootDir() + src);
if (in == null){
//try fully qualified name
in = getClass().getClassLoader().getResourceAsStream(src);
if (in == null) {
logger.error("Cant find overlay source");
}
}
return in;
}
public void processOverlay(String overlaySrc, org.pentaho.ui.xul.dom.Document targetDocument,
XulDomContainer container) throws XulException {
InputStream in = getInputStreamForSrc(overlaySrc);
Document doc = null;
ResourceBundle res = null;
try {
res = ResourceBundle.getBundle(overlaySrc.replace(".xul", ""));
if(res == null){
res = ResourceBundle.getBundle((this.getRootDir() + overlaySrc).replace(".xul", ""));
if(res == null){
logger.error("could not find resource bundle, defaulting to main");
res = mainBundle;
}
}
} catch (MissingResourceException e) {
logger.warn("no default resource bundle available: "+overlaySrc);
}
String runningTranslatedOutput = getDocFromInputStream(in).asXML(); //TODO IOUtils this
if(res != null){
try{
runningTranslatedOutput = ResourceBundleTranslator.translate(runningTranslatedOutput, res);
} catch(IOException e){
logger.error("Error loading resource bundle for overlay: "+overlaySrc, e);
}
}
//check for top-level message bundle and apply it
if(this.mainBundle != null){
try{
runningTranslatedOutput = ResourceBundleTranslator.translate(runningTranslatedOutput, this.mainBundle);
try{
SAXReader rdr = new SAXReader();
String upperedIdDoc = this.upperCaseIDAttrs(runningTranslatedOutput.toString());
doc = rdr.read(new StringReader(upperedIdDoc));
} catch(DocumentException e){
logger.error("Error loading XML while applying top level message bundle to overlay file:", e);
}
} catch(IOException e){
logger.error("Error loading Resource Bundle File to apply to overlay: ",e);
}
} else {
try{
SAXReader rdr = new SAXReader();
String upperedIdDoc = this.upperCaseIDAttrs(runningTranslatedOutput.toString());
doc = rdr.read(new StringReader(upperedIdDoc));
} catch(DocumentException e){
logger.error("Error loading XML while applying top level message bundle to overlay file:", e);
}
}
Element overlayRoot = doc.getRootElement();
for (Object child : overlayRoot.elements()) {
Element overlay = (Element) child;
String overlayId = overlay.attributeValue("ID");
org.pentaho.ui.xul.dom.Element sourceElement = targetDocument.getElementById(overlayId);
if (sourceElement == null) {
logger.warn("Cannot overlay element with id [" + overlayId + "] as it does not exist in the target document.");
continue;
}
for (Object childToParse : overlay.elements()) {
Element childElement = (Element) childToParse;
logger.info("Processing overlay on element with id: " + overlayId);
parser.reset();
parser.setContainer(container);
XulComponent c = parser.parse(childElement, (XulContainer) sourceElement);
String insertBefore = childElement.attributeValue("insertbefore");
String insertAfter = childElement.attributeValue("insertafter");
String position = childElement.attributeValue("position");
XulContainer sourceContainer = ((XulContainer) sourceElement);
//determine position to place it
int positionToInsert = -1;
if(insertBefore != null){
org.pentaho.ui.xul.dom.Element insertBeforeTarget = targetDocument.getElementById(insertBefore);
positionToInsert = sourceContainer.getChildNodes().indexOf(insertBeforeTarget);
} else if(insertAfter != null){
org.pentaho.ui.xul.dom.Element insertAfterTarget = targetDocument.getElementById(insertAfter);
positionToInsert = sourceContainer.getChildNodes().indexOf(insertAfterTarget);
} else if(position != null){
int pos = Integer.parseInt(position);
positionToInsert = (pos <= sourceContainer.getChildNodes().size()) ? pos : -1;
}
if(positionToInsert == -1){
//default to last
positionToInsert = sourceContainer.getChildNodes().size();
}
sourceContainer.addComponentAt(c, positionToInsert);
sourceContainer.addChildAt(c, positionToInsert);
logger.info("added child: " + c);
}
List attribs = overlay.attributes();
//merge in attributes
for(Object o : attribs){
Attribute atr = (Attribute) o;
try{
BeanUtils.setProperty(sourceElement, atr.getName(), atr.getValue());
} catch(InvocationTargetException e){
logger.error(e);
} catch(IllegalAccessException e){
logger.error(e);
}
}
}
}
public void removeOverlay(String overlaySrc, org.pentaho.ui.xul.dom.Document targetDocument, XulDomContainer container)
throws XulException {
final Document doc = getDocFromClasspath(overlaySrc);
Element overlayRoot = doc.getRootElement();
for (Object child : overlayRoot.elements()) {
Element overlay = (Element) child;
for (Object childToParse : overlay.elements()) {
String childId = ((Element) childToParse).attributeValue("ID");
org.pentaho.ui.xul.dom.Element prevOverlayedEle = targetDocument.getElementById(childId);
if (prevOverlayedEle == null) {
logger.info("Source Element from target document is null: " + childId);
continue;
}
prevOverlayedEle.getParent().removeChild(prevOverlayedEle);
}
}
}
private String upperCaseIDAttrs(String src) {
String result = src.replace(" id=", " ID=");
return result;
}
public void setOuterContext(Object context) {
outerContext = context;
}
public boolean isRegistered(String elementName) {
return this.parser.handlers.containsKey(elementName);
}
} |
package org.petschko.rpgmakermv.decrypt;
import com.sun.istack.internal.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.petschko.lib.File;
import java.nio.file.FileSystemException;
import java.util.ArrayList;
class Decrypter {
static final String defaultSignature = "5250474d56000000";
static final String defaultVersion = "000301";
static final String defaultRemain = "0000000000";
private String decryptCode = null;
private String[] realDecryptCode = null;
private int headerLen = 16;
private String signature = "5250474d56000000";
private String version = "000301";
private String remain = "0000000000";
private boolean ignoreFakeHeader = false;
/**
* Creates a new Decrypter instance
*/
Decrypter() {
}
/**
* Creates a new Decrypter instance with a Decryption Code
*
* @param decryptCode - Decryption-Code
*/
Decrypter(@NotNull String decryptCode) {
this.setDecryptCode(decryptCode);
}
/**
* Return the Decrypt-Code
*
* @return DecryptCode or null if not set
*/
String getDecryptCode() {
return decryptCode;
}
/**
* Sets the Decrypt-Code
*
* @param decryptCode - Decrypt-Code
*/
void setDecryptCode(@NotNull String decryptCode) {
this.decryptCode = decryptCode;
}
/**
* Returns the Real Decrypt-Code as Array
*
* @return Real Decrypt-Code as Array
*/
private String[] getRealDecryptCode() {
if(this.realDecryptCode == null)
this.calcRealDecryptionCode();
return realDecryptCode;
}
/**
* Sets the Real Decrypt-Code as Array
*
* @param realDecryptCode - Real Decrypt-Code as Array
*/
private void setRealDecryptCode(@NotNull String[] realDecryptCode) {
this.realDecryptCode = realDecryptCode;
}
/**
* Returns the Byte-Length of the File-Header
*
* @return - File-Header Length in Bytes
*/
int getHeaderLen() {
return headerLen;
}
/**
* Sets the File-Header Length in Bytes
*
* @param headerLen - File-Header Length in Bytes
*/
void setHeaderLen(@NotNull int headerLen) {
this.headerLen = headerLen;
}
/**
* Returns the Signature
*
* @return - Signature
*/
String getSignature() {
return signature;
}
/**
* Sets the Signature
*
* @param signature - Signature
*/
void setSignature(@NotNull String signature) {
this.signature = signature;
}
/**
* Returns the Version
*
* @return - Version
*/
String getVersion() {
return version;
}
/**
* Sets the Version
*
* @param version - Version
*/
void setVersion(@NotNull String version) {
this.version = version;
}
/**
* Returns Remain
*
* @return - Remain
*/
String getRemain() {
return remain;
}
/**
* Sets Remain
*
* @param remain - Remain
*/
void setRemain(@NotNull String remain) {
this.remain = remain;
}
/**
* Returns if Fake-Header can be ignored
*
* @return - true if Fake-Header should be ignored else false
*/
boolean isIgnoreFakeHeader() {
return ignoreFakeHeader;
}
/**
* Set if Fake-Header should be ignored
*
* @param ignoreFakeHeader - true if Fake-Header can be ignored else false
*/
void setIgnoreFakeHeader(boolean ignoreFakeHeader) {
this.ignoreFakeHeader = ignoreFakeHeader;
}
/**
* Reads the Decrypt-Code into an Array with 2 Paired Strings
*
* @throws NullPointerException - Decrypt-Code is null
*/
private void calcRealDecryptionCode() throws NullPointerException {
if(this.getDecryptCode() == null)
throw new NullPointerException("DecryptCode");
String[] decryptArray = this.getDecryptCode().split("(?<=\\G.{2})");
ArrayList<String> verifiedDecryptArray = new ArrayList<>();
// Remove empty parts
for(String aDecryptArray : decryptArray) {
if(! aDecryptArray.equals(""))
verifiedDecryptArray.add(aDecryptArray);
}
this.setRealDecryptCode(verifiedDecryptArray.toArray(new String[verifiedDecryptArray.size()]));
}
/**
* Decrypts the File (Header) and removes the Encryption-Header
*
* @param file - Encrypted File
* @throws Exception - Various Exceptions
*/
void decryptFile(File file) throws Exception {
try {
if(! file.load())
throw new FileSystemException(file.getFilePath(), "", "Can't load File-Content...");
} catch(Exception e) {
e.printStackTrace();
return;
}
// Check if all required external stuff is here
if(this.getDecryptCode() == null)
throw new NullPointerException("Decryption-Code is not set!");
if(file.getContent() == null)
throw new NullPointerException("File-Content is not loaded!");
if(file.getContent().length < (this.getHeaderLen() * 2))
throw new Exception("File is to short (<" + (this.getHeaderLen() * 2) + " Bytes)");
// Get Content
byte[] content = file.getContent();
// Check Header
if(! this.isIgnoreFakeHeader())
if(! this.checkFakeHeader(content))
throw new Exception("Header is Invalid!");
// Remove Fake-Header from rest
content = Decrypter.getByteArray(content, this.getHeaderLen());
// Decrypt Real-Header & First part of the Content
if(content.length > 0) {
for(int i = 0; i < this.getHeaderLen(); i++) {
content[i] = (byte) (content[i] ^ (byte) Integer.parseInt(this.getRealDecryptCode()[i], 16));
}
}
// Update File-Content
file.setContent(content);
file.changeExtension(Decrypter.realExtByFakeExt(file.getExtension()));
}
/**
* Check if the Fake-Header is valid
*
* @param content - File-Content as Byte-Array
* @return - true if the header is valid else false
*/
boolean checkFakeHeader(byte[] content) {
byte[] header = Decrypter.getByteArray(content, 0, this.getHeaderLen());
byte[] refBytes = new byte[this.getHeaderLen()];
String refStr = this.getSignature() + this.getVersion() + this.getRemain();
// Generate reference bytes
for(int i = 0; i < this.getHeaderLen(); i++) {
int subStrStart = i * 2;
refBytes[i] = (byte) Integer.parseInt(refStr.substring(subStrStart, subStrStart + 2), 16);
}
// Verify header (Check if its an encrypted file)
for(int i = 0; i < this.getHeaderLen(); i++) {
if(refBytes[i] != header[i])
return false;
}
return true;
}
/**
* Detect the Decryption-Code from the given File
*
* @param file - JSON-File with Decryption-Key
* @param keyName - Key-Name of the Decryption-Key
* @throws JSONException - Key not Found Exception
*/
void detectEncryptionKey(File file, String keyName) throws JSONException {
try {
if(! file.load())
throw new FileSystemException(file.getFilePath(), "", "Can't load File-Content...");
} catch(Exception e) {
e.printStackTrace();
return;
}
JSONObject jsonObj;
String key;
try {
String fileContentAsString = new String(file.getContent(), "UTF-8");
jsonObj = new JSONObject(fileContentAsString);
} catch(Exception e) {
e.printStackTrace();
return;
}
key = jsonObj.getString(keyName);
this.setDecryptCode(key);
}
/**
* Get a new Byte-Array with given start pos and length
*
* @param byteArray - Byte-Array where to extract a new Byte-Array
* @param startPos - Start-Position on the Byte-Array (0 is first pos)
* @param length - Length of the new Array (Values below 0 means to Old-Array end)
* @return - New Byte-Array
*/
private static byte[] getByteArray(byte[] byteArray, int startPos, int length) {
// Don't allow start-values below 0
if(startPos < 0)
startPos = 0;
// Check if length is to below 0 (to end of array)
if(length < 0)
length = byteArray.length - startPos;
byte[] newByteArray = new byte[length];
int n = 0;
for(int i = startPos; i < (startPos + length); i++) {
// Check if byte array is on the last pos and return shorter byte array if
if(byteArray.length <= i)
return getByteArray(newByteArray, 0, n);
newByteArray[n] = byteArray[i];
n++;
}
return newByteArray;
}
/**
* Get a new Byte-Array from the given start pos to the end of the array
*
* @param byteArray - Byte-Array where to extract a new Byte-Array
* @param startPos - Start-Position on the Byte-Array (0 is first pos)
* @return - New Byte-Array
*/
private static byte[] getByteArray(byte[] byteArray, int startPos) {
return getByteArray(byteArray, startPos, -1);
}
/**
* Returns the real Extension of the current fake extension
*
* @param fakeExt - Fake Extension where you want to get the real Extension
* @return - Real File-Extension
*/
private static String realExtByFakeExt(@NotNull String fakeExt) {
switch(fakeExt.toLowerCase()) {
case "rpgmvp":
return "png";
case "rpgmvm":
return "m4a";
case "rpgmvo":
return "ogg";
default:
return "unknown";
}
}
} |
package org.seqcode.deepseq.events;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.seqcode.data.motifdb.WeightMatrix;
import org.seqcode.deepseq.experiments.ControlledExperiment;
import org.seqcode.deepseq.experiments.ExperimentCondition;
import org.seqcode.deepseq.experiments.ExperimentManager;
/**
* BindingManager stores lists of binding events and motifs associated with experiment conditions,
* and binding models associated with replicates.
* These data structures used to be under the relevant experiment components, but we moved them here to
* allow experiment loading to be independent.
*
* @author mahony
*
*/
public class BindingManager {
protected EventsConfig config;
protected ExperimentManager manager;
protected List<BindingEvent> events;
protected Map<ExperimentCondition, List <BindingEvent>> conditionEvents;
protected Map<ExperimentCondition, WeightMatrix> motifs;
protected Map<ExperimentCondition, WeightMatrix> freqMatrices;
protected Map<ExperimentCondition, Integer> motifOffsets;
protected Map<ControlledExperiment, BindingModel> models;
protected Map<ExperimentCondition, Integer> maxInfluenceRange;
public BindingManager(EventsConfig con, ExperimentManager exptman){
config = con;
manager = exptman;
events = new ArrayList<BindingEvent>();
conditionEvents = new HashMap<ExperimentCondition, List <BindingEvent>>();
motifs = new HashMap<ExperimentCondition, WeightMatrix>();
freqMatrices = new HashMap<ExperimentCondition, WeightMatrix>();
motifOffsets = new HashMap<ExperimentCondition, Integer>();
models = new HashMap<ControlledExperiment, BindingModel>();
maxInfluenceRange = new HashMap<ExperimentCondition, Integer>();
for(ExperimentCondition cond : manager.getConditions()){
conditionEvents.put(cond, new ArrayList<BindingEvent>());
motifOffsets.put(cond,0);
maxInfluenceRange.put(cond,0);
}
}
public List<BindingEvent> getBindingEvents(){return events;}
public List<BindingEvent> getConditionBindingEvents(ExperimentCondition ec){return conditionEvents.get(ec);}
public WeightMatrix getMotif(ExperimentCondition ec){return motifs.get(ec);}
public WeightMatrix getFreqMatrix(ExperimentCondition ec){return freqMatrices.get(ec);}
public Integer getMotifOffset(ExperimentCondition ec){return motifOffsets.get(ec);}
public BindingModel getBindingModel(ControlledExperiment ce){return models.get(ce);}
public Integer getMaxInfluenceRange(ExperimentCondition ec){return maxInfluenceRange.get(ec);}
public void setBindingEvents(List<BindingEvent> e){events =e;}
public void setConditionBindingEvents(ExperimentCondition ec, List<BindingEvent> e){conditionEvents.put(ec, e);}
public void setMotif(ExperimentCondition ec, WeightMatrix m){motifs.put(ec, m);}
public void setFreqMatrix(ExperimentCondition ec, WeightMatrix m){freqMatrices.put(ec, m);}
public void setMotifOffset(ExperimentCondition ec, Integer i){motifOffsets.put(ec, i);}
public void setBindingModel(ControlledExperiment ce, BindingModel mod){models.put(ce, mod);}
public void updateMaxInfluenceRange(ExperimentCondition ec){
int max=0;
for(ControlledExperiment rep : ec.getReplicates()){
if(getBindingModel(rep).getInfluenceRange()>max)
max=getBindingModel(rep).getInfluenceRange();
}maxInfluenceRange.put(ec, max);
}
/**
* Print the events
* @param outRoot
*/
public void printConditionEvents(ExperimentCondition ec, String outRoot){
try{
String outName = outRoot+"."+ec.getName()+".events";
if(config.getEventsFileTXTExtension())
outName = outName+".txt";
FileWriter fw = new FileWriter(outName);
fw.write(BindingEvent.fullHeadString()+"\n");
for(BindingEvent e : getConditionBindingEvents(ec)){
fw.write(e.toString()+"\n");
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Print the replicate counts at events
* @param outRoot
*/
public void printReplicateCounts(ExperimentCondition ec, String outRoot){
try{
String outName = outRoot+"."+ec.getName()+".repcounts";
FileWriter fw = new FileWriter(outName);
fw.write(BindingEvent.repCountHeadString()+"\n");
for(BindingEvent e : getConditionBindingEvents(ec)){
fw.write(e.getRepCountString()+"\n");
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* For each controlled experiment, simply calculate the proportion of reads in the provided
* list of binding events to everything else.
* @param regs
*/
public void estimateSignalVsNoiseFractions(List<BindingEvent> signalEvents){
for(ExperimentCondition c : manager.getConditions()){
for(ControlledExperiment r : c.getReplicates()){
double repSigCount =0, repNoiseCount=0;
for(BindingEvent event : signalEvents){
if(event.isFoundInCondition(c))
repSigCount += event.getRepSigHits(r);
}
repNoiseCount = r.getSignal().getHitCount() - repSigCount;
r.setSignalVsNoiseFraction(repSigCount/r.getSignal().getHitCount());
System.err.println(r.getName()+"\t"+r.getIndex()+"\tsignal-noise ratio:\t"+String.format("%.4f",r.getSignalVsNoiseFraction()));
}
}
}
/**
* Count the binding events present in a given condition
* @param cond
* @return
*/
public int countEventsInCondition(ExperimentCondition cond, double qMinThres){
int count=0;
for(BindingEvent e : events){
if(e.isFoundInCondition(cond) && e.getCondSigVCtrlP(cond) <=qMinThres)
count++;
}
return count;
}
/**
* Count the differential binding events present in a given pair of conditions
* @param cond
* @return
*/
public int countDiffEventsBetweenConditions(ExperimentCondition cond, ExperimentCondition othercond, double qMinThres, double diffPMinThres){
int count=0;
for(BindingEvent e : events){
if(e.isFoundInCondition(cond) && e.getCondSigVCtrlP(cond) <=qMinThres)
if(e.getInterCondP(cond, othercond)<=diffPMinThres && e.getInterCondFold(cond, othercond)>0)
count++;
}
return count;
}
/**
* Print all binding events to files
*/
public void writeBindingEventFiles(String filePrefix, double qMinThres, boolean runDiffTests, double diffPMinThres){
if(events.size()>0){
try {
//Full output table (all non-zero components)
String filename = filePrefix+".all.events.table";
if(config.getEventsFileTXTExtension())
filename = filename+".txt";
FileWriter fout = new FileWriter(filename);
fout.write(BindingEvent.fullHeadString()+"\n");
for(BindingEvent e : events)
fout.write(e.toString()+"\n");
fout.close();
//Per-condition event files
for(ExperimentCondition cond : manager.getConditions()){
//Sort on the current condition
BindingEvent.setSortingCond(cond);
Collections.sort(events, new Comparator<BindingEvent>(){
public int compare(BindingEvent o1, BindingEvent o2) {return o1.compareBySigCtrlPvalue(o2);}
});
//Print events
String condName = cond.getName();
condName = condName.replaceAll("/", "-");
filename = filePrefix+"_"+condName+".events";
if(config.getEventsFileTXTExtension())
filename = filename+".txt";
fout = new FileWriter(filename);
fout.write(BindingEvent.conditionHeadString(cond)+"\n");
for(BindingEvent e : events){
double Q = e.getCondSigVCtrlP(cond);
//Because of the ML step and component sharing, I think that an event could be assigned a significant number of reads without being "present" in the condition's EM model.
if(e.isFoundInCondition(cond) && Q <=qMinThres)
fout.write(e.getConditionString(cond)+"\n");
}
fout.close();
}
//Differential event files
if(manager.getNumConditions()>1 && runDiffTests){
for(ExperimentCondition cond : manager.getConditions()){
//Sort on the current condition
BindingEvent.setSortingCond(cond);
Collections.sort(events, new Comparator<BindingEvent>(){
public int compare(BindingEvent o1, BindingEvent o2) {return o1.compareBySigCtrlPvalue(o2);}
});
for(ExperimentCondition othercond : manager.getConditions()){
if(!cond.equals(othercond)){
//Print diff events
String condName = cond.getName();
String othercondName = othercond.getName();
condName = condName.replaceAll("/", "-");
filename = filePrefix+"_"+condName+"_gt_"+othercondName+".diff.events";
if(config.getEventsFileTXTExtension())
filename = filename+".txt";
fout = new FileWriter(filename);
fout.write(BindingEvent.conditionShortHeadString(cond)+"\n");
for(BindingEvent e : events){
double Q = e.getCondSigVCtrlP(cond);
//Because of the ML step and component sharing, I think that an event could be assigned a significant number of reads without being "present" in the condition's EM model.
if(e.isFoundInCondition(cond) && Q <=qMinThres){
if(e.getInterCondP(cond, othercond)<=diffPMinThres && e.getInterCondFold(cond, othercond)>0){
fout.write(e.getConditionString(cond)+"\n");
}
}
}
fout.close();
}
}
}
}
//If necessary, print per-replicate event base composition files
if(config.getCalcEventBaseCompositions()){
for(ExperimentCondition cond : manager.getConditions()){
for(ControlledExperiment rep : cond.getReplicates()){
//Print events
String repName = rep.getName();
repName = repName.replaceAll("/", "-");
repName = repName.replaceAll(":", "-");
filename = filePrefix+"_"+repName+".eventsbasecomps.txt";
fout = new FileWriter(filename);
fout.write("#Position\tEventRegA\tEventRegC\tEventRegG\tEventRegT\tEventTagA\tEventTagC\tEventTagG\tEventTagT\tBubbleRegA\tBubbleRegC\tBubbleRegG\tBubbleRegT\tBubbleTagA\tBubbleTagC\tBubbleTagG\tBubbleTagT\tBubbleIndex\n");
for(BindingEvent e : events){
double Q = e.getCondSigVCtrlP(cond);
if(e.isFoundInCondition(cond) && Q <=qMinThres){
float[] eventTagBases = e.getRepEventTagBases(rep);
float[] bubbleTagBases = e.getRepBubbleTagBases(rep);
float[] eventBases = e.getEventBases();
float[] bubbleBases = e.getBubbleBases();
float bubbleIndex = -1;
float expectedT=0, expectedACG=0;
if(bubbleBases[3]>0){
expectedT = bubbleTagBases[3] / bubbleBases[3];
float baseACG = bubbleBases[0]+bubbleBases[1]+bubbleBases[2];
if(baseACG>0)
expectedACG = (bubbleTagBases[0]+bubbleTagBases[1]+bubbleTagBases[2])/baseACG;
if(expectedACG>0)
bubbleIndex = expectedT/expectedACG;
}
fout.write(e.getPoint()+"\t"+
eventBases[0]+"\t"+eventBases[1]+"\t"+eventBases[2]+"\t"+eventBases[3]+"\t"+
eventTagBases[0]+"\t"+eventTagBases[1]+"\t"+eventTagBases[2]+"\t"+eventTagBases[3]+"\t"+
bubbleBases[0]+"\t"+bubbleBases[1]+"\t"+bubbleBases[2]+"\t"+bubbleBases[3]+"\t"+
bubbleTagBases[0]+"\t"+bubbleTagBases[1]+"\t"+bubbleTagBases[2]+"\t"+bubbleTagBases[3]+"\t"+
bubbleIndex+
"\n");
}
}
fout.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Print all binding events to files
*/
public void writeFullEventFile(String filename){
if(events.size()>0){
try {
if(config.getEventsFileTXTExtension())
filename = filename+".txt";
//Full dataset table
FileWriter fout = new FileWriter(filename);
fout.write(BindingEvent.fullHeadString()+"\n");
for(BindingEvent e : events)
fout.write(e.toString()+"\n");
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Print all motifs to file
*/
public void writeMotifFile(String filename){
try {
if(config.getEventsFileTXTExtension())
filename = filename+".txt";
//Full dataset table
FileWriter fout = new FileWriter(filename);
for(ExperimentCondition cond : manager.getConditions()){
if(getFreqMatrix(cond)!=null)
fout.write(WeightMatrix.printTransfacMatrix(getFreqMatrix(cond), cond.getName()));
}
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Print replicate data counts to a file
*/
public void writeReplicateCounts(String filename){
if(events.size()>0){
try {
//Full dataset table
FileWriter fout = new FileWriter(filename);
fout.write(BindingEvent.repCountHeadString()+"\n");
for(BindingEvent e : events)
fout.write(e.getRepCountString()+"\n");
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Print all binding events to screen
* TESTING ONLY
*/
public void printBindingEvents(){
System.err.println(events.size()+" events found");
for(BindingEvent e : events){
System.err.println(e.toString());
}
}
} |
package org.treetank.sessionlayer;
import org.treetank.api.IReadTransaction;
import org.treetank.nodelayer.AbstractNode;
import org.treetank.utils.TypedValue;
/**
* <h1>ReadTransaction</h1>
*
* <p>
* Read-only transaction wiht single-threaded cursor semantics. Each
* read-only transaction works on a given revision key.
* </p>
*/
public class ReadTransaction implements IReadTransaction {
/** Session state this write transaction is bound to. */
private SessionState mSessionState;
/** State of transaction including all cached stuff. */
private ReadTransactionState mTransactionState;
/** Strong reference to currently selected node. */
private AbstractNode mCurrentNode;
/** Is the cursor currently pointing to an attribute? */
private boolean mIsAttribute;
/** Tracks whether the transaction is closed. */
private boolean mClosed;
/**
* Constructor.
*
* @param sessionState Session state to work with.
* @param transactionState Transaction state to work with.
*/
protected ReadTransaction(
final SessionState sessionState,
final ReadTransactionState transactionState) {
mSessionState = sessionState;
mTransactionState = transactionState;
mCurrentNode = getTransactionState().getNode(DOCUMENT_ROOT_KEY);
mIsAttribute = false;
mClosed = false;
}
/**
* {@inheritDoc}
*/
public final long getRevisionNumber() {
assertNotClosed();
return mTransactionState.getRevisionRootPage().getRevisionNumber();
}
/**
* {@inheritDoc}
*/
public final long getRevisionSize() {
assertNotClosed();
return mTransactionState.getRevisionRootPage().getRevisionSize();
}
/**
* {@inheritDoc}
*/
public final long getRevisionTimestamp() {
assertNotClosed();
return mTransactionState.getRevisionRootPage().getRevisionTimestamp();
}
/**
* {@inheritDoc}
*/
public final boolean moveTo(final long nodeKey) {
assertNotClosed();
// Do nothing if this node is already selected.
if ((mCurrentNode.getNodeKey() == nodeKey) && !mIsAttribute) {
return true;
}
if (nodeKey != NULL_NODE_KEY) {
mIsAttribute = false;
// Remember old node and fetch new one.
final AbstractNode oldNode = mCurrentNode;
try {
mCurrentNode = mTransactionState.getNode(nodeKey);
} catch (Exception e) {
mCurrentNode = null;
}
if (mCurrentNode != null) {
return true;
} else {
mCurrentNode = oldNode;
return false;
}
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public final boolean moveToToken(final String token) {
assertNotClosed();
final AbstractNode oldNode = mCurrentNode;
moveToFullTextRoot();
boolean contained = true;
for (final char character : token.toCharArray()) {
if (hasFirstChild()) {
moveToFirstChild();
while (isFullTextKind()
&& (getNameKey() != character)
&& hasRightSibling()) {
moveToRightSibling();
}
contained = contained && (getNameKey() == character);
} else {
contained = false;
}
}
if (contained) {
return true;
} else {
mCurrentNode = oldNode;
return false;
}
}
/**
* {@inheritDoc}
*/
public final boolean moveToDocumentRoot() {
return moveTo(DOCUMENT_ROOT_KEY);
}
/**
* {@inheritDoc}
*/
public final boolean moveToFullTextRoot() {
return moveTo(FULLTEXT_ROOT_KEY);
}
/**
* {@inheritDoc}
*/
public final boolean moveToParent() {
return moveTo(mCurrentNode.getParentKey());
}
/**
* {@inheritDoc}
*/
public final boolean moveToFirstChild() {
return moveTo(mCurrentNode.getFirstChildKey());
}
/**
* {@inheritDoc}
*/
public final boolean moveToLeftSibling() {
return moveTo(mCurrentNode.getLeftSiblingKey());
}
/**
* {@inheritDoc}
*/
public final boolean moveToRightSibling() {
return moveTo(mCurrentNode.getRightSiblingKey());
}
/**
* {@inheritDoc}
*/
public final boolean moveToAttribute(final int index) {
final AbstractNode attributeNode = mCurrentNode.getAttribute(index);
if (attributeNode != null) {
mCurrentNode = attributeNode;
mIsAttribute = true;
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public final long getNodeKey() {
assertNotClosed();
return mCurrentNode.getNodeKey();
}
/**
* {@inheritDoc}
*/
public final boolean hasParent() {
assertNotClosed();
return mCurrentNode.hasParent();
}
/**
* {@inheritDoc}
*/
public final long getParentKey() {
assertNotClosed();
return mCurrentNode.getParentKey();
}
/**
* {@inheritDoc}
*/
public final boolean hasFirstChild() {
assertNotClosed();
return mCurrentNode.hasFirstChild();
}
/**
* {@inheritDoc}
*/
public final long getFirstChildKey() {
assertNotClosed();
return mCurrentNode.getFirstChildKey();
}
/**
* {@inheritDoc}
*/
public final boolean hasLeftSibling() {
assertNotClosed();
return mCurrentNode.hasLeftSibling();
}
/**
* {@inheritDoc}
*/
public final long getLeftSiblingKey() {
assertNotClosed();
return mCurrentNode.getLeftSiblingKey();
}
/**
* {@inheritDoc}
*/
public final boolean hasRightSibling() {
assertNotClosed();
return mCurrentNode.hasRightSibling();
}
/**
* {@inheritDoc}
*/
public final long getRightSiblingKey() {
assertNotClosed();
return mCurrentNode.getRightSiblingKey();
}
/**
* {@inheritDoc}
*/
public final long getChildCount() {
assertNotClosed();
return mCurrentNode.getChildCount();
}
/**
* {@inheritDoc}
*/
public final int getAttributeCount() {
assertNotClosed();
return mCurrentNode.getAttributeCount();
}
/**
* {@inheritDoc}
*/
public final int getAttributeNameKey(final int index) {
assertNotClosed();
return mCurrentNode.getAttribute(index).getNameKey();
}
/**
* {@inheritDoc}
*/
public final String getAttributeName(final int index) {
assertNotClosed();
return nameForKey(mCurrentNode.getAttribute(index).getNameKey());
}
/**
* {@inheritDoc}
*/
public final int getAttributeURIKey(final int index) {
assertNotClosed();
return mCurrentNode.getAttribute(index).getURIKey();
}
/**
* {@inheritDoc}
*/
public final String getAttributeURI(final int index) {
assertNotClosed();
return nameForKey(mCurrentNode.getAttribute(index).getURIKey());
}
/**
* {@inheritDoc}
*/
public final int getAttributeValueType(final int index) {
assertNotClosed();
return mCurrentNode.getAttribute(index).getValueType();
}
/**
* {@inheritDoc}
*/
public final String getAttributeValueAsAtom(final int index) {
assertNotClosed();
return TypedValue.atomize(
mCurrentNode.getAttribute(index).getValueType(),
mCurrentNode.getAttribute(index).getValue());
}
/**
* {@inheritDoc}
*/
public final byte[] getAttributeValueAsByteArray(final int index) {
assertNotClosed();
return mCurrentNode.getAttribute(index).getValue();
}
/**
* {@inheritDoc}
*/
public final String getAttributeValueAsString(final int index) {
assertNotClosed();
if (mCurrentNode.getAttribute(index).getValueType() != STRING_TYPE) {
throw new IllegalStateException(
"Can not get string if type of value is not string.");
}
return TypedValue.parseString(mCurrentNode.getAttribute(index).getValue());
}
/**
* {@inheritDoc}
*/
public final int getAttributeValueAsInt(final int index) {
assertNotClosed();
if (mCurrentNode.getAttribute(index).getValueType() != INT_TYPE) {
throw new IllegalStateException(
"Can not get int if type of value is not int.");
}
return TypedValue.parseInt(mCurrentNode.getAttribute(index).getValue());
}
/**
* {@inheritDoc}
*/
public final long getAttributeValueAsLong(final int index) {
assertNotClosed();
if (mCurrentNode.getAttribute(index).getValueType() != LONG_TYPE) {
throw new IllegalStateException(
"Can not get long if type of value is not long.");
}
return TypedValue.parseLong(mCurrentNode.getAttribute(index).getValue());
}
/**
* {@inheritDoc}
*/
public final boolean getAttributeValueAsBoolean(final int index) {
assertNotClosed();
if (mCurrentNode.getAttribute(index).getValueType() != BOOLEAN_TYPE) {
throw new IllegalStateException(
"Can not get boolean if type of value is not boolean.");
}
return TypedValue.parseBoolean(mCurrentNode.getAttribute(index).getValue());
}
/**
* {@inheritDoc}
*/
public final int getNamespaceCount() {
assertNotClosed();
return mCurrentNode.getNamespaceCount();
}
/**
* {@inheritDoc}
*/
public final int getNamespacePrefixKey(final int index) {
assertNotClosed();
return mCurrentNode.getNamespace(index).getPrefixKey();
}
/**
* {@inheritDoc}
*/
public final String getNamespacePrefix(final int index) {
assertNotClosed();
return nameForKey(mCurrentNode.getNamespace(index).getPrefixKey());
}
/**
* {@inheritDoc}
*/
public final int getNamespaceURIKey(final int index) {
assertNotClosed();
return mCurrentNode.getNamespace(index).getURIKey();
}
/**
* {@inheritDoc}
*/
public final String getNamespaceURI(final int index) {
assertNotClosed();
return nameForKey(mCurrentNode.getNamespace(index).getURIKey());
}
/**
* {@inheritDoc}
*/
public final int getKind() {
assertNotClosed();
return mCurrentNode.getKind();
}
/**
* {@inheritDoc}
*/
public final boolean isDocumentRootKind() {
assertNotClosed();
return mCurrentNode.isDocumentRoot();
}
/**
* {@inheritDoc}
*/
public final boolean isElementKind() {
assertNotClosed();
return mCurrentNode.isElement();
}
/**
* {@inheritDoc}
*/
public final boolean isAttributeKind() {
assertNotClosed();
return mCurrentNode.isAttribute();
}
/**
* {@inheritDoc}
*/
public final boolean isTextKind() {
assertNotClosed();
return mCurrentNode.isText();
}
/**
* {@inheritDoc}
*/
public final boolean isFullTextKind() {
assertNotClosed();
return mCurrentNode.isFullText();
}
/**
* {@inheritDoc}
*/
public final boolean isFullTextLeafKind() {
assertNotClosed();
return mCurrentNode.isFullTextLeaf();
}
/**
* {@inheritDoc}
*/
public final boolean isFullTextRootKind() {
assertNotClosed();
return mCurrentNode.isFullTextRoot();
}
/**
* {@inheritDoc}
*/
public final int getNameKey() {
assertNotClosed();
return mCurrentNode.getNameKey();
}
/**
* {@inheritDoc}
*/
public final String getName() {
assertNotClosed();
return mTransactionState.getName(mCurrentNode.getNameKey());
}
/**
* {@inheritDoc}
*/
public final int getURIKey() {
assertNotClosed();
return mCurrentNode.getURIKey();
}
/**
* {@inheritDoc}
*/
public final String getURI() {
assertNotClosed();
return mTransactionState.getName(mCurrentNode.getURIKey());
}
/**
* {@inheritDoc}
*/
public final int getValueType() {
assertNotClosed();
return mCurrentNode.getValueType();
}
/**
* {@inheritDoc}
*/
public final String getValueAsAtom() {
assertNotClosed();
return TypedValue.atomize(mCurrentNode.getValueType(), mCurrentNode
.getValue());
}
/**
* {@inheritDoc}
*/
public final byte[] getValueAsByteArray() {
assertNotClosed();
return mCurrentNode.getValue();
}
/**
* {@inheritDoc}
*/
public final String getValueAsString() {
assertNotClosed();
if (mCurrentNode.getValueType() != STRING_TYPE) {
throw new IllegalStateException(
"Can not get string if type of value is not string.");
}
return TypedValue.parseString(mCurrentNode.getValue());
}
/**
* {@inheritDoc}
*/
public final int getValueAsInt() {
assertNotClosed();
if (mCurrentNode.getValueType() != INT_TYPE) {
throw new IllegalStateException(
"Can not get int if type of value is not int.");
}
return TypedValue.parseInt(mCurrentNode.getValue());
}
/**
* {@inheritDoc}
*/
public final long getValueAsLong() {
assertNotClosed();
if (mCurrentNode.getValueType() != LONG_TYPE) {
throw new IllegalStateException(
"Can not get long if type of value is not long.");
}
return TypedValue.parseLong(mCurrentNode.getValue());
}
/**
* {@inheritDoc}
*/
public final boolean getValueAsBoolean() {
assertNotClosed();
if (mCurrentNode.getValueType() != BOOLEAN_TYPE) {
throw new IllegalStateException(
"Can not get boolean if type of value is not boolean.");
}
return TypedValue.parseBoolean(mCurrentNode.getValue());
}
/**
* {@inheritDoc}
*/
public final int keyForName(final String name) {
assertNotClosed();
return name.hashCode();
}
/**
* {@inheritDoc}
*/
public final String nameForKey(final int key) {
assertNotClosed();
return mTransactionState.getName(key);
}
/**
* {@inheritDoc}
*/
public void close() {
if (!mClosed) {
// Close own state.
mTransactionState.close();
// Callback on session to make sure everything is cleaned up.
mSessionState.closeReadTransaction();
// Immediately release all references.
mSessionState = null;
mTransactionState = null;
mCurrentNode = null;
mClosed = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
assertNotClosed();
String name = "";
try {
name = getName();
} catch (Exception e) {
throw new IllegalStateException(e);
}
return "Node "
+ this.getNodeKey()
+ "\nwith name: "
+ name
+ "\nand value:"
+ getValueAsByteArray();
}
/**
* Set state to closed.
*/
protected final void setClosed() {
mClosed = true;
}
/**
* Is the transaction closed?
*
* @return True if the transaction was closed.
*/
protected final boolean isClosed() {
return mClosed;
}
/**
* Make sure that the session is not yet closed when calling this method.
*/
protected final void assertNotClosed() {
if (mClosed) {
throw new IllegalStateException("Transaction is already closed.");
}
}
/**
* Getter for superclasses.
*
* @return The state of this transaction.
*/
protected final ReadTransactionState getTransactionState() {
return mTransactionState;
}
/**
* Replace the state of the transaction.
*
* @param transactionState State of transaction.
*/
protected final void setTransactionState(
final ReadTransactionState transactionState) {
mTransactionState = transactionState;
}
/**
* Getter for superclasses.
*
* @return The session state.
*/
protected final SessionState getSessionState() {
return mSessionState;
}
/**
* Set session state.
*
* @param sessionState Session state to set.
*/
protected final void setSessionState(final SessionState sessionState) {
mSessionState = sessionState;
}
/**
* Getter for superclasses.
*
* @return The current node.
*/
protected final AbstractNode getCurrentNode() {
return mCurrentNode;
}
/**
* Setter for superclasses.
*
* @param currentNode The current node to set.
*/
protected final void setCurrentNode(final AbstractNode currentNode) {
mCurrentNode = currentNode;
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2129.swRobotics2016b;
import org.usfirst.frc2129.swRobotics2016b.commands.AutonomousCommand;
import org.usfirst.frc2129.swRobotics2016b.subsystems.Drive;
import org.usfirst.frc2129.swRobotics2016b.subsystems.Elevator;
import org.usfirst.frc2129.swRobotics2016b.subsystems.IntakeRoller;
import org.usfirst.frc2129.swRobotics2016b.subsystems.PowerDistribution;
import org.usfirst.frc2129.swRobotics2016b.subsystems.Shooter_BallPusher;
import org.usfirst.frc2129.swRobotics2016b.subsystems.Shooter_Spinners;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Preferences;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
public static Preferences preferences;
CameraServer server;
Command autonomousCommand;
public static OI oi;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static Drive drive;
public static Shooter_Spinners shooter_Spinners;
public static IntakeRoller intakeRoller;
public static PowerDistribution powerDistribution;
public static Shooter_BallPusher shooter_BallPusher;
public static Elevator elevator;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
RobotMap.init();
server = CameraServer.getInstance();
server.setQuality(50);
server.startAutomaticCapture("cam0");
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
drive = new Drive();
shooter_Spinners = new Shooter_Spinners();
intakeRoller = new IntakeRoller();
powerDistribution = new PowerDistribution();
shooter_BallPusher = new Shooter_BallPusher();
elevator = new Elevator();
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
// OI must be constructed after subsystems. If the OI creates Commands
//(which it very likely will), subsystems are not guaranteed to be
// constructed yet. Thus, their requires() statements may grab null
// pointers. Bad news. Don't move it.
oi = new OI();
// instantiate the command used for the autonomous period
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
autonomousCommand = new AutonomousCommand();
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
// Make the Preferences available to the app through Robot.preferences
preferences = Preferences.getInstance();
// Display the status of each of the subsystems in SmartDashboard
SmartDashboard.putData(drive);
SmartDashboard.putData(Robot.elevator);
SmartDashboard.putData(shooter_Spinners);
SmartDashboard.putData(shooter_BallPusher);
SmartDashboard.putData(intakeRoller);
SmartDashboard.putData(powerDistribution);
}
/**
* This function is called when the disabled button is hit.
* You can use it to reset subsystems before shutting down.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
public void autonomousInit() {
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
} |
package pcap.reconst.reconstructor;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import pcap.reconst.beans.TcpConnection;
import pcap.reconst.beans.TcpSequenceCounter;
import pcap.reconst.beans.TimestampPair;
import pcap.reconst.beans.packet.PlaceholderTcpPacket;
import pcap.reconst.beans.packet.TcpPacket;
public class TcpReassembler {
private static Log log = LogFactory.getLog(TcpReassembler.class);
private TcpSequenceCounter reqCounter = null, respCounter = null;
private List<TcpPacket> orderedPackets = new ArrayList<TcpPacket>();
private List<Integer> reqIndexes = new ArrayList<Integer>();
private List<Integer> respIndexes = new ArrayList<Integer>();
private String packetData = null;
private Map<Integer, Integer> packetPositions = new HashMap<Integer, Integer>();
private boolean rebuildData = true;
public boolean isIncomplete() {
for (TcpPacket packet : orderedPackets) {
if (packet instanceof PlaceholderTcpPacket) {
return true;
}
}
return false;
}
public boolean isEmpty() {
return orderedPackets.isEmpty();
}
public String getOrderedPacketData() {
if (rebuildData || packetData == null) {
buildPacketData();
rebuildData = false;
}
return packetData;
}
public void buildPacketData() {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < orderedPackets.size(); i++) {
byte[] data = orderedPackets.get(i).getData();
if (data != null && data.length > 0) {
int startpos = buf.length();
buf.append(new String(data));
packetPositions.put(buf.length(), i);
if (log.isDebugEnabled()) {
log.debug("Start position: " + startpos + " End position: "
+ buf.length() + "\n" + new String(data));
}
}
}
packetData = buf.toString();
}
public TimestampPair getTimestampRange(String needle) {
if (rebuildData || packetData == null) {
buildPacketData();
rebuildData = false;
}
int beginIndex = this.packetData.indexOf(needle);
int endIndex = beginIndex + needle.length();
if (log.isDebugEnabled()) {
log.debug("Find timestamp for:\n" + needle + "\nbegin index: "
+ beginIndex + " end index: " + endIndex);
}
double startTS = -1.0, endTS = -1.0;
List<Integer> positions = new ArrayList<Integer>(
packetPositions.keySet());
Collections.sort(positions);
for (int pos : positions) {
if (startTS < 0.0 && beginIndex < pos) {
TcpPacket packet = orderedPackets.get(packetPositions.get(pos));
startTS = Double.parseDouble(packet.getTimestampSec() + "."
+ packet.getTimestampUSec());
}
if (endTS < 0.0 && endIndex <= pos) {
TcpPacket packet = orderedPackets.get(packetPositions.get(pos));
endTS = Double.parseDouble(packet.getTimestampSec() + "."
+ packet.getTimestampUSec());
}
}
if (log.isDebugEnabled()) {
log.debug("start: " + startTS + " end: " + endTS);
}
if (startTS > -1.0) {
return new TimestampPair(startTS, endTS);
}
return null;
}
public TcpReassembler() {
}
/*
* The main function of the class receives a tcp packet and reconstructs the
* stream
*/
public void reassemblePacket(TcpPacket tcpPacket) throws Exception {
if (log.isDebugEnabled()) {
log.debug(String
.format("captured_len = %d, len = %d, headerlen = %d, datalen = %d",
tcpPacket.getCaptureLength(),
tcpPacket.getLength(), tcpPacket.getHeaderLength(),
tcpPacket.getDataLength()));
}
reassembleTcp(new TcpConnection(tcpPacket), tcpPacket);
}
private void reassembleTcp(TcpConnection tcpConnection, TcpPacket packet)
throws Exception {
if (log.isDebugEnabled()) {
log.debug(String
.format("sequence=%d ack_num=%d length=%d dataLength=%d synFlag=%s %s srcPort=%s %s dstPort=%s",
packet.getSequence(), packet.getAckNum(),
packet.getLength(), packet.getDataLength(),
packet.getSyn(), tcpConnection.getSrcIp(),
tcpConnection.getSrcPort(),
tcpConnection.getDstIp(),
tcpConnection.getDstPort()));
}
boolean first = false;
PacketType packetType = null;
// Now check if the packet is for this connection.
InetAddress srcIp = tcpConnection.getSrcIp();
int srcPort = tcpConnection.getSrcPort();
// Check to see if we have seen this source IP and port before.
// check both source IP and port; the connection might be between two
// different ports on the same machine...
if (reqCounter == null) {
reqCounter = new TcpSequenceCounter(srcIp, srcPort);
packetType = PacketType.Request;
first = true;
} else {
if (reqCounter.getAddress().equals(srcIp)
&& reqCounter.getPort() == srcPort) {
// check if request is already being handled... this is a
// fragmented packet
packetType = PacketType.Request;
} else {
if (respCounter == null) {
respCounter = new TcpSequenceCounter(srcIp, srcPort);
packetType = PacketType.Response;
first = true;
} else if (respCounter.getAddress().equals(srcIp)
&& respCounter.getPort() == srcPort) {
// check if response is already being handled... this is a
// fragmented packet
packetType = PacketType.Response;
}
}
}
if (packetType == null) {
throw new Exception(
"ERROR in TcpReassembler: Too many or too few addresses!");
}
if (log.isDebugEnabled()) {
log.debug((isRequest(packetType) ? "request" : "response")
+ " packet...");
}
TcpSequenceCounter currentCounter = isRequest(packetType) ? reqCounter
: respCounter;
updateSequence(first, currentCounter, packet, packetType);
}
private boolean isRequest(PacketType packetType) {
return PacketType.Request == packetType;
}
private void updateSequence(boolean first, TcpSequenceCounter tcpSeq,
TcpPacket packet, PacketType type) throws IOException {
// figure out sequence number stuff
if (first) {
// this is the first time we have seen this src's sequence number
tcpSeq.setSeq(packet.getSequence() + packet.getDataLength());
if (packet.getSyn()) {
tcpSeq.incrementSeq();
}
// add to ordered packets
addOrderedPacket(packet, type);
return;
}
// if we are here, we have already seen this src, let's try and figure
// out if this packet is in the right place
if (packet.getSequence() < tcpSeq.getSeq()) {
if (!this.checkPlaceholders(packet, type)) {
if (log.isDebugEnabled()) {
log.debug("Unable to place packet.\n" + packet);
}
}
}
if (packet.getSequence() == tcpSeq.getSeq()) {
// packet in sequence
tcpSeq.addToSeq(packet.getDataLength());
if (packet.getSyn()) {
tcpSeq.incrementSeq();
}
addOrderedPacket(packet, type);
} else {
// out of order packet
if (packet.getDataLength() > 0
&& packet.getSequence() > tcpSeq.getSeq()) {
PlaceholderTcpPacket ppacket = new PlaceholderTcpPacket(
packet.getSourceIP(), packet.getSourcePort(),
packet.getDestinationIP(), packet.getDestinationPort(),
tcpSeq.getSeq(),
(int) (packet.getSequence() - this
.getLastOrderedSequence(type)));
this.addOrderedPacket(ppacket, type);
this.addOrderedPacket(packet, type);
tcpSeq.setSeq(packet.getSequence());
}
}
}
private boolean checkPlaceholders(TcpPacket packet, PacketType type) {
boolean retval = false;
for (Integer index : this.getPacketIndexes(type)) {
TcpPacket pospacket = orderedPackets.get(index);
if (pospacket instanceof PlaceholderTcpPacket) {
// overlap placeholder beginning
if (packet.getSequence() < pospacket.getSequence()
&& (packet.getSequence() + packet.getLength()) < (pospacket
.getSequence() + pospacket.getLength())) {
if (log.isDebugEnabled()) {
log.debug("Overlap placeholder beginning.\n" + packet);
}
// retval = true;
// break;
}
// overlap placeholder ending
if (packet.getSequence() > pospacket.getSequence()
&& (packet.getSequence() + packet.getLength()) > (pospacket
.getSequence() + pospacket.getLength())) {
if (log.isDebugEnabled()) {
log.debug("Overlap placeholder ending.\n" + packet);
}
// retval = true;
// break;
}
// in the middle of the place holder
if (packet.getSequence() >= pospacket.getSequence()
&& (packet.getSequence() + packet.getLength()) <= (pospacket
.getSequence() + pospacket.getLength())) {
// exactly fits a place holder
if (packet.getSequence() == pospacket.getSequence()
&& packet.getLength() == pospacket.getLength()) {
this.setOrderedPacket(packet, type, index);
} else {
long leftlen = packet.getSequence()
- pospacket.getSequence();
long leftseq = pospacket.getSequence();
long rightlen = pospacket.getSequence()
+ pospacket.getLength() - packet.getSequence()
+ packet.getLength();
long rightseq = packet.getSequence()
+ packet.getLength();
PlaceholderTcpPacket lpacket = new PlaceholderTcpPacket(
packet.getSourceIP(), packet.getSourcePort(),
packet.getDestinationIP(),
packet.getDestinationPort(), leftseq,
(int) leftlen);
PlaceholderTcpPacket rpacket = new PlaceholderTcpPacket(
packet.getSourceIP(), packet.getSourcePort(),
packet.getDestinationIP(),
packet.getDestinationPort(), rightlen,
(int) rightseq);
if (lpacket.getLength() > 0) {
this.setOrderedPacket(lpacket, type, index);
this.insertOrderedPacket(packet, type, index + 1);
if (rpacket.getLength() > 0) {
this.insertOrderedPacket(rpacket, type,
index + 2);
}
} else {
this.setOrderedPacket(packet, type, index);
this.insertOrderedPacket(rpacket, type, index + 1);
}
}
retval = true;
break;
}
}
}
return retval;
}
private List<Integer> getPacketIndexes(PacketType type) {
return isRequest(type) ? reqIndexes : respIndexes;
}
private void incPacketIndexes(int greaterthan, int inc) {
for (int i = 0; i < reqIndexes.size(); i++) {
if (reqIndexes.get(i) > greaterthan) {
reqIndexes.set(i, reqIndexes.get(i) + inc);
}
}
for (int i = 0; i < respIndexes.size(); i++) {
if (respIndexes.get(i) > greaterthan) {
respIndexes.set(i, respIndexes.get(i) + inc);
}
}
}
private void setOrderedPacket(TcpPacket packet, PacketType type, int index) {
rebuildData = true;
Integer indexObj = index;
orderedPackets.set(index, packet);
if (isRequest(type)) {
if (!reqIndexes.contains(indexObj)) {
reqIndexes.add(indexObj);
}
if (respIndexes.contains(indexObj)) {
respIndexes.remove(indexObj);
}
} else {
if (!respIndexes.contains(indexObj)) {
respIndexes.add(indexObj);
}
if (reqIndexes.contains(indexObj)) {
reqIndexes.remove(indexObj);
}
}
}
private void insertOrderedPacket(TcpPacket packet, PacketType type,
int index) {
rebuildData = true;
orderedPackets.add(index, packet);
incPacketIndexes(index, 1);
if (isRequest(type)) {
reqIndexes.add(index);
} else {
respIndexes.add(index);
}
}
private void addOrderedPacket(TcpPacket packet, PacketType type) {
rebuildData = true;
orderedPackets.add(packet);
if (isRequest(type)) {
reqIndexes.add(orderedPackets.size() - 1);
} else {
respIndexes.add(orderedPackets.size() - 1);
}
}
private long getLastOrderedSequence(PacketType type) {
TcpPacket last = null;
if (isRequest(type)) {
if (reqIndexes.size() > 0) {
last = orderedPackets
.get(reqIndexes.get(reqIndexes.size() - 1));
}
} else {
if (respIndexes.size() > 0) {
last = orderedPackets
.get(respIndexes.get(respIndexes.size() - 1));
}
}
if (last != null) {
return last.getSequence();
}
return -1;
}
} |
package projectsettings;
import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.credentialStore.Credentials;
import netsuite.NSAccount;
import netsuite.NSClient;
import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.ide.passwordSafe.impl.PasswordSafeImpl;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import netsuite.NSRolesRestServiceController;
import java.util.ArrayList;
public class ProjectSettingsController {
final private String PROJECT_SETTING_NETSUITE_EMAIL = "nsProjectEmail";
final private String PROJECT_SETTING_NETSUITE_ROOT_FOLDER_ = "nsProjectRootFolder";
final private String PROJECT_SETTING_NETSUITE_ACCOUNT = "nsAccount";
final private String PROJECT_SETTING_NETSUITE_ACCOUNT_NAME = "nsAccountName";
final private String PROJECT_SETTING_NETSUITE_ACCOUNT_ROLE = "nsAccountRole";
final private String PROJECT_SETTING_NETSUITE_ENVIRONMENT = "nsEnvironment";
private final PropertiesComponent propertiesComponent;
private final PasswordSafeImpl passwordSafe;
private final Project project;
public ProjectSettingsController(Project project) {
this.project = project;
this.propertiesComponent = PropertiesComponent.getInstance(project);
this.passwordSafe = (PasswordSafeImpl)PasswordSafe.getInstance();
}
public String getNsEmail() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_EMAIL);
}
public void setNsEmail(String nsEmail) {
if (nsEmail != null && !nsEmail.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_EMAIL, nsEmail);
}
}
public String getNsRootFolder() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_ROOT_FOLDER_);
}
public void setNsRootFolder(String nsRootFolder) {
if (nsRootFolder != null && !nsRootFolder.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_ROOT_FOLDER_, nsRootFolder);
}
}
public String getNsAccount() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_ACCOUNT);
}
public void setNsAccount(String nsAccount) {
if (nsAccount != null && !nsAccount.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_ACCOUNT, nsAccount);
}
}
public String getNsAccountName() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_ACCOUNT_NAME);
}
public void setNsAccountName(String nsAccountName) {
if (nsAccountName != null && !nsAccountName.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_ACCOUNT_NAME, nsAccountName);
}
}
public String getNsAccountRole() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_ACCOUNT_ROLE);
}
public void setNsAccountRole(String nsAccountRole) {
if (nsAccountRole != null && !nsAccountRole.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_ACCOUNT_ROLE, nsAccountRole);
}
}
public String getNsEnvironment() {
return propertiesComponent.getValue(PROJECT_SETTING_NETSUITE_ENVIRONMENT);
}
public void setNsEnvironment(String nsEnvironment) {
if (nsEnvironment != null && !nsEnvironment.isEmpty()) {
propertiesComponent.setValue(PROJECT_SETTING_NETSUITE_ENVIRONMENT, nsEnvironment);
}
}
public void saveProjectPassword(NSClient client) {
if (client != null) {
CredentialAttributes attributes = new CredentialAttributes(client.getNSAccount().getAccountName() + ":" + client.getNSAccount().getAccountId(), client.getNSAccount().getAccountEmail(), this.getClass(), false);
Credentials saveCredentials = new Credentials(attributes.getUserName(), client.getNSAccount().getAccountPassword());
PasswordSafe.getInstance().set(attributes, saveCredentials);
}
}
public String getProjectPassword() {
CredentialAttributes attributes = new CredentialAttributes(this.getNsAccountName() + ":" + this.getNsAccount(), this.getNsEmail(), this.getClass(), false);
return PasswordSafe.getInstance().getPassword(attributes);
}
public boolean hasAllProjectSettings() {
return (getNsEmail() != null && !getNsEmail().isEmpty() &&
getNsRootFolder() != null && !getNsRootFolder().isEmpty() &&
getNsAccount() != null && !getNsAccount().isEmpty() &&
getNsEnvironment() != null && !getNsEnvironment().isEmpty());
}
public NSAccount getNSAccountForProject() {
NSRolesRestServiceController nsRolesRestServiceController = new NSRolesRestServiceController();
ArrayList<NSAccount> nsAccounts = nsRolesRestServiceController.getNSAccounts(getNsEmail(), getProjectPassword(), getNsEnvironment());
NSAccount projectNSAccount = null;
if (nsAccounts != null) {
for (NSAccount account : nsAccounts) {
if (account.getAccountName().equals(getNsAccountName()) &&
account.getAccountId().equals(getNsAccount()) &&
account.getRoleId().equals(getNsAccountRole())) {
projectNSAccount = account;
break;
}
}
}
return projectNSAccount;
}
} |
package br.com.caelum.brutal.dao;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import java.util.Arrays;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Before;
import org.junit.Test;
import br.com.caelum.brutal.builder.QuestionBuilder;
import br.com.caelum.brutal.model.Answer;
import br.com.caelum.brutal.model.Question;
import br.com.caelum.brutal.model.Tag;
import br.com.caelum.brutal.model.TagUsage;
import br.com.caelum.brutal.model.User;
public class TagDAOTest extends DatabaseTestCase{
private TagDAO tags;
private User leo;
private Tag java;
private Tag ruby;
@Before
public void setup() {
this.tags = new TagDAO(session);
leo = user("leonardo", "leo@leo");
java = new Tag("java", "", leo);
ruby = new Tag("ruby", "", leo);
session.save(leo);
session.save(java);
session.save(ruby);
}
@Test
public void should_load_recent_tags_used() throws Exception {
DateTimeUtils.setCurrentMillisFixed(new DateTime().minusMonths(3).getMillis());
questionWith(Arrays.asList(java));
DateTimeUtils.setCurrentMillisSystem();
questionWith(Arrays.asList(java));
questionWith(Arrays.asList(java));
questionWith(Arrays.asList(ruby));
List<TagUsage> recentTagsUsage = tags.getRecentTagsSince(new DateTime().minusMonths(2));
assertEquals(2, recentTagsUsage.size());
assertEquals(2l, recentTagsUsage.get(0).getUsage().longValue());
assertEquals(1l, recentTagsUsage.get(1).getUsage().longValue());
assertEquals(java.getId(), recentTagsUsage.get(0).getTag().getId());
assertEquals(ruby.getId(), recentTagsUsage.get(1).getTag().getId());
}
@Test
public void should_load_tags_with_usage_with_provided_name() throws Exception {
questionWith(Arrays.asList(java));
questionWith(Arrays.asList(java));
questionWith(Arrays.asList(java));
questionWith(Arrays.asList(ruby));
List<Tag> tagsLike = tags.findTagsLike("ja");
assertEquals(1, tagsLike.size());
assertEquals(3l, tagsLike.get(0).getUsageCount().longValue());
assertEquals(java.getId(), tagsLike.get(0).getId());
}
@Test
public void should_get_main_tags_of_the_provided_user() throws Exception {
Question javaQuestion = questionWith(Arrays.asList(java));
Answer javaAnswer = answer("just do this and that and you will be happy forever", javaQuestion, leo);
session.save(javaAnswer);
Question oneMoreJavaQuestion = questionWith(Arrays.asList(java));
Answer oneMoreJavaAnswer = answer("just do this and that and you will be happy forever", oneMoreJavaQuestion, leo);
session.save(oneMoreJavaAnswer);
Question rubyQuestion = questionWith(Arrays.asList(ruby));
Answer rubyAnswer = answer("just do this and that and you will be happy forever", rubyQuestion, leo);
session.save(rubyAnswer);
User chico = user("chicoh", "chico@chico.com");
session.save(chico);
Question otherJavaQuestion = questionWith(Arrays.asList(java));
Answer otherJavaAnswer = answer("just do this and that and you will be happy forever", otherJavaQuestion, chico);
session.save(otherJavaAnswer);
List<TagUsage> mainTags = tags.findMainTagsOfUser(leo);
assertEquals(2, mainTags.size());
assertEquals(2l, mainTags.get(0).getUsage().longValue());
assertEquals(1l, mainTags.get(1).getUsage().longValue());
}
@Test
public void should_load_all_tags_with_the_name_in_the_provided_string() throws Exception {
List<Tag> tagsByNames = tags.findAllByNames("java ruby doesntexist");
assertEquals(3, tagsByNames.size());
assertEquals(java.getId(), tagsByNames.get(0).getId());
assertEquals(ruby.getId(), tagsByNames.get(1).getId());
assertNull(tagsByNames.get(2));
}
@Test
public void should_get_all_tag_names() throws Exception {
List<String> tagsNames = tags.allNames();
assertEquals(2, tagsNames.size());
assertEquals(java.getName(), tagsNames.get(0));
assertEquals(ruby.getName(), tagsNames.get(1));
}
private Question questionWith(List<Tag> tags) {
Question question = new QuestionBuilder().withAuthor(leo).withTags(tags).build();
session.save(question);
return question;
}
} |
package ca.thoughtwire.lock;
import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
/**
* @author vanessa.williams
*/
public class HazelcastLockIT {
public static void main(String[] args)
{
/*
* 1st arg = 1 if I'm the process that's started 1st & will crash; 0 if not
*/
HazelcastLockIT instance = new HazelcastLockIT(args[0].equals("1"));
instance.test();
}
public HazelcastLockIT(boolean crashProcess)
{
this.crashProcess = crashProcess;
}
public void test()
{
Config standardConfig;
if (crashProcess)
{
standardConfig = new ClasspathXmlConfig("hazelcast1.xml");
}
else
{
standardConfig = new ClasspathXmlConfig("hazelcast2.xml");
}
grid = Hazelcast.newHazelcastInstance(standardConfig);
latch = grid.getCountDownLatch("crash_lock");
latch.trySetCount(2);
Locker locker = new Locker();
new Thread(locker).run();
}
class Locker implements Runnable
{
@Override
public void run() {
DistributedLockService lockService = DistributedLockService.newHazelcastLockService(grid);
try {
ReadWriteLock lock1, lock2, lock3, lock4;
lock1 = lockService.getReentrantReadWriteLock(LOCK1);
lock2 = lockService.getReentrantReadWriteLock(LOCK2);
lock3 = lockService.getReentrantReadWriteLock(LOCK3);
lock4 = lockService.getReentrantReadWriteLock(LOCK4);
if (crashProcess)
{
System.out.println("Crash process acquiring locks");
lock1.readLock().lock();
lock2.readLock().lock();
lock3.writeLock().lock();
lock4.writeLock().lock();
System.out.println("Crash process counting down...");
latch.countDown();
System.out.println("Locks acquired");
System.out.println("Waiting on latch...");
latch.await(20000, TimeUnit.MILLISECONDS);
System.out.println("Exiting normally");
System.exit(0);
}
else
{
System.out.println("Counting down...");
latch.countDown();
System.out.println("Waiting on latch...");
latch.await(20000, TimeUnit.MILLISECONDS);
lock1.readLock().lock();
lock2.readLock().lock();
lock3.readLock().lock();
lock4.readLock().lock();
System.out.println("Locks acquired");
lock1.readLock().unlock();
lock2.readLock().unlock();
lock3.readLock().unlock();
lock4.readLock().unlock();
System.out.println("Locks released");
System.exit(0);
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
private boolean crashProcess = false;
private HazelcastInstance grid;
private ICountDownLatch latch;
private static final String LOCK1 = "Lock1";
private static final String LOCK2 = "Lock2";
private static final String LOCK3 = "Lock3";
private static final String LOCK4 = "Lock4";
} |
package com.github.andriell.db;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertEquals;
public class HashDateTest {
@Test
public void test() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-config.xml");
applicationContext.registerShutdownHook();
HashDateDaoImpl dateDao = applicationContext.getBean("hashDateDaoImpl", HashDateDaoImpl.class);
assertEquals(true, dateDao.checkSec("test", 2));
assertEquals(false, dateDao.checkSec("test", 2));
try {
Thread.sleep(3000);
} catch (InterruptedException ignored) {}
assertEquals(true, dateDao.checkSec("test", 2));
assertEquals(false, dateDao.checkSec("test", 2));
}
} |
package com.hosopy.actioncable;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.ws.WebSocket;
import com.squareup.okhttp.ws.WebSocketListener;
import okio.Buffer;
import okio.BufferedSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
@RunWith(JUnit4.class)
public class ConsumerTest {
private static final int TIMEOUT = 10000;
@Test
public void createWithValidUri() throws URISyntaxException {
final Consumer consumer = new Consumer(new URI("ws://example.com:28080"));
assertThat(consumer, isA(Consumer.class));
}
@Test
public void createWithValidUriAndOptions() throws URISyntaxException {
final Consumer consumer = new Consumer(new URI("ws://example.com:28080"), new Consumer.Options());
assertThat(consumer, isA(Consumer.class));
}
@Test
public void getSubscriptions() throws URISyntaxException {
final URI uri = new URI("ws://example.com:28080");
final Consumer consumer = new Consumer(uri);
assertThat(consumer.getSubscriptions(), notNullValue());
}
@Test
public void getConnection() throws URISyntaxException {
final URI uri = new URI("ws://example.com:28080");
final Consumer consumer = new Consumer(uri);
assertThat(consumer.getConnection(), notNullValue());
}
@Test(timeout = TIMEOUT)
public void open() throws IOException, InterruptedException {
final BlockingQueue<String> events = new LinkedBlockingQueue<String>();
final MockWebServer mockWebServer = new MockWebServer();
final MockResponse response = new MockResponse();
response.withWebSocketUpgrade(new DefaultWebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
events.offer("onOpen");
}
});
mockWebServer.enqueue(response);
mockWebServer.start();
final Consumer consumer = new Consumer(mockWebServer.url("/").uri());
consumer.open();
assertThat(events.take(), is("onOpen"));
mockWebServer.shutdown();
}
@Test(timeout = TIMEOUT)
public void close() throws IOException, InterruptedException {
final BlockingQueue<String> events = new LinkedBlockingQueue<String>();
final MockWebServer mockWebServer = new MockWebServer();
final MockResponse response = new MockResponse();
response.withWebSocketUpgrade(new DefaultWebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
events.offer("onOpen");
}
@Override
public void onClose(int code, String reason) {
events.offer("onClose");
}
});
mockWebServer.enqueue(response);
mockWebServer.start();
final Consumer consumer = new Consumer(mockWebServer.url("/").uri());
consumer.open();
events.take(); // onOpen
consumer.close();
assertThat(events.take(), is("onClose"));
mockWebServer.shutdown();
}
@Test(timeout = TIMEOUT)
public void send() throws IOException, InterruptedException {
final BlockingQueue<String> events = new LinkedBlockingQueue<String>();
final MockWebServer mockWebServer = new MockWebServer();
final MockResponse response = new MockResponse();
response.withWebSocketUpgrade(new DefaultWebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
events.offer("onOpen");
}
@Override
public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
events.offer("onMessage:" + payload.readUtf8());
payload.close();
}
});
mockWebServer.enqueue(response);
mockWebServer.start();
final Consumer consumer = new Consumer(mockWebServer.url("/").uri());
consumer.open();
events.take(); // onOpen
// At this point, the server has received onOpen, but the connection has not always received onOpen.
// Continue sending until connection succeeds sending.
while (!consumer.send(Command.subscribe("identifier"))) {
Thread.sleep(100);
}
assertThat(events.take(), is("onMessage:{\"command\":\"subscribe\",\"identifier\":\"identifier\"}"));
mockWebServer.shutdown();
}
private static class DefaultWebSocketListener implements WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
}
@Override
public void onFailure(IOException e, Response response) {
}
@Override
public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
payload.close();
}
@Override
public void onPong(Buffer payload) {
}
@Override
public void onClose(int code, String reason) {
}
}
} |
package com.mangopay.core;
import com.mangopay.core.enumerations.CurrencyIso;
import com.mangopay.core.enumerations.ReportType;
import com.mangopay.core.enumerations.SortDirection;
import com.mangopay.entities.ReportRequest;
import org.junit.Test;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.*;
/**
* API Reports test methods.
*/
public class ReportApiImplTest extends BaseTest {
private static final int SMALL_AMOUNT = 100;
private static final int LARGE_AMOUNT = 9999;
private static final CurrencyIso CURRENCY = CurrencyIso.EUR;
@Test
public void createTransactionsReport() throws Exception {
createReport(ReportType.TRANSACTIONS);
}
@Test
public void createWalletsReport() throws Exception {
createReport(ReportType.WALLETS);
}
private void createReport(ReportType type) throws Exception {
ReportRequest reportPost = new ReportRequest();
reportPost.setReportType(type);
ReportRequest report = this.api.getReportApi().create(reportPost);
assertNotNull(report);
assertTrue(report.getId().length() > 0);
}
@Test
public void createFilteredTransactionsReport() throws Exception {
ReportRequest report = createFilteredTransactionsReport(ReportType.TRANSACTIONS);
checkReport(report);
}
private ReportRequest createFilteredTransactionsReport(ReportType type) throws Exception {
ReportRequest reportPost = new ReportRequest();
reportPost.setReportType(type);
int minFees = 10;
CurrencyIso minCurrency = CurrencyIso.USD;
int maxFees = 20;
CurrencyIso maxCurrency = CurrencyIso.EUR;
String johnsId = this.getJohn().getId();
String walletId = this.getJohnsWallet().getId();
reportPost.setFilters(new FilterReports());
if (type.equals(ReportType.WALLETS)) {
reportPost.getFilters().setOwnerId(johnsId);
reportPost.getFilters().setMinBalanceAmount(SMALL_AMOUNT);
reportPost.getFilters().setMinBalanceCurrency(CURRENCY);
reportPost.getFilters().setMaxBalanceAmount(LARGE_AMOUNT);
reportPost.getFilters().setMaxBalanceCurrency(CURRENCY);
} else {
reportPost.getFilters().setAuthorId(johnsId);
reportPost.getFilters().setWalletId(walletId);
reportPost.getFilters().setMinFeesAmount(minFees);
reportPost.getFilters().setMinFeesCurrency(minCurrency);
reportPost.getFilters().setMaxFeesAmount(maxFees);
reportPost.getFilters().setMaxFeesCurrency(maxCurrency);
}
return this.api.getReportApi().create(reportPost);
}
private void checkReport(ReportRequest report) throws Exception {
assertNotNull(report);
assertTrue(report.getId().length() > 0);
assertNotNull(report.getFilters());
if (report.getReportType().equals(ReportType.WALLETS)) {
assertNotNull(report.getFilters().getOwnerId());
assertEquals(this.getJohn().getId(), report.getFilters().getOwnerId());
assertEquals(report.getFilters().getMinBalanceAmount(), SMALL_AMOUNT);
assertEquals(report.getFilters().getMinBalanceCurrency(), CURRENCY);
assertEquals(report.getFilters().getMaxBalanceAmount(), LARGE_AMOUNT);
assertEquals(report.getFilters().getMaxBalanceCurrency(), CURRENCY);
} else {
assertNotNull(report.getFilters().getAuthorId());
assertEquals(this.getJohn().getId(), report.getFilters().getAuthorId());
assertNotNull(report.getFilters().getWalletId());
assertEquals(this.getJohnsWallet().getId(), report.getFilters().getWalletId());
}
}
@Test
public void createFilteredWalletsReport() throws Exception {
ReportRequest report = createFilteredTransactionsReport(ReportType.WALLETS);
checkReport(report);
}
@Test
public void createWalletReport() throws Exception {
ReportRequest reportRequest = new ReportRequest();
ReportRequest report = this.api.getReportApi().createWalletReport(reportRequest);
assertNotNull(report);
assertEquals(report.getReportType(), ReportType.WALLETS);
}
@Test
public void getReport() throws Exception {
ReportRequest report = this.getJohnsReport();
ReportRequest getReport = this.api.getReportApi().get(report.getId());
assertEquals(getReport.getId(), report.getId());
}
@Test
public void getReports() throws Exception {
ReportRequest report = this.getNewJohnsReport();
Pagination pagination = new Pagination(1, 10);
Sorting sort = new Sorting();
sort.addField("CreationDate", SortDirection.desc);
List<ReportRequest> list = this.api.getReportApi().getAll(pagination, null, sort);
/*
Due to concurrent nature of how unit tests are launched,
it is not guaranteed that report created in this method
will be the newest one in the reports list received from
API. Therefore another solution is needed here, such as
looking for the report among few the newest ones (here 10).
*/
int j = -1;
for (int i = 0; i < list.size(); i++) {
if (report.getId().equals(list.get(i).getId())) {
j = i;
break;
}
}
assertTrue(j > -1);
assertEquals(report.getId(), list.get(j).getId());
assertEquals(pagination.getPage(), 1);
assertEquals(pagination.getItemsPerPage(), 10);
FilterReportsList filters = new FilterReportsList();
filters.setAfterDate(list.get(j).getCreationDate());
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
filters.setBeforeDate(c.getTimeInMillis() / 1000);
list = this.api.getReportApi().getAll(pagination, filters, sort);
assertNotNull(list);
assertTrue(list.isEmpty());
filters.setBeforeDate(filters.getAfterDate());
c.set(Calendar.YEAR, c.get(Calendar.YEAR) - 10);
filters.setAfterDate(c.getTimeInMillis() / 1000);
list = this.api.getReportApi().getAll(pagination, filters, sort);
assertNotNull(list);
assertTrue(list.size() > 0);
}
} |
package com.netflix.priam;
import java.util.Arrays;
import java.util.List;
import com.google.common.collect.Lists;
import com.google.inject.Singleton;
import com.netflix.priam.IConfiguration;
@Singleton
public class FakeConfiguration implements IConfiguration
{
public String region;
public String appName;
public String zone;
public String instance_id;
public String restorePrefix;
public FakeConfiguration(String region, String appName, String zone, String ins_id)
{
this.region = region;
this.appName = appName;
this.zone = zone;
this.instance_id = ins_id;
this.restorePrefix = "";
}
@Override
public void intialize()
{
// TODO Auto-generated method stub
}
@Override
public String getBackupLocation()
{
// TODO Auto-generated method stub
return "casstestbackup";
}
@Override
public String getBackupPrefix()
{
// TODO Auto-generated method stub
return "TEST-netflix.platform.S3";
}
@Override
public boolean isCommitLogBackup()
{
// TODO Auto-generated method stub
return false;
}
@Override
public String getCommitLogLocation()
{
// TODO Auto-generated method stub
return "cass/commitlog";
}
@Override
public String getDataFileLocation()
{
// TODO Auto-generated method stub
return "cass/data";
}
@Override
public String getCacheLocation()
{
// TODO Auto-generated method stub
return null;
}
@Override
public List<String> getRacs()
{
return Arrays.asList("az1", "az2", "az3");
}
@Override
public int getJmxPort()
{
return 7199;
}
@Override
public int getThriftPort()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public String getSnitch()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getRac()
{
return this.zone;
}
@Override
public String getHostname()
{
// TODO Auto-generated method stub
return instance_id;
}
@Override
public String getInstanceName()
{
return instance_id;
}
@Override
public String getHeapSize()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getHeapNewSize()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getBackupHour()
{
// TODO Auto-generated method stub
return 12;
}
@Override
public String getRestoreSnapshot()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getAppName()
{
return appName;
}
@Override
public int getMaxBackupUploadThreads()
{
// TODO Auto-generated method stub
return 2;
}
@Override
public String getDC()
{
// TODO Auto-generated method stub
return this.region;
}
@Override
public int getMaxBackupDownloadThreads()
{
// TODO Auto-generated method stub
return 3;
}
public void setRestorePrefix(String prefix)
{
// TODO Auto-generated method stub
restorePrefix = prefix;
}
@Override
public String getRestorePrefix()
{
// TODO Auto-generated method stub
return restorePrefix;
}
@Override
public String getBackupCommitLogLocation()
{
return "cass/backup/cl/";
}
@Override
public boolean isMultiDC()
{
// TODO Auto-generated method stub
return false;
}
@Override
public String getASGName()
{
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isIncrBackup()
{
return true;
}
@Override
public String getHostIP()
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getUploadThrottle()
{
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isLocalBootstrapEnabled() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getInMemoryCompactionLimit() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getCompactionThroughput() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getMaxDirectMemory()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getBootClusterName()
{
// TODO Auto-generated method stub
return "cass_bootstrap";
}
@Override
public String getCassHome()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getCassStartupScript()
{
// TODO Auto-generated method stub
return null;
}
@Override
public List<String> getRestoreKeySpaces()
{
// TODO Auto-generated method stub
return Lists.newArrayList();
}
@Override
public long getBackupChunkSize()
{
return 5L*1024*1024;
}
@Override
public void setDC(String region)
{
// TODO Auto-generated method stub
}
@Override
public boolean isRestoreClosestToken()
{
// TODO Auto-generated method stub
return false;
}
@Override
public String getCassStopScript()
{
return "teststopscript";
}
@Override
public int getStoragePort()
{
return 7000;
}
@Override
public String getSeedProviderName()
{
return "com.netflix.priam.cassandra.NFSeedProvider";
}
@Override
public int getBackupRetentionDays()
{
return 5;
}
@Override
public List<String> getBackupRacs()
{
return Lists.newArrayList();
}
public int getMaxHintWindowInMS()
{
return 36000;
}
@Override
public int getHintHandoffDelay()
{
// TODO Auto-generated method stub
return 0;
}
} |
package hudson.plugins.git;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.matrix.Axis;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.model.*;
import hudson.plugins.git.GitPublisher.BranchToPush;
import hudson.plugins.git.GitPublisher.NoteToPush;
import hudson.plugins.git.GitPublisher.TagToPush;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.LocalBranch;
import hudson.plugins.git.extensions.impl.PreBuildMerge;
import hudson.scm.NullSCM;
import hudson.tasks.BuildStepDescriptor;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.Issue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests for {@link GitPublisher}
*
* @author Kohsuke Kawaguchi
*/
public class GitPublisherTest extends AbstractGitTestCase {
@Bug(5005)
public void testMatrixBuild() throws Exception {
final AtomicInteger run = new AtomicInteger(); // count the number of times the perform is called
commit("a", johnDoe, "commit
MatrixProject mp = createMatrixProject("xyz");
mp.setAxes(new AxisList(new Axis("VAR","a","b")));
mp.setScm(new GitSCM(workDir.getAbsolutePath()));
mp.getPublishersList().add(new GitPublisher(
Collections.singletonList(new TagToPush("origin","foo","message",true, false)),
Collections.<BranchToPush>emptyList(),
Collections.<NoteToPush>emptyList(),
true, true, false) {
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
run.incrementAndGet();
try {
return super.perform(build, launcher, listener);
} finally {
// until the 3rd one (which is the last one), we shouldn't create a tag
if (run.get()<3)
assertFalse(existsTag("foo"));
}
}
@Override
public BuildStepDescriptor getDescriptor() {
return (BuildStepDescriptor)Hudson.getInstance().getDescriptorOrDie(GitPublisher.class); // fake
}
private Object writeReplace() { return new NullSCM(); }
});
MatrixBuild b = assertBuildStatusSuccess(mp.scheduleBuild2(0).get());
System.out.println(b.getLog());
assertTrue(existsTag("foo"));
assertTrue(containsTagMessage("foo", "message"));
// twice for MatrixRun, which is to be ignored, then once for matrix completion
assertEquals(3,run.get());
}
public void testMergeAndPush() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null)));
scm.getExtensions().add(new LocalBranch("integration"));
project.setScm(scm);
project.getPublishersList().add(new GitPublisher(
Collections.<TagToPush>emptyList(),
Collections.singletonList(new BranchToPush("origin", "integration")),
Collections.<NoteToPush>emptyList(),
true, true, false));
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
String sha1 = getHeadRevision(build1, "integration");
assertEquals(sha1, testRepo.git.revParse(Constants.HEAD).name());
}
@Issue("JENKINS-24082")
public void testForcePush() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
project.getPublishersList().add(new GitPublisher(
Collections.<TagToPush>emptyList(),
Collections.singletonList(new BranchToPush("origin", "otherbranch")),
Collections.<NoteToPush>emptyList(),
true, true, true));
commit("commitFile", johnDoe, "Initial Commit");
testRepo.git.branch("otherbranch");
testRepo.git.checkout("otherbranch");
commit("otherCommitFile", johnDoe, "commit lost on force push");
testRepo.git.checkout("master");
commit("commitFile2", johnDoe, "commit to be pushed");
ObjectId expectedCommit = testRepo.git.revParse("master");
build(project, Result.SUCCESS, "commitFile");
assertEquals(expectedCommit, testRepo.git.revParse("otherbranch"));
}
/**
* Fix push to remote when skipTag is enabled
*/
@Bug(17769)
public void testMergeAndPushWithSkipTagEnabled() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null, new ArrayList<GitSCMExtension>());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null)));
scm.getExtensions().add(new LocalBranch("integration"));
project.setScm(scm);
project.getPublishersList().add(new GitPublisher(
Collections.<TagToPush>emptyList(),
Collections.singletonList(new BranchToPush("origin", "integration")),
Collections.<NoteToPush>emptyList(),
true, true, false));
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
String sha1 = getHeadRevision(build1, "integration");
assertEquals(sha1, testRepo.git.revParse(Constants.HEAD).name());
}
@Bug(24786)
public void testMergeAndPushWithCharacteristicEnvVar() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
/*
* JOB_NAME seemed like the more obvious choice, but when run from a
* multi-configuration job, the value of JOB_NAME includes an equals
* sign. That makes log parsing and general use of the variable more
* difficult. JENKINS_SERVER_COOKIE is a characteristic env var which
* probably never includes an equals sign.
*/
String envName = "JENKINS_SERVER_COOKIE";
String envValue = project.getCharacteristicEnvVars().get(envName, "NOT-SET");
assertFalse("Env " + envName + " not set", envValue.equals("NOT-SET"));
checkEnvVar(project, envName, envValue);
}
@Bug(24786)
public void testMergeAndPushWithSystemEnvVar() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
String envName = Functions.isWindows() ? "COMPUTERNAME" : "LOGNAME";
String envValue = System.getenv().get(envName);
assertNotNull("Env " + envName + " not set", envValue);
assertFalse("Env " + envName + " empty", envValue.isEmpty());
checkEnvVar(project, envName, envValue);
}
private void checkEnvVar(FreeStyleProject project, String envName, String envValue) throws Exception {
String envReference = "${" + envName + "}";
List<GitSCMExtension> scmExtensions = new ArrayList<GitSCMExtension>();
scmExtensions.add(new PreBuildMerge(new UserMergeOptions("origin", envReference, null)));
scmExtensions.add(new LocalBranch(envReference));
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null, scmExtensions);
project.setScm(scm);
String tagNameReference = envReference + "-tag"; // ${BRANCH_NAME}-tag
String tagNameValue = envValue + "-tag"; // master-tag
String tagMessageReference = envReference + " tag message";
String noteReference = "note for " + envReference;
String noteValue = "note for " + envValue;
GitPublisher publisher = new GitPublisher(
Collections.singletonList(new TagToPush("origin", tagNameReference, tagMessageReference, false, true)),
Collections.singletonList(new BranchToPush("origin", envReference)),
Collections.singletonList(new NoteToPush("origin", noteReference, Constants.R_NOTES_COMMITS, false)),
true, true, true);
assertTrue(publisher.isForcePush());
assertTrue(publisher.isPushBranches());
assertTrue(publisher.isPushMerge());
assertTrue(publisher.isPushNotes());
assertTrue(publisher.isPushOnlyIfSuccess());
assertTrue(publisher.isPushTags());
project.getPublishersList().add(publisher);
// create initial commit
commit("commitFileBase", johnDoe, "Initial Commit");
ObjectId initialCommit = testRepo.git.getHeadRev(testRepo.gitDir.getAbsolutePath(), "master");
assertTrue(testRepo.git.isCommitInRepo(initialCommit));
// Create branch in the test repo (pulled into the project workspace at build)
assertFalse("Test repo has " + envValue + " branch", hasBranch(envValue));
testRepo.git.branch(envValue);
assertTrue("Test repo missing " + envValue + " branch", hasBranch(envValue));
assertFalse(tagNameValue + " in " + testRepo, testRepo.git.tagExists(tagNameValue));
// Build the branch
final FreeStyleBuild build0 = build(project, Result.SUCCESS, "commitFileBase");
String build0HeadBranch = getHeadRevision(build0, envValue);
assertEquals(build0HeadBranch, initialCommit.getName());
assertTrue(tagNameValue + " not in " + testRepo, testRepo.git.tagExists(tagNameValue));
assertTrue(tagNameValue + " not in build", build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists());
// Create a topic branch in the source repository and commit to topic branch
String topicBranch = envValue + "-topic1";
assertFalse("Test repo has " + topicBranch + " branch", hasBranch(topicBranch));
testRepo.git.checkout(null, topicBranch);
assertTrue("Test repo has no " + topicBranch + " branch", hasBranch(topicBranch));
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
ObjectId topicCommit = testRepo.git.getHeadRev(testRepo.gitDir.getAbsolutePath(), topicBranch);
assertTrue(testRepo.git.isCommitInRepo(topicCommit));
// Run a build, should be on the topic branch, tagged, and noted
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
FilePath myWorkspace = build1.getWorkspace();
assertTrue(myWorkspace.child(commitFile1).exists());
assertTrue("Tag " + tagNameValue + " not in build", myWorkspace.child(".git/refs/tags/" + tagNameValue).exists());
String build1Head = getHeadRevision(build1, envValue);
assertEquals(build1Head, testRepo.git.revParse(Constants.HEAD).name());
assertEquals("Wrong head commit in build1", topicCommit.getName(), build1Head);
}
private boolean existsTag(String tag) throws InterruptedException {
Set<String> tags = git.getTagNames("*");
return tags.contains(tag);
}
private boolean containsTagMessage(String tag, String str) throws InterruptedException {
String msg = git.getTagMessage(tag);
return msg.contains(str);
}
private boolean hasBranch(String branchName) throws GitException, InterruptedException {
Set<Branch> testRepoBranches = testRepo.git.getBranches();
for (Branch branch : testRepoBranches) {
if (branch.getName().equals(branchName)) {
return true;
}
}
return false;
}
} |
package org.jmotor.util;
import junit.framework.TestCase;
import org.jmotor.util.meta.Student;
import org.junit.Test;
import java.io.IOException;
public class ObjectUtilitiesTest extends TestCase {
@Test
public void testInvoke() {
Student student = new Student();
ObjectUtilities.invoke(student, "setStuId", "0002");
ObjectUtilities.invoke(student, "show", "0002", "Dog");
System.out.println(student.getStuId());
}
@Test
public void testSerializable() throws IOException, ClassNotFoundException {
Student student = new Student();
student.setStuId("00001");
student.setName("Jobs");
student.setClassName("IT");
String fileName = ObjectUtilities.writeObject(student);
if (StringUtilities.isBlank(fileName)) {
System.out.println("Failure");
} else {
Student readObject = ObjectUtilities.readObject(fileName);
System.out.println(readObject);
}
}
public void test() {
System.out.println(StringUtilities.repeat("?", ",", 5));
}
} |
package org.numenta.nupic.network;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.numenta.nupic.algorithms.Anomaly.KEY_MODE;
import static org.numenta.nupic.algorithms.Anomaly.KEY_USE_MOVING_AVG;
import static org.numenta.nupic.algorithms.Anomaly.KEY_WINDOW_SIZE;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.algorithms.Anomaly;
import org.numenta.nupic.algorithms.Anomaly.Mode;
import org.numenta.nupic.algorithms.CLAClassifier;
import org.numenta.nupic.datagen.ResourceLocator;
import org.numenta.nupic.encoders.MultiEncoder;
import org.numenta.nupic.network.sensor.FileSensor;
import org.numenta.nupic.network.sensor.HTMSensor;
import org.numenta.nupic.network.sensor.ObservableSensor;
import org.numenta.nupic.network.sensor.Publisher;
import org.numenta.nupic.network.sensor.Sensor;
import org.numenta.nupic.network.sensor.SensorParams;
import org.numenta.nupic.network.sensor.SensorParams.Keys;
import org.numenta.nupic.research.SpatialPooler;
import org.numenta.nupic.research.TemporalMemory;
import org.numenta.nupic.util.ArrayUtils;
import org.numenta.nupic.util.MersenneTwister;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func1;
/**
* Tests the "heart and soul" of the Network API
*
* @author DavidRay
*
*/
public class LayerTest {
/** Total used for spatial pooler priming tests */
private int TOTAL = 0;
private int timesWithinThreshold = 0;
private final double THRESHOLD = 7.0E-16;
private int lastSeqNum = 0;
/**
* Resets the warm up detection variable state
*/
private void resetWarmUp() {
this.timesWithinThreshold = 0;
this.lastSeqNum = 0;
}
/**
* Checks the anomaly score against a known threshold which indicates that the
* TM predictions have been "warmed up". When there have been enough occurrences
* within the threshold, we conclude that the algorithms have been adequately
* stabilized.
*
* @param l the {@link Layer} in question
* @param anomalyScore the current anomaly score
* @return
*/
private boolean isWarmedUp(Layer<Map<String, Object>> l, double anomalyScore) {
if(anomalyScore > 0 && anomalyScore < THRESHOLD && (lastSeqNum == 0 || lastSeqNum == l.getRecordNum() - 1)) {
++timesWithinThreshold;
lastSeqNum = l.getRecordNum();
}else{
lastSeqNum = 0;
timesWithinThreshold = 0;
}
if(timesWithinThreshold > 13) {
return true;
}
return false;
}
@Test
public void testMasking() {
byte algo_content_mask = 0;
// -- Build up mask
algo_content_mask |= Layer.CLA_CLASSIFIER;
assertEquals(4, algo_content_mask);
algo_content_mask |= Layer.SPATIAL_POOLER;
assertEquals(5, algo_content_mask);
algo_content_mask |= Layer.TEMPORAL_MEMORY;
assertEquals(7, algo_content_mask);
algo_content_mask |= Layer.ANOMALY_COMPUTER;
assertEquals(15, algo_content_mask);
// -- Now Peel Off
algo_content_mask ^= Layer.ANOMALY_COMPUTER;
assertEquals(7, algo_content_mask);
assertEquals(0, algo_content_mask & Layer.ANOMALY_COMPUTER);
assertEquals(2, algo_content_mask & Layer.TEMPORAL_MEMORY);
algo_content_mask ^= Layer.TEMPORAL_MEMORY;
assertEquals(5, algo_content_mask);
algo_content_mask ^= Layer.SPATIAL_POOLER;
assertEquals(4, algo_content_mask);
algo_content_mask ^= Layer.CLA_CLASSIFIER;
assertEquals(0, algo_content_mask);
}
@Test
public void testGetAllValues() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
// Test that we get the expected exception if there hasn't been any processing.
try {
l.getAllValues("dayOfWeek", 1);
fail();
}catch(Exception e) {
assertEquals("Predictions not available. Either classifiers unspecified or inferencing has not yet begun.", e.getMessage());
}
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(0, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
Object[] values = l.getAllValues("dayOfWeek", 1);
assertNotNull(values);
assertTrue(values.length == 1);
assertEquals(0.0D, values[0]);
}
boolean isHalted = false;
@Test
public void testHalt() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {
assertTrue(l.isHalted());
isHalted = true;
}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
System.out.println("output = " + Arrays.toString(output.getSDR()));
}
});
try {
l.halt();
l.getLayerThread().join();
assertTrue(isHalted);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
int trueCount = 0;
@Test
public void testReset() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-4reset.csv")));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
if(l.getSensor().getMetaInfo().isReset()) {
trueCount++;
}
}
});
try {
l.getLayerThread().join();
assertEquals(3, trueCount);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
int seqResetCount = 0;
@Test
public void testSequenceChangeReset() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-4seqReset.csv")));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
if(l.getSensor().getMetaInfo().isReset()) {
seqResetCount++;
}
}
});
try {
l.getLayerThread().join();
assertEquals(3, seqResetCount);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testLayerWithObservableInput() {
Publisher manual = Publisher.builder()
.addHeader("timestamp,consumption")
.addHeader("datetime,float")
.addHeader("B")
.build();
Sensor<ObservableSensor<String[]>> sensor = Sensor.create(
ObservableSensor::create,
SensorParams.create(
Keys::obs, new Object[] {"name", manual}));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<ObservableSensor<String[]>> htmSensor = (HTMSensor<ObservableSensor<String[]>>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
int idx = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
switch(idx) {
case 0: assertEquals("[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]", Arrays.toString(output.getSDR()));
break;
case 1: assertEquals("[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]", Arrays.toString(output.getSDR()));
break;
case 2: assertEquals("[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]", Arrays.toString(output.getSDR()));
break;
}
++idx;
}
});
try {
String[] entries = {
"7/2/10 0:00,21.2",
"7/2/10 1:00,34.0",
"7/2/10 2:00,40.4",
};
// Send inputs through the observable
for(String s : entries) {
manual.onNext(s);
}
Thread.sleep(100);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testLayerWithGenericObservable() {
Parameters p = NetworkTestHarness.getParameters();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
Func1<ManualInput, ManualInput> addedFunc = l -> {
return l.customObject("Interposed: " + Arrays.toString(l.getSDR()));
};
Network n = Network.create("Generic Test", p)
.add(Network.createRegion("R1")
.add(Network.createLayer("L1", p)
.add(addedFunc)
.add(new SpatialPooler())));
@SuppressWarnings("unchecked")
Layer<int[]> l = (Layer<int[]>)n.lookup("R1").lookup("L1");
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, i.getSDR()));
assertEquals("Interposed: [1, 1, 0, 0, 0, 0, 0, 1]", i.getCustomObject());
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, i.getSDR()));
assertEquals("Interposed: [1, 1, 1, 0, 0, 0, 0, 0]", i.getCustomObject());
}
++test;
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
@Test
public void testBasicSetupEncoder_UsingSubscribe() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);
final int[][] expected = new int[7][8];
expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
l.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
Map<String, Object> inputs = new HashMap<String, Object>();
for(double i = 0;i < 7;i++) {
inputs.put("dayOfWeek", i);
l.compute(inputs);
}
}
@Test
public void testBasicSetupEncoder_UsingObserve() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);
final int[][] expected = new int[7][8];
expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
Observable<Inference> o = l.observe();
o.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
Map<String, Object> inputs = new HashMap<String, Object>();
for(double i = 0;i < 7;i++) {
inputs.put("dayOfWeek", i);
l.compute(inputs);
}
}
@Test
public void testBasicSetupEncoder_AUTO_MODE() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
int[][] expected = new int[][] {
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}
};
l.start();
// Test with 2 subscribers //
l.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
// System.out.println("output = " + Arrays.toString(output.getSDR()));
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
l.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
// System.out.println("output2 = " + Arrays.toString(output.getSDR()));
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
try {
l.getLayerThread().join();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* Temporary test to test basic sequence mechanisms
*/
@Test
public void testBasicSetup_SpatialPooler_MANUAL_MODE() {
Parameters p = NetworkTestHarness.getParameters();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference spatialPoolerOutput) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
}
++test;
}
});
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
/**
* Temporary test to test basic sequence mechanisms
*/
@Test
public void testBasicSetup_SpatialPooler_AUTO_MODE() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("days-of-week.csv")));
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
Layer<int[]> l = new Layer<>(n);
l.add(htmSensor).add(new SpatialPooler());
l.start();
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference spatialPoolerOutput) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
}
++test;
}
});
try {
l.getLayerThread().join();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* Temporary test to test basic sequence mechanisms
*/
@Test
public void testBasicSetup_TemporalMemory_MANUAL_MODE() {
Parameters p = NetworkTestHarness.getParameters();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
final int[] input1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] input2 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
final int[] input3 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
final int[] input4 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
final int[] input5 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
final int[] input6 = new int[] { 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] input7 = new int[] { 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 };
final int[][] inputs = { input1, input2, input3, input4, input5, input6, input7 };
int[] expected1 = { 1, 5, 11, 12, 13 };
int[] expected2 = { 2, 3, 11, 12, 13, 14 };
int[] expected3 = { 2, 3, 8, 9, 12, 17, 18 };
int[] expected4 = { 1, 2, 3, 5, 7, 8, 11, 12, 16, 17, 18 };
int[] expected5 = { 2, 7, 8, 9, 17, 18, 19 };
int[] expected6 = { 1, 7, 8, 9, 17, 18 };
int[] expected7 = { 1, 5, 7, 11, 12, 16 };
final int[][] expecteds = { expected1, expected2, expected3, expected4, expected5, expected6, expected7 };
Layer<int[]> l = new Layer<>(p, null, null, new TemporalMemory(), null, null);
int timeUntilStable = 415;
l.subscribe(new Observer<Inference>() {
int test = 0;
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference output) {
if(seq / 7 >= timeUntilStable) {
//System.out.println("seq: " + (seq) + " --> " + (test) + " output = " + Arrays.toString(output.getSDR()));
assertTrue(Arrays.equals(expecteds[test], output.getSDR()));
}
if(test == 6) test = 0;
else test++;
seq++;
}
});
// Now push some fake data through so that "onNext" is called above
for(int j = 0;j < timeUntilStable;j++) {
for(int i = 0;i < inputs.length;i++) {
l.compute(inputs[i]);
}
}
for(int j = 0;j < 2;j++) {
for(int i = 0;i < inputs.length;i++) {
l.compute(inputs[i]);
}
}
}
@Test
public void testBasicSetup_SPandTM() {
Parameters p = NetworkTestHarness.getParameters();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), null, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) {}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(0, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
@Test
public void testSpatialPoolerPrimerDelay() {
Parameters p = NetworkTestHarness.getParameters();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
// First test without prime directive :-P
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, i.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, i.getSDR()));
}
++test;
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
// NOW TEST WITH prime directive
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42)); // due to static RNG we have to reset the sequence
p.setParameterByKey(KEY.SP_PRIMER_DELAY, 1);
Layer<int[]> l2 = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l2.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
// should be one and only onNext() called
assertTrue(Arrays.equals(expected1, i.getSDR()));
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l2.compute(inputs[0]);
l2.compute(inputs[1]);
}
/**
* Simple test to verify data gets passed through the {@link CLAClassifier}
* configured within the chain of components.
*/
@Test
public void testBasicClassifierSetup() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(0, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
}
/**
* The {@link SpatialPooler} sometimes needs to have data run through it
* prior to passing the data on to subsequent algorithmic components. This
* tests the ability to specify exactly the number of input records for
* the SpatialPooler to consume before passing records on.
*/
@Test
public void testMoreComplexSpatialPoolerPriming() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 20;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT, TOTAL);
}
/**
* Tests the ability for multiple subscribers to receive copies of
* a given {@link Layer}'s computed values.
*/
@Test
public void test2ndAndSubsequentSubscribersPossible() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 50;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
int NUM_SUBSCRIBERS = 3;
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals( ((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT) * NUM_SUBSCRIBERS, TOTAL);
}
boolean testingAnomaly;
double highestAnomaly = 0;
/**
* <p>
* Complex test that tests the Anomaly function automatically being setup and working.
* To test this, we do the following:
* </p><p>
* <ol>
* <li>Reset the warm up state vars</li>
* <li>Warm up prediction inferencing - make sure predictions are trained</li>
* <li>Throw in an anomalous record</li>
* <li>Test to make sure the Layer detects the anomaly, and that it is significantly registered</li>
* </ol>
* </p>
*/
@Test
public void testAnomalySetup() {
TOTAL = 0;
// Reset warm up detection state
resetWarmUp();
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 10;
final int INPUT_GROUP_COUNT = 7; // Days of Week
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
Map<String, Object> params = new HashMap<>();
params.put(KEY_MODE, Mode.PURE);
params.put(KEY_WINDOW_SIZE, 3);
params.put(KEY_USE_MOVING_AVG, true);
Anomaly anomalyComputer = Anomaly.create(params);
final Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(),
Boolean.TRUE, anomalyComputer);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
TOTAL++;
assertNotNull(i);
if(testingAnomaly) {
//System.out.println("tested anomaly = " + i.getAnomalyScore());
if(i.getAnomalyScore() > highestAnomaly) highestAnomaly = i.getAnomalyScore();
}
// System.out.println("prev predicted = " + Arrays.toString(l.getPreviousPredictedColumns()));
// System.out.println("current active = " + Arrays.toString(l.getActiveColumns()));
// System.out.println("rec# " + i.getRecordNum() + ", input " + i.getLayerInput() + ", anomaly = " + i.getAnomalyScore() + ", inference = " + l.getInference());
}
});
// Warm up so that we can have a baseline to detect an anomaly
Map<String, Object> multiInput = new HashMap<>();
boolean isWarmedUp = false;
while(l.getInference() == null || !isWarmedUp) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
if(l.getInference() != null && isWarmedUp(l, l.getInference().getAnomalyScore())) {
isWarmedUp = true;
}
}
}
// Now throw in an anomaly and see if it is detected.
boolean exit = false;
for(int i = 0;!exit && i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
if(i == 2) {
testingAnomaly = true;
multiInput.put("dayOfWeek", j+=0.5);
l.compute(multiInput);
exit = true;
//break;
}else{
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
}
// Now assert we detected anomaly greater than average and significantly greater than 0 (i.e. 20%)
//System.out.println("highestAnomaly = " + highestAnomaly);
assertTrue(highestAnomaly > 0.2);
}
@Test
public void testGetAllPredictions() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 200;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
final Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
// UNCOMMENT TO VIEW STABILIZATION OF PREDICTED FIELDS
// System.out.println("Day: " + ((Map<String, Object>)i.getLayerInput()).get("dayOfWeek") + " - " + Arrays.toString(ArrayUtils.where(l.getActiveColumns(), ArrayUtils.WHERE_1)) +
// " - " + Arrays.toString(l.getPreviousPredictedColumns()));
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT, TOTAL);
double[] all = l.getAllPredictions("dayOfWeek", 1);
double highestVal = Double.NEGATIVE_INFINITY;
int highestIdx = -1;
int i = 0;
for(double d : all) {
if(d > highestVal) {
highestIdx = i;
highestVal = d;
}
i++;
}
assertEquals(highestIdx, l.getMostProbableBucketIndex("dayOfWeek", 1));
assertEquals(7, l.getAllPredictions("dayOfWeek", 1).length);
assertTrue(Arrays.equals(ArrayUtils.where(l.getActiveColumns(), ArrayUtils.WHERE_1), l.getPreviousPredictedColumns()));
}
/**
* Test that a given layer can return an {@link Observable} capable of
* service multiple subscribers.
*/
@Test
public void testObservableRetrieval() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
final Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
final List<int[]> emissions = new ArrayList<int[]>();
Observable<Inference> o = l.observe();
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getActiveColumns());
}
});
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getActiveColumns());
}
});
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getActiveColumns());
}
});
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
assertEquals(3, emissions.size());
int[] e1 = emissions.get(0);
for(int[] ia : emissions) {
assertTrue(ia == e1);//test same object propagated
}
}
/**
* Simple test to verify data gets passed through the {@link CLAClassifier}
* configured within the chain of components.
*/
boolean flowReceived = false;
@Test
public void testFullLayerFluentAssembly() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
p.setParameterByKey(KEY.POTENTIAL_RADIUS, 200);
p.setParameterByKey(KEY.INHIBITION_RADIUS, 50);
p.setParameterByKey(KEY.GLOBAL_INHIBITIONS, true);
System.out.println(p);
Map<String, Object> params = new HashMap<>();
params.put(KEY_MODE, Mode.PURE);
params.put(KEY_WINDOW_SIZE, 3);
params.put(KEY_USE_MOVING_AVG, true);
Anomaly anomalyComputer = Anomaly.create(params);
Layer<?> l = Network.createLayer("TestLayer", p)
.alterParameter(KEY.AUTO_CLASSIFY, true)
.add(anomalyComputer)
.add(new TemporalMemory())
.add(new SpatialPooler())
.add(Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv"))));
l.getConnections().printParameters();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
if(flowReceived) return; // No need to set this value multiple times
System.out.println("classifier size = " + i.getClassifiers().size());
flowReceived = i.getClassifiers().size() == 4 &&
i.getClassifiers().get("timestamp") != null &&
i.getClassifiers().get("consumption") != null;
}
});
l.start();
try {
l.getLayerThread().join();
assertTrue(flowReceived);
}catch(Exception e) {
e.printStackTrace();
}
}
} |
package org.apache.commons.lang;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.lang.builder.BuilderTestSuite;
import org.apache.commons.lang.enum.EnumTestSuite;
import org.apache.commons.lang.exception.ExceptionTestSuite;
import org.apache.commons.lang.math.MathTestSuite;
import org.apache.commons.lang.time.TimeTestSuite;
/**
* Test suite for [lang].
*
* @author Stephen Colebourne
* @version $Id: AllLangTestSuite.java,v 1.3 2003/08/19 02:38:56 bayard Exp $
*/
public class AllLangTestSuite extends TestCase {
/**
* Construct a new instance.
*/
public AllLangTestSuite(String name) {
super(name);
}
/**
* Command-line interface.
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* Get the suite of tests
*/
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("Commons-Lang (all) Tests");
suite.addTest(LangTestSuite.suite());
suite.addTest(BuilderTestSuite.suite());
suite.addTest(EnumTestSuite.suite());
suite.addTest(ExceptionTestSuite.suite());
suite.addTest(MathTestSuite.suite());
suite.addTest(TimeTestSuite.suite());
return suite;
}
} |
package ru.cfuv.ieu.phonebook;
import ru.cfuv.ieu.phonebook.model.PhonebookContact;
import ru.cfuv.ieu.phonebook.model.PhonebookNumber;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PhonebookRepository {
private Connection connection;
public PhonebookRepository() {
try {
connection = DriverManager.getConnection("jdbc:sqlite:" +
"phonebook.db");
connection.setAutoCommit(false);
setup();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void setup() {
try {
if (execute("select count(*) from sqlite_master where" +
" type = 'table' and name != 'sqlite_sequence';")
.getInt(1) == 0) {
executeUpdate("create table contacts " +
"(id integer primary key autoincrement," +
"name varchar(255))");
executeUpdate("create table numbers " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT," +
"number varchar(255))");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void cleanup() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private ResultSet execute(String query) {
try {
Statement stmt = connection.createStatement();
return stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private void executeUpdate(String query) {
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateName(PhonebookContact contact, String name) {
try {
PreparedStatement stmt = connection.prepareStatement(
"update contacts set name = ? where id = ?");
stmt.setString(1, name);
stmt.setInt(2, contact.getId());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addNumber(PhonebookContact contact, PhonebookNumber number) {
try {
PreparedStatement stmt = connection.prepareStatement(
"insert into numbers (contact, number) values (?, ?)");
stmt.setInt(1, contact.getId());
stmt.setString(2, number.getNumber());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void removeNumber(PhonebookContact contact, PhonebookNumber number) {
try {
PreparedStatement stmt = connection.prepareStatement(
"delete from numbers where contact = ? and number = ?");
stmt.setInt(1, contact.getId());
stmt.setString(2, number.getNumber());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<PhonebookContact> getContacts() {
List<PhonebookContact> contacts = new ArrayList<>();
ResultSet resContacts = execute("select * from contacts");
try {
while (resContacts.next()) {
int id = resContacts.getInt(1);
String name = resContacts.getString(2);
List<PhonebookNumber> numbers = new ArrayList<>();
ResultSet resNumbers = execute("select * from numbers where" +
" contact = " + id);
while (resNumbers.next()) {
numbers.add(new PhonebookNumber(resNumbers.getString(3)));
}
resNumbers.close();
PhonebookContact contact = new PhonebookContact(this, id, name,
numbers);
contacts.add(contact);
}
resContacts.close();
} catch (SQLException e) {
e.printStackTrace();
}
return contacts;
}
public void addContact(String name, String snumber) {
PhonebookNumber number = new PhonebookNumber(snumber);
addContact(name, new ArrayList<>(Collections.singletonList(number)));
}
public void addContact(String name, List<PhonebookNumber> numbers) {
try {
PreparedStatement insert = connection.prepareStatement(
"insert into contacts (name) values (?)");
insert.setString(1, name);
insert.executeUpdate();
int rowid = execute("select last_insert_rowid()").getInt(1);
for (PhonebookNumber number : numbers) {
PreparedStatement insert2 = connection.prepareStatement(
"insert into numbers (contact, number) values (?, ?)");
insert2.setInt(1, rowid);
insert2.setString(2, number.getNumber());
insert2.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
package org.atlasapi.topic;
import java.util.Map;
import org.atlasapi.content.Described;
import org.atlasapi.entity.Aliased;
import org.atlasapi.entity.Id;
import org.atlasapi.entity.Sourced;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.meta.annotations.FieldName;
import com.metabroadcast.common.collect.ImmutableOptionalMap;
import com.metabroadcast.common.collect.OptionalMap;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
public class Topic extends Described implements Sourced, Aliased {
private Type type;
private String namespace;
private String value;
public enum Type {
SUBJECT("subject"),
PERSON("person"),
PLACE("place"),
ARTIST("artist"),
EVENT("event"),
PRODUCT("product"),
WORK("work"),
GENRE("genre"),
LABEL("label"),
UNKNOWN("unknown");
private final String key;
Type(String key) {
this.key = key;
}
@FieldName("key")
public String key() {
return key;
}
@Override
public String toString() {
return key;
}
@Deprecated
public static Map<String, Type> TYPE_KEY_LOOKUP = Maps.uniqueIndex(
ImmutableSet.copyOf(Type.values()),
new Function<Type, String>() {
@Override
public String apply(Type input) {
return input.key;
}
}
);
private static final Function<Type, String> TO_KEY =
new Function<Type, String>() {
@Override
public String apply(Type input) {
return input.key();
}
};
public static final Function<Type, String> toKey() {
return TO_KEY;
}
private static final ImmutableSet<Type> ALL =
ImmutableSet.copyOf(Type.values());
public static final ImmutableSet<Type> all() {
return ALL;
}
private static final OptionalMap<String, Type> INDEX =
ImmutableOptionalMap.fromMap(Maps.uniqueIndex(all(), toKey()));
private static final Function<String, Optional<Type>> FROM_KEY =
Functions.forMap(INDEX);
public static final Function<String, Optional<Type>> fromKey() {
return FROM_KEY;
}
public static Type fromKey(String key) {
return INDEX.get(key).orNull();
}
public static Type fromKey(String key, Type deflt) {
return INDEX.get(key).or(deflt);
}
}
public Topic() {
this(null, null, null);
}
public Topic(long id) {
this(Id.valueOf(id), null, null);
}
public Topic(Id id) {
this(id, null, null);
}
public Topic(Id id, String namespace, String value) {
setId(id);
setMediaType(null);
this.namespace = namespace;
this.value = value;
}
public TopicRef toRef() {
return new TopicRef(getId(), getSource());
}
public static Topic copyTo(Topic from, Topic to) {
Described.copyTo(from, to);
to.type = from.type;
to.namespace = from.namespace;
to.value = from.value;
return to;
}
@Override public <T extends Described> T copyTo(T to) {
if (to instanceof Topic) {
copyTo(this, (Topic) to);
return to;
}
return super.copyTo(to);
}
@Override public Topic copy() {
return copyTo(this, new Topic());
}
@Override
public Topic createNew() {
return new Topic();
}
@FieldName("type")
public Type getType() {
return this.type;
}
@FieldName("namespace")
@Deprecated
public String getNamespace() {
return this.namespace;
}
@FieldName("value")
@Deprecated
public String getValue() {
return this.value;
}
public void setType(Type type) {
this.type = type;
}
@Deprecated
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Deprecated
public void setValue(String value) {
this.value = value;
}
} |
package org.jimmutable.storage;
import org.jimmutable.core.objects.common.Kind;
import org.jimmutable.core.objects.common.ObjectId;
import org.jimmutable.core.serialization.Format;
/**
* CODE REVIEW
*
* Code needs javadoc
*
* Follow spacing conventions
*
* @author kanej
*
*/
public abstract class Storable {
abstract public Kind getSimpleKind();
abstract public ObjectId getSimpleObjectId();
abstract public String serialize(Format format);
public StorageKey createStorageKey() {
return new StorageKey(getSimpleKind(), getSimpleObjectId(), StorageKeyExtension.XML);
}
} |
package soot.dex.instructions;
import java.util.HashSet;
import java.util.Set;
import org.jf.dexlib.TypeIdItem;
import org.jf.dexlib.Code.Instruction;
import org.jf.dexlib.Code.InstructionWithReference;
import org.jf.dexlib.Code.TwoRegisterInstruction;
import org.jf.dexlib.Code.Format.Instruction22c;
import soot.ArrayType;
import soot.Local;
import soot.Type;
import soot.Value;
import soot.dex.Debug;
import soot.dex.DexBody;
import soot.dex.DexType;
import soot.dex.DvkTyper;
import soot.jimple.AssignStmt;
import soot.jimple.Jimple;
import soot.jimple.NewArrayExpr;
import soot.jimple.internal.JAssignStmt;
public class NewArrayInstruction extends DexlibAbstractInstruction {
public NewArrayInstruction (Instruction instruction, int codeAdress) {
super(instruction, codeAdress);
}
public void jimplify (DexBody body) {
if(!(instruction instanceof Instruction22c))
throw new IllegalArgumentException("Expected Instruction22c but got: "+instruction.getClass());
Instruction22c newArray = (Instruction22c)instruction;
int dest = newArray.getRegisterA();
Value size = body.getRegisterLocal(newArray.getRegisterB());
Type t = DexType.toSoot((TypeIdItem) newArray.getReferencedItem());
// NewArrayExpr needs the ElementType as it increases the array dimension by 1
Type arrayType = ((ArrayType) t).getElementType();
Debug.printDbg("array element type: "+ arrayType);
NewArrayExpr newArrayExpr = Jimple.v().newNewArrayExpr(arrayType, size);
Local l = body.getRegisterLocal(dest);
AssignStmt assign = Jimple.v().newAssignStmt(l, newArrayExpr);
defineBlock(assign);
tagWithLineNumber(assign);
body.add(assign);
if (DvkTyper.ENABLE_DVKTYPER) {
int op = (int)instruction.opcode.value;
body.captureAssign((JAssignStmt)assign, op); // TODO: ref. type may be null!
}
}
@Override
boolean overridesRegister(int register) {
TwoRegisterInstruction i = (TwoRegisterInstruction) instruction;
int dest = i.getRegisterA();
return register == dest;
}
@Override
public Set<DexType> introducedTypes() {
InstructionWithReference i = (InstructionWithReference) instruction;
Set<DexType> types = new HashSet<DexType>();
types.add(new DexType((TypeIdItem) i.getReferencedItem()));
return types;
}
} |
package com.boundary.sdk;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QueueRouteTest extends CamelSpringTestSupport {
public static int DEFAULT_MESSAGES_SENT=17;
private static final String IN_URI="seda:testinQueueIn";
private static final String OUT_URI="mock:testingMockOut";
@Produce(uri = IN_URI)
private ProducerTemplate producerTemplate;
@EndpointInject(uri = OUT_URI)
private MockEndpoint mockOut;
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("META-INF/boundary-event-to-json.xml");
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
// TBD: Provide shutdown strategy where the thread does not give up
CamelContext context = context();
QueueRouteBuilder q = new QueueRouteBuilder();
q.setFromUri(IN_URI);
q.setToUri(OUT_URI);
q.setQueueName("TESTING");
return q;
}
@Test
public void testSendOneEvent() throws Exception {
mockOut.setExpectedMessageCount(10);
RawEvent event = RawEvent.getDefaultEvent();
event.setTitle("TEST EVENT");
for (int i = DEFAULT_MESSAGES_SENT ; i != 0 ; i
producerTemplate.sendBody(event);
Thread.sleep(10);
}
mockOut.await(60,TimeUnit.SECONDS);
assertMockEndpointsSatisfied();
}
} |
package com.ctrip.ops.sysdev;
import com.ctrip.ops.sysdev.filters.GeoIP2;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TestGeoIP2 {
@Test
public void testGeoIP2() throws Exception {
File f = new File("/tmp/GeoLite2-City.mmdb");
if (!f.exists() || f.isDirectory()) {
throw new Exception("please put /tmp/GeoLite2-City.mmdb and then test");
}
HashMap config = new HashMap() {
{
put("source", "clientip");
put("database", "/tmp/GeoLite2-City.mmdb");
}
};
GeoIP2 geoip2Filter = new GeoIP2(config);
Map event = new HashMap();
event.put("clientip", "61.240.136.69");
event = geoip2Filter.process(event);
Assert.assertEquals(((Map) event.get("geoip")).get("country_name"), "China");
Assert.assertEquals(((Map) event.get("geoip")).get("country_code"), "CN");
Assert.assertEquals(((Map) event.get("geoip")).get("country_isocode"), "CN");
Assert.assertNull(((Map) event.get("geoip")).get("subdivision_name"));
Assert.assertNull(((Map) event.get("geoip")).get("city_name"));
event = new HashMap();
event.put("clientip", "115.239.211.112");
event = geoip2Filter.process(event);
Assert.assertEquals(((Map) event.get("geoip")).get("country_name"), "China");
Assert.assertEquals(((Map) event.get("geoip")).get("country_code"), "CN");
Assert.assertEquals(((Map) event.get("geoip")).get("country_isocode"), "CN");
Assert.assertEquals(((Map) event.get("geoip")).get("city_name"), "Hangzhou");
Assert.assertEquals(((Map) event.get("geoip")).get("subdivision_name"), "Zhejiang");
Assert.assertEquals(((Map) event.get("geoip")).get("longitude"), 120.1614);
Assert.assertEquals(((Map) event.get("geoip")).get("latitude"), 30.2936);
event = new HashMap();
event.put("clientip", "10.10.10.10");
event = geoip2Filter.process(event);
Assert.assertNull(event.get("geoip"));
Assert.assertEquals(((ArrayList) event.get("tags")).get(0), "geoipfail");
config = new HashMap() {
{
put("source", "clientip");
put("database", "/tmp/GeoLite2-City.mmdb");
put("country_code", false);
put("latitude", false);
put("longitude", false);
}
};
geoip2Filter = new GeoIP2(config);
event = new HashMap();
event.put("clientip", "115.239.211.112");
event = geoip2Filter.process(event);
Assert.assertEquals(((Map) event.get("geoip")).get("country_name"), "China");
Assert.assertEquals(((Map) event.get("geoip")).get("country_isocode"), "CN");
Assert.assertEquals(((Map) event.get("geoip")).get("city_name"), "Hangzhou");
Assert.assertEquals(((Map) event.get("geoip")).get("subdivision_name"), "Zhejiang");
Assert.assertNull(((Map) event.get("geoip")).get("country_code"));
Assert.assertNull(((Map) event.get("geoip")).get("latitude"));
Assert.assertNull(((Map) event.get("geoip")).get("longitude"));
Assert.assertEquals(((double[]) ((Map) event.get("geoip")).get("location"))[0], 120.1614);
Assert.assertEquals(((double[]) ((Map) event.get("geoip")).get("location"))[1], 30.2936);
f = new File("/tmp/GeoLite2-Country.mmdb");
if (f.exists() && !f.isDirectory()) {
config = new HashMap() {
{
put("source", "clientip");
put("database", "/tmp/GeoLite2-Country.mmdb");
}
};
geoip2Filter = new GeoIP2(config);
event = new HashMap();
event.put("clientip", "115.239.211.112");
event = geoip2Filter.process(event);
Assert.assertEquals(((Map) event.get("geoip")).get("country_name"), "China");
Assert.assertEquals(((Map) event.get("geoip")).get("country_code"), "CN");
Assert.assertEquals(((Map) event.get("geoip")).get("country_isocode"), "CN");
Assert.assertNull(((Map) event.get("geoip")).get("city_name"));
}
}
} |
package com.jcabi.github;
import com.jcabi.aspects.Tv;
import java.util.Iterator;
import org.apache.commons.lang3.NotImplementedException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test case for {@link RtSearch}.
*
* @author Carlos Miranda (miranda.cma@gmail.com)
* @version $Id$
* @checkstyle MultipleStringLiterals (41 lines)
*/
public final class RtSearchITCase {
/**
* RtSearch can search for repos.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForRepos() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().repos("repo", "stars", "desc"),
Matchers.not(Matchers.emptyIterableOf(Repo.class))
);
}
/**
* RtSearch can fetch multiple pages of a large result (more than 25 items).
*
* @throws Exception if a problem occurs
*/
@Test
public void canFetchMultiplePages() throws Exception {
final Iterator<Repo> iter = RtSearchITCase.github().search().repos(
"java", "", ""
).iterator();
int count = 0;
while (iter.hasNext() && count < Tv.HUNDRED) {
iter.next();
count += 1;
}
MatcherAssert.assertThat(
count,
Matchers.greaterThanOrEqualTo(Tv.HUNDRED)
);
}
/**
* RtSearch can search for issues.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForIssues() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().issues("issue", "updated", "desc"),
Matchers.not(Matchers.emptyIterableOf(Issue.class))
);
}
/**
* RtSearch can search for users.
*
* @throws Exception if a problem occurs
*/
@Test
public void canSearchForUsers() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().users("jcabi", "joined", "desc"),
Matchers.not(Matchers.emptyIterableOf(User.class))
);
}
@Test
public void canSearchForContents() throws Exception {
MatcherAssert.assertThat(
RtSearchITCase.github().search().codes("addClass repo:jquery/jquery", "joined", "desc"),
Matchers.not(Matchers.emptyIterableOf(Content.class))
);
}
/**
* Return github for test.
* @return Github
*/
private static Github github() {
final String key = System.getProperty("failsafe.github.key");
Assume.assumeThat(key, Matchers.notNullValue());
return new RtGithub(key);
}
} |
package com.senac.petshop.rn;
import com.senac.petshop.bean.Dono;
import java.util.Date;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
*
* @author lossurdo
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DonoRNTest {
private Dono dono = null;
@Before
public void init() {
dono = new Dono(99999);
dono.setCpf("9999888855");
dono.setNome("Anna Faris");
dono.setDataNascimento(new Date());
dono.setEmail("anna.f@gmail.com");
dono.setTelefoneCelular("5559999");
}
@Test
public void test_A_Salvar() {
System.out.println("salvar");
DonoRN rn = new DonoRN();
rn.salvar(dono);
Assert.assertNotNull(rn.consultar(dono));
}
@Test
public void test_B_Consultar() {
System.out.println("consultar");
DonoRN rn = new DonoRN();
Assert.assertNull(rn.consultar(new Dono(22222)));
}
@Test
public void test_C_Pesquisar() {
System.out.println("pesquisar");
DonoRN rn = new DonoRN();
Set<Dono> resultado = rn.pesquisar("maria");
Assert.assertTrue(resultado.size()>0);
}
} |
package core.time;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
public class DateTimeFormatterTest {
@Test
public void formatDate() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate date = LocalDate.of(2015, Month.OCTOBER, 30);
// Format date from formatter or from date
assertEquals(formatter.format(date), "2015-10-30");
assertEquals(date.format(formatter), "2015-10-30");
}
@Test
public void formatTime() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime time = LocalTime.of(10, 30, 15, 1000);
// Format time from formatter or from time
assertEquals(formatter.format(time), "10:30:15.000001");
assertEquals(time.format(formatter), "10:30:15.000001");
}
@Test
public void formatDateTime() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.of(2015, Month.OCTOBER, 30, 10, 30, 15, 1000);
// Format dateTime from formatter or from dateTime
assertEquals(formatter.format(dateTime), "2015-10-30T10:30:15.000001");
assertEquals(dateTime.format(formatter), "2015-10-30T10:30:15.000001");
}
@Test
public void parseDate() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
assertEquals(LocalDate.parse("2015-10-30", formatter), LocalDate.of(2015, Month.OCTOBER, 30));
}
@Test
public void parseTime() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
assertEquals(LocalTime.parse("10:30:15", formatter), LocalTime.of(10, 30, 15));
}
@Test
public void parseDateTime() {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.of(2015, Month.OCTOBER, 30, 10, 30, 15);
assertEquals(LocalDateTime.parse("2015-10-30T10:30:15", formatter), dateTime);
}
@Test
public void formatDateWithCustomFormatter() {
LocalDate date = LocalDate.of(2016, Month.JANUARY, 1);
checkDateCustomFormatter(date, "yy/M/d", "16/1/1");
checkDateCustomFormatter(date, "yy/M/dd", "16/1/01");
checkDateCustomFormatter(date, "yy/MM/dd", "16/01/01");
checkDateCustomFormatter(date, "yyyy/MMM/dd", "2016/Jan/01");
}
private void checkDateCustomFormatter(LocalDate date, String pattern, String expected) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.US);
assertEquals(date.format(formatter), expected);
}
@Test
public void formatTimeWithCustomFormatter() {
LocalTime time = LocalTime.of(1, 5, 5, 1000);
checkCustomTimeFormatter(time, "h:m:s", "1:5:5");
checkCustomTimeFormatter(time, "h:m:ss", "1:5:05");
checkCustomTimeFormatter(time, "h:mm:ss", "1:05:05");
checkCustomTimeFormatter(time, "hh:mm:ss", "01:05:05");
checkCustomTimeFormatter(time, "hh:mm:ss.SSS", "01:05:05.000");
checkCustomTimeFormatter(time, "hh:mm:ss.SSSSSS", "01:05:05.000001");
}
private void checkCustomTimeFormatter(LocalTime time, String pattern, String expected) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.US);
assertEquals(time.format(formatter), expected);
}
@Test
public void formatDateTimeWithCustomFormatter() {
LocalDateTime dateTime = LocalDateTime.of(2016, Month.JANUARY, 1, 1, 5, 5, 1000);
checkCustomDateTimeFormatter(dateTime, "yy/M/d h:m:s", "16/1/1 1:5:5");
checkCustomDateTimeFormatter(dateTime, "yy/M/d h:m:ss", "16/1/1 1:5:05");
checkCustomDateTimeFormatter(dateTime, "yy/M/d h:mm:ss", "16/1/1 1:05:05");
checkCustomDateTimeFormatter(dateTime, "yy/M/d hh:mm:ss", "16/1/1 01:05:05");
checkCustomDateTimeFormatter(dateTime, "yy/M/dd hh:mm:ss", "16/1/01 01:05:05");
checkCustomDateTimeFormatter(dateTime, "yy/MM/dd hh:mm:ss", "16/01/01 01:05:05");
checkCustomDateTimeFormatter(dateTime, "yy/MMM/dd hh:mm:ss", "16/Jan/01 01:05:05");
checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss", "2016/Jan/01 01:05:05");
checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss.SSS", "2016/Jan/01 01:05:05.000");
checkCustomDateTimeFormatter(dateTime, "yyyy/MMM/dd hh:mm:ss.SSSSSS", "2016/Jan/01 01:05:05.000001");
}
private void checkCustomDateTimeFormatter(LocalDateTime dateTime, String pattern, String expected) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.US);
assertEquals(dateTime.format(formatter), expected);
}
} |
package examples.session;
import com.vtence.molecule.Application;
import com.vtence.molecule.Response;
import com.vtence.molecule.WebServer;
import com.vtence.molecule.middlewares.CookieSessionTracker;
import com.vtence.molecule.middlewares.Cookies;
import com.vtence.molecule.routing.DynamicRoutes;
import com.vtence.molecule.session.CookieSessionStore;
import com.vtence.molecule.session.Session;
import java.io.IOException;
import java.time.Clock;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.MINUTES;
/**
* Here's an example of setting up HTTP sessions. We use a a signed cookie store but you could very well
* swap the pool implementation for, e.g. an in memory session pool.
* <p>
* <p>
* Each client is given a secure session identifier, stored as session cookie.
* If the client request it, we make the cookie persistent (for 5 min).
* Every time the session is accessed, we refresh the client cookie expiry date.
* </p>
* <p>
* The session pool expires stale sessions after 30 minutes.
* As a protection mechanism, we also expire sessions that are older than 2 days,
* even if they have been maintained active.
* </p>
*/
public class SessionExample {
private static final int FIVE_MINUTES = (int) MINUTES.toSeconds(5);
private static final int THIRTY_MINUTES = (int) MINUTES.toSeconds(30);
private static final int TWO_DAYS = (int) DAYS.toSeconds(2);
private final Clock clock;
public SessionExample(Clock clock) {
this.clock = clock;
}
public void run(WebServer server) throws IOException {
// Create a cookie based session store - session content is stored on the client
// Our secret key for encrypting sessions will be "secret"
CookieSessionStore sessions = CookieSessionStore.secure("secret");
// Alternatively, you could use an in-memory session pool like this:
// SessionPool sessions = SessionPool.secure();
// Invalidate stale sessions after 30 minutes
sessions.idleTimeout(THIRTY_MINUTES);
// Invalidate sessions that are over 2 days old, even if they are maintained active
sessions.timeToLive(TWO_DAYS);
// Use the provided clock to get time
sessions.usingClock(clock);
// Enable cookie support
server.add(new Cookies())
// Track sessions using transient - a.k.a session - cookies by default
// You can change of the name of the cookie used to track sessions
.add(new CookieSessionTracker(sessions).usingCookieName("molecule.session"))
.start(new DynamicRoutes() {{
// The default route greets the signed in user
map("/").to(Application.of(request -> {
// There's always a session bound to the request, although it may be empty and fresh
// We can safely read a new session. The session won't be saved to the pool unless
// it's been written or it was already present in the pool.
Session session = Session.get(request);
// If our user has already identified to our site,
// we have a username stored in the session
String username = session.contains("username") ? session.<String>get("username") : "Guest";
return Response.ok()
.done("Hello, " + username);
}));
// The sign in route
post("/login").to(Application.of(request -> {
// We expect a username parameter
String username = request.parameter("username");
Session session = Session.get(request);
// Store the username in the session. Since the session has been written to,
// it will automatically be saved to the pool by the end of the request cycle
session.put("username", username);
// If remember me is checked, make session cookie persistent with a max age of 5 minutes
if (request.hasParameter("remember_me")) {
session.maxAge(FIVE_MINUTES);
}
// If renew, make a fresh session to avoid session fixation attacks
// by generating a new session id
if (request.hasParameter("renew")) {
Session freshSession = new Session();
freshSession.merge(session);
freshSession.bind(request);
}
return Response.redirect("/")
.done();
}));
// The sign out route
delete("/logout").to(Application.of(request -> {
Session session = Session.get(request);
// We invalidate the session, which prevents further use and removes the session
// from the pool at the end of the request cycle
session.invalidate();
return Response.redirect("/")
.done();
}));
}}
);
}
public static void main(String[] args) throws IOException {
SessionExample example = new SessionExample(Clock.systemDefaultZone());
// Run the default web server
WebServer webServer = WebServer.create();
example.run(webServer);
System.out.println("Access at " + webServer.uri());
}
} |
package loci.common.utests;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import loci.common.Location;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Unit tests for the loci.common.Location class.
*
* @see loci.common.Location
*/
public class LocationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");
// -- Fields --
private Location[] files;
private boolean[] exists;
private boolean[] isDirectory;
private boolean[] isHidden;
private String[] mode;
private boolean[] isRemote;
private boolean isOnline;
// -- Setup methods --
@BeforeClass
public void setup() throws IOException {
File tmpDirectory = new File(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "-location-test");
boolean success = tmpDirectory.mkdirs();
tmpDirectory.deleteOnExit();
File hiddenFile = File.createTempFile(".hiddenTest", null, tmpDirectory);
hiddenFile.deleteOnExit();
File invalidFile = File.createTempFile("invalidTest", null, tmpDirectory);
String invalidPath = invalidFile.getAbsolutePath();
invalidFile.delete();
File validFile = File.createTempFile("validTest", null, tmpDirectory);
validFile.deleteOnExit();
files = new Location[] {
new Location(validFile.getAbsolutePath()),
new Location(invalidPath),
new Location(tmpDirectory),
new Location("http:
new Location("https:
new Location("https:
new Location(hiddenFile)
};
exists = new boolean[] {
true, false, true, false, true, false, true
};
isDirectory = new boolean[] {
false, false, true, false, false, false, false
};
isHidden = new boolean[] {
false, false, false, false, false, false, true
};
mode = new String[] {
"rw", "", "rw", "", "r", "","rw"
};
isRemote = new boolean[] {
false, false, false, true, true, true, false
};
}
@BeforeClass
public void checkIfOnline() throws IOException {
try {
new Socket("www.openmicroscopy.org", 80).close();
isOnline = true;
} catch (IOException e) {
isOnline = false;
}
}
private void skipIfOffline(int i) throws SkipException {
if (isRemote[i] && !isOnline) {
throw new SkipException("must be online to test " + files[i].getName());
}
}
// -- Tests --
@Test
public void testReadWriteMode() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
String msg = files[i].getName();
assertEquals(msg, files[i].canRead(), mode[i].contains("r"));
assertEquals(msg, files[i].canWrite(), mode[i].contains("w"));
}
}
@Test
public void testAbsolute() {
for (Location file : files) {
assertEquals(file.getName(), file.getAbsolutePath(),
file.getAbsoluteFile().getAbsolutePath());
}
}
@Test
public void testExists() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
assertEquals(files[i].getName(), files[i].exists(), exists[i]);
}
}
@Test
public void testCanonical() throws IOException {
for (Location file : files) {
assertEquals(file.getName(), file.getCanonicalPath(),
file.getCanonicalFile().getAbsolutePath());
}
}
@Test
public void testParent() {
for (Location file : files) {
assertEquals(file.getName(), file.getParent(),
file.getParentFile().getAbsolutePath());
}
}
@Test
public void testParentNull() {
Location nullParent = new Location((String) null, "nullParentFile");
assertEquals(nullParent.getName(), String.valueOf("null"), nullParent.getParentFile());
nullParent = new Location((Location) null, "nullParentFile");
assertEquals(nullParent.getName(), String.valueOf("null"), nullParent.getParentFile());
}
@Test
public void testIsDirectory() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isDirectory(), isDirectory[i]);
}
}
@Test
public void testIsFile() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
assertEquals(files[i].getName(), files[i].isFile(),
!isDirectory[i] && exists[i]);
}
}
@Test
public void testIsHidden() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isHidden() || IS_WINDOWS, isHidden[i] || IS_WINDOWS);
}
}
@Test
public void testListFiles() {
for (int i=0; i<files.length; i++) {
String[] completeList = files[i].list();
String[] unhiddenList = files[i].list(true);
Location[] fileList = files[i].listFiles();
if (!files[i].isDirectory()) {
assertEquals(files[i].getName(), completeList, null);
assertEquals(files[i].getName(), unhiddenList, null);
assertEquals(files[i].getName(), fileList, null);
continue;
}
assertEquals(files[i].getName(), completeList.length, fileList.length);
List<String> complete = Arrays.asList(completeList);
for (String child : unhiddenList) {
assertEquals(files[i].getName(), complete.contains(child), true);
assertEquals(files[i].getName(),
new Location(files[i], child).isHidden(), false);
}
for (int f=0; f<fileList.length; f++) {
assertEquals(files[i].getName(),
fileList[f].getName(), completeList[f]);
}
}
}
@Test
public void testToURL() throws IOException {
for (Location file : files) {
String path = file.getAbsolutePath();
if (!path.contains(":
if (IS_WINDOWS) {
path = "file:/" + path;
}
else {
path = "file://" + path;
}
}
if (file.isDirectory() && !path.endsWith(File.separator)) {
path += File.separator;
}
assertEquals(file.getName(), file.toURL(), new URL(path));
}
}
@Test
public void testToString() {
for (Location file : files) {
assertEquals(file.getName(), file.toString(), file.getAbsolutePath());
}
}
} |
package org.gitlab4j.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Comment;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.Diff;
import org.gitlab4j.api.models.Project;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* In order for these tests to run you must set the following properties in test-gitlab4j.properties
*
* TEST_NAMESPACE
* TEST_PROJECT_NAME
* TEST_HOST_URL
* TEST_PRIVATE_TOKEN
*
* If any of the above are NULL, all tests in this class will be skipped.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestCommitsApi {
// The following needs to be set to your test repository
private static final String TEST_PROJECT_NAME;
private static final String TEST_NAMESPACE;
private static final String TEST_HOST_URL;
private static final String TEST_PRIVATE_TOKEN;
private static final String TEST_PROJECT_SUBDIRECTORY_PATH = "src/main/docs/test-project.txt";
static {
TEST_NAMESPACE = TestUtils.getProperty("TEST_NAMESPACE");
TEST_PROJECT_NAME = TestUtils.getProperty("TEST_PROJECT_NAME");
TEST_HOST_URL = TestUtils.getProperty("TEST_HOST_URL");
TEST_PRIVATE_TOKEN = TestUtils.getProperty("TEST_PRIVATE_TOKEN");
}
private static GitLabApi gitLabApi;
public TestCommitsApi() {
super();
}
@BeforeClass
public static void setup() {
String problems = "";
if (TEST_NAMESPACE == null || TEST_NAMESPACE.trim().length() == 0) {
problems += "TEST_NAMESPACE cannot be empty\n";
}
if (TEST_PROJECT_NAME == null || TEST_PROJECT_NAME.trim().length() == 0) {
problems += "TEST_PROJECT_NAME cannot be empty\n";
}
if (TEST_HOST_URL == null || TEST_HOST_URL.trim().length() == 0) {
problems += "TEST_HOST_URL cannot be empty\n";
}
if (TEST_PRIVATE_TOKEN == null || TEST_PRIVATE_TOKEN.trim().length() == 0) {
problems += "TEST_PRIVATE_TOKEN cannot be empty\n";
}
if (problems.isEmpty()) {
gitLabApi = new GitLabApi(ApiVersion.V4, TEST_HOST_URL, TEST_PRIVATE_TOKEN);
} else {
System.err.print(problems);
}
}
@Before
public void beforeMethod() {
assumeTrue(gitLabApi != null);
}
@Test
public void testDiff() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId());
assertNotNull(commits);
assertTrue(commits.size() > 0);
List<Diff> diffs = gitLabApi.getCommitsApi().getDiff(project.getId(), commits.get(0).getId());
assertNotNull(diffs);
assertTrue(diffs.size() > 0);
diffs = gitLabApi.getCommitsApi().getDiff(TEST_NAMESPACE + "/" + TEST_PROJECT_NAME, commits.get(0).getId());
assertNotNull(diffs);
assertTrue(diffs.size() > 0);
}
@Test
public void testComments() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(0), new Date());
assertNotNull(commits);
assertTrue(commits.size() > 0);
String note = "This is a note.";
Comment addedComment = gitLabApi.getCommitsApi().addComment(project.getId(), commits.get(0).getId(), note);
assertNotNull(addedComment);
assertEquals(note, addedComment.getNote());
List<Comment> comments = gitLabApi.getCommitsApi().getComments(project.getId(), commits.get(0).getId());
assertNotNull(comments);
assertTrue(comments.size() > 0);
}
@Test
public void testCommitsSince() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(), null);
assertNotNull(commits);
assertTrue(commits.isEmpty());
commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(0), new Date());
assertNotNull(commits);
assertTrue(commits.size() > 0);
commits = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(0), new Date(), 1, 10);
assertNotNull(commits);
assertTrue(commits.size() > 0);
Pager<Commit> pager = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(), null, 10);
assertNotNull(pager);
assertTrue(pager.getTotalItems() == 0);
pager = gitLabApi.getCommitsApi().getCommits(project.getId(), null, new Date(0), null, 10);
assertNotNull(pager);
assertTrue(pager.getTotalItems() > 0);
}
@Test
public void testCommitsSinceWithPath() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(
project.getId(), null, new Date(0), new Date(), TEST_PROJECT_SUBDIRECTORY_PATH);
assertNotNull(commits);
assertTrue(commits.size() > 0);
}
@Test
public void testCommitsByPath() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
CommitsApi commitsApi = gitLabApi.getCommitsApi();
List<Commit> commits = commitsApi.getCommits(project.getId(), "master", null);
assertNotNull(commits);
assertTrue(commits.size() > 0);
commits = commitsApi.getCommits(project.getId(), "master", "README");
assertNotNull(commits);
assertTrue(commits.size() > 0);
commitsApi = gitLabApi.getCommitsApi();
commits = commitsApi.getCommits(project.getId(), "master", "README.md");
assertNotNull(commits);
assertTrue(commits.size() > 0);
commits = commitsApi.getCommits(project.getId(), "master", TEST_PROJECT_SUBDIRECTORY_PATH);
assertNotNull(commits);
assertTrue(commits.size() > 0);
}
@Test
public void testCommitsByPathNotFound() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
try {
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId(), "master", "this-file-does-not-exist.an-extension");
assertTrue(commits == null || commits.isEmpty());
} catch (GitLabApiException gle) {
assertEquals(Response.Status.NOT_FOUND, gle.getHttpStatus());
}
}
} |
package org.threeten.extra;
import static java.time.DayOfWeek.FRIDAY;
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.DayOfWeek.THURSDAY;
import static java.time.DayOfWeek.TUESDAY;
import static java.time.DayOfWeek.WEDNESDAY;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.AMPM_OF_DAY;
import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_AMPM;
import static java.time.temporal.ChronoField.CLOCK_HOUR_OF_DAY;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.HOUR_OF_AMPM;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.INSTANT_SECONDS;
import static java.time.temporal.ChronoField.MICRO_OF_DAY;
import static java.time.temporal.ChronoField.MICRO_OF_SECOND;
import static java.time.temporal.ChronoField.MILLI_OF_DAY;
import static java.time.temporal.ChronoField.MILLI_OF_SECOND;
import static java.time.temporal.ChronoField.MINUTE_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.NANO_OF_DAY;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.OFFSET_SECONDS;
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
import static java.time.temporal.ChronoField.SECOND_OF_DAY;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.IsoFields.DAY_OF_QUARTER;
import static java.time.temporal.IsoFields.QUARTER_OF_YEAR;
import static java.time.temporal.IsoFields.WEEK_BASED_YEAR;
import static java.time.temporal.IsoFields.WEEK_OF_WEEK_BASED_YEAR;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.chrono.IsoChronology;
import java.time.chrono.ThaiBuddhistDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Locale;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test
public class TestYearWeek {
private static final YearWeek TEST_NON_LEAP = YearWeek.of(2014, 1);
private static final YearWeek TEST = YearWeek.of(2015, 1);
@DataProvider(name = "sampleYearWeeks")
Object[][] provider_sampleYearWeeks() {
return new Object[][]{
{2015, 1},
{2015, 2},
{2015, 3},
{2015, 4},
{2015, 5},
{2015, 6},
{2015, 7},
{2015, 8},
{2015, 9},
{2015, 10},
{2015, 11},
{2015, 12},
{2015, 13},
{2015, 14},
{2015, 15},
{2015, 16},
{2015, 17},
{2015, 18},
{2015, 19},
{2015, 20},
{2015, 21},
{2015, 22},
{2015, 21},
{2015, 22},
{2015, 23},
{2015, 23},
{2015, 24},
{2015, 25},
{2015, 26},
{2015, 27},
{2015, 28},
{2015, 29},
{2015, 30},
{2015, 31},
{2015, 32},
{2015, 33},
{2015, 34},
{2015, 35},
{2015, 36},
{2015, 37},
{2015, 38},
{2015, 39},
{2015, 40},
{2015, 41},
{2015, 42},
{2015, 43},
{2015, 44},
{2015, 45},
{2015, 46},
{2015, 47},
{2015, 48},
{2015, 49},
{2015, 50},
{2015, 51},
{2015, 52},
{2015, 53}
};
}
@DataProvider(name = "53WeekYear")
Object[][] provider_53WeekYear() {
return new Object[][]{
{4},
{9},
{15},
{20},
{26},
{32},
{37},
{43},
{48},
{54},
{60},
{65},
{71},
{76},
{82},
{88},
{93},
{99},
{105},
{111},
{116},
{122},
{128},
{133},
{139},
{144},
{150},
{156},
{161},
{167},
{172},
{178},
{184},
{189},
{195},
{201},
{207},
{212},
{218},
{224},
{229},
{235},
{240},
{246},
{252},
{257},
{263},
{268},
{274},
{280},
{285},
{291},
{296},
{303},
{308},
{314},
{320},
{325},
{331},
{336},
{342},
{348},
{353},
{359},
{364},
{370},
{376},
{381},
{387},
{392},
{398}
};
}
@DataProvider(name = "sampleAtDay")
Object[][] provider_sampleAtDay() {
return new Object[][]{
{2014, 52, MONDAY, 2014, 12, 22},
{2014, 52, TUESDAY, 2014, 12, 23},
{2014, 52, WEDNESDAY, 2014, 12, 24},
{2014, 52, THURSDAY, 2014, 12, 25},
{2014, 52, FRIDAY, 2014, 12, 26},
{2014, 52, SATURDAY, 2014, 12, 27},
{2014, 52, SUNDAY, 2014, 12, 28},
{2015, 1, MONDAY, 2014, 12, 29},
{2015, 1, TUESDAY, 2014, 12, 30},
{2015, 1, WEDNESDAY, 2014, 12, 31},
{2015, 1, THURSDAY, 2015, 1, 1},
{2015, 1, FRIDAY, 2015, 1, 2},
{2015, 1, SATURDAY, 2015, 1, 3},
{2015, 1, SUNDAY, 2015, 1, 4},
{2015, 53, FRIDAY, 2016, 1, 1},
{2015, 53, SATURDAY, 2016, 1, 2},
{2015, 53, SUNDAY, 2016, 1, 3},
{2016, 1, MONDAY, 2016, 1, 4},
{2016, 52, SUNDAY, 2017, 1, 1},
{2017, 1, MONDAY, 2017, 1, 2},
{2017, 1, TUESDAY, 2017, 1, 3},
{2017, 1, WEDNESDAY, 2017, 1, 4},
{2017, 1, THURSDAY, 2017, 1, 5},
{2017, 1, FRIDAY, 2017, 1, 6},
{2017, 1, SATURDAY, 2017, 1, 7},
{2017, 1, SUNDAY, 2017, 1, 8},
{2025, 1, MONDAY, 2024, 12, 30},
};
}
public void test_interfaces() {
assertTrue(Serializable.class.isAssignableFrom(YearWeek.class));
assertTrue(Comparable.class.isAssignableFrom(YearWeek.class));
assertTrue(TemporalAdjuster.class.isAssignableFrom(YearWeek.class));
assertTrue(TemporalAccessor.class.isAssignableFrom(YearWeek.class));
}
public void test_serialization() throws IOException, ClassNotFoundException {
YearWeek test = YearWeek.of(2015, 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(test);
}
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
baos.toByteArray()));
assertEquals(ois.readObject(), test);
}
// now()
@Test
public void test_now() {
YearWeek expected = YearWeek.now(Clock.systemDefaultZone());
YearWeek test = YearWeek.now();
for (int i = 0; i < 100; i++) {
if (expected.equals(test)) {
return;
}
expected = YearWeek.now(Clock.systemDefaultZone());
test = YearWeek.now();
}
assertEquals(test, expected);
}
// now(ZoneId)
@Test(expectedExceptions = NullPointerException.class)
public void now_ZoneId_nullZoneId() {
YearWeek.now((ZoneId) null);
}
@Test
public void now_ZoneId() {
ZoneId zone = ZoneId.of("UTC+01:02:03");
YearWeek expected = YearWeek.now(Clock.system(zone));
YearWeek test = YearWeek.now(zone);
for (int i = 0; i < 100; i++) {
if (expected.equals(test)) {
return;
}
expected = YearWeek.now(Clock.system(zone));
test = YearWeek.now(zone);
}
assertEquals(test, expected);
}
// now(Clock)
@Test
public void now_Clock() {
Instant instant = LocalDateTime.of(2010, 12, 31, 0, 0).toInstant(ZoneOffset.UTC);
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
YearWeek test = YearWeek.now(clock);
assertEquals(test.getYear(), 2010);
assertEquals(test.getWeek(), 52);
}
@Test(expectedExceptions = NullPointerException.class)
public void now_Clock_nullClock() {
YearWeek.now((Clock) null);
}
// of(int, int)
@Test(dataProvider = "sampleYearWeeks")
public void test_of(int year, int week) {
YearWeek yearWeek = YearWeek.of(year, week);
assertEquals(yearWeek.getYear(), year);
assertEquals(yearWeek.getWeek(), week);
}
public void test_carry() {
assertTrue(YearWeek.of(2014, 53).equals(TEST));
}
@Test(expectedExceptions = DateTimeException.class)
public void test_of_year_tooLow() {
YearWeek.of(Integer.MIN_VALUE, 1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_of_year_tooHigh() {
YearWeek.of(Integer.MAX_VALUE, 1);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_of_invalidWeekValue() {
YearWeek.of(2015, 54);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_of_invalidWeekValueZero() {
YearWeek.of(2015, 0);
}
// isSupported(TemporalField)
public void test_isSupported_TemporalField() {
assertEquals(TEST.isSupported((TemporalField) null), false);
assertEquals(TEST.isSupported(NANO_OF_SECOND), false);
assertEquals(TEST.isSupported(NANO_OF_DAY), false);
assertEquals(TEST.isSupported(MICRO_OF_SECOND), false);
assertEquals(TEST.isSupported(MICRO_OF_DAY), false);
assertEquals(TEST.isSupported(MILLI_OF_SECOND), false);
assertEquals(TEST.isSupported(MILLI_OF_DAY), false);
assertEquals(TEST.isSupported(SECOND_OF_MINUTE), false);
assertEquals(TEST.isSupported(SECOND_OF_DAY), false);
assertEquals(TEST.isSupported(MINUTE_OF_HOUR), false);
assertEquals(TEST.isSupported(MINUTE_OF_DAY), false);
assertEquals(TEST.isSupported(HOUR_OF_AMPM), false);
assertEquals(TEST.isSupported(CLOCK_HOUR_OF_AMPM), false);
assertEquals(TEST.isSupported(HOUR_OF_DAY), false);
assertEquals(TEST.isSupported(CLOCK_HOUR_OF_DAY), false);
assertEquals(TEST.isSupported(AMPM_OF_DAY), false);
assertEquals(TEST.isSupported(DAY_OF_WEEK), false);
assertEquals(TEST.isSupported(ALIGNED_DAY_OF_WEEK_IN_MONTH), false);
assertEquals(TEST.isSupported(ALIGNED_DAY_OF_WEEK_IN_YEAR), false);
assertEquals(TEST.isSupported(DAY_OF_MONTH), false);
assertEquals(TEST.isSupported(DAY_OF_YEAR), false);
assertEquals(TEST.isSupported(EPOCH_DAY), false);
assertEquals(TEST.isSupported(ALIGNED_WEEK_OF_MONTH), false);
assertEquals(TEST.isSupported(ALIGNED_WEEK_OF_YEAR), false);
assertEquals(TEST.isSupported(MONTH_OF_YEAR), false);
assertEquals(TEST.isSupported(PROLEPTIC_MONTH), false);
assertEquals(TEST.isSupported(YEAR_OF_ERA), false);
assertEquals(TEST.isSupported(YEAR), false);
assertEquals(TEST.isSupported(ERA), false);
assertEquals(TEST.isSupported(INSTANT_SECONDS), false);
assertEquals(TEST.isSupported(OFFSET_SECONDS), false);
assertEquals(TEST.isSupported(QUARTER_OF_YEAR), false);
assertEquals(TEST.isSupported(DAY_OF_QUARTER), false);
assertEquals(TEST.isSupported(WEEK_BASED_YEAR), true);
assertEquals(TEST.isSupported(WEEK_OF_WEEK_BASED_YEAR), true);
}
// atDay(DayOfWeek)
@Test(dataProvider = "sampleAtDay")
public void test_atDay(int weekBasedYear, int weekOfWeekBasedYear, DayOfWeek dayOfWeek, int year, int month, int dayOfMonth) {
YearWeek yearWeek = YearWeek.of(weekBasedYear, weekOfWeekBasedYear);
LocalDate expected = LocalDate.of(year, month, dayOfMonth);
LocalDate actual = yearWeek.atDay(dayOfWeek);
assertEquals(actual, expected);
}
@Test
public void test_atDay_loop20years() {
YearWeek yearWeek = YearWeek.of(1998, 51);
LocalDate expected = LocalDate.of(1998, 12, 14);
for (int i = 0; i < (20 * 53); i++) {
for (int j = 1; j <= 7; j++) {
DayOfWeek dow = DayOfWeek.of(j);
LocalDate actual = yearWeek.atDay(dow);
assertEquals(actual, expected);
expected = expected.plusDays(1);
}
yearWeek = yearWeek.plusWeeks(1);
}
}
@Test(expectedExceptions = NullPointerException.class)
public void test_atDay_null() {
TEST.atDay(null);
}
// is53WeekYear()
@Test(dataProvider = "53WeekYear")
public void test_is53WeekYear(int year) {
YearWeek yearWeek = YearWeek.of(year, 1);
assertTrue(yearWeek.is53WeekYear());
}
// compareTo()
public void test_compareTo() {
for (int year1 = -100; year1 < 100; year1++) {
for (int week1 = 1; week1 < 53; week1++) {
YearWeek a = YearWeek.of(year1, week1);
for (int year2 = -100; year2 < 100; year2++) {
for (int week2 = 1; week2 < 53; week2++) {
YearWeek b = YearWeek.of(year2, week2);
if (year1 < year2) {
assertEquals(a.compareTo(b) < 0, true);
assertEquals(b.compareTo(a) > 0, true);
assertEquals(a.isAfter(b), false);
assertEquals(b.isBefore(a), false);
assertEquals(b.isAfter(a), true);
assertEquals(a.isBefore(b), true);
} else if (year1 > year2) {
assertEquals(a.compareTo(b) > 0, true);
assertEquals(b.compareTo(a) < 0, true);
assertEquals(a.isAfter(b), true);
assertEquals(b.isBefore(a), true);
assertEquals(b.isAfter(a), false);
assertEquals(a.isBefore(b), false);
} else {
if (week1 < week2) {
assertEquals(a.compareTo(b) < 0, true);
assertEquals(b.compareTo(a) > 0, true);
assertEquals(a.isAfter(b), false);
assertEquals(b.isBefore(a), false);
assertEquals(b.isAfter(a), true);
assertEquals(a.isBefore(b), true);
} else if (week1 > week2) {
assertEquals(a.compareTo(b) > 0, true);
assertEquals(b.compareTo(a) < 0, true);
assertEquals(a.isAfter(b), true);
assertEquals(b.isBefore(a), true);
assertEquals(b.isAfter(a), false);
assertEquals(a.isBefore(b), false);
} else {
assertEquals(a.compareTo(b), 0);
assertEquals(b.compareTo(a), 0);
assertEquals(a.isAfter(b), false);
assertEquals(b.isBefore(a), false);
assertEquals(b.isAfter(a), false);
assertEquals(a.isBefore(b), false);
}
}
}
}
}
}
}
@Test(expectedExceptions = NullPointerException.class)
public void test_compareTo_nullYearWeek() {
TEST.compareTo(null);
}
// from(TemporalAccessor)
@Test(dataProvider = "sampleAtDay")
public void test_from(int weekBasedYear, int weekOfWeekBasedYear, DayOfWeek dayOfWeek, int year, int month, int dayOfMonth) {
YearWeek expected = YearWeek.of(weekBasedYear, weekOfWeekBasedYear);
LocalDate ld = LocalDate.of(year, month, dayOfMonth);
assertEquals(YearWeek.from(ld), expected);
assertEquals(YearWeek.from(ThaiBuddhistDate.from(ld)), expected);
assertEquals(YearWeek.from(expected), expected);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_from_TemporalAccessor_noDerive() {
YearWeek.from(LocalTime.NOON);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_from_TemporalAccessor_null() {
YearWeek.from((TemporalAccessor) null);
}
// get(TemporalField)
public void test_get() {
assertEquals(TEST.get(WEEK_BASED_YEAR), 2015);
assertEquals(TEST.get(WEEK_OF_WEEK_BASED_YEAR), 1);
}
@Test(expectedExceptions = UnsupportedTemporalTypeException.class)
public void test_get_invalidField() {
TEST.get(YEAR);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_get_null() {
TEST.get((TemporalField) null);
}
// getLong(TemporalField)
public void test_getLong() {
assertEquals(TEST.getLong(WEEK_BASED_YEAR), 2015L);
assertEquals(TEST.getLong(WEEK_OF_WEEK_BASED_YEAR), 1L);
}
@Test(expectedExceptions = UnsupportedTemporalTypeException.class)
public void test_getLong_invalidField() {
TEST.getLong(YEAR);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_getLong_null() {
TEST.getLong((TemporalField) null);
}
// lengthOfYear()
public void test_lengthOfYear() {
assertEquals(YearWeek.of(2014, 1).lengthOfYear(), 364);
assertEquals(YearWeek.of(2015, 1).lengthOfYear(), 371);
}
// toString()
public void test_toString() {
assertEquals(TEST.toString(), "2015-W01");
}
// parse(CharSequence)
public void test_parse_CharSequence() {
assertEquals(YearWeek.parse("2015-W01"), TEST);
}
@Test(expectedExceptions = DateTimeParseException.class)
public void test_parse_CharSequenceDate_invalidYear() {
YearWeek.parse("12345-W7");
}
@Test(expectedExceptions = DateTimeParseException.class)
public void test_parse_CharSequenceDate_invalidWeek() {
YearWeek.parse("2015-W54");
}
@Test(expectedExceptions = NullPointerException.class)
public void test_parse_CharSequenceDate_nullCharSequence() {
YearWeek.parse((CharSequence) null);
}
// parse(CharSequence,DateTimeFormatter)
public void test_parse_CharSequenceDateTimeFormatter() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH);
assertEquals(YearWeek.parse("Mon W1 2015", f), TEST);
}
@Test(expectedExceptions = DateTimeParseException.class)
public void test_parse_CharSequenceDateDateTimeFormatter_invalidWeek() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH);
YearWeek.parse("Mon W99 2015", f);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_parse_CharSequenceDateTimeFormatter_nullCharSequence() {
DateTimeFormatter f = DateTimeFormatter.ofPattern("E 'W'w YYYY").withLocale(Locale.ENGLISH);
YearWeek.parse((CharSequence) null, f);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_parse_CharSequenceDateTimeFormatter_nullDateTimeFormatter() {
YearWeek.parse("", (DateTimeFormatter) null);
}
// format()
public void test_format() {
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendValue(WEEK_BASED_YEAR, 4)
.appendLiteral('-')
.appendValue(WEEK_OF_WEEK_BASED_YEAR, 2)
.toFormatter();
assertEquals(TEST.format(f), "2015-01");
}
// adjustInto()
public void test_adjustInto() {
YearWeek yw = YearWeek.of(2016, 1);
LocalDate date = LocalDate.of(2015, 6, 20);
assertEquals(yw.adjustInto(date), LocalDate.of(2016, 1, 9));
}
@Test(expectedExceptions = DateTimeException.class)
public void test_adjustInto_badChronology() {
YearWeek yw = YearWeek.of(2016, 1);
ThaiBuddhistDate date = ThaiBuddhistDate.from(LocalDate.of(2015, 6, 20));
yw.adjustInto(date);
}
// range(TemporalField)
public void test_range() {
assertEquals(TEST_NON_LEAP.range(WEEK_BASED_YEAR), WEEK_BASED_YEAR.range());
assertEquals(TEST.range(WEEK_BASED_YEAR), WEEK_BASED_YEAR.range());
assertEquals(TEST_NON_LEAP.range(WEEK_OF_WEEK_BASED_YEAR), ValueRange.of(1, 52));
assertEquals(TEST.range(WEEK_OF_WEEK_BASED_YEAR), ValueRange.of(1, 53));
}
@Test(expectedExceptions = UnsupportedTemporalTypeException.class)
public void test_range_invalidField() {
TEST.range(YEAR);
}
@Test(expectedExceptions = NullPointerException.class)
public void test_range_null() {
TEST.range((TemporalField) null);
}
// withYear(int)
public void test_withYear() {
assertEquals(YearWeek.of(2015, 1).withYear(2014), YearWeek.of(2014, 1));
assertEquals(YearWeek.of(2015, 53).withYear(2009), YearWeek.of(2009, 53));
}
public void test_withYear_sameYear() {
assertEquals(YearWeek.of(2015, 1).withYear(2015), YearWeek.of(2015, 1));
}
public void test_withYear_resolve() {
assertEquals(YearWeek.of(2015, 53).withYear(2014), YearWeek.of(2014, 52));
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withYear_int_max() {
TEST.withYear(Integer.MAX_VALUE);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withYear_int_min() {
TEST.withYear(Integer.MIN_VALUE);
}
// withWeek(int)
public void test_withWeek() {
assertEquals(TEST.withWeek(52), YearWeek.of(2015, 52));
assertEquals(YearWeek.of(2014, 1).withWeek(53), TEST);
}
public void test_withWeek_sameWeek() {
assertEquals(YearWeek.of(2014, 2).withWeek(2), YearWeek.of(2014, 2));
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withWeek_int_max() {
TEST.withWeek(Integer.MAX_VALUE);
}
@Test(expectedExceptions = DateTimeException.class)
public void test_withWeek_int_min() {
TEST.withWeek(Integer.MIN_VALUE);
}
// plusYears(long)
public void test_plusYears() {
assertEquals(TEST.plusYears(-2), YearWeek.of(2013, 1));
assertEquals(TEST.plusYears(-1), YearWeek.of(2014, 1));
assertEquals(TEST.plusYears(0), TEST);
assertEquals(TEST.plusYears(1), YearWeek.of(2016, 1));
assertEquals(TEST.plusYears(2), YearWeek.of(2017, 1));
}
public void test_plusYears_changeWeek() {
assertEquals(YearWeek.of(2015, 53).plusYears(-1), YearWeek.of(2014, 52));
assertEquals(YearWeek.of(2015, 53).plusYears(0), YearWeek.of(2015, 53));
assertEquals(YearWeek.of(2015, 53).plusYears(1), YearWeek.of(2016, 52));
assertEquals(YearWeek.of(2015, 53).plusYears(5), YearWeek.of(2020, 53));
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusYears_max_long() {
TEST.plusYears(Long.MAX_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusYears_min_long() {
TEST.plusYears(Long.MIN_VALUE);
}
// plusWeeks(long)
public void test_plusWeeks() {
assertEquals(TEST.plusWeeks(0), TEST);
assertEquals(TEST.plusWeeks(1), YearWeek.of(2015, 2));
assertEquals(TEST.plusWeeks(2), YearWeek.of(2015, 3));
assertEquals(TEST.plusWeeks(51), YearWeek.of(2015, 52));
assertEquals(TEST.plusWeeks(52), YearWeek.of(2015, 53));
assertEquals(TEST.plusWeeks(53), YearWeek.of(2016, 1));
assertEquals(TEST.plusWeeks(314), YearWeek.of(2021, 1));
}
public void test_plusWeeks_negative() {
assertEquals(TEST.plusWeeks(0), TEST);
assertEquals(TEST.plusWeeks(-1), YearWeek.of(2014, 52));
assertEquals(TEST.plusWeeks(-2), YearWeek.of(2014, 51));
assertEquals(TEST.plusWeeks(-51), YearWeek.of(2014, 2));
assertEquals(TEST.plusWeeks(-52), YearWeek.of(2014, 1));
assertEquals(TEST.plusWeeks(-53), YearWeek.of(2013, 52));
assertEquals(TEST.plusWeeks(-261), YearWeek.of(2009, 53));
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusWeeks_max_long() {
TEST.plusWeeks(Long.MAX_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_plusWeeks_min_long() {
TEST.plusWeeks(Long.MIN_VALUE);
}
// minusYears(long)
public void test_minusYears() {
assertEquals(TEST.minusYears(-2), YearWeek.of(2017, 1));
assertEquals(TEST.minusYears(-1), YearWeek.of(2016, 1));
assertEquals(TEST.minusYears(0), TEST);
assertEquals(TEST.minusYears(1), YearWeek.of(2014, 1));
assertEquals(TEST.minusYears(2), YearWeek.of(2013, 1));
}
public void test_minusYears_changeWeek() {
assertEquals(YearWeek.of(2015, 53).minusYears(-5), YearWeek.of(2020, 53));
assertEquals(YearWeek.of(2015, 53).minusYears(-1), YearWeek.of(2016, 52));
assertEquals(YearWeek.of(2015, 53).minusYears(0), YearWeek.of(2015, 53));
assertEquals(YearWeek.of(2015, 53).minusYears(1), YearWeek.of(2014, 52));
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minusYears_max_long() {
TEST.minusYears(Long.MAX_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minusYears_min_long() {
TEST.minusYears(Long.MIN_VALUE);
}
// minusWeeks(long)
public void test_minusWeeks() {
assertEquals(TEST.minusWeeks(0), TEST);
assertEquals(TEST.minusWeeks(1), YearWeek.of(2014, 52));
assertEquals(TEST.minusWeeks(2), YearWeek.of(2014, 51));
assertEquals(TEST.minusWeeks(51), YearWeek.of(2014, 2));
assertEquals(TEST.minusWeeks(52), YearWeek.of(2014, 1));
assertEquals(TEST.minusWeeks(53), YearWeek.of(2013, 52));
assertEquals(TEST.minusWeeks(261), YearWeek.of(2009, 53));
}
public void test_minusWeeks_negative() {
assertEquals(TEST.minusWeeks(0), TEST);
assertEquals(TEST.minusWeeks(-1), YearWeek.of(2015, 2));
assertEquals(TEST.minusWeeks(-2), YearWeek.of(2015, 3));
assertEquals(TEST.minusWeeks(-51), YearWeek.of(2015, 52));
assertEquals(TEST.minusWeeks(-52), YearWeek.of(2015, 53));
assertEquals(TEST.minusWeeks(-53), YearWeek.of(2016, 1));
assertEquals(TEST.minusWeeks(-314), YearWeek.of(2021, 1));
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minWeeks_max_long() {
TEST.plusWeeks(Long.MAX_VALUE);
}
@Test(expectedExceptions = ArithmeticException.class)
public void test_minWeeks_min_long() {
TEST.plusWeeks(Long.MIN_VALUE);
}
// query(TemporalQuery)
@Test
public void test_query() {
assertEquals(TEST.query(TemporalQueries.chronology()), IsoChronology.INSTANCE);
assertEquals(TEST.query(TemporalQueries.localDate()), null);
assertEquals(TEST.query(TemporalQueries.localTime()), null);
assertEquals(TEST.query(TemporalQueries.offset()), null);
assertEquals(TEST.query(TemporalQueries.precision()), null);
assertEquals(TEST.query(TemporalQueries.zone()), null);
assertEquals(TEST.query(TemporalQueries.zoneId()), null);
}
// equals() / hashCode()
@Test(dataProvider = "sampleYearWeeks")
public void test_equalsAndHashCodeContract(int year, int week) {
YearWeek a = YearWeek.of(year, week);
YearWeek b = YearWeek.of(year, week);
assertTrue(a.equals(b));
assertTrue(b.equals(a));
assertTrue(a.hashCode() == b.hashCode());
}
public void test_equals() {
YearWeek a = YearWeek.of(2015, 4);
YearWeek b = YearWeek.of(2015, 6);
YearWeek c = YearWeek.of(2016, 6);
assertFalse(a.equals(b));
assertFalse(a.equals(c));
assertFalse(b.equals(a));
assertFalse(b.equals(c));
assertFalse(c.equals(a));
assertFalse(c.equals(b));
}
public void test_equals_incorrectType() {
assertTrue(TEST.equals(null) == false);
assertEquals(TEST.equals("Incorrect type"), false);
}
// toString()
@DataProvider(name = "sampleToString")
Object[][] provider_sampleToString() {
return new Object[][]{
{2015, 1, "2015-W01"},
{2015, 10, "2015-W10"},
{999, 1, "0999-W01"},
{-999, 1, "-0999-W01"},
{10000, 1, "+10000-W01"},
{-10000, 1, "-10000-W01"},};
}
@Test(dataProvider = "sampleToString")
public void test_toString(int year, int week, String expected) {
YearWeek yearWeek = YearWeek.of(year, week);
String s = yearWeek.toString();
assertEquals(s, expected);
}
} |
package markehme.factionsplus.MCore;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import com.massivecraft.factions.entity.Faction;
import com.massivecraft.factions.entity.UPlayer;
import com.massivecraft.mcore.ps.PS;
import com.massivecraft.mcore.store.Entity;
public class FactionData extends Entity<FactionData> {
// META
public static FactionData get(Object oid)
{
return FactionDataColls.get().get2(oid);
}
// OVERRIDE: ENTITY
@Override
public FactionData load(FactionData that) {
this.faction = that.faction;
this.warpLocation = that.warpLocation;
this.warpPasswords = that.warpPasswords;
this.announcement = that.announcement;
this.bannedPlayerIDs = that.bannedPlayerIDs;
this.jailedPlayerIDs = that.jailedPlayerIDs;
this.jailLocation = that.jailLocation;
this.rules = that.rules;
return this;
}
@Override
public void preDetach(String id) {
// Not sure we need to use this yet.
//String universe = this.getUniverse();
}
// METHODS
/**
* Check if a warp exists.
* @param name
* @return
*/
public boolean warpExists(String name) {
if(warpLocation.containsKey(name.toLowerCase())) {
return true;
}
return false;
}
/**
* Check if a warp has a password. Returns true if a warp has a password.
* @param name
* @return
*/
public boolean warpHasPassword(String name) {
return (warpPasswords.get(name.toLowerCase()) != null);
}
/**
* Validate the password of a warp, returns true if it is valid.
* @param name
* @param pass
* @return
*/
public boolean warpValidatePassword(String name, String pass) {
if(!warpHasPassword(name.toLowerCase())) {
return true;
}
if(warpPasswords.get(name.toLowerCase()) == pass) {
return true;
}
return false;
}
/**
* Returns the (PS) Location of a warp
* @param warp
* @return
*/
public PS getWarpLocation(String warp) {
return(warpLocation.get(warp.toLowerCase()));
}
/**
* Returns a map of the warps and their locations
* @return
*/
public Map<String, PS> getWarps() {
return null;
}
public boolean isJailed(UPlayer uPlayer) {
return(isJailed(uPlayer.getPlayer()));
}
public boolean isJailed(Player player) {
return(this.jailedPlayerIDs.containsKey(player.getUniqueId().toString()));
}
// VARIABLES
public Faction faction = null;
public Map<String, PS> warpLocation = new LinkedHashMap<String, PS>();
public Map<String, String> warpPasswords = new LinkedHashMap<String, String>();
public String announcement = null;
public Map<String, String> bannedPlayerIDs = new LinkedHashMap<String, String>();
public Map<String, PS> jailedPlayerIDs = new LinkedHashMap<String, PS>();
public PS jailLocation = null;
public List<String> rules = new ArrayList<String>();
} |
package mise.marssa.interfaces.control;
import mise.marssa.data_types.float_datatypes.MFloat;
import mise.marssa.exceptions.ConfigurationError;
import mise.marssa.exceptions.OutOfRange;
/**
* interface for ramping module
*
* @author Alan
* @version 1.0
* @updated 08-Jul-2011 15:00:19
*/
public interface IRamping {
/**
* Ramps the output value from the current value to the desired value
* @param desiredValue the value which is desired on the output
* @throws InterruptedException
* @throws ConfigurationError
* @throws OutOfRange
*/
public void rampTo(MFloat desiredValue) throws InterruptedException, ConfigurationError, OutOfRange;
/**
* Get current value of the Ramping instance<br />
* This is the same as the last value which was sent on the outputValue method of the IController Interface
* Note: The Ramping instance might not necessarily be in the idle state. If it is in the process of executing the rampTo method, the current value will be returned
* @return the current value of the Ramping instance
* @see mise.marssa.interfaces.control.IController
*/
public MFloat getCurrentValue();
void increase(MFloat incrementValue) throws InterruptedException,
ConfigurationError, OutOfRange;
void decrease(MFloat decrementValue) throws InterruptedException,
ConfigurationError, OutOfRange;
} |
package net.jforum.view.forum.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.context.RequestContext;
import net.jforum.dao.PostDAO;
import net.jforum.entities.Post;
import net.jforum.entities.Smilie;
import net.jforum.repository.BBCodeRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.repository.SmiliesRepository;
import net.jforum.security.SecurityConstants;
import net.jforum.util.SafeHtml;
import net.jforum.util.bbcode.BBCode;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
/**
* @author Rafael Steil
* @version $Id: PostCommon.java,v 1.45 2007/08/19 07:10:27 andowson Exp $
*/
public class PostCommon
{
private static PostCommon instance = new PostCommon();
/**
* Gets the instance.
* This method only exists to situations where an instance is
* needed in the template context, so we don't need to
* create a new instance every time.
* @return PostCommon
*/
public static PostCommon getInstance()
{
return instance;
}
public static Post preparePostForDisplay(Post p)
{
if (p.getText() == null) {
return p;
}
StringBuffer text = new StringBuffer(p.getText());
if (!p.isHtmlEnabled()) {
ViewCommon.replaceAll(text, "<", "<");
ViewCommon.replaceAll(text, ">", ">");
}
// Do not remove the trailing blank space, as it would
// cause some regular expressions to fail
ViewCommon.replaceAll(text, "\n", "<br /> ");
p.setText(SafeHtml.avoidJavascript(text.toString()));
// Then, search for bb codes
if (p.isBbCodeEnabled()) {
p.setText(processBBCodes(p.getText()));
}
p.setText(parseDefaultRequiredBBCode(p.getText(),
BBCodeRepository.getBBCollection().getAlwaysProcessList()));
// Smilies...
if (p.isSmiliesEnabled()) {
p.setText(processSmilies(new StringBuffer(p.getText()),
SmiliesRepository.getSmilies()));
}
return p;
}
public static String parseDefaultRequiredBBCode(String text, Collection bbList)
{
for (Iterator iter = bbList.iterator(); iter.hasNext(); ) {
BBCode bb = (BBCode)iter.next();
text = text.replaceAll(bb.getRegex(), bb.getReplace());
}
return text;
}
public static String processBBCodes(String text)
{
if (text == null || text.indexOf('[') == -1 || text.indexOf(']') == -1) {
return text;
}
for (Iterator iter = BBCodeRepository.getBBCollection().getBbList().iterator(); iter.hasNext();) {
BBCode bb = (BBCode)iter.next();
if (!bb.getTagName().startsWith("code")) {
text = text.replaceAll(bb.getRegex(), bb.getReplace());
}
else if ("code".equals(bb.getTagName())) {
Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
StringBuffer sb = new StringBuffer(text);
while (matcher.find()) {
StringBuffer contents = new StringBuffer(matcher.group(1));
ViewCommon.replaceAll(contents, "<br /> ", "\n");
// Do not allow other bb tags inside "code"
ViewCommon.replaceAll(contents, "[", "&
ViewCommon.replaceAll(contents, "]", "&
// Try to bypass smilies interpretation
ViewCommon.replaceAll(contents, "(", "&
ViewCommon.replaceAll(contents, ")", "&
// XML-like tags
ViewCommon.replaceAll(contents, "<", "<");
ViewCommon.replaceAll(contents, ">", ">");
//ViewCommon.replaceAll(contents, "\n", "<br />");
ViewCommon.replaceAll(contents, "\t", " ");
StringBuffer replace = new StringBuffer(bb.getReplace());
int index = replace.indexOf("$1");
if (index > -1) {
replace.replace(index, index + 2, contents.toString());
}
index = sb.indexOf("[code]");
int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();
if (lastIndex > index) {
sb.replace(index, lastIndex, replace.toString());
}
}
text = sb.toString();
}
else if ("code-highlight".equals(bb.getTagName())) {
Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
StringBuffer sb = new StringBuffer(text);
while (matcher.find()) {
StringBuffer lang = new StringBuffer(matcher.group(1));
StringBuffer contents = new StringBuffer(matcher.group(2));
ViewCommon.replaceAll(contents, "<br /> ", "\n");
// Do not allow other bb tags inside "code"
ViewCommon.replaceAll(contents, "[", "&
ViewCommon.replaceAll(contents, "]", "&
// Try to bypass smilies interpretation
ViewCommon.replaceAll(contents, "(", "&
ViewCommon.replaceAll(contents, ")", "&
// XML-like tags
ViewCommon.replaceAll(contents, "<", "<");
ViewCommon.replaceAll(contents, ">", ">");
//ViewCommon.replaceAll(contents, "\n", "<br />");
ViewCommon.replaceAll(contents, "\t", " ");
StringBuffer replace = new StringBuffer(bb.getReplace());
int index = replace.indexOf("$1");
if (index > -1) {
replace.replace(index, index + 2, lang.toString());
}
index = replace.indexOf("$2");
if (index > -1) {
replace.replace(index, index + 2, contents.toString());
}
index = sb.indexOf("[code=");
int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();
if (lastIndex > index) {
sb.replace(index, lastIndex, replace.toString());
}
}
text = sb.toString();
}
}
return text;
}
/**
* Replace the smlies code by the respective URL.
* @param text The text to process
* @param smilies the relation of {@link Smilie} instances
* @return the parsed text. Note that the StringBuffer you pass as parameter
* will already have the right contents, as the replaces are done on the instance
*/
public static String processSmilies(StringBuffer text, List smilies)
{
for (Iterator iter = smilies.iterator(); iter.hasNext(); ) {
Smilie s = (Smilie) iter.next();
int pos = text.indexOf(s.getCode());
// The counter is used as prevention, in case
// the while loop turns into an always true
// expression, for any reason
int count = 0;
while (pos > -1 && count++ < 500) {
text.replace(pos, pos + s.getCode().length(), s.getUrl());
pos = text.indexOf(s.getCode());
}
}
return text.toString();
}
public static Post fillPostFromRequest()
{
Post p = new Post();
p.setTime(new Date());
return fillPostFromRequest(p, false);
}
public static Post fillPostFromRequest(Post p, boolean isEdit)
{
RequestContext request = JForumExecutionContext.getRequest();
p.setSubject(SafeHtml.makeSafe(request.getParameter("subject")));
p.setBbCodeEnabled(request.getParameter("disable_bbcode") == null);
p.setSmiliesEnabled(request.getParameter("disable_smilies") == null);
p.setSignatureEnabled(request.getParameter("attach_sig") != null);
if (!isEdit) {
p.setUserIp(request.getRemoteAddr());
p.setUserId(SessionFacade.getUserSession().getUserId());
}
boolean htmlEnabled = SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
request.getParameter("forum_id"));
p.setHtmlEnabled(htmlEnabled && request.getParameter("disable_html") == null);
if (p.isHtmlEnabled()) {
p.setText(SafeHtml.makeSafe(request.getParameter("message")));
}
else {
p.setText(request.getParameter("message"));
}
return p;
}
public static List topicPosts(PostDAO dao, boolean canEdit, int userId, int topicId, int start, int count)
{
boolean needPrepare = true;
List posts;
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
posts = PostRepository.selectAllByTopicByLimit(topicId, start, count);
needPrepare = false;
}
else {
posts = dao.selectAllByTopicByLimit(topicId, start, count);
}
List helperList = new ArrayList();
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
for (Iterator iter = posts.iterator(); iter.hasNext(); ) {
Post p;
if (needPrepare) {
p = (Post)iter.next();
}
else {
p = new Post((Post)iter.next());
}
if (canEdit || (p.getUserId() != anonymousUser && p.getUserId() == userId)) {
p.setCanEdit(true);
}
helperList.add(needPrepare ? PostCommon.preparePostForDisplay(p) : p);
}
return helperList;
}
} |
package net.jforum.view.forum.common;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.context.RequestContext;
import net.jforum.dao.PostDAO;
import net.jforum.entities.Post;
import net.jforum.entities.Smilie;
import net.jforum.repository.BBCodeRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.repository.SmiliesRepository;
import net.jforum.security.SecurityConstants;
import net.jforum.util.SafeHtml;
import net.jforum.util.bbcode.BBCode;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
/**
* @author Rafael Steil
* @version $Id: PostCommon.java,v 1.58 2007/09/24 03:26:47 rafaelsteil Exp $
*/
public class PostCommon
{
public static Post preparePostForDisplay(Post post)
{
if (post.getText() == null) {
return post;
}
StringBuffer text = new StringBuffer(post.getText());
if (!post.isHtmlEnabled()) {
ViewCommon.replaceAll(text, "<", "<");
ViewCommon.replaceAll(text, ">", ">");
}
// Do not remove the trailing blank space, as it would
// cause some regular expressions to fail
ViewCommon.replaceAll(text, "\n", "<br /> ");
SafeHtml safeHtml = new SafeHtml();
post.setText(text.toString());
post.setText(safeHtml.makeSafe(post.getText()));
processText(post);
post.setText(safeHtml.ensureAllAttributesAreSafe(post.getText()));
return post;
}
private static void processText(Post post)
{
int codeIndex = post.getText().indexOf("[code");
int codeEndIndex = codeIndex > -1 ? post.getText().indexOf("[/code]") : -1;
boolean hasCodeBlock = false;
if (codeIndex == -1 || codeEndIndex == -1) {
post.setText(prepareTextForDisplayExceptCodeTag(post.getText().toString(),
post.isBbCodeEnabled(), post.isSmiliesEnabled()));
}
else if (post.isBbCodeEnabled()) {
hasCodeBlock = true;
int nextStartPos = 0;
StringBuffer result = new StringBuffer(post.getText().length());
while (codeIndex > -1 && codeEndIndex > -1 && codeEndIndex > codeIndex) {
codeEndIndex += "[/code]".length();
String nonCodeResult = prepareTextForDisplayExceptCodeTag(post.getText().substring(nextStartPos, codeIndex),
post.isBbCodeEnabled(), post.isSmiliesEnabled());
String codeResult = parseCode(post.getText().substring(codeIndex, codeEndIndex));
result.append(nonCodeResult).append(codeResult);
nextStartPos = codeEndIndex;
codeIndex = post.getText().indexOf("[code", codeEndIndex);
codeEndIndex = codeIndex > -1 ? post.getText().indexOf("[/code]", codeIndex) : -1;
}
if (nextStartPos > -1) {
String nonCodeResult = prepareTextForDisplayExceptCodeTag(post.getText().substring(nextStartPos),
post.isBbCodeEnabled(), post.isSmiliesEnabled());
result.append(nonCodeResult);
}
post.setText(result.toString());
}
if (hasCodeBlock) {
JForumExecutionContext.getTemplateContext().put("hasCodeBlock", hasCodeBlock);
}
}
private static String parseCode(String text)
{
for (Iterator iter = BBCodeRepository.getBBCollection().getBbList().iterator(); iter.hasNext();) {
BBCode bb = (BBCode)iter.next();
if (bb.getTagName().startsWith("code")) {
Matcher matcher = Pattern.compile(bb.getRegex()).matcher(text);
StringBuffer sb = new StringBuffer(text);
while (matcher.find()) {
StringBuffer lang = null;
StringBuffer contents = null;
if ("code".equals(bb.getTagName())) {
contents = new StringBuffer(matcher.group(1));
}
else {
lang = new StringBuffer(matcher.group(1));
contents = new StringBuffer(matcher.group(2));
}
ViewCommon.replaceAll(contents, "<br /> ", "\n");
// XML-like tags
ViewCommon.replaceAll(contents, "<", "<");
ViewCommon.replaceAll(contents, ">", ">");
// Note: there is no replacing for spaces and tabs as
// we are relying on the Javascript SyntaxHighlighter library
// to do it for us
StringBuffer replace = new StringBuffer(bb.getReplace());
int index = replace.indexOf("$1");
if ("code".equals(bb.getTagName())) {
if (index > -1) {
replace.replace(index, index + 2, contents.toString());
}
index = sb.indexOf("[code]");
}
else {
if (index > -1) {
replace.replace(index, index + 2, lang.toString());
}
index = replace.indexOf("$2");
if (index > -1) {
replace.replace(index, index + 2, contents.toString());
}
index = sb.indexOf("[code=");
}
int lastIndex = sb.indexOf("[/code]", index) + "[/code]".length();
if (lastIndex > index) {
sb.replace(index, lastIndex, replace.toString());
}
}
text = sb.toString();
}
}
return text;
}
public static String prepareTextForDisplayExceptCodeTag(String text, boolean isBBCodeEnabled, boolean isSmilesEnabled)
{
if (text == null) {
return text;
}
if (isSmilesEnabled) {
text = processSmilies(new StringBuffer(text));
}
if (isBBCodeEnabled && text.indexOf('[') > -1 && text.indexOf(']') > -1) {
for (Iterator iter = BBCodeRepository.getBBCollection().getBbList().iterator(); iter.hasNext();) {
BBCode bb = (BBCode)iter.next();
if (!bb.getTagName().startsWith("code")) {
text = text.replaceAll(bb.getRegex(), bb.getReplace());
}
}
}
text = parseDefaultRequiredBBCode(text);
return text;
}
public static String parseDefaultRequiredBBCode(String text)
{
Collection list = BBCodeRepository.getBBCollection().getAlwaysProcessList();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
BBCode bb = (BBCode)iter.next();
text = text.replaceAll(bb.getRegex(), bb.getReplace());
}
return text;
}
/**
* Replace the smlies code by the respective URL.
* @param text The text to process
* @return the parsed text. Note that the StringBuffer you pass as parameter
* will already have the right contents, as the replaces are done on the instance
*/
public static String processSmilies(StringBuffer text)
{
List smilies = SmiliesRepository.getSmilies();
for (Iterator iter = smilies.iterator(); iter.hasNext(); ) {
Smilie s = (Smilie) iter.next();
int pos = text.indexOf(s.getCode());
// The counter is used as prevention, in case
// the while loop turns into an always true
// expression, for any reason
int counter = 0;
while (pos > -1 && counter++ < 300) {
text.replace(pos, pos + s.getCode().length(), s.getUrl());
pos = text.indexOf(s.getCode());
}
}
return text.toString();
}
public static Post fillPostFromRequest()
{
Post p = new Post();
p.setTime(new Date());
return fillPostFromRequest(p, false);
}
public static Post fillPostFromRequest(Post p, boolean isEdit)
{
RequestContext request = JForumExecutionContext.getRequest();
p.setSubject(request.getParameter("subject"));
p.setBbCodeEnabled(request.getParameter("disable_bbcode") == null);
p.setSmiliesEnabled(request.getParameter("disable_smilies") == null);
p.setSignatureEnabled(request.getParameter("attach_sig") != null);
if (!isEdit) {
p.setUserIp(request.getRemoteAddr());
p.setUserId(SessionFacade.getUserSession().getUserId());
}
boolean htmlEnabled = SecurityRepository.canAccess(SecurityConstants.PERM_HTML_DISABLED,
request.getParameter("forum_id"));
p.setHtmlEnabled(htmlEnabled && request.getParameter("disable_html") == null);
if (p.isHtmlEnabled()) {
p.setText(new SafeHtml().makeSafe(request.getParameter("message")));
}
else {
p.setText(request.getParameter("message"));
}
return p;
}
public static boolean canEditPost(Post post)
{
return SessionFacade.isLogged()
&& (post.getUserId() == SessionFacade.getUserSession().getUserId()
|| SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_EDIT));
}
public static List topicPosts(PostDAO dao, boolean canEdit, int userId, int topicId, int start, int count)
{
boolean needPrepare = true;
List posts;
if (SystemGlobals.getBoolValue(ConfigKeys.POSTS_CACHE_ENABLED)) {
posts = PostRepository.selectAllByTopicByLimit(topicId, start, count);
needPrepare = false;
}
else {
posts = dao.selectAllByTopicByLimit(topicId, start, count);
}
List helperList = new ArrayList();
int anonymousUser = SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID);
for (Iterator iter = posts.iterator(); iter.hasNext(); ) {
Post p;
if (needPrepare) {
p = (Post)iter.next();
}
else {
p = new Post((Post)iter.next());
}
if (canEdit || (p.getUserId() != anonymousUser && p.getUserId() == userId)) {
p.setCanEdit(true);
}
helperList.add(needPrepare ? PostCommon.preparePostForDisplay(p) : p);
}
return helperList;
}
} |
package net.lucenews.controller;
import java.util.*;
import net.lucenews.*;
import net.lucenews.atom.*;
import net.lucenews.model.*;
import net.lucenews.model.exception.*;
import net.lucenews.view.*;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.w3c.dom.*;
public class FacetController extends Controller {
public static void doGet (LuceneContext c) throws Exception {
LuceneWebService service = c.getService();
LuceneIndexManager manager = service.getIndexManager();
LuceneRequest request = c.getRequest();
LuceneResponse response = c.getResponse();
LuceneIndex[] indices = manager.getIndices( request.getIndexNames() );
String[] facets = request.getFacets();
// Atom feed
Feed feed = new Feed();
// DOM Document
org.w3c.dom.Document document = XMLController.newDocument();
// load the readers
IndexReader[] readers = new IndexReader[ indices.length ];
for (int i = 0; i < indices.length; i++) {
readers[ i ] = indices[ i ].getIndexReader();
}
MultiReader reader = new MultiReader( readers );
// build the query
Query query = null;
if ( c.getOpenSearchQuery() != null && c.getOpenSearchQuery().getSearchTerms() != null ) {
query = c.getQueryParser().parse( c.getOpenSearchQuery().getSearchTerms() );
}
else {
query = new MatchAllDocsQuery();
}
// build the filter
Filter filter = new CachingWrapperFilter( new QueryFilter( query ) );
if ( c.getFilter() != null ) {
filter = new CachingWrapperFilter( c.getFilter() );
}
BitSet bits = filter.bits( reader );
// build an entry for each facet
for (String facet : facets) {
Entry entry = new Entry();
entry.setTitle( facet );
Element div = document.createElement("div");
div.setAttribute( "xmlns", XMLController.getXHTMLNamespace() );
Element dl = document.createElement("dl");
TermEnum termEnumeration = reader.terms( new Term( facet, "" ) );
while ( termEnumeration.next() && termEnumeration.term().field().equals( facet ) ) {
TermDocs termDocuments = reader.termDocs( termEnumeration.term() );
String name = termEnumeration.term().text();
int count = 0;
while ( termDocuments.next() ) {
if ( bits.get( termDocuments.doc() ) ) {
count++;
}
}
// only mention facets with more than one hit
if ( count > 0 ) {
Element dt = document.createElement("dt");
dt.appendChild( document.createTextNode( name ) );
dl.appendChild( dt );
Element dd = document.createElement("dd");
dd.appendChild( document.createTextNode( String.valueOf( count ) ) );
dl.appendChild( dd );
}
}
div.appendChild( dl );
entry.setContent( Content.xhtml( div ) );
feed.addEntry( entry );
}
// put back the readers
for (int i = 0; i < indices.length; i++) {
indices[ i ].putIndexReader( readers[ i ] );
}
AtomView.process( c, feed );
}
} |
package net.sf.jaer.eventprocessing;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLException;
import java.awt.Cursor;
import java.awt.Desktop;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Set;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import net.sf.jaer.Description;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.HasPropertyTooltips;
import net.sf.jaer.util.PropertyTooltipSupport;
/**
* An abstract class that all event processing methods should subclass.
* Subclasses are introspected to build a GUI to control the filter in
* {@link FilterPanel} - see this class to see how to add these introspected
* controls to an EventFilter GUI control panel.
* <p>
* Filters that are enclosed inside another filter are given a preferences node
* that is derived from the the chip class that the filter is used on and the
* enclosing filter class. The same preferences node name is used for
* FilterChain's that are enclosed inside an EventFilter.
* <p>
* Fires PropertyChangeEvent for the following
* <ul>
* <li> "filterEnabled" - when the filter is enabled or disabled this event is
* fired, if the subclass has not overridden the setFilterEnabled method
* </ul>
*
* @see FilterPanel FilterPanel - which is where EventFilter's GUIs are built.
* @see net.sf.jaer.graphics.FrameAnnotater FrameAnnotator - to annotate the
* graphical output.
* @see net.sf.jaer.eventprocessing.EventFilter2D EventFilter2D - which
* processes events.
* @see net.sf.jaer.eventprocessing.FilterChain FilterChain - about enclosing
* filters inside other filters.
* @author tobi
*/
@Description("Base event processing class")
public abstract class EventFilter extends Observable implements HasPropertyTooltips {
/**
* URL for jAER wiki help page for event filters
*/
public static final String HELP_WIKI_URL = "http://sourceforge.net/p/jaer/wiki/";
/**
* Use this key for global parameters in your filter constructor, as in
* <pre> setPropertyTooltip(TOOLTIP_GROUP_GLOBAL, "propertyName", "property tip string");
* </pre>
*/
public static final String TOOLTIP_GROUP_GLOBAL = PropertyTooltipSupport.TOOLTIP_GROUP_GLOBAL;
public EventProcessingPerformanceMeter perf;
/**
* The preferences for this filter, by default in the EventFilter package
* node
*
* @see setEnclosed
*/
private Preferences prefs = null; // default null, constructed when AEChip is known Preferences.userNodeForPackage(EventFilter.class);
/**
* Provides change support, e.g. for enabled state. Filters can cause their
* FilterPanel GUI control for a property to update if they fire a
* PropertyChangeEvent in the property setter, giving the name of the
* property as the event. For example, Filters can also use support to
* inform each other about changes in state.
*/
protected PropertyChangeSupport support = new PropertyChangeSupport(this);
/**
* All filters can log to this logger
*/
public static final Logger log = Logger.getLogger("EventFilter");
/**
* true if filter is enclosed by another filter
*/
private boolean enclosed = false;
/**
* The enclosing filter
*/
private EventFilter enclosingFilter = null;
/**
* The enclosed single filter. This object is used for GUI building - any
* processing must be handled in filterPacket
*/
protected EventFilter enclosedFilter;
/**
* An enclosed filterChain - these filters must be manually applied (coded)
* in the filterPacket method but a GUI for them is automatically built.
* Initially null - subclasses must make a new FilterChain and set it for
* this filter.
*/
protected FilterChain enclosedFilterChain;
/**
* This boolean controls annotation for filters that are FrameAnnotator
*/
protected boolean annotationEnabled = true;
/**
* Used by filterPacket to say whether to filter events; default false
*/
protected boolean filterEnabled = false;
/**
* Flags this EventFilter as "selected" for purposes of control
*/
public boolean selected = false;
// /** true means the events are filtered in place, replacing the contents of the input packet and more
// *efficiently using memory. false means a new event packet is created and populated for the output of the filter.
// *<p>
// *default is false
// */
// protected boolean filterInPlaceEnabled=false;
/**
* chip that we are filtering for
*/
protected AEChip chip;
// for checkBlend()
private boolean hasBlendChecked = false;
private boolean hasBlend = false;
protected PropertyTooltipSupport tooltipSupport = new PropertyTooltipSupport();
/**
* Creates a new instance of AbstractEventFilter but does not enable it.
*
* @param chip the chip to filter for
* @see #setPreferredEnabledState
*/
public EventFilter(AEChip chip) {
this.chip = chip;
try {
prefs = constructPrefsNode();
} catch (Exception e) {
log.warning("Constructing prefs for " + this + ": " + e.getMessage() + " cause=" + e.getCause());
}
}
/**
* should reset the filter to initial state
*/
abstract public void resetFilter();
/**
* Should allocate and initialize memory. it may be called when the chip
* e.g. size parameters are changed after creation of the filter.
*/
abstract public void initFilter();
/**
* Clean up that should run when before filter is finalized, e.g. dispose of
* Components. Subclasses can override this method which does nothing by
* default.
*/
synchronized public void cleanup() {
}
/**
* Filters can be enabled for processing.
*
* @return true if filter is enabled
*/
synchronized public boolean isFilterEnabled() {
return filterEnabled;
}
/**
* Filters can be enabled for processing. Setting enabled also sets an
* enclosed filter to the same state. Setting filter enabled state only
* stores the preference value for enabled state if the filter is not
* enclosed inside another filter, to avoid setting global preferences for
* the filter enabled state.
* <p>
* Fires a property change event "filterEnabled" so that GUIs can be
* updated.
* </p>
*
* @param enabled true to enable filter. false should have effect that
* output events are the same as input.
* @see #setPreferredEnabledState
*/
synchronized public void setFilterEnabled(boolean enabled) {
boolean wasEnabled = filterEnabled;
filterEnabled = enabled;
if (getEnclosedFilter() != null) {
getEnclosedFilter().setFilterEnabled(filterEnabled);
}
if (getEnclosedFilterChain() != null) {
for (EventFilter f : getEnclosedFilterChain()) {
f.setFilterEnabled(enabled);
}
}
// log.info(getClass().getName()+".setFilterEnabled("+filterEnabled+")");
if (!isEnclosed()) {
String key = prefsEnabledKey();
prefs.putBoolean(key, enabled);
}
support.firePropertyChange("filterEnabled", new Boolean(wasEnabled), new Boolean(enabled));
}
/**
* @return the chip this filter is filtering for
*/
public AEChip getChip() {
return chip;
}
/**
* @param chip the chip to filter
*/
public void setChip(AEChip chip) {
this.chip = chip;
}
/**
* Gets the enclosed filter
*
* @return the enclosed filter
*/
public EventFilter getEnclosedFilter() {
return enclosedFilter;
}
/**
* Sets another filter to be enclosed inside this one - this enclosed filter
* should be applied first and must be applied by the filter. This enclosed
* filter is displayed hierarchically in the FilterPanel used in
* FilterFrame.
*
* @param enclosedFilter the filter to enclose
* @param enclosingFilter the filter that is enclosing this filter
* @see #setEnclosed
*/
public void setEnclosedFilter(final EventFilter enclosedFilter, final EventFilter enclosingFilter) {
this.enclosedFilter = enclosedFilter;
this.enclosingFilter = enclosingFilter;
if (enclosedFilter != null) {
enclosedFilter.setEnclosed(true, enclosingFilter);
}
}
/**
* Each filter has an annotationEnabled flag that is used to graphical
* annotation of the filter, e.g. a spatial border, text strings, global
* graphical overlay, etc. isAnnotationEnabled returns
* <ul>
* <li>false if filter is not FrameAnnotater.
* <li>true if the filter is not enclosed and the filter. is enabled and
* annotation is enabled.
* <li>It returns false if the filter is enclosed and the enclosing filter
* is not enabled.
* </ul>
*
* @return true to show filter annotation should be shown
*/
public boolean isAnnotationEnabled() {
if (!(this instanceof FrameAnnotater)) {
return false;
}
if (annotationEnabled && isFilterEnabled() && !isEnclosed()) {
return true;
}
if (annotationEnabled && isFilterEnabled() && isEnclosed() && getEnclosingFilter().isFilterEnabled()) {
return true;
}
return false;
}
/**
* @param annotationEnabled true to draw annotations
*/
public void setAnnotationEnabled(boolean annotationEnabled) {
this.annotationEnabled = annotationEnabled;
}
/**
* Is filter enclosed inside another filter?
*
* @return true if this filter is enclosed inside another
*/
public boolean isEnclosed() {
return enclosed;
}
/**
* Sets flag to show this instance is enclosed. If this flag is set to true,
* then preferences node is changed to a node unique for the enclosing
* filter class.
*
* @param enclosingFilter the filter that is enclosing this
* @param enclosed true if this filter is enclosed
*/
public void setEnclosed(boolean enclosed, final EventFilter enclosingFilter) {
this.enclosed = enclosed;
this.enclosingFilter = enclosingFilter;
}
/**
* Returns the enclosed filter chain
*
* @return the chain
*/
public FilterChain getEnclosedFilterChain() {
return enclosedFilterChain;
}
/**
* Sets an enclosed filter chain which should by convention be processed
* first by the filter (but need not be). Also flags all the filters in the
* chain as enclosed.
*
* @param enclosedFilterChain the chain
*/
public void setEnclosedFilterChain(FilterChain enclosedFilterChain) {
if (this.enclosedFilterChain != null) {
log.warning("replacing existing enclosedFilterChain= " + this.enclosedFilterChain + " with new enclosedFilterChain= " + enclosedFilterChain);
}
if (enclosedFilterChain.isEmpty()) {
log.warning("empty filter chain in " + this + " - you should set the filter chain after all filters have been added to it so that enclosed filters can be processed");
}
this.enclosedFilterChain = enclosedFilterChain;
for (EventFilter f : enclosedFilterChain) {
f.setEnclosed(true, this);
}
}
/**
* @return the enclosing filter if this filter is enclosed
*/
public EventFilter getEnclosingFilter() {
return enclosingFilter;
}
/**
* Sets the enclosing filter for this
*/
public void setEnclosingFilter(EventFilter enclosingFilter) {
this.enclosingFilter = enclosingFilter;
}
/**
* Flags this EventFilter as "selected" by exposing the GUI controls for
* filter parameters. This is different than "enabled".
*
* @return the selected
*/
public boolean isSelected() {
return selected;
}
/**
* Flags this EventFilter as selected. Used e.g. for GUI so that this can
* control its user interface, e.g. so that mouse events are ignored if this
* is not selected.
*
* @param selected the selected to set, true means this is "selected".
*/
public void setSelected(boolean selected) {
boolean old = this.selected;
this.selected = selected;
support.firePropertyChange("selected", old, selected);
}
/**
* Every filter has a PropertyChangeSupport object. This support is used by
* the FilterPanel GUI to be informed of property changes when property
* setters fire a property change with the property name and old and new
* values. This change in the property then will update the FilterPanel GUI
* control value. For example, the following shows how the boolean property
* <code>pathsEnabled</code> is handled.
* <pre>
* public void setPathsEnabled(boolean pathsEnabled) {
* boolean old=this.pathsEnabled;
* this.pathsEnabled = pathsEnabled;
* getSupport().firePropertyChange("pathsEnabled", old, pathsEnabled);
* putBoolean("pathsEnabled", pathsEnabled);
* }
* </pre> EventFilters can also use support for informing each other about
* changes in state. An EventFilter declares itself to be a
* PropertyChangeListener and then adds itself to another EventFilters
* support as a PropertyChangeListener.
*
* @return the support
*/
public PropertyChangeSupport getSupport() {
return support;
}
/**
* Convenience method to set cursor on containing AEViewer window if it
* exists, in case of long running operations. Typical usage is as follows:
* <pre><code>
* try{
* setCursor(new Cursor(Cursor.WAIT_CURSOR));
* // code to execute, in Swing thread
* } finally {
* setCursor(Cursor.getDefaultCursor());
* }
* </code>
* </pre>
*
* @param cursor
*/
protected void setCursor(Cursor cursor) {
if(chip!=null && chip.getAeViewer()!=null){
chip.getAeViewer().setCursor(cursor);
}
}
/** Convenience method to check if blending in OpenGL is available, and if so, to turn it on.
*
* @param gl the GL2 context
*/
protected void checkBlend(GL2 gl) {
if (!hasBlendChecked) {
hasBlendChecked = true;
String glExt = gl.glGetString(GL.GL_EXTENSIONS);
if (glExt.indexOf("GL_EXT_blend_color") != -1) {
hasBlend = true;
}
}
if (hasBlend) {
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
log.warning("tried to use glBlend which is supposed to be available but got following exception");
gl.glDisable(GL.GL_BLEND);
e.printStackTrace();
hasBlend = false;
}
}
}
/**
* The development status of an EventFilter. An EventFilter can implement
* the static method getDevelopmentStatus which returns the filter's
* DevelopmentStatus so that the EventFilter can be tagged or sorted for
* selection.
* <ul>
* <li>Alpha - the filter is experimental.
* <li>Beta - the filter functions but may have bugs.
* <li>Released - the filter is in regular use.
* <li>Unknown - the status is not known.
* </ul>
*/
public enum DevelopmentStatus {
Alpha, Beta, Released, Unknown
};
/**
* Override this enum to show the EventFilter's developement status.
*
* @see DevelopmentStatus
*/
public static DevelopmentStatus getDevelopmentStatus() {
return DevelopmentStatus.Unknown;
}
// preferences methods that add the filter name to the key automatically
/**
* Returns the Preferences node for this filter. This node is based on the
* chip class package but may be modified to a sub-node if the filter is
* enclosed inside another filter.
*
* @return the preferences node
* @see #setEnclosed
*/
public Preferences getPrefs() {
return prefs;
}
/**
* Synonym for getPrefs().
*
* @return the prefs node
* @see #getPrefs()
*/
public Preferences prefs() {
return prefs;
}
/**
* Sets the preferences node for this filter
*
* @param prefs the node
*/
public void setPrefs(Preferences prefs) {
this.prefs = prefs;
}
/**
* Constructs the prefs node for this EventFilter. It is based on the Chip
* preferences node if the chip exists, otherwise on the EventFilter class
* package. If the filter is enclosed, then the node includes the package of
* the enclosing filter class so that enclosed filters take in
* individualized preferences depending on where they are enclosed.
*/
private Preferences constructPrefsNode() {
Preferences prefs;
if (chip == null) {
prefs = Preferences.userNodeForPackage(getClass()); // base on EventFilter.class package
log.warning("null chip, basing prefs on EventFilter package");
} else {
prefs = chip.getPrefs(); // base on chip class
}
// are we being constructed by the initializer of an enclosing filter?
// if so, we should set up our preferences node so that we use a preferences node
// that is unique for the enclosing filter
// if we are being constucted inside another filter's init, then after we march
// down the stack trace and find ourselves, the next element should be another
// filter's init
// Checks if we are being constucted by another filter's initializer. If so, make a new
// prefs node that is derived from the enclosing filter class name.
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
boolean next = false;
String enclClassName = null;
for (StackTraceElement e : trace) {
if (e.getMethodName().contains("<init>")) {
if (next) {
enclClassName = e.getClassName();
break;
}
if (e.getClassName().equals(getClass().getName())) {
next = true;
}
}
}
// System.out.println("enclClassName="+enclClassName);
try {
if (enclClassName != null) {
Class enclClass = Class.forName(enclClassName);
if (EventFilter.class.isAssignableFrom(enclClass)) {
prefs = getPrefsForEnclosedFilter(prefs, enclClassName);
//log.info("This filter " + this.getClass() + " is enclosed in " + enclClass + " and has new Preferences node=" + prefs);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return prefs;
}
/**
* If the filter is enclosed, it's prefs node is the enclosing node plus the
* enclosing filter class node
*/
private Preferences getPrefsForEnclosedFilter(Preferences prefs, String enclClassName) {
// int clNaInd=enclClassName.lastIndexOf(".");
// enclClassName=enclClassName.substring(clNaInd,enclClassName.length());
prefs = Preferences.userRoot().node(prefs.absolutePath() + "/" + enclClassName.replace(".", "/"));
return prefs;
}
/**
* Sets the filter enabled according to the preference for enabled
*/
public void setPreferredEnabledState() {
setFilterEnabled(prefs.getBoolean(prefsEnabledKey(), filterEnabled));
}
/**
* Returns the prefernces key for the filter
*
* @return "<SimpleClassName>.filterEnabled" e.g.
* DirectionSelectiveFilter.filterEnabled
*/
public String prefsEnabledKey() {
String key = this.getClass().getSimpleName() + ".filterEnabled";
return key;
}
/**
* Returns if the property preference has previously been stored. Can be
* used to set a default value for a property if it has not yet been
* initialized.
*
* @return true is a String "getString" on the key returns non-null.
*/
protected boolean isPreferenceStored(String key) {
return getString(key, null) != null;
}
/**
* The header part of the Preferences key, e.g. "BackgroundActivityFilter.".
*
* @return the string header for built-in preferences.
*/
protected String prefsKeyHeader() {
return getClass().getSimpleName() + ".";
}
// <editor-fold defaultstate="collapsed" desc="-- putter Methods for types of preference variables --">
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putLong(String key, long value) {
prefs.putLong(prefsKeyHeader() + key, value);
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putInt(String key, int value) {
prefs.putInt(prefsKeyHeader() + key, value);
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putFloat(String key, float value) {
prefs.putFloat(prefsKeyHeader() + key, value);
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putDouble(String key, double value) {
prefs.putDouble(prefsKeyHeader() + key, value);
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putByteArray(String key, byte[] value) {
prefs.putByteArray(prefsKeyHeader() + key, value);
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putFloatArray(String key, float[] value) {
prefs.putInt(prefsKeyHeader() + key + "Length", value.length);
for (int i = 0; i < value.length; i++) {
prefs.putFloat(prefsKeyHeader() + key + i, value[i]);
}
}
/**
* Puts a preference.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putBoolean(String key, boolean value) {
prefs.putBoolean(prefsKeyHeader() + key, value);
}
/**
* Puts a preference string.
*
* @param key the property name, e.g. "tauMs"
* @param value the value to be stored
*/
public void putString(String key, String value) {
prefs.put(prefsKeyHeader() + key, value);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="-- getter Methods for all types of preference variables --">
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs"
* @param def the value to be stored
* @return long value
*/
public long getLong(String key, long def) {
return prefs.getLong(prefsKeyHeader() + key, def);
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return int value
*/
public int getInt(String key, int def) {
return prefs.getInt(prefsKeyHeader() + key, def);
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return float value
*/
public float getFloat(String key, float def) {
return prefs.getFloat(prefsKeyHeader() + key, def);
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return double value
*/
public double getDouble(String key, double def) {
return prefs.getDouble(prefsKeyHeader() + key, def);
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return byte[] in preferences
*/
public byte[] getByteArray(String key, byte[] def) {
return prefs.getByteArray(prefsKeyHeader() + key, def);
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return float[] in preferences
*/
public float[] getFloatArray(String key, float[] def) {
int length = prefs.getInt(prefsKeyHeader() + key + "Length", 0);
if (def.length != length) {
return def;
}
float[] outArray = new float[length];
for (int i = 0; i < length; i++) {
outArray[i] = prefs.getFloat(prefsKeyHeader() + key + i, 0.0f);
}
return outArray;
}
/**
* Gets a preference from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return boolean value
*/
public boolean getBoolean(String key, boolean def) {
return prefs.getBoolean(prefsKeyHeader() + key, def);
}
/**
* Gets a preference string from the built in preferences node.
*
* @param key the property name, e.g. "tauMs".
* @param def the default value if there is no preference already stored.
* @return string value
*/
public String getString(String key, String def) {
return prefs.get(prefsKeyHeader() + key, def);
}
// </editor-fold>
/**
* Returns Description value of this filter as annotated by Description
* annotation. Note this method is not static and requires the EventFilter
* to already be constructed. The ClassChooser dialog uses the annotation to
* obtain class Descriptions without constructing the objects first.
*
* @return the String description (the value() of the Description) or null
* if no description is available or any exception is thrown.
*/
public String getDescription() {
try {
Class c = this.getClass();
Description d = (Description) c.getAnnotation(Description.class);
if (d == null) {
return null;
}
return d.value();
} catch (Exception e) {
return null;
}
}
private void showInBrowser(String url) {
if (!Desktop.isDesktopSupported()) {
log.warning("No Desktop support, can't show help from " + url);
return;
}
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException | URISyntaxException ex) {
log.warning("Couldn't show " + url + "; caught " + ex);
}
}
/**
* Shows help from the jAER wiki page for filter documentation
*/
public void showHelpInBrowser() {
showInBrowser(EventFilter.HELP_WIKI_URL + "filt." + getClass().getName());
}
/**
* Adds a property to a group, creating the group if needed.
*
* @param groupName a named parameter group.
* @param propertyName the property name.
*/
public void addPropertyToGroup(String groupName, String propertyName) {
tooltipSupport.addPropertyToGroup(groupName, propertyName);
}
/**
* Developers can use setPropertyTooltip to add an optional tool-tip for a
* filter property so that the tip is shown as the tool-tip for the label or
* check-box property in the generated GUI.
* <p>
* In netbeans, you can add this macro to ease entering tooltips for filter
* parameters:
* <pre>
* select-word copy-to-clipboard caret-begin-line caret-down "{setPropertyTooltip(\"" paste-from-clipboard "\",\"\");}" insert-break caret-up caret-end-line caret-backward caret-backward caret-backward caret-backward
* </pre>
*
* @param propertyName the name of the property (e.g. an int, float, or
* boolean, e.g. "dt")
* @param tooltip the tooltip String to display
*/
final public void setPropertyTooltip(String propertyName, String tooltip) {
tooltipSupport.setPropertyTooltip(propertyName, tooltip);
}
/**
* Convenience method to add properties to groups along with adding a tip
* for the property.
*
* @param groupName the property group name.
* @param propertyName the property name.
* @param tooltip the tip.
* @see #TOOLTIP_GROUP_GLOBAL
*/
final public void setPropertyTooltip(String groupName, String propertyName, String tooltip) {
tooltipSupport.setPropertyTooltip(groupName, propertyName, tooltip);
}
/**
* @return the tooltip for the property
*/
@Override
final public String getPropertyTooltip(String propertyName) {
return tooltipSupport.getPropertyTooltip(propertyName);
}
/**
* Returns the name of the property group for a property.
*
* @param propertyName the property name string.
* @return the property group name.
*/
public String getPropertyGroup(String propertyName) {
return tooltipSupport.getPropertyGroup(propertyName);
}
/**
* Gets the list of property names in a particular group.
*
* @param groupName the name of the group.
* @return the ArrayList of property names in the group.
*/
public ArrayList<String> getPropertyGroupList(String groupName) {
return tooltipSupport.getPropertyGroupList(groupName);
}
/**
* Returns the set of property groups.
*
* @return Set view of property groups.
*/
public Set<String> getPropertyGroupSet() {
return tooltipSupport.getPropertyGroupSet();
}
/**
* Returns the mapping from property name to group name. If null, no groups
* have been declared.
*
* @return the map, or null if no groups have been declared by adding any
* properties.
* @see #property2GroupMap
*/
public HashMap<String, String> getPropertyGroupMap() {
return tooltipSupport.getPropertyGroupMap();
}
/**
* Returns true if the filter has property groups.
*/
public boolean hasPropertyGroups() {
return tooltipSupport.hasPropertyGroups();
}
} |
package net.sf.jaer.eventprocessing.filter;
import java.awt.Font;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
import java.util.TimeZone;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.aemonitor.AEConstants;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.AbstractAEPlayer;
import net.sf.jaer.graphics.ChipCanvas;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.gl2.GLUT;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.PolarityEvent.Polarity;
import net.sf.jaer.eventio.AEFileInputStreamInterface;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Annotates the rendered data stream canvas with additional information like a
* clock with absolute time, a bar showing instantaneous activity rate, a graph
* showing historical activity over the file, etc. These features are enabled by
* flags of the filter.
*
* @author tobi
*/
@Description("Adds useful information annotation to the display, e.g. date/time/event rate")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class Info extends EventFilter2D implements FrameAnnotater, PropertyChangeListener, Observer {
private AEFileInputStreamInterface aeFileInputStream = null; // current recorded file input stream
private DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ISO_DATE_TIME;
private DateTimeFormatter timeFormat=DateTimeFormatter.ISO_TIME;
private boolean analogClock = getPrefs().getBoolean("Info.analogClock", true);
private boolean digitalClock = getPrefs().getBoolean("Info.digitalClock", true);
private boolean date = getPrefs().getBoolean("Info.date", true);
private boolean absoluteTime = getPrefs().getBoolean("Info.absoluteTime", true);
private int timeOffsetMs = getPrefs().getInt("Info.timeOffsetMs", 0);
private float timestampScaleFactor = getPrefs().getFloat("Info.timestampScaleFactor", 1);
private float eventRateScaleMax = getPrefs().getFloat("Info.eventRateScaleMax", 1e5f);
private boolean timeScaling = getPrefs().getBoolean("Info.timeScaling", true);
private boolean showRateTrace = getBoolean("showRateTrace", true);
public final int MAX_SAMPLES = 1000; // to avoid running out of memory
private int maxSamples = getInt("maxSamples", MAX_SAMPLES);
private long dataFileTimestampStartTimeUs = 0;
private long wrappingCorrectionMs = 0;
private long absoluteStartTimeMs = 0;
volatile private long clockTimeMs = 0; // volatile because this field accessed by filtering and rendering threads
volatile private long updateTimeMs = 0; // volatile because this field accessed by filtering and rendering threads
// volatile private float eventRateMeasured = 0; // volatile, also shared
private boolean addedViewerPropertyChangeListener = false; // need flag because viewer doesn't exist on creation
private boolean eventRate = getBoolean("Info.eventRate", true);
private TypedEventRateEstimator typedEventRateEstimator;
private HashMap<EventRateEstimator, RateHistory> rateHistories = new HashMap();
private XYTypeFilter xyTypeFilter;
private EngineeringFormat engFmt = new EngineeringFormat();
private String maxRateString = engFmt.format(eventRateScaleMax);
private String maxTimeString = "unknown";
private boolean logStatistics = false;
private TobiLogger tobiLogger = null;
private boolean showAccumulatedEventCount = getBoolean("showAccumulatedEventCount", true);
private long accumulatedDVSEventCount = 0, accumulatedAPSSampleCount = 0, accumulatedIMUSampleCount = 0;
private long accumulatedDVSOnEventCount = 0, accumulatedDVSOffEventCount = 0;
private long accumulateTimeUs = 0;
/**
* computes the absolute time (since 1970) or relative time (in file) given
* the timestamp. The internal wrappingCorrection and any scaling and start
* time is applied.
*
* @param relativeTimeInFileMs the relative time in file in ms
* @return the absolute or relative time depending on absoluteTime switch,
* or the System.currentTimeMillis() if we are in live playback mode
*/
private long computeDisplayTime(long relativeTimeInFileMs) {
long t;
if ((chip.getAeViewer() != null) && (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.LIVE)) {
t = System.currentTimeMillis();
} else {
t = relativeTimeInFileMs + wrappingCorrectionMs;
t = (long) (t * timestampScaleFactor);
if (absoluteTime) {
t += absoluteStartTimeMs;
}
t = t + timeOffsetMs;
}
return t;
}
/**
* @return the logStatistics
*/
public boolean isLogStatistics() {
return logStatistics;
}
/**
* @param logStatistics the logStatistics to set
*/
synchronized public void setLogStatistics(boolean logStatistics) {
boolean old = this.logStatistics;
if (logStatistics) {
if (!this.logStatistics) {
setEventRate(true);
String s = "# statistics from Info filter logged starting at " + new Date() + " and originating from ";
if (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.PLAYBACK) {
s = s + " file " + chip.getAeViewer().getAePlayer().getAEInputStream().getFile().toString();
} else {
s = s + " input during PlayMode=" + chip.getAeViewer().getPlayMode().toString();
}
s = s + "\n# evenRateFilterTauMs=" + typedEventRateEstimator.getEventRateTauMs();
s = s + "\n#relativeLoggingTimeMs\tabsDataTimeSince1970Ms\teventRateHz";
if (tobiLogger == null) {
tobiLogger = new TobiLogger("Info", s);
} else {
tobiLogger.setHeaderLine(s);
}
tobiLogger.setEnabled(true);
}
} else if (this.logStatistics) {
tobiLogger.setEnabled(false);
log.info("stopped logging Info data to " + tobiLogger);
}
this.logStatistics = logStatistics;
getSupport().firePropertyChange("logStatistics", old, this.logStatistics);
}
public void doStartLogging() {
setLogStatistics(true);
}
public void doStopLogging() {
setLogStatistics(false);
}
// private long lastUpdateTime = 0;
// private final int MAX_WARNINGS_AND_UPDATE_INTERVAL = 100;
// private int warningCount = 0;
/**
* make event rate statistics be computed throughout a large package which
* could span many seconds....
*
*/
@Override
public void update(Observable o, Object arg) {
}
/**
* @return the showAccumulatedEventCount
*/
public boolean isShowAccumulatedEventCount() {
return showAccumulatedEventCount;
}
/**
* @param showAccumulatedEventCount the showAccumulatedEventCount to set
*/
public void setShowAccumulatedEventCount(boolean showAccumulatedEventCount) {
this.showAccumulatedEventCount = showAccumulatedEventCount;
putBoolean("showAccumulatedEventCount", showAccumulatedEventCount);
}
private void clearRateHistories() {
if (rateHistories != null) {
for (RateHistory r : rateHistories.values()) {
r.clear();
}
}
}
private long rateHistoriesStartTimeMs = Long.MAX_VALUE, rateHistoriesEndTimeMs = Long.MIN_VALUE;
private float rateHistoriesMinRate = Float.MAX_VALUE, rateHistoriesMaxRate = Float.MIN_VALUE;
private void computeRateHistoriesLimits() {
rateHistoriesStartTimeMs = Long.MAX_VALUE;
rateHistoriesEndTimeMs = Long.MIN_VALUE;
rateHistoriesMinRate = Float.MAX_VALUE;
rateHistoriesMaxRate = Float.MIN_VALUE;
if (rateHistories != null) {
for (RateHistory r : rateHistories.values()) {
if (r.startTimeMs < rateHistoriesStartTimeMs) {
rateHistoriesStartTimeMs = r.startTimeMs;
}
if (r.endTimeMs > rateHistoriesEndTimeMs) {
rateHistoriesEndTimeMs = r.endTimeMs;
}
if (r.minRate < rateHistoriesMinRate) {
rateHistoriesMinRate = r.minRate;
}
if (r.maxRate > rateHistoriesMaxRate) {
rateHistoriesMaxRate = r.maxRate;
}
}
}
}
private class RateHistory {
private LinkedList<RateSamples> rateSamples = new LinkedList();
private TextRenderer renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 24));
private long lastTimeAdded = Long.MIN_VALUE;
// make following global to cover all histories for common scale for plots
private long startTimeMs = Long.MAX_VALUE, endTimeMs = Long.MIN_VALUE;
private float minRate = Float.MAX_VALUE, maxRate = Float.MIN_VALUE;
synchronized void clear() {
rateSamples.clear();
startTimeMs = Long.MAX_VALUE;
endTimeMs = Long.MIN_VALUE;
minRate = Float.MAX_VALUE;
maxRate = Float.MIN_VALUE;
lastTimeAdded = Long.MIN_VALUE;
}
synchronized void addSample(long time, float rate) {
if (time < lastTimeAdded) {
log.info("time went backwards by " + (time - lastTimeAdded) + "ms, clearing history");
clear();
}
// System.out.println(String.format("adding RateHistory point at t=%-20d, dt=%-15d",time,(time-lastTimeAdded)));
// long dt=time-lastTimeAdded;
// log.info(String.format("added new sample with dt=%d ms and rate=%.1f Hz",dt,rate));
lastTimeAdded = time;
if (rateSamples.size() >= getMaxSamples()) {
RateSamples s = rateSamples.get(2);
startTimeMs = s.time;
rateSamples.removeFirst();
return;
}
rateSamples.add(new RateSamples(time, rate));
if (time < startTimeMs) {
startTimeMs = time;
}
if (time > endTimeMs) {
endTimeMs = time;
}
if (rate < minRate) {
minRate = rate;
}
if (rate > maxRate) {
maxRate = rate;
}
}
synchronized private void draw(GLAutoDrawable drawable, int sign) {
final int sx = chip.getSizeX(), sy = chip.getSizeY();
final int yorig = sy / 3, ysize = sy / 4; // where graph starts along y axis of chip
int n = rateSamples.size();
final long deltaTimeUs = rateHistoriesEndTimeMs - rateHistoriesStartTimeMs;
if ((n < 2) || ((deltaTimeUs) == 0)) {
return;
}
GL2 gl = drawable.getGL().getGL2();
if (sign > 0) {
gl.glColor3f(.82f, .8f, .2f);
} else {
gl.glColor3f(.8f, .2f, .2f);
}
gl.glLineWidth(1.5f);
// draw xaxis
gl.glBegin(GL.GL_LINES);
float x0 = 0;
gl.glVertex2f(x0, yorig);
gl.glVertex2f(sx, yorig);
gl.glEnd();
// draw y axis
gl.glBegin(GL.GL_LINE_STRIP);
gl.glVertex2f(x0, yorig);
gl.glVertex2f(x0, yorig + ysize);
gl.glEnd();
gl.glPushMatrix();
// gl.glColor3f(1, 1, .8f);
gl.glLineWidth(1.5f);
gl.glTranslatef(0.5f, yorig, 0);
// gl.glRotatef(90, 0, 0, 1);
// gl.glRotatef(-90, 0, 0, 1);
gl.glScalef((float) (sx - 1) / (deltaTimeUs), (ysize) / (maxRate), 1);
gl.glBegin(GL.GL_LINE_STRIP);
for (RateSamples s : rateSamples) {
gl.glVertex2f(s.time - rateHistoriesStartTimeMs, s.rate * sign);
}
gl.glEnd();
gl.glPopMatrix();
gl.glPushMatrix();
maxRateString = String.format("max %s eps", engFmt.format(rateHistoriesMaxRate));
maxTimeString = String.format("%s s", engFmt.format((deltaTimeUs) * .001f));
GLUT glut = chip.getCanvas().getGlut();
int font = GLUT.BITMAP_9_BY_15;
ChipCanvas.Borders borders = chip.getCanvas().getBorders();
float w = drawable.getSurfaceWidth() - (2 * borders.leftRight * chip.getCanvas().getScale());
// int ntypes = typedEventRateEstimator.getNumCellTypes();
float sw = (glut.glutBitmapLength(font, maxRateString) / w) * sx;
gl.glRasterPos3f(0, yorig + ysize * sign, 0);
glut.glutBitmapString(font, maxRateString);
sw = (glut.glutBitmapLength(font, maxTimeString) / w) * sx;
gl.glRasterPos3f(sx - sw, sy * .3f, 0);
glut.glutBitmapString(font, maxTimeString);
gl.glPopMatrix();
}
synchronized private void initFromAEFileInputStream(AEFileInputStreamInterface fis) {
aeFileInputStream = fis;
endTimeMs = (AEConstants.TICK_DEFAULT_US * fis.getFirstTimestamp()) / 1000;
endTimeMs = (AEConstants.TICK_DEFAULT_US * fis.getLastTimestamp()) / 1000;
if (endTimeMs < startTimeMs) {
clear();
}
}
}
private class RateSamples {
long time;
float rate;
public RateSamples(long time, float rate) {
this.time = time;
this.rate = rate;
}
}
/**
* Creates a new instance of Info for the chip
*
* @param chip the chip object
*/
public Info(AEChip chip) {
super(chip);
xyTypeFilter = new XYTypeFilter(chip);
typedEventRateEstimator = new TypedEventRateEstimator(chip);
typedEventRateEstimator.getSupport().addPropertyChangeListener(EventRateEstimator.EVENT_RATE_UPDATE, this);
FilterChain fc = new FilterChain(chip);
fc.add(xyTypeFilter);
fc.add(typedEventRateEstimator);
setEnclosedFilterChain(fc);
setPropertyTooltip("analogClock", "show normal circular clock");
setPropertyTooltip("digitalClock", "show digital clock; includes timezone as last component of time (e.g. -0800) if availble from file or local computer");
setPropertyTooltip("date", "show date");
setPropertyTooltip("absoluteTime", "enable to show absolute time, disable to show timestmp time (usually relative to start of recording");
setPropertyTooltip("showTimeAsEventTimestamp", "if enabled, time will be displayed in your timezone, e.g. +1 hour in Zurich relative to GMT; if disabled, time will be displayed in GMT");
setPropertyTooltip("timeOffsetMs", "add this time in ms to the displayed time");
setPropertyTooltip("timestampScaleFactor", "scale timestamps by this factor to account for crystal offset");
setPropertyTooltip("eventRateScaleMax", "scale event rates to this maximum");
setPropertyTooltip("timeScaling", "shows time scaling relative to real time");
setPropertyTooltip("eventRate", "shows average event rate");
setPropertyTooltip("eventRateSigned", "uses signed event rate for ON positive and OFF negative");
setPropertyTooltip("eventRateTauMs", "lowpass time constant in ms for filtering event rate");
setPropertyTooltip("showRateTrace", "shows a historical trace of event rate");
setPropertyTooltip("maxSamples", "maximum number of samples before clearing rate history");
setPropertyTooltip("logStatistics", "<html>enables logging of any activiated statistics (e.g. event rate) to a log file <br>written to the startup folder (host/java). <p>See the logging output for the file location.");
setPropertyTooltip("showAccumulatedEventCount", "Shows accumulated event count since the last reset or rewind. Use it to Mark a location in a file, and then see how many events have been recieved.");
}
private boolean increaseWrappingCorrectionOnNextPacket = false;
/**
* handles tricky property changes coming from AEViewer and
* AEFileInputStream
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() instanceof AEFileInputStream) {
if (evt.getPropertyName().equals(AEInputStream.EVENT_REWOUND)) {
log.info("rewind PropertyChangeEvent received by " + this + " from " + evt.getSource());
wrappingCorrectionMs = 0;
clearRateHistories();
resetAccumulatedStatistics();
setLogStatistics(false);
} else if (evt.getPropertyName().equals(AEInputStream.EVENT_WRAPPED_TIME)) {
increaseWrappingCorrectionOnNextPacket = true;
// System.out.println("property change in Info that is wrap time event");
log.info("timestamp wrap event received by " + this + " from " + evt.getSource() + " oldValue=" + evt.getOldValue() + " newValue=" + evt.getNewValue() + ", wrappingCorrectionMs will increase on next packet");
} else if (evt.getPropertyName().equals(AEInputStream.EVENT_INIT)) {
log.info("EVENT_INIT recieved, signaling new input stream");
aeFileInputStream = (AEFileInputStream) (evt.getSource());
for (RateHistory r : rateHistories.values()) {
r.initFromAEFileInputStream(aeFileInputStream);
}
} else if (evt.getPropertyName().equals(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP)) {
// rateHistory.clear();
}
} else if (evt.getSource() instanceof AEViewer) {
if (evt.getPropertyName().equals(AEViewer.EVENT_FILEOPEN)) { // TODO don't get this because AEViewer doesn't refire event from AEPlayer and we don't get this on initial fileopen because this filter has not yet been run so we have not added ourselves to the viewer
// new value is file name
aeFileInputStream=chip.getAeViewer().getAePlayer().getAEInputStream();
getAbsoluteStartingTimeMsFromFile();
for (RateHistory r : rateHistories.values()) {
r.clear();
}
} else if (evt.getPropertyName().equals(AEViewer.EVENT_ACCUMULATE_ENABLED)) {
resetAccumulatedStatistics();
}else if (evt.getPropertyName().equals(AEViewer.EVENT_PLAYMODE)) {
if(AEViewer.PlayMode.valueOf((String)evt.getNewValue())==AEViewer.PlayMode.LIVE){
aeFileInputStream=null; // TODO not best coding; forces local timezone for live playback
}
}
} else if (evt.getSource() instanceof EventRateEstimator) {
if (evt.getPropertyName().equals(EventRateEstimator.EVENT_RATE_UPDATE)) {
UpdateMessage msg = (UpdateMessage) evt.getNewValue();
// System.out.println("dt=" + (msg.timestamp - lastUpdateTime)/1000+" ms");
// for large files, the relativeTimeInFileMs wraps around after 2G us and then every 4G us
long relativeTimeInFileMs = (msg.timestamp - dataFileTimestampStartTimeUs) / 1000;
updateTimeMs = computeDisplayTime(relativeTimeInFileMs);
// long dt = (updateTimeMs - lastUpdateTime);
// if (dt > eventRateFilter.getEventRateTauMs() * 2) { // TODO hack to get around problem that sometimes the wrap preceeds the actual data
// log.warning("not adding this RateHistory point because dt is too big, indicating a big wrap came too soon");
// return;
// if (((updateTimeMs < lastUpdateTime) && (warningCount < MAX_WARNINGS_AND_UPDATE_INTERVAL)) || ((warningCount % MAX_WARNINGS_AND_UPDATE_INTERVAL) == 0)) {
// warningCount++;
// log.warning("Negative delta time detected; dt=" + dt);
// lastUpdateTime = updateTimeMs;
if (showRateTrace) {
if (rateHistories == null || typedEventRateEstimator.getNumCellTypes() != rateHistories.values().size()) {
rateHistories.clear();
EventRateEstimator[] r = typedEventRateEstimator.getEventRateEstimators();
for (int i = 0; i < r.length; i++) {
RateHistory h = new RateHistory();
rateHistories.put(r[i], h);
}
}
rateHistories.get(msg.source).addSample(updateTimeMs, ((EventRateEstimator) msg.source).getFilteredEventRate());
}
if (logStatistics) {
String s = String.format("%20d\t%20.2g", updateTimeMs, typedEventRateEstimator.getFilteredEventRate());
tobiLogger.log(s);
}
}
}
}
private void resetAccumulatedStatistics() {
accumulatedDVSEventCount = 0;
accumulatedDVSOnEventCount = 0;
accumulatedDVSOffEventCount = 0;
accumulatedAPSSampleCount = 0;
accumulatedIMUSampleCount = 0;
accumulateTimeUs = 0;
}
private void getAbsoluteStartingTimeMsFromFile() {
AbstractAEPlayer player = chip.getAeViewer().getAePlayer();
if (player != null) {
AEFileInputStreamInterface in = (player.getAEInputStream());
if (in != null) {
log.info("added ourselves for PropertyChangeEvents from " + in);
in.getSupport().addPropertyChangeListener(this);
dataFileTimestampStartTimeUs = in.getFirstTimestamp();
absoluteStartTimeMs = in.getAbsoluteStartingTimeMs();
}
}
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
if (!addedViewerPropertyChangeListener) {
if (chip.getAeViewer() != null) {
chip.getAeViewer().addPropertyChangeListener(this);
chip.getAeViewer().getAePlayer().getSupport().addPropertyChangeListener(this); // TODO might be duplicated callback
addedViewerPropertyChangeListener = true;
getAbsoluteStartingTimeMsFromFile();
}
}
if ((in != null) && (in.getSize() > 0)) {
if (resetTimeEnabled) {
resetTimeEnabled = false;
dataFileTimestampStartTimeUs = in.getFirstTimestamp();
}
}
in = getEnclosedFilterChain().filterPacket(in);
long relativeTimeInFileMs = (in.getLastTimestamp() - dataFileTimestampStartTimeUs) / 1000;
clockTimeMs = computeDisplayTime(relativeTimeInFileMs);
// if the reader generated a bigwrap, then it told us already, before we processed this packet.
// This msg said that the *next* packet will be wrapped.
// so just process this packet normally, as above, then increment our wrap correction after that.
if (increaseWrappingCorrectionOnNextPacket) {
long old = wrappingCorrectionMs;
boolean fwds = true; // TODO backwards not handled yet, since we don't know from wrap event which way we are going in a file
wrappingCorrectionMs = wrappingCorrectionMs + (fwds ? (1L << 32L) / 1000 : -(1L << 31L) / 1000); // 4G us
increaseWrappingCorrectionOnNextPacket = false;
// System.out.println("In Info, because flag was set, increased wrapping correction by "+(wrappingCorrectionMs-old));
log.info("because flag was set, increased wrapping correction by " + (wrappingCorrectionMs - old));
}
if (in instanceof ApsDvsEventPacket) {
ApsDvsEventPacket apsPkt = (ApsDvsEventPacket) in;
Iterator<ApsDvsEvent> i = apsPkt.fullIterator();
while (i.hasNext()) {
ApsDvsEvent e = i.next();
if (e.isImuSample()) {
accumulatedIMUSampleCount++;
} else if (e.isApsData()) {
accumulatedAPSSampleCount++;
} else if (e.isDVSEvent()) {
accumulatedDVSEventCount++;
if (e.getPolarity() == Polarity.On) {
accumulatedDVSOnEventCount++;
} else if (e.getPolarity() == Polarity.Off) {
accumulatedDVSOffEventCount++;
}
}
}
} else {
accumulatedDVSEventCount += in.getSize();
}
accumulateTimeUs += in.getDurationUs();
return in;
}
@Override
synchronized public void resetFilter() {
typedEventRateEstimator.resetFilter();
clearRateHistories();
resetAccumulatedStatistics();
}
@Override
public void initFilter() {
}
GLU glu = null;
GLUquadric wheelQuad;
@Override
public void annotate(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
drawClock(gl, clockTimeMs); // clockTimeMs is updated at the end of each packet, when the clock is displayed
drawEventRateBars(drawable);
drawAccumulatedEventCount(drawable);
if (chip.getAeViewer() != null) {
drawTimeScaling(drawable, chip.getAeViewer().getTimeExpansion());
}
drawRateSamples(drawable);
}
private void drawClock(GL2 gl, long t) {
final int radius = 20, hourLen = 10, minLen = 18, secLen = 7, msLen = 19;
Instant instant=Instant.ofEpochMilli(t);
ZonedDateTime zdt=null;
if(aeFileInputStream!=null && aeFileInputStream.getZoneId()!=null){
zdt=ZonedDateTime.ofInstant(instant, aeFileInputStream.getZoneId());
}else{
zdt=ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
}
final int hour = zdt.getHour()%12;
final int hourofday = zdt.getHour();
if ((hourofday > 18) || (hourofday < 6)) {
gl.glColor3f(.5f, .5f, 1);
} else {
gl.glColor3f(1f, 1f, .5f);
}
if (analogClock) {
// draw clock circle
if (glu == null) {
glu = new GLU();
}
if (wheelQuad == null) {
wheelQuad = glu.gluNewQuadric();
}
gl.glPushMatrix();
{
gl.glTranslatef(radius + 2, radius + 6, 0); // clock center
glu.gluQuadricDrawStyle(wheelQuad, GLU.GLU_FILL);
glu.gluDisk(wheelQuad, radius, radius + 0.5f, 24, 1);
// draw hour, minute, second hands
// each hand has x,y components related to periodicity of clock and time
gl.glColor3f(1, 1, 1);
// ms hand
gl.glLineWidth(1f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, 0);
double a = (2 * Math.PI * zdt.getNano()/100000) / 1000;
float x = msLen * (float) Math.sin(a);
float y = msLen * (float) Math.cos(a);
gl.glVertex2f(x, y);
gl.glEnd();
// second hand
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, 0);
a = (2 * Math.PI * zdt.getSecond()) / 60;
x = secLen * (float) Math.sin(a);
y = secLen * (float) Math.cos(a);
gl.glVertex2f(x, y);
gl.glEnd();
// minute hand
gl.glLineWidth(4f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, 0);
int minute = zdt.getMinute();
a = (2 * Math.PI * minute) / 60;
x = minLen * (float) Math.sin(a);
y = minLen * (float) Math.cos(a); // y= + when min=0, pointing at noon/midnight on clock
gl.glVertex2f(x, y);
gl.glEnd();
// hour hand
gl.glLineWidth(6f);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, 0);
a = (2 * Math.PI * (hour + (minute / 60.0))) / 12; // a=0 for midnight, a=2*3/12*pi=pi/2 for 3am/pm, etc
x = hourLen * (float) Math.sin(a);
y = hourLen * (float) Math.cos(a);
gl.glVertex2f(x, y);
gl.glEnd();
}
gl.glPopMatrix();
}
if (digitalClock) {
gl.glPushMatrix();
gl.glRasterPos3f(0, 0, 0);
GLUT glut = chip.getCanvas().getGlut();
if (date) {
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, dateTimeFormatter.format(zdt));
}else{
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, timeFormat.format(zdt));
}
gl.glPopMatrix();
}
}
private void drawEventRateBars(GLAutoDrawable drawable) {
if (!isEventRate()) {
return;
}
GL2 gl = drawable.getGL().getGL2();
// positioning of rate bars depends on num types and display size
ChipCanvas.Borders borders = chip.getCanvas().getBorders();
// get screen width in screen pixels, subtract borders in screen pixels to find width of drawn chip area in screen pixels
float /*h = drawable.getHeight(), */ w = drawable.getSurfaceWidth() - (2 * borders.leftRight * chip.getCanvas().getScale());
int ntypes = typedEventRateEstimator.getNumCellTypes();
final int sx = chip.getSizeX(), sy = chip.getSizeY();
final float yorig = .9f * sy, xpos = 0, ystep = Math.max(.03f * sy, 6), barh = .03f * sy;
gl.glPushMatrix();
// gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
// gl.glLoadIdentity();
gl.glColor3f(1, 1, 1);
int font = GLUT.BITMAP_9_BY_15;
GLUT glut = chip.getCanvas().getGlut();
int nbars = typedEventRateEstimator.isMeasureIndividualTypesEnabled() ? ntypes : 1;
for (int i = 0; i < nbars; i++) {
final float rate = typedEventRateEstimator.getFilteredEventRate(i);
float bary = yorig - (ystep * i);
gl.glRasterPos3f(xpos, bary, 0);
String s = null;
if (typedEventRateEstimator.isMeasureIndividualTypesEnabled()) {
s = String.format("Type %d: %10s", i, engFmt.format(rate) + " Hz");
} else {
s = String.format("All %d types: %10s", ntypes, engFmt.format(rate) + " Hz");
}
// get the string length in screen pixels , divide by chip array in screen pixels,
// and multiply by number of pixels to get string length in screen pixels.
float sw = (glut.glutBitmapLength(font, s) / w) * sx;
glut.glutBitmapString(font, s);
gl.glRectf(xpos + sw, bary + barh, xpos + sw + ((rate * sx) / getEventRateScaleMax()), bary);
}
gl.glPopMatrix();
}
private void drawAccumulatedEventCount(GLAutoDrawable drawable) {
if (!showAccumulatedEventCount) {
return;
}
GL2 gl = drawable.getGL().getGL2();
gl.glColor3f(1, 1, 1);
int font = GLUT.BITMAP_9_BY_15;
final int sx = chip.getSizeX(), sy = chip.getSizeY();
final float yorig = .7f * sy, xpos = 0;
GLUT glut = chip.getCanvas().getGlut();
gl.glRasterPos3f(xpos, yorig, 0);
int n = chip.getNumPixels();
float cDvs = (float) accumulatedDVSEventCount;
float cDvsOn = (float) accumulatedDVSOnEventCount;
float cDvsOff = (float) accumulatedDVSOffEventCount;
float cAps = (float) accumulatedAPSSampleCount;
float cImu = (float) accumulatedIMUSampleCount;
float t = 1e-6f * (float) accumulateTimeUs;
String s = String.format("In %ss:\n%s DVS events (%seps, %seps/pix)\n %s DVS ON events (%seps, %seps/pix)\n %s DVS OFF events (%seps, %seps/pix)\n%s APS samples (%ssps)\n%s IMU samples (%ssps)",
engFmt.format(t),
engFmt.format(accumulatedDVSEventCount), engFmt.format(cDvs / t), engFmt.format(cDvs / t / n),
engFmt.format(accumulatedDVSOnEventCount), engFmt.format(cDvsOn / t), engFmt.format(cDvsOn / t / n),
engFmt.format(accumulatedDVSOffEventCount), engFmt.format(cDvsOff / t), engFmt.format(cDvsOff / t / n),
engFmt.format(accumulatedAPSSampleCount / 2), engFmt.format(cAps / 2 / t), // divide by two for reset/signal reads
engFmt.format(accumulatedIMUSampleCount), engFmt.format(cImu / t));
MultilineAnnotationTextRenderer.setScale(.2f);
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .8f);
MultilineAnnotationTextRenderer.renderMultilineString(s);
// glut.glutBitmapString(font, s);
}
public void drawRateSamples(GLAutoDrawable drawable) {
if (!showRateTrace) {
return;
}
if (rateHistories == null) {
return;
}
computeRateHistoriesLimits();
synchronized (this) {
int i = 0;
for (RateHistory r : rateHistories.values()) {
r.draw(drawable, (int) Math.signum((i % 2) - .5f)); // alternate -1, +1
i++;
}
}
}
private void drawTimeScaling(GLAutoDrawable drawable, float timeExpansion) {
if (!isTimeScaling()) {
return;
}
final int sx = chip.getSizeX(), sy = chip.getSizeY();
final float yorig = .95f * sy, xpos = 0, barh = .03f * sy;
int h = drawable.getSurfaceHeight(), w = drawable.getSurfaceWidth();
GL2 gl = drawable.getGL().getGL2();
gl.glPushMatrix();
gl.glColor3f(1, 1, 1);
GLUT glut = chip.getCanvas().getGlut();
StringBuilder s = new StringBuilder();
if ((timeExpansion < 1) && (timeExpansion != 0)) {
s.append('/');
timeExpansion = 1 / timeExpansion;
} else {
s.append('x');
}
int font = GLUT.BITMAP_9_BY_15;
String s2 = String.format("Time factor: %10s", engFmt.format(timeExpansion) + s);
float sw = (glut.glutBitmapLength(font, s2) / (float) w) * sx;
gl.glRasterPos3f(0, yorig, 0);
glut.glutBitmapString(font, s2);
float x0 = xpos;
float x1 = (float) (xpos + (x0 * Math.log10(timeExpansion)));
float y0 = sy + barh;
float y1 = y0;
gl.glRectf(x0, y0, x1, y1);
gl.glPopMatrix();
}
public boolean isAnalogClock() {
return analogClock;
}
public void setAnalogClock(boolean analogClock) {
this.analogClock = analogClock;
getPrefs().putBoolean("Info.analogClock", analogClock);
}
public boolean isDigitalClock() {
return digitalClock;
}
public void setDigitalClock(boolean digitalClock) {
this.digitalClock = digitalClock;
getPrefs().putBoolean("Info.digitalClock", digitalClock);
}
public boolean isDate() {
return date;
}
public void setDate(boolean date) {
this.date = date;
getPrefs().putBoolean("Info.date", date);
}
public boolean isAbsoluteTime() {
return absoluteTime;
}
public void setAbsoluteTime(boolean absoluteTime) {
this.absoluteTime = absoluteTime;
getPrefs().putBoolean("Info.absoluteTime", absoluteTime);
}
public boolean isEventRate() {
return eventRate;
}
/**
* True to show event rate in Hz
*/
public void setEventRate(boolean eventRate) {
boolean old = this.eventRate;
this.eventRate = eventRate;
getPrefs().putBoolean("Info.eventRate", eventRate);
getSupport().firePropertyChange("eventRate", old, eventRate);
}
private volatile boolean resetTimeEnabled = false;
/**
* Reset the time zero marker to the next packet's first timestamp
*/
public void doResetTime() {
resetTimeEnabled = true;
}
public int getTimeOffsetMs() {
return timeOffsetMs;
}
public void setTimeOffsetMs(int timeOffsetMs) {
this.timeOffsetMs = timeOffsetMs;
getPrefs().putInt("Info.timeOffsetMs", timeOffsetMs);
}
public float getTimestampScaleFactor() {
return timestampScaleFactor;
}
public void setTimestampScaleFactor(float timestampScaleFactor) {
this.timestampScaleFactor = timestampScaleFactor;
getPrefs().putFloat("Info.timestampScaleFactor", timestampScaleFactor);
}
/**
* @return the eventRateScaleMax
*/
public float getEventRateScaleMax() {
return eventRateScaleMax;
}
/**
* @param eventRateScaleMax the eventRateScaleMax to set
*/
public void setEventRateScaleMax(float eventRateScaleMax) {
this.eventRateScaleMax = eventRateScaleMax;
getPrefs().putFloat("Info.eventRateScaleMax", eventRateScaleMax);
maxRateString = engFmt.format(eventRateScaleMax);
}
/**
* @return the timeScaling
*/
public boolean isTimeScaling() {
return timeScaling;
}
/**
* @param timeScaling the timeScaling to set
*/
public void setTimeScaling(boolean timeScaling) {
this.timeScaling = timeScaling;
getPrefs().putBoolean("Info.timeScaling", timeScaling);
}
/**
* @return the showRateTrace
*/
public boolean isShowRateTrace() {
return showRateTrace;
}
/**
* @param showRateTrace the showRateTrace to set
*/
public void setShowRateTrace(boolean showRateTrace) {
this.showRateTrace = showRateTrace;
putBoolean("showRateTrace", showRateTrace);
}
/**
* @return the maxSamples
*/
public int getMaxSamples() {
return maxSamples;
}
/**
* @param maxSamples the maxSamples to set
*/
public void setMaxSamples(int maxSamples) {
int old = this.maxSamples;
if (maxSamples < 100) {
maxSamples = 100;
}
this.maxSamples = maxSamples;
putInt("maxSamples", maxSamples);
getSupport().firePropertyChange("maxSamples", old, maxSamples);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.