lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
mit
|
bf593e516067689c0895c8291648d88136f33ae2
| 0
|
dmusican/Elegit,dmusican/Elegit,dmusican/Elegit
|
package elegit;
/**
* Class for uploading logged data
*/
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
public class DataSubmitter {
private static final String submitUrl = "http://elegit.mathcs.carleton.edu/logging/upload.php";
private static final Logger logger = LogManager.getLogger();
private static final String LOG_FILE_NAME = "elegit.log";
public DataSubmitter() {
}
public String submitData(String uuid) {
logger.info("Submit data called");
String logPath = Paths.get("logs").toString();
File logDirectory = new File(logPath);
File[] logsToUpload=logDirectory.listFiles();
String lastUUID="";
if (uuid==null || uuid.equals("")) {
uuid=UUID.randomUUID().toString();
logger.info("Making a new uuid.");
}
for (File logFile: logsToUpload) {
if (!logFile.isFile() || logFile.getName().equals(LOG_FILE_NAME)) {
if (logsToUpload.length == 1) {
logger.info("No new logs to upload today");
break;
}
}
// Move the file to a uuid filename for upload to the server.
try {
logFile = Files.copy(logFile.toPath(), logFile.toPath().resolveSibling(uuid+".log")).toFile();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Attempting to upload log: {}",logFile.getName());
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(submitUrl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(logFile);
builder.addPart("fileToUpload",fileBody);
HttpEntity builtEntity = builder.build();
httppost.setEntity(builtEntity);
logger.info(httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
logger.info("Executing request: " + response.getStatusLine());
logger.info(EntityUtils.toString(response.getEntity()));
lastUUID=uuid;
} catch (Exception e) {
logger.error("Response status check failed.");
response.close();
return null;
}
} catch (Exception e) {
logger.error("Failed to execute request. Attempting to close client.");
try {
httpclient.close();
} catch (Exception f) {
logger.error("Failed to close client.");
return null;
}
return null;
}
// Delete the log file as we might be uploading more!
logFile.delete();
}
// Clean up the directory
for (File file: logDirectory.listFiles()) {
if (!file.getName().equals(LOG_FILE_NAME))
file.delete();
}
return lastUUID;
}
}
|
src/main/java/elegit/DataSubmitter.java
|
package elegit;
/**
* Class for uploading logged data
*/
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
public class DataSubmitter {
private static final String submitUrl = "http://elegit.mathcs.carleton.edu/logging/upload.php";
private static final Logger logger = LogManager.getLogger();
private static final String LOG_FILE_NAME = "elegit.log";
public DataSubmitter() {
}
public String submitData(String uuid) {
logger.info("Submit data called");
String logPath = Paths.get("logs").toString();
File logDirectory = new File(logPath);
File[] logsToUpload=logDirectory.listFiles();
String lastUUID="";
if (uuid==null || uuid.equals("")) {
uuid=UUID.randomUUID().toString();
logger.info("Making a new uuid.");
}
for (File logFile: logsToUpload) {
if (!logFile.isFile() || logFile.getName().equals(LOG_FILE_NAME)) {
if (logsToUpload.length == 1) logger.info("No new logs to upload today");
break;
}
// Move the file to a uuid filename for upload to the server.
try {
logFile = Files.copy(logFile.toPath(), logFile.toPath().resolveSibling(uuid+".log")).toFile();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Attempting to upload log: {}",logFile.getName());
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(submitUrl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(logFile);
builder.addPart("fileToUpload",fileBody);
HttpEntity builtEntity = builder.build();
httppost.setEntity(builtEntity);
logger.info(httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
logger.info("Executing request: " + response.getStatusLine());
logger.info(EntityUtils.toString(response.getEntity()));
lastUUID=uuid;
} catch (Exception e) {
logger.error("Response status check failed.");
response.close();
return null;
}
} catch (Exception e) {
logger.error("Failed to execute request. Attempting to close client.");
try {
httpclient.close();
} catch (Exception f) {
logger.error("Failed to close client.");
return null;
}
return null;
}
}
// Clean up the directory
for (File file: logDirectory.listFiles()) {
if (!file.getName().equals(LOG_FILE_NAME))
file.delete();
}
return lastUUID;
}
}
|
Fixed data submission error where it could only upload 1 old log file
|
src/main/java/elegit/DataSubmitter.java
|
Fixed data submission error where it could only upload 1 old log file
|
|
Java
|
mit
|
cf0885490917f1cae7eb6fb943856e2daecea045
| 0
|
bounswe/bounswe2015group7,bounswe/bounswe2015group7,bounswe/bounswe2015group7,bounswe/bounswe2015group7
|
public class MathematicalOperations {
public int binaryPlus(int x,int y){
return x+y;
}
public int binaryMinus(int x, int y) {
return x-y;
}
public int times(int x, int y){ // returns x*y;
return x*y;
}
public int divide (int x, int y){// returns x/y
return x/y;
}
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
public float inverseDivide(int x, int y){
//returns y/x
return y/x;
}
}
|
src/main/java/MathematicalOperations.java
|
public class MathematicalOperations {
public int binaryPlus(int x,int y){
return x+y;
}
public int binaryMinus(int x, int y) {
return x-y;
}
public int times(int x, int y){ // returns x*y;
return x*y;
}
public int divide (int x, int y){// returns x/y
return x/y;
}
public double power (double x, int y){// returns x^y
double result=1;
if(y==0){
return 1;
}
if(y<0){
x=1/x;
}
for(int i=0; i<y; i++){
result = result*x;
}
return result;
}
public float inverseDivide(int x, int y){
//returns y/x
return y/x;
}
}
|
power operation has been added
|
src/main/java/MathematicalOperations.java
|
power operation has been added
|
|
Java
|
mit
|
b55ef92ffa6cd0a8600a8315939528ce9346a0cb
| 0
|
domisum/AuxiliumLib
|
package io.domisum.lib.auxiliumlib.ticker;
import io.domisum.lib.auxiliumlib.annotations.API;
import io.domisum.lib.auxiliumlib.util.DurationUtil;
import lombok.RequiredArgsConstructor;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
@API
public class IntervalTaskTicker
extends Ticker
{
// CONSTANTS
private static final Duration TICK_INTERVAL = Duration.ofMillis(10);
private static final Duration TASK_ERROR_COOLDOWN = Duration.ofSeconds(10);
// TASKS
private final Set<IntervalTask> tasks = new HashSet<>();
private boolean tasksLocked = false;
// INIT
@API
public IntervalTaskTicker(String threadName, Duration timeout)
{
super(threadName, TICK_INTERVAL, timeout);
}
@API
public synchronized void addTask(String taskName, Runnable task, Duration interval)
{
if(tasksLocked)
throw new IllegalStateException("can't add tasks after first start");
var intervalTask = new IntervalTask(taskName, task, interval);
tasks.add(intervalTask);
}
@API
@Override
public synchronized void start()
{
tasksLocked = true;
super.start();
}
// TICK
@Override
protected void tick(Supplier<Boolean> shouldStop)
{
for(var task : tasks)
{
if(Thread.currentThread().isInterrupted())
return;
if(shouldStop.get())
return;
if(task.shouldRunNow())
task.run();
}
}
// TASK
@RequiredArgsConstructor
private class IntervalTask
{
// BASE ATTRIBUTES
private final String name;
private final Runnable task;
private final Duration interval;
// STATUS
private Instant nextExecution = Instant.MIN;
// GETTERS
protected boolean shouldRunNow()
{
return DurationUtil.hasPassed(nextExecution);
}
// RUN
protected void run()
{
try
{
task.run();
nextExecution = Instant.now().plus(interval);
}
catch(RuntimeException e)
{
logger.error("error occured during execution of task {}", name, e);
nextExecution = Instant.now().plus(TASK_ERROR_COOLDOWN);
}
}
}
}
|
src/main/java/io/domisum/lib/auxiliumlib/ticker/IntervalTaskTicker.java
|
package io.domisum.lib.auxiliumlib.ticker;
import io.domisum.lib.auxiliumlib.annotations.API;
import io.domisum.lib.auxiliumlib.util.DurationUtil;
import lombok.RequiredArgsConstructor;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
@API
public class IntervalTaskTicker
extends Ticker
{
// CONSTANTS
private static final Duration TICK_INTERVAL = Duration.ofMillis(10);
private static final Duration TASK_ERROR_COOLDOWN = Duration.ofSeconds(10);
// TASKS
private final Set<IntervalTask> tasks = new HashSet<>();
private boolean tasksLocked = false;
// INIT
@API
public IntervalTaskTicker(String threadName, Duration timeout)
{
super(threadName, TICK_INTERVAL, timeout);
}
@API
public synchronized void addTask(String taskName, Runnable task, Duration interval)
{
if(tasksLocked)
throw new IllegalStateException("can't add tasks after first start");
var intervalTask = new IntervalTask(taskName, task, interval);
tasks.add(intervalTask);
}
@API
@Override
public synchronized void start()
{
tasksLocked = true;
super.start();
}
// TICK
@Override
protected void tick(Supplier<Boolean> shouldStop)
{
for(var task : tasks)
{
if(Thread.currentThread().isInterrupted())
return;
if(shouldStop.get())
return;
if(task.shouldRunNow())
task.run();
}
}
// TASK
@RequiredArgsConstructor
private class IntervalTask
{
// BASE ATTRIBUTES
private final String name;
private final Runnable task;
private final Duration interval;
// STATUS
private Instant nextExecution = Instant.MAX;
// GETTERS
protected boolean shouldRunNow()
{
return DurationUtil.hasPassed(nextExecution);
}
// RUN
protected void run()
{
try
{
task.run();
nextExecution = Instant.now().plus(interval);
}
catch(RuntimeException e)
{
logger.error("error occured during execution of task {}", name, e);
nextExecution = Instant.now().plus(TASK_ERROR_COOLDOWN);
}
}
}
}
|
Fixed interval task ticker first nextExecution
|
src/main/java/io/domisum/lib/auxiliumlib/ticker/IntervalTaskTicker.java
|
Fixed interval task ticker first nextExecution
|
|
Java
|
mit
|
26404ab0f4026acbc1a85385bb15d436b8099a83
| 0
|
Clerenz/folder-sync
|
package de.clemensloos.folder_sync;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The sync engine.
*/
public class Sync {
public static final String SLASH = "/";
public static Logger log = LogManager.getLogger(Sync.class);
private static volatile boolean keepGoing = true;
private SyncConfig config;
public Sync(SyncConfig config) {
this.config = config;
}
public void sync() {
Thread.currentThread().setName("MAIN");
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
for (Target t : config.getTargetList()) {
Thread thread = new SyncThread(t);
shutdownHook.setCurrentThread(thread);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
shutdownHook.setCurrentThread(null);
}
}
private class ShutdownHook extends Thread {
private Thread currentThread = null;
void setCurrentThread(Thread thread) {
this.currentThread = thread;
}
@Override
public void run() {
Thread.currentThread().setName("HOOK");
keepGoing = false;
if (currentThread != null) {
log.info("Safely shutting down ...");
try {
currentThread.join();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
}
}
}
private class SyncThread extends Thread {
private Target t;
SyncThread(Target t) {
this.t = t;
}
@Override
public void run() {
try {
t.logPreStart();
t.setFilesTotal(countFiles(t.getSourceFile()));
t.setSizeTotal(sizeOf(t.getSourceFile()));
t.logStart();
resursiveSync(t, "");
t.logEnd();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
private void resursiveSync(Target t, String file) throws IOException {
if (!keepGoing) {
return;
}
File source = new File(t.getSource() + (file.equals("") ? "" : SLASH + file));
File target = new File(t.getTarget() + (file.equals("") ? "" : SLASH + file));
// Handle directory
if (source.isDirectory()) {
if (target.exists() && target.isDirectory()) {
String[] sourceChildArray = source.list(config.getFilenameFilter());
if (sourceChildArray != null) {
List<String> sourceChildList = Arrays.asList(sourceChildArray);
if (config.isRandom()) {
Collections.shuffle(sourceChildList);
}
for (String child : sourceChildList) {
resursiveSync(t, file + SLASH + child);
}
}
String[] targetChildArray = target.list();
if (targetChildArray == null) {
return;
}
List<String> targetChildList = Arrays.asList(targetChildArray);
if (config.isRandom()) {
Collections.shuffle(targetChildList);
}
for (String child : targetChildList) {
if (!new File(source, child).exists() || !config.getFilenameFilter().accept(target, child)) {
log.debug("Delete obsolete file " + file + SLASH + child);
if (new File(target, child).isDirectory()) {
t.filesDeleted(countFiles(new File(target, child)));
FileUtils.deleteDirectory(new File(target, child));
} else {
t.fileDeleted();
new File(target, child).delete();
}
}
}
return;
}
if (target.exists() && !target.isDirectory()) {
log.debug("Delete wrong file " + file);
t.fileDeleted();
target.delete();
}
log.debug("Copy new directory " + file);
copyDirectory(source, target, t);
return;
}
// Handle file
if (source.isFile()) {
if (target.exists() && target.isFile()) {
if (needsUpdate(source, target)) {
if(source.canRead()) {
log.debug("Replace newer file " + file);
t.fileUpdated();
target.delete();
FileUtils.copyFile(source, target);
}
else {
log.info("Skip replacing locked file " + source.getAbsolutePath());
}
return;
}
log.trace("Skipping file " + file);
t.fileOkay();
return;
}
if (target.exists() && !target.isFile()) {
log.debug("Delete wrong folder " + file);
t.filesDeleted(countFiles(target));
FileUtils.deleteDirectory(target);
}
if (source.canRead()) {
log.debug("Copy new file " + file);
t.fileAdded();
FileUtils.copyFile(source, target);
} else {
log.info("Skip locked file " + source.getAbsolutePath());
}
}
}
/**
* Check whether a file needs to be updated.
*
* @param source
* @param target
* @return true if the file requires an update.
* @throws IOException
*/
private boolean needsUpdate(File source, File target) throws IOException {
return (FileUtils.isFileNewer(source, target)
|| (config.isCompareSize() && FileUtils.sizeOf(source) != FileUtils.sizeOf(target))
|| (config.isCompareChecksum() && FileUtils.checksumCRC32(source) != FileUtils.checksumCRC32(target)));
}
/**
* Get number of files in subdirectories
*
* @param f
* File or folder
* @return number of files
*/
private int countFiles(File f) {
if (f.isDirectory()) {
int c = 0;
if (f.listFiles() == null) {
return 0;
}
for (File child : f.listFiles()) {
c += countFiles(child);
}
return c;
} else {
return 1;
}
}
/**
* Get file / folder size human readable
*
* @param f
* File or folder
* @return e. g. 120 KB or 7 MB
*/
private String sizeOf(File f) {
return FileUtils.byteCountToDisplaySize(FileUtils.sizeOfAsBigInteger(f));
}
/**
* Recursively copy a directory.
*
* @param source
* @param target
* @param t
* @throws IOException
*/
public static void copyDirectory(File source, File target, Target t) throws IOException {
if (source.isDirectory()) {
if (source.list() != null) {
target.mkdir();
for (File sourceChild : source.listFiles()) {
copyDirectory(sourceChild, new File(target, sourceChild.getName()), t);
}
target.setLastModified(source.lastModified());
}
} else {
if (source.canRead()) {
t.fileAdded();
FileUtils.copyFile(source, target);
}
else {
log.info("Skip locked file " + source.getAbsolutePath());
}
}
}
}
|
src/main/java/de/clemensloos/folder_sync/Sync.java
|
package de.clemensloos.folder_sync;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The sync engine.
*/
public class Sync {
public static final String SLASH = "/";
public static Logger log = LogManager.getLogger(Sync.class);
private static volatile boolean keepGoing = true;
private SyncConfig config;
public Sync(SyncConfig config) {
this.config = config;
}
public void sync() {
Thread.currentThread().setName("MAIN");
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
for (Target t : config.getTargetList()) {
Thread thread = new SyncThread(t);
shutdownHook.setCurrentThread(thread);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
shutdownHook.setCurrentThread(null);
}
}
private class ShutdownHook extends Thread {
private Thread currentThread = null;
void setCurrentThread(Thread thread) {
this.currentThread = thread;
}
@Override
public void run() {
Thread.currentThread().setName("HOOK");
keepGoing = false;
if (currentThread != null) {
log.info("Safely shutting down ...");
try {
currentThread.join();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
}
}
}
private class SyncThread extends Thread {
private Target t;
SyncThread(Target t) {
this.t = t;
}
@Override
public void run() {
try {
t.logPreStart();
t.setFilesTotal(countFiles(t.getSourceFile()));
t.setSizeTotal(sizeOf(t.getSourceFile()));
t.logStart();
resursiveSync(t, "");
t.logEnd();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
private void resursiveSync(Target t, String file) throws IOException {
if (!keepGoing) {
return;
}
File source = new File(t.getSource() + (file.equals("") ? "" : SLASH + file));
File target = new File(t.getTarget() + (file.equals("") ? "" : SLASH + file));
// Handle directory
if (source.isDirectory()) {
if (target.exists() && target.isDirectory()) {
String[] sourceChildArray = source.list(config.getFilenameFilter());
if (sourceChildArray != null) {
List<String> sourceChildList = Arrays.asList(sourceChildArray);
if (config.isRandom()) {
Collections.shuffle(sourceChildList);
}
for (String child : sourceChildList) {
resursiveSync(t, file + SLASH + child);
}
}
String[] targetChildArray = target.list();
if (targetChildArray == null) {
return;
}
List<String> targetChildList = Arrays.asList(targetChildArray);
if (config.isRandom()) {
Collections.shuffle(targetChildList);
}
for (String child : targetChildList) {
if (!new File(source, child).exists() || !config.getFilenameFilter().accept(target, child)) {
log.debug("Delete obsolete file " + file + SLASH + child);
if (new File(target, child).isDirectory()) {
t.filesDeleted(countFiles(new File(target, child)));
FileUtils.deleteDirectory(new File(target, child));
} else {
t.fileDeleted();
new File(target, child).delete();
}
}
}
return;
}
if (target.exists() && !target.isDirectory()) {
log.debug("Delete wrong file " + file);
t.fileDeleted();
target.delete();
}
log.debug("Copy new directory " + file);
copyDirectory(source, target, t);
return;
}
// Handle file
if (source.isFile()) {
if (target.exists() && target.isFile()) {
if (needsUpdate(source, target)) {
log.debug("Replace newer file " + file);
t.fileUpdated();
target.delete();
FileUtils.copyFile(source, target);
return;
}
log.trace("Skipping file " + file);
t.fileOkay();
return;
}
if (target.exists() && !target.isFile()) {
log.debug("Delete wrong folder " + file);
t.filesDeleted(countFiles(target));
FileUtils.deleteDirectory(target);
}
log.debug("Copy new file " + file);
t.fileAdded();
FileUtils.copyFile(source, target);
}
}
/**
* Check whether a file needs to be updated.
*
* @param source
* @param target
* @return true if the file requires an update.
* @throws IOException
*/
private boolean needsUpdate(File source, File target) throws IOException {
return (FileUtils.isFileNewer(source, target)
|| (config.isCompareSize() && FileUtils.sizeOf(source) != FileUtils.sizeOf(target))
|| (config.isCompareChecksum() && FileUtils.checksumCRC32(source) != FileUtils.checksumCRC32(target)));
}
/**
* Get number of files in subdirectories
*
* @param f
* File or folder
* @return number of files
*/
private int countFiles(File f) {
if (f.isDirectory()) {
int c = 0;
if (f.listFiles() == null) {
return 0;
}
for (File child : f.listFiles()) {
c += countFiles(child);
}
return c;
} else {
return 1;
}
}
/**
* Get file / folder size human readable
*
* @param f
* File or folder
* @return e. g. 120 KB or 7 MB
*/
private String sizeOf(File f) {
return FileUtils.byteCountToDisplaySize(FileUtils.sizeOfAsBigInteger(f));
}
/**
* Recursively copy a directory.
*
* @param source
* @param target
* @param t
* @throws IOException
*/
public static void copyDirectory(File source, File target, Target t) throws IOException {
if (source.isDirectory()) {
if (source.list() != null) {
target.mkdir();
for (File sourceChild : source.listFiles()) {
copyDirectory(sourceChild, new File(target, sourceChild.getName()), t);
}
target.setLastModified(source.lastModified());
}
} else {
t.fileAdded();
FileUtils.copyFile(source, target);
}
}
}
|
Skip locked files
|
src/main/java/de/clemensloos/folder_sync/Sync.java
|
Skip locked files
|
|
Java
|
cc0-1.0
|
8846eb400fb58bc8c7510af78a725dad92a7c082
| 0
|
sonota/java-cli-template,sonota88/java-cli-template,sonota/java_cli_template,sonota/java_cli_template,sonota88/java-cli-template,sonota/java-cli-template,sonota88/java-cli-template
|
package sample;
import static util.Utils.readFile;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Config {
/**
* devel | test | prod
*/
private static String profile;
@SuppressWarnings("unused")
private static String currentDir;
private static String projectDir;
private static Properties props;
static {
props = new Properties();
}
public static String getProfile() {
return profile;
}
public static void setProfile(String profile) {
Config.profile = profile;
}
public static void setCurrentDir(String dir){
currentDir = normalizePath(System.getProperty("os.name"), dir);
}
public static void setProjectDir(String dir){
projectDir = normalizePath(System.getProperty("os.name"), dir);
}
/**
* "/c/path/to/..." => "C:/path/to/..."
*/
private static String normalizePath(String osName, String path) {
if (osName.toLowerCase().startsWith("windows")) {
List<String> m = re_match("^/([a-zA-Z])/", path);
if (m.isEmpty()) {
return path;
} else {
return m.get(1).toUpperCase() + ":" + path.substring(2);
}
} else {
return path;
}
}
private static List<String> re_match(String restr, String target) {
Pattern p = Pattern.compile(restr);
Matcher m = p.matcher(target);
if (m.find()) {
List<String> groups = new ArrayList<>();
for (int i = 0; i <= m.groupCount(); i++) {
groups.add(m.group(i));
}
return groups;
} else {
return Collections.emptyList();
}
}
public static void load() {
String suffix = "";
if (!profile.equals("prod")) {
suffix = "_" + profile;
}
String path = projectRelativePath("config" + suffix + ".properties");
String propsSrc = readFile(path);
try (StringReader sr = new StringReader(propsSrc)) {
props.load(sr);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static String prop(String key){
return props.getProperty(key);
}
/**
* @param tail
* @return project dir + tail (full path)
*/
public static String projectRelativePath(String tail){
try {
return new File(projectDir, tail).getCanonicalPath();
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
|
src/main/java/sample/Config.java
|
package sample;
import static util.Utils.readFile;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Config {
/**
* devel | test | prod
*/
private static String profile;
@SuppressWarnings("unused")
private static String currentDir;
private static String projectDir;
private static Properties props;
static {
props = new Properties();
}
public static String getProfile() {
return profile;
}
public static void setProfile(String profile) {
Config.profile = profile;
}
public static void setCurrentDir(String dir){
currentDir = normalizePath(System.getProperty("os.name"), dir);
}
public static void setProjectDir(String dir){
projectDir = normalizePath(System.getProperty("os.name"), dir);
}
/**
* "/c/path/to/..." => "C:/path/to/..."
*/
private static String normalizePath(String osName, String path) {
if (osName.toLowerCase().startsWith("windows")) {
List<String> m = re_match("^/([a-zA-Z])/", path);
if (m.isEmpty()) {
return path;
} else {
return m.get(1).toUpperCase() + ":" + path.substring(2);
}
} else {
return path;
}
}
private static List<String> re_match(String restr, String target) {
Pattern p = Pattern.compile(restr);
Matcher m = p.matcher(target);
if (m.find()) {
List<String> ss = new ArrayList<>();
for (int i = 0; i <= m.groupCount(); i++) {
ss.add(m.group(i));
}
return ss;
} else {
return Collections.emptyList();
}
}
public static void load() {
String suffix = "";
if (!profile.equals("prod")) {
suffix = "_" + profile;
}
String path = projectRelativePath("config" + suffix + ".properties");
String propsSrc = readFile(path);
try (StringReader sr = new StringReader(propsSrc)) {
props.load(sr);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static String prop(String key){
return props.getProperty(key);
}
/**
* @param tail
* @return project dir + tail (full path)
*/
public static String projectRelativePath(String tail){
try {
return new File(projectDir, tail).getCanonicalPath();
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
|
refactor: rename: ss => groups
|
src/main/java/sample/Config.java
|
refactor: rename: ss => groups
|
|
Java
|
agpl-3.0
|
9212b13e014828c083715e91ba6e07437d83c11b
| 0
|
acontes/programming,acontes/programming,acontes/programming,acontes/scheduling,PaulKh/scale-proactive,ow2-proactive/programming,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,acontes/scheduling,paraita/programming,paraita/programming,ow2-proactive/programming,mnip91/proactive-component-monitoring,paraita/programming,acontes/programming,fviale/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,fviale/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,jrochas/scale-proactive,jrochas/scale-proactive,jrochas/scale-proactive,ow2-proactive/programming,acontes/scheduling,paraita/programming,acontes/programming,mnip91/programming-multiactivities,acontes/programming,acontes/scheduling,mnip91/programming-multiactivities,acontes/scheduling,lpellegr/programming,fviale/programming,acontes/programming,mnip91/programming-multiactivities,fviale/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,jrochas/scale-proactive,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,acontes/scheduling,PaulKh/scale-proactive,lpellegr/programming,mnip91/proactive-component-monitoring,lpellegr/programming,ow2-proactive/programming,jrochas/scale-proactive,PaulKh/scale-proactive,lpellegr/programming,lpellegr/programming,jrochas/scale-proactive,paraita/programming,acontes/scheduling,ow2-proactive/programming,fviale/programming,fviale/programming,lpellegr/programming,mnip91/programming-multiactivities,ow2-proactive/programming,paraita/programming
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive-support@inria.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.exceptions;
import org.objectweb.proactive.core.ProActiveException;
/**
* An interface for non functional exceptions
* Should implement Serializable but Exception class do it
* @author ProActive Team
* @version 1.0, 2003/04/01
* @since ProActive 1.0.2
*
*/
public class NonFunctionalException extends ProActiveException {
/**
* separator for exception description
*/
static protected String separator = " :: ";
/**
* self description of the non functional exception
*/
protected String description;
/**
* Constructs a <code>NonFunctionalException</code> with no specified
* detail message.
*/
public NonFunctionalException() {
super();
description = "NFE" + separator;
}
/**
* Constructs a <code>NonFunctionalException</code> with the specified
* detail message and nested exception.
* @param s the detail message
*/
public NonFunctionalException(String s) {
super(s);
description = "NFE" + separator;
}
/**
* Constructs a <code>NonFunctionalException</code> with the specified
* detail message and nested exception.
* @param s the detail message
* @param ex the nested exception
*/
public NonFunctionalException(String s, Throwable ex) {
super(s, ex);
description = "NFE" + separator;
}
/**
* Constructs a <code>NonFunctionalException</code> with the specified
* detail message and nested exception.
* @param ex the nested exception
*/
public NonFunctionalException(Throwable ex) {
super(ex);
description = "NFE" + separator;
}
/**
* @return description
*/
public String getDescription() {
return description;
}
}
|
src/org/objectweb/proactive/core/exceptions/NonFunctionalException.java
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive-support@inria.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.exceptions;
import org.objectweb.proactive.core.ProActiveException;
/**
* An interface for non functional exceptions
* Should implement Serializable but Exception class do it
* @author ProActive Team
* @version 1.0, 2003/04/01
* @since ProActive 1.0.2
*
*/
public class NonFunctionalException extends ProActiveException {
/**
* separator for exception description
*/
static protected String separator = " :: ";
/**
* self description of the non functional exception
*/
protected String description;
/**
* Constructs a <code>NonFunctionalException</code> with no specified
* detail message.
*/
public NonFunctionalException() {
super();
description = "NFE" + separator;
}
/**
* Constructs a <code>NonFunctionalException</code> with the specified
* detail message and nested exception.
* @param s the detail message
* @param ex the nested exception
*/
public NonFunctionalException(String s, Throwable ex) {
super(s, ex);
description = "NFE" + separator;
}
/**
* Constructs a <code>NonFunctionalException</code> with the specified
* detail message and nested exception.
* @param ex the nested exception
*/
public NonFunctionalException(Throwable ex) {
super(ex);
description = "NFE" + separator;
}
/**
* @return description
*/
public String getDescription() {
return description;
}
}
|
NFE : add simple constructor to create NFE
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@1375 28e8926c-6b08-0410-baaa-805c5e19b8d6
|
src/org/objectweb/proactive/core/exceptions/NonFunctionalException.java
|
NFE : add simple constructor to create NFE
|
|
Java
|
agpl-3.0
|
91cae66b368482385bbbb224573ce9231a72f040
| 0
|
LedgerHQ/ledger-javacard,LedgerHQ/ledger-javacard
|
/*
*******************************************************************************
* Java Card Bitcoin Hardware Wallet
* (c) 2015 Ledger
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************
*/
package com.ledger.wallet;
import javacard.framework.Util;
import javacard.security.Signature;
public class Bip32 {
protected static final short OFFSET_DERIVATION_INDEX = (short)64;
private static final byte BITCOIN_SEED[] = {
'B', 'i', 't', 'c', 'o', 'i', 'n', ' ', 's', 'e', 'e', 'd'
};
private static final short OFFSET_TMP = (short)100;
private static final short OFFSET_BLOCK = (short)127;
// seed : scratch, offset 0 -> result in masterDerived
// depending on the implementation, if a native transient HMAC is used, the key size might be fixed
// on the first call
// if that's the case, power cycle / deselect between initial seed derivation and all other key derivations
public static void deriveSeed(byte seedLength) {
if (Crypto.signatureHmac != null) {
Crypto.keyHmac.setKey(BITCOIN_SEED, (short)0, (short)BITCOIN_SEED.length);
if ((LedgerWalletApplet.proprietaryAPI != null) && (LedgerWalletApplet.proprietaryAPI.hasHmacSHA512())) {
LedgerWalletApplet.proprietaryAPI.hmacSHA512(Crypto.keyHmac, LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0);
}
else {
Crypto.signatureHmac.init(Crypto.keyHmac, Signature.MODE_SIGN);
Crypto.signatureHmac.sign(LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0);
}
}
else {
HmacSha512.hmac(BITCOIN_SEED, (short)0, (short)BITCOIN_SEED.length, LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0, LedgerWalletApplet.scratch256, (short)64);
}
}
// scratch255 : 0-64 : key + chain / 64-67 : derivation index / 100-165 : tmp
// apduBuffer : block (128, starting at 127)
// result : scratch255 0-64
public static boolean derive(byte[] apduBuffer) {
boolean isZero = true;
byte i;
if ((LedgerWalletApplet.scratch256[OFFSET_DERIVATION_INDEX] & (byte)0x80) == 0) {
if (LedgerWalletApplet.proprietaryAPI != null) {
LedgerWalletApplet.proprietaryAPI.getUncompressedPublicPoint(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
if (!Bip32Cache.copyLastPublic(LedgerWalletApplet.scratch256, OFFSET_TMP)) {
return false;
}
}
AddressUtils.compressPublicKey(LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
LedgerWalletApplet.scratch256[OFFSET_TMP] = 0;
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 1), (short)32);
}
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, OFFSET_DERIVATION_INDEX, LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 33), (short)4);
if (Crypto.signatureHmac != null) {
Crypto.keyHmac.setKey(LedgerWalletApplet.scratch256, (short)32, (short)32);
if ((LedgerWalletApplet.proprietaryAPI != null) && (LedgerWalletApplet.proprietaryAPI.hasHmacSHA512())) {
LedgerWalletApplet.proprietaryAPI.hmacSHA512(Crypto.keyHmac, LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
Crypto.signatureHmac.init(Crypto.keyHmac, Signature.MODE_SIGN);
Crypto.signatureHmac.sign(LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
}
else {
HmacSha512.hmac(LedgerWalletApplet.scratch256, (short)32, (short)32, LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP, apduBuffer, OFFSET_BLOCK);
}
if (MathMod256.ucmp(LedgerWalletApplet.scratch256, OFFSET_TMP, Secp256k1.SECP256K1_R, (short)0) >= 0) {
return false;
}
MathMod256.addm(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, OFFSET_TMP, LedgerWalletApplet.scratch256, (short)0, Secp256k1.SECP256K1_R, (short)0);
for (i=0; i<(byte)32; i++) {
if (LedgerWalletApplet.scratch256[i] != 0) {
isZero = false;
break;
}
}
if (isZero) {
return false;
}
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 32), LedgerWalletApplet.scratch256, (short)32, (short)32);
return true;
}
}
|
src/com/ledger/wallet/Bip32.java
|
/*
*******************************************************************************
* Java Card Bitcoin Hardware Wallet
* (c) 2015 Ledger
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************
*/
package com.ledger.wallet;
import javacard.framework.Util;
import javacard.security.Signature;
public class Bip32 {
protected static final short OFFSET_DERIVATION_INDEX = (short)64;
private static final byte BITCOIN_SEED[] = {
'B', 'i', 't', 'c', 'o', 'i', 'n', ' ', 's', 'e', 'e', 'd'
};
private static final short OFFSET_TMP = (short)100;
private static final short OFFSET_BLOCK = (short)127;
// seed : scratch, offset 0 -> result in masterDerived
public static void deriveSeed(byte seedLength) {
if (Crypto.signatureHmac != null) {
Crypto.keyHmac.setKey(BITCOIN_SEED, (short)0, (short)BITCOIN_SEED.length);
if ((LedgerWalletApplet.proprietaryAPI != null) && (LedgerWalletApplet.proprietaryAPI.hasHmacSHA512())) {
LedgerWalletApplet.proprietaryAPI.hmacSHA512(Crypto.keyHmac, LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0);
}
else {
Crypto.signatureHmac.init(Crypto.keyHmac, Signature.MODE_SIGN);
Crypto.signatureHmac.sign(LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0);
}
}
else {
HmacSha512.hmac(BITCOIN_SEED, (short)0, (short)BITCOIN_SEED.length, LedgerWalletApplet.scratch256, (short)0, seedLength, LedgerWalletApplet.masterDerived, (short)0, LedgerWalletApplet.scratch256, (short)64);
}
}
// scratch255 : 0-64 : key + chain / 64-67 : derivation index / 100-165 : tmp
// apduBuffer : block (128, starting at 127)
// result : scratch255 0-64
public static boolean derive(byte[] apduBuffer) {
boolean isZero = true;
byte i;
if ((LedgerWalletApplet.scratch256[OFFSET_DERIVATION_INDEX] & (byte)0x80) == 0) {
if (LedgerWalletApplet.proprietaryAPI != null) {
LedgerWalletApplet.proprietaryAPI.getUncompressedPublicPoint(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
if (!Bip32Cache.copyLastPublic(LedgerWalletApplet.scratch256, OFFSET_TMP)) {
return false;
}
}
AddressUtils.compressPublicKey(LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
LedgerWalletApplet.scratch256[OFFSET_TMP] = 0;
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 1), (short)32);
}
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, OFFSET_DERIVATION_INDEX, LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 33), (short)4);
if (Crypto.signatureHmac != null) {
Crypto.keyHmac.setKey(LedgerWalletApplet.scratch256, (short)32, (short)32);
if ((LedgerWalletApplet.proprietaryAPI != null) && (LedgerWalletApplet.proprietaryAPI.hasHmacSHA512())) {
LedgerWalletApplet.proprietaryAPI.hmacSHA512(Crypto.keyHmac, LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
else {
Crypto.signatureHmac.init(Crypto.keyHmac, Signature.MODE_SIGN);
Crypto.signatureHmac.sign(LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP);
}
}
else {
HmacSha512.hmac(LedgerWalletApplet.scratch256, (short)32, (short)32, LedgerWalletApplet.scratch256, OFFSET_TMP, (short)37, LedgerWalletApplet.scratch256, OFFSET_TMP, apduBuffer, OFFSET_BLOCK);
}
if (MathMod256.ucmp(LedgerWalletApplet.scratch256, OFFSET_TMP, Secp256k1.SECP256K1_R, (short)0) >= 0) {
return false;
}
MathMod256.addm(LedgerWalletApplet.scratch256, (short)0, LedgerWalletApplet.scratch256, OFFSET_TMP, LedgerWalletApplet.scratch256, (short)0, Secp256k1.SECP256K1_R, (short)0);
for (i=0; i<(byte)32; i++) {
if (LedgerWalletApplet.scratch256[i] != 0) {
isZero = false;
break;
}
}
if (isZero) {
return false;
}
Util.arrayCopyNonAtomic(LedgerWalletApplet.scratch256, (short)(OFFSET_TMP + 32), LedgerWalletApplet.scratch256, (short)32, (short)32);
return true;
}
}
|
Details on specific implementation workarounds
|
src/com/ledger/wallet/Bip32.java
|
Details on specific implementation workarounds
|
|
Java
|
agpl-3.0
|
b461725a09fc82d697dc9c37e95eb3b43255bea0
| 0
|
isaactsg/ICS4U-Final-Project,isaactsg/Nutrient-Calculator
|
/*
Copyright (C) 2016 Isaac Wismer & Andrew Xu
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ics4u.ics4u_final_project;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MeasureSelectionActivity extends AppCompatActivity {
Ingredient selected;
boolean edit;
String[] types, items;
Context c = this;
Spinner measureType, measureSize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.measure_selector);
//check if it's a new ingredient or an edit
if (RecipeCreateActivity.search) {
selected = IngredientSelectionActivity.getResults().get(RecyclerViewHolders.location);
} else {
selected = RecipeCreateActivity.recipe.getSingleIngredientIndex(RecyclerViewHolders.location);
}
RecipeCreateActivity.search = false;
measureSize = (Spinner) findViewById(R.id.measurement_amount);
measureType = (Spinner) findViewById(R.id.measurement_type);
setTitle("Ingredient Amount");
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
AdapterView.OnItemSelectedListener onSpinnerType = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setSizeSpinner((int) id);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
AdapterView.OnItemSelectedListener onSpinnerSize = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
TextView name = (TextView) findViewById(R.id.ingredient_title);
name.setText(selected.getName());
//set the spinner lists
types = new String[]{"Metric Cooking Measures", "mL", "g", "Other"};
items = new String[]{"1/4 Teaspoon", "1/2 Teaspoon", "1 Teaspoon", "1 Tablespoon", "1/4 Cup", "1/3 Cup", "1/2 Cup", "1 Cup"};
edit = (selected.getUnit() != null);
System.out.println("Edit: " + edit);
//remove spinner options if mL is unavailable
if (!checkMeasuresML(selected.getID())) {
types = new String[]{"g", "Other"};
measureSize.setEnabled(false);
} else {
measureSize.setEnabled(true);
}
if (selected.getMeasures().isEmpty()) {
Toast.makeText(this, "Error: No measures available. Cannot use ingredient; Please choose another.", Toast.LENGTH_LONG);
this.finish();
} else {
if (edit) {
while (selected.getSingleMeasureIndex(selected.getMeasures().size() - 1).getName().equals("")) { //prevents empty measures in the list
selected.getMeasures().remove(selected.getMeasures().size() - 1);
}
}
}
//show the spinners
measureType.setPrompt("Please select a measure type");
ArrayAdapter<String> typesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, types);
measureType.setAdapter(typesAdapter);
measureType.setOnItemSelectedListener(onSpinnerType);
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
measureSize.setOnItemSelectedListener(onSpinnerSize);
//if it's an edit, set the spinner values
if (edit) {
measureType.setSelection(selected.getUnitNum());
setSizeSpinner(selected.getUnitNum());
// FIXME: 1/17/2016 fix this always being 1
measureSize.setSelection(selected.getFractionNum());
EditText measureQuantity = (EditText) findViewById(R.id.ingredient_amount);
measureQuantity.setText(String.valueOf(selected.getQuantity()));
}
}
/**
* This method checks if mL is available for this ingredient
*
* @param ID the ID of the measure
* @return whether or not it can be measured in mL
*/
public boolean checkMeasuresML(int ID) {
//get conversion rates
if (!edit)getConv(ID);
//check the conversions for mL measurements
for (int i = 0; i < selected.getMeasures().size(); i++) {
int measureID = selected.getSingleMeasureIndex(i).getID();
//if it has any of the known mL measures, allow it to be used
if (measureID > 340 && measureID < 380) {
return true;
} else if (measureID > 384 && measureID < 394) {
return true;
} else if (measureID > 412 && measureID < 427) {
return true;
} else if (measureID == 439 || measureID == 388
|| measureID == 389 || measureID == 923
|| measureID == 932 || measureID == 638
|| measureID == 640 || measureID == 641
|| measureID == 430 || measureID == 939
|| measureID == 943 || measureID == 429
|| measureID == 428 || measureID == 383) {
return true;
} else if (measureID >= 385 && measureID <= 387) {
return true;
}
}
return false;
}//End checkMeasurementML()
/**
* This method may cause errors with the new arraylists. Check this if there
* is an issue
*
* @param ID the ID of the measure
*/
public void getConv(int ID) {
System.out.println("Getting conversion rates for food ID = " + ID);
//search for the nutrient ID in the file
int begin = Database.binarySearch(Database.convFact, ID, 0, Database.convFact.size() - 1);
if (begin == -1) {
System.out.println("Not Found");
}
//step back to the beginning of the nutrient
while (begin > 0 && (int) Database.convFact.get(begin - 1)[0] == ID) {
begin--;
}
//read until the end of the nutrient
for (int i = begin; (int) Database.convFact.get(i)[0] == ID; i++) {
if ((int) Database.convFact.get(i)[1] != 1572) {
selected.addMeasure((int) Database.convFact.get(i)[1], (Double) Database.convFact.get(i)[2]);
}
}
// for (int i = 0; i < convFact.size(); i++) {
// //get the measure conversion factor and measure ID
// if (ID == (int) convFact.get(i)[0] && (int) convFact.get(i)[1] != 1572) {
// GUI.recipe.getSingleIngredientID(ID).addMeasure((int) convFact.get(i)[1], (Double) convFact.get(i)[2]);
// }
// }
//loop through the ingredients
for (int i = 0; i < selected.getMeasures().size(); i++) {
//get the id of the measure
int measureID = selected.getSingleMeasureIndex(i).getID();
//delete if it's a no measure ingredient
if (measureID == 1572) {
selected.removeSingleMeasure(i);
//move back the counter becuase an inde was removed
i--;
} else {
//otherwise get the name
//System.out.println("ID" + measureID);
selected.getSingleMeasureIndex(i).setName(Database.msName.get(Database.binarySearch(Database.msName, measureID, 0, Database.msName.size() - 1))[1].toString());
}
}
// counter = 0;
// for (int i = 0; i < msName.size(); i++) {
// if (GUI.recipe.getSingleIngredientID(ID).getMeasures().size() == counter) {
// break;
// }
// //get the measure name
// //temp = Double.parseDouble(conversionRates.get(counter)[0].toString());
// int measureID = GUI.recipe.getSingleIngredientID(ID).getSingleMeasureIndex(counter).getID();
// if (measureID == (Integer) msName.get(i)[0] && measureID != 1572) {
// // conversionRates.get(counter)[2] = aobj[1];//Add measure Name
// GUI.recipe.getSingleIngredientID(ID).getSingleMeasureID((Integer) msName.get(i)[0]).setName(msName.get(i)[1].toString());
// counter++;
// //dont allow no measure specified
// } else if (measureID == 1572) {
// //conversionRates.remove(counter);
// GUI.recipe.getSingleIngredientID(ID).removeSingleMeasure(counter);
// }
// }
}//end getConv
@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_measurement, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
EditText quantityBox = (EditText) findViewById(R.id.ingredient_amount);
if (id == R.id.action_add) {
int temp;
String ingredient = "";
int quantity = Integer.parseInt(quantityBox.getText().toString());
if (measureType.getSelectedItem().toString() == "Metric Cooking Measures") {
//make a name that has the amount in the title
//this took waaaay too long to make
//add the correct fraction to the beginning of the ingredient name
if (quantity > 1) {
temp = Integer.parseInt(measureSize.getSelectedItem().toString().substring(0, 1)) * quantity;
if (measureSize.getSelectedItemPosition() != 2 && measureSize.getSelectedItemPosition() != 3 && measureSize.getSelectedItemPosition() != 7) {//not full measures eg 1 cup
if (temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) >= 1) {
if (temp % Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3)) == 0) {
ingredient = temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) + measureSize.getSelectedItem().toString().substring(3);
if (temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) > 1) {
ingredient += "s";
}
ingredient += " " + selected.getName();
} else {
ingredient += (int) Math.floor(temp / Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3)));
temp -= Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3));
double temp2 = (double) temp / Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3));
temp2 -= Math.floor(temp2);//leftovers
if (temp2 == 0.25) {
ingredient += " 1/4";
} else if (temp2 == 0.5) {
ingredient += " 1/2";
} else if (temp2 == 0.75) {
ingredient += " 3/4";
} else if ((temp2 + "").substring(2, 3).equals("3")) {
ingredient += " 1/3";
} else {
ingredient += " 2/3";
}
ingredient += measureSize.getSelectedItem().toString().substring(3) + "s" + " " + selected.getName();
}
} else {
ingredient = temp + measureSize.getSelectedItem().toString().substring(1) + "s" + " " + selected.getName();
}
} else {
ingredient = temp + measureSize.getSelectedItem().toString().substring(1) + "s" + " " + selected.getName();
}
} else {
ingredient = measureSize.getSelectedItem() + " " + selected.getName();
}
} else if (measureType.getSelectedItem().toString() == "g") {
if (quantity < 1000) {
ingredient = quantity + "g " + selected.getName();
} else {
ingredient = ((double) quantity / 1000.0) + "Kg " + selected.getName();
}
} else if (measureType.getSelectedItem().toString() == "Other") {
String str = "";
int i;
for (i = 0; i < measureSize.getSelectedItem().toString().length(); i++) {//get the numbers from the front of the other name
if (measureSize.getSelectedItem().toString().charAt(i) >= 48
&& measureSize.getSelectedItem().toString().charAt(i) <= 57) {
str += measureSize.getSelectedItem().toString().charAt(i);
} else {
break;
}
}
int num = Integer.parseInt(str);
int num2 = num * quantity;
ingredient = num2 + measureSize.getSelectedItem().toString().substring(i) + " " + selected.getName();
} else if (quantity < 1000) {
ingredient = quantity + "mL " + selected.getName();
} else {
ingredient = ((double) quantity / 1000.0) + "L " + selected.getName();
}
//get the information from the spinners
selected.setUnit(measureType.getSelectedItem().toString());
selected.setUnitNum(measureType.getSelectedItemPosition());
selected.setFractionNum(measureSize.getSelectedItemPosition());
if (measureSize.getSelectedItem() != null) {
selected.setFractionName(measureSize.getSelectedItem().toString());
}
selected.setFormattedName(ingredient);
selected.setQuantity(quantity);
//add to the recipe
if (edit) {
RecipeCreateActivity.recipe.setSingleIngredient(RecyclerViewHolders.location, selected);
} else {
RecipeCreateActivity.recipe.addIngredient(selected);
}
//close
RecipeCreateActivity.addedIngred = true;
this.finish();
IngredientSelectionActivity.onIngredient = false;
} else if (id == R.id.action_cancel) {
this.finish();
IngredientSelectionActivity.onIngredient = false;
}
return super.onOptionsItemSelected(item);
}
private void setSizeSpinner(int id) {
//change what is showing depending on what unit is selected
if (types[id].equals("Metric Cooking Measures")) {
//set the things in the spinner to the metric measures
items = new String[]{"1/4 Teaspoon", "1/2 Teaspoon", "1 Teaspoon", "1 Tablespoon", "1/4 Cup", "1/3 Cup", "1/2 Cup", "1 Cup"};
//make that the adapter
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(c, android.R.layout.simple_spinner_dropdown_item, items);
//set prompt and set as adapter
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
//enable it
measureSize.setEnabled(true);
} else if (types[id].equals("Other")) {
//for some reason it's showing each of the measures twice
// FIXME: 1/13/2016 this should only be a temp fix.
//set the spinner items to be the "other measures"
items = new String[selected.getMeasures().size()];
for (int i = 0; i < items.length; i++) {
items[i] = selected.getSingleMeasureIndex(i).getName();
}
//set and set prompt, enable
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(c, android.R.layout.simple_spinner_dropdown_item, items);
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
measureSize.setEnabled(true);
} else {
//if mL or g, disable the spinner
measureSize.setEnabled(false);
}
}
}
|
app/src/main/java/ics4u/ics4u_final_project/MeasureSelectionActivity.java
|
/*
Copyright (C) 2016 Isaac Wismer & Andrew Xu
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ics4u.ics4u_final_project;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MeasureSelectionActivity extends AppCompatActivity {
Ingredient selected;
boolean edit;
String[] types, items;
Context c = this;
Spinner measureType, measureSize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.measure_selector);
//check if it's a new ingredient or an edit
if (RecipeCreateActivity.search) {
selected = IngredientSelectionActivity.getResults().get(RecyclerViewHolders.location);
} else {
selected = RecipeCreateActivity.recipe.getSingleIngredientIndex(RecyclerViewHolders.location);
}
RecipeCreateActivity.search = false;
measureSize = (Spinner) findViewById(R.id.measurement_amount);
measureType = (Spinner) findViewById(R.id.measurement_type);
setTitle("Ingredient Amount");
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
AdapterView.OnItemSelectedListener onSpinnerType = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setSizeSpinner((int) id);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
AdapterView.OnItemSelectedListener onSpinnerSize = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
TextView name = (TextView) findViewById(R.id.ingredient_title);
name.setText(selected.getName());
//set the spinner lists
types = new String[]{"Metric Cooking Measures", "mL", "g", "Other"};
items = new String[]{"1/4 Teaspoon", "1/2 Teaspoon", "1 Teaspoon", "1 Tablespoon", "1/4 Cup", "1/3 Cup", "1/2 Cup", "1 Cup"};
edit = (selected.getUnit() != null);
//remove spinner options if mL is unavailable
if (!checkMeasuresML(selected.getID())) {
types = new String[]{"g", "Other"};
measureSize.setEnabled(false);
} else {
measureSize.setEnabled(true);
}
if (selected.getMeasures().isEmpty()) {
Toast.makeText(this, "Error: No measures available. Cannot use ingredient; Please choose another.", Toast.LENGTH_LONG);
this.finish();
} else {
if (edit) {
while (selected.getSingleMeasureIndex(selected.getMeasures().size() - 1).getName().equals("")) { //prevents empty measures in the list
selected.getMeasures().remove(selected.getMeasures().size() - 1);
}
}
}
//show the spinners
measureType.setPrompt("Please select a measure type");
ArrayAdapter<String> typesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, types);
measureType.setAdapter(typesAdapter);
measureType.setOnItemSelectedListener(onSpinnerType);
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
measureSize.setOnItemSelectedListener(onSpinnerSize);
//if it's an edit, set the spinner values
if (edit) {
measureType.setSelection(selected.getUnitNum());
setSizeSpinner(selected.getUnitNum());
// FIXME: 1/17/2016 fix this always being 1
measureSize.setSelection(selected.getFractionNum());
EditText measureQuantity = (EditText) findViewById(R.id.ingredient_amount);
measureQuantity.setText(String.valueOf(selected.getQuantity()));
}
}
/**
* This method checks if mL is available for this ingredient
*
* @param ID the ID of the measure
* @return whether or not it can be measured in mL
*/
public boolean checkMeasuresML(int ID) {
//get conversion rates
getConv(ID);
//check the conversions for mL measurements
for (int i = 0; i < selected.getMeasures().size(); i++) {
int measureID = selected.getSingleMeasureIndex(i).getID();
//if it has any of the known mL measures, allow it to be used
if (measureID > 340 && measureID < 380) {
return true;
} else if (measureID > 384 && measureID < 394) {
return true;
} else if (measureID > 412 && measureID < 427) {
return true;
} else if (measureID == 439 || measureID == 388
|| measureID == 389 || measureID == 923
|| measureID == 932 || measureID == 638
|| measureID == 640 || measureID == 641
|| measureID == 430 || measureID == 939
|| measureID == 943 || measureID == 429
|| measureID == 428 || measureID == 383) {
return true;
} else if (measureID >= 385 && measureID <= 387) {
return true;
}
}
return false;
}//End checkMeasurementML()
/**
* This method may cause errors with the new arraylists. Check this if there
* is an issue
*
* @param ID the ID of the measure
*/
public void getConv(int ID) {
System.out.println("Getting conversion rates for food ID = " + ID);
//search for the nutrient ID in the file
int begin = Database.binarySearch(Database.convFact, ID, 0, Database.convFact.size() - 1);
if (begin == -1) {
System.out.println("Not Found");
}
//step back to the beginning of the nutrient
while (begin > 0 && (int) Database.convFact.get(begin - 1)[0] == ID) {
begin--;
}
//read until the end of the nutrient
for (int i = begin; (int) Database.convFact.get(i)[0] == ID; i++) {
if ((int) Database.convFact.get(i)[1] != 1572) {
selected.addMeasure((int) Database.convFact.get(i)[1], (Double) Database.convFact.get(i)[2]);
}
}
// for (int i = 0; i < convFact.size(); i++) {
// //get the measure conversion factor and measure ID
// if (ID == (int) convFact.get(i)[0] && (int) convFact.get(i)[1] != 1572) {
// GUI.recipe.getSingleIngredientID(ID).addMeasure((int) convFact.get(i)[1], (Double) convFact.get(i)[2]);
// }
// }
//loop through the ingredients
for (int i = 0; i < selected.getMeasures().size(); i++) {
//get the id of the measure
int measureID = selected.getSingleMeasureIndex(i).getID();
//delete if it's a no measure ingredient
if (measureID == 1572) {
selected.removeSingleMeasure(i);
//move back the counter becuase an inde was removed
i--;
} else {
//otherwise get the name
//System.out.println("ID" + measureID);
selected.getSingleMeasureIndex(i).setName(Database.msName.get(Database.binarySearch(Database.msName, measureID, 0, Database.msName.size() - 1))[1].toString());
}
}
// counter = 0;
// for (int i = 0; i < msName.size(); i++) {
// if (GUI.recipe.getSingleIngredientID(ID).getMeasures().size() == counter) {
// break;
// }
// //get the measure name
// //temp = Double.parseDouble(conversionRates.get(counter)[0].toString());
// int measureID = GUI.recipe.getSingleIngredientID(ID).getSingleMeasureIndex(counter).getID();
// if (measureID == (Integer) msName.get(i)[0] && measureID != 1572) {
// // conversionRates.get(counter)[2] = aobj[1];//Add measure Name
// GUI.recipe.getSingleIngredientID(ID).getSingleMeasureID((Integer) msName.get(i)[0]).setName(msName.get(i)[1].toString());
// counter++;
// //dont allow no measure specified
// } else if (measureID == 1572) {
// //conversionRates.remove(counter);
// GUI.recipe.getSingleIngredientID(ID).removeSingleMeasure(counter);
// }
// }
}//end getConv
@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_measurement, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
EditText quantityBox = (EditText) findViewById(R.id.ingredient_amount);
if (id == R.id.action_add) {
int temp;
String ingredient = "";
int quantity = Integer.parseInt(quantityBox.getText().toString());
if (measureType.getSelectedItem().toString() == "Metric Cooking Measures") {
//make a name that has the amount in the title
//this took waaaay too long to make
//add the correct fraction to the beginning of the ingredient name
if (quantity > 1) {
temp = Integer.parseInt(measureSize.getSelectedItem().toString().substring(0, 1)) * quantity;
if (measureSize.getSelectedItemPosition() != 2 && measureSize.getSelectedItemPosition() != 3 && measureSize.getSelectedItemPosition() != 7) {//not full measures eg 1 cup
if (temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) >= 1) {
if (temp % Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3)) == 0) {
ingredient = temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) + measureSize.getSelectedItem().toString().substring(3);
if (temp / Integer.parseInt(measureSize.getSelectedItem().toString().substring(2, 3)) > 1) {
ingredient += "s";
}
ingredient += " " + selected.getName();
} else {
ingredient += (int) Math.floor(temp / Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3)));
temp -= Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3));
double temp2 = (double) temp / Double.parseDouble(measureSize.getSelectedItem().toString().substring(2, 3));
temp2 -= Math.floor(temp2);//leftovers
if (temp2 == 0.25) {
ingredient += " 1/4";
} else if (temp2 == 0.5) {
ingredient += " 1/2";
} else if (temp2 == 0.75) {
ingredient += " 3/4";
} else if ((temp2 + "").substring(2, 3).equals("3")) {
ingredient += " 1/3";
} else {
ingredient += " 2/3";
}
ingredient += measureSize.getSelectedItem().toString().substring(3) + "s" + " " + selected.getName();
}
} else {
ingredient = temp + measureSize.getSelectedItem().toString().substring(1) + "s" + " " + selected.getName();
}
} else {
ingredient = temp + measureSize.getSelectedItem().toString().substring(1) + "s" + " " + selected.getName();
}
} else {
ingredient = measureSize.getSelectedItem() + " " + selected.getName();
}
} else if (measureType.getSelectedItem().toString() == "g") {
if (quantity < 1000) {
ingredient = quantity + "g " + selected.getName();
} else {
ingredient = ((double) quantity / 1000.0) + "Kg " + selected.getName();
}
} else if (measureType.getSelectedItem().toString() == "Other") {
String str = "";
int i;
for (i = 0; i < measureSize.getSelectedItem().toString().length(); i++) {//get the numbers from the front of the other name
if (measureSize.getSelectedItem().toString().charAt(i) >= 48
&& measureSize.getSelectedItem().toString().charAt(i) <= 57) {
str += measureSize.getSelectedItem().toString().charAt(i);
} else {
break;
}
}
int num = Integer.parseInt(str);
int num2 = num * quantity;
ingredient = num2 + measureSize.getSelectedItem().toString().substring(i) + " " + selected.getName();
} else if (quantity < 1000) {
ingredient = quantity + "mL " + selected.getName();
} else {
ingredient = ((double) quantity / 1000.0) + "L " + selected.getName();
}
//get the information from the spinners
selected.setUnit(measureType.getSelectedItem().toString());
selected.setUnitNum(measureType.getSelectedItemPosition());
selected.setFractionNum(measureSize.getSelectedItemPosition());
if (measureSize.getSelectedItem() != null) {
selected.setFractionName(measureSize.getSelectedItem().toString());
}
selected.setFormattedName(ingredient);
selected.setQuantity(quantity);
//add to the recipe
if (RecyclerViewHolders.edit) {
RecipeCreateActivity.recipe.setSingleIngredient(RecyclerViewHolders.location, selected);
} else {
RecipeCreateActivity.recipe.addIngredient(selected);
}
//close
RecipeCreateActivity.addedIngred = true;
this.finish();
IngredientSelectionActivity.onIngredient = false;
} else if (id == R.id.action_cancel) {
this.finish();
IngredientSelectionActivity.onIngredient = false;
}
return super.onOptionsItemSelected(item);
}
private void setSizeSpinner(int id) {
//change what is showing depending on what unit is selected
if (types[id].equals("Metric Cooking Measures")) {
//set the things in the spinner to the metric measures
items = new String[]{"1/4 Teaspoon", "1/2 Teaspoon", "1 Teaspoon", "1 Tablespoon", "1/4 Cup", "1/3 Cup", "1/2 Cup", "1 Cup"};
//make that the adapter
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(c, android.R.layout.simple_spinner_dropdown_item, items);
//set prompt and set as adapter
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
//enable it
measureSize.setEnabled(true);
} else if (types[id].equals("Other")) {
//for some reason it's showing each of the measures twice
// FIXME: 1/13/2016 this should only be a temp fix.
//set the spinner items to be the "other measures"
items = new String[selected.getMeasures().size() / 2];
for (int i = 0; i < items.length; i++) {
items[i] = selected.getSingleMeasureIndex(i).getName();
}
//set and set prompt, enable
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<>(c, android.R.layout.simple_spinner_dropdown_item, items);
measureSize.setPrompt("Please select a measure");
measureSize.setAdapter(sizeAdapter);
measureSize.setEnabled(true);
} else {
//if mL or g, disable the spinner
measureSize.setEnabled(false);
}
}
}
|
Fixed editing ingredient bug, where it would save as a duplicate ingredient
|
app/src/main/java/ics4u/ics4u_final_project/MeasureSelectionActivity.java
|
Fixed editing ingredient bug, where it would save as a duplicate ingredient
|
|
Java
|
agpl-3.0
|
6a60ed0ba7d5939009f3fe28cfa97d22f064617a
| 0
|
j00615888/poker,j00615888/poker,tempbottle/pokerth,Pik-9/pokerth,tempbottle/pokerth,r00tguard/pokerth,Pik-9/pokerth,Pik-9/pokerth,Pik-9/pokerth,j00615888/poker,r00tguard/pokerth,tempbottle/pokerth,r00tguard/pokerth,j00615888/poker,tempbottle/pokerth,tempbottle/pokerth,q4z1/pokerth,j00615888/poker,q4z1/pokerth,Pik-9/pokerth,q4z1/pokerth,tempbottle/pokerth,r00tguard/pokerth,r00tguard/pokerth,Pik-9/pokerth,pokerth/pokerth,q4z1/pokerth,pokerth/pokerth,j00615888/poker,Pik-9/pokerth,pokerth/pokerth,q4z1/pokerth,r00tguard/pokerth,q4z1/pokerth,q4z1/pokerth,r00tguard/pokerth,pokerth/pokerth,pokerth/pokerth
|
/* PokerTH automated tests.
Copyright (C) 2010 Lothar May
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pokerth_test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Test;
import pokerth_protocol.*;
import pokerth_protocol.NetGameInfo.EndRaiseModeEnumType;
import pokerth_protocol.NetGameInfo.NetGameTypeEnumType;
import pokerth_protocol.StartEventMessage.StartEventMessageSequenceType;
public class StartNormalGameTest extends TestBase {
@Test
public void testGameStartMessage() throws Exception {
guestInit();
Collection<Integer> l = new ArrayList<Integer>();
NetGameInfo gameInfo = createGameInfo(5, EndRaiseModeEnumType.EnumType.doubleBlinds, 0, 100, GuestUser + " run normal game", l, 10, 0, 11, 20000);
sendMessage(createJoinGameRequestMsg(
gameInfo,
NetGameTypeEnumType.EnumType.normalGame,
5,
7,
""));
PokerTHMessage msg;
do {
msg = receiveMessage();
} while (msg.isPlayerListMessageSelected() || msg.isGameListMessageSelected());
if (msg.isJoinGameReplyMessageSelected()) {
if (!msg.getJoinGameReplyMessage().getValue().getJoinGameResult().isJoinGameAckSelected()) {
fail("Could not create game!");
}
}
else {
failOnErrorMessage(msg);
fail("Invalid message.");
}
long gameId = msg.getJoinGameReplyMessage().getValue().getGameId().getValue();
StartEventMessageSequenceType gameStartType = new StartEventMessageSequenceType();
gameStartType.setGameId(new NonZeroId(gameId));
gameStartType.setFillWithComputerPlayers(true);
StartEventMessage startMsg = new StartEventMessage();
startMsg.setValue(gameStartType);
msg = new PokerTHMessage();
msg.selectStartEventMessage(startMsg);
sendMessage(msg);
do {
msg = receiveMessage();
} while (msg.isGameListMessageSelected());
if (msg.isGameStartMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
}
}
|
tests/src/pokerth_test/StartNormalGameTest.java
|
package pokerth_test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.Test;
import pokerth_protocol.*;
import pokerth_protocol.NetGameInfo.EndRaiseModeEnumType;
import pokerth_protocol.NetGameInfo.NetGameTypeEnumType;
import pokerth_protocol.StartEventMessage.StartEventMessageSequenceType;
public class StartNormalGameTest extends TestBase {
@Test
public void testGameStartMessage() throws Exception {
guestInit();
Collection<Integer> l = new ArrayList<Integer>();
NetGameInfo gameInfo = createGameInfo(5, EndRaiseModeEnumType.EnumType.doubleBlinds, 0, 100, GuestUser + " run normal game", l, 10, 0, 11, 20000);
sendMessage(createJoinGameRequestMsg(
gameInfo,
NetGameTypeEnumType.EnumType.normalGame,
5,
7,
""));
PokerTHMessage msg;
do {
msg = receiveMessage();
} while (msg.isPlayerListMessageSelected() || msg.isGameListMessageSelected());
if (msg.isJoinGameReplyMessageSelected()) {
if (!msg.getJoinGameReplyMessage().getValue().getJoinGameResult().isJoinGameAckSelected()) {
fail("Could not create game!");
}
}
else {
failOnErrorMessage(msg);
fail("Invalid message.");
}
long gameId = msg.getJoinGameReplyMessage().getValue().getGameId().getValue();
StartEventMessageSequenceType gameStartType = new StartEventMessageSequenceType();
gameStartType.setGameId(new NonZeroId(gameId));
gameStartType.setFillWithComputerPlayers(true);
StartEventMessage startMsg = new StartEventMessage();
startMsg.setValue(gameStartType);
msg = new PokerTHMessage();
msg.selectStartEventMessage(startMsg);
sendMessage(msg);
do {
msg = receiveMessage();
} while (msg.isGameListMessageSelected());
if (msg.isGameStartMessageSelected()) {
failOnErrorMessage(msg);
fail("Invalid message.");
}
}
}
|
Adding copyright notice. Note that all test cases are AGPL3.
|
tests/src/pokerth_test/StartNormalGameTest.java
|
Adding copyright notice. Note that all test cases are AGPL3.
|
|
Java
|
agpl-3.0
|
5e3cb6be1ca7b6f6e550df29edde7e95bbcfddb2
| 0
|
jrochas/scale-proactive,mnip91/programming-multiactivities,fviale/programming,PaulKh/scale-proactive,jrochas/scale-proactive,jrochas/scale-proactive,ow2-proactive/programming,mnip91/programming-multiactivities,mnip91/programming-multiactivities,paraita/programming,lpellegr/programming,acontes/programming,lpellegr/programming,PaulKh/scale-proactive,lpellegr/programming,mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,acontes/programming,ow2-proactive/programming,lpellegr/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,paraita/programming,mnip91/proactive-component-monitoring,acontes/programming,paraita/programming,PaulKh/scale-proactive,acontes/programming,fviale/programming,fviale/programming,paraita/programming,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,jrochas/scale-proactive,acontes/programming,fviale/programming,paraita/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,jrochas/scale-proactive,ow2-proactive/programming,fviale/programming,lpellegr/programming,ow2-proactive/programming,acontes/programming,paraita/programming,mnip91/programming-multiactivities,acontes/programming,ow2-proactive/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,fviale/programming,lpellegr/programming,mnip91/programming-multiactivities,ow2-proactive/programming,mnip91/proactive-component-monitoring,jrochas/scale-proactive
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.benchmarks.NAS.MG;
import java.io.Serializable;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PASPMD;
import org.objectweb.proactive.benchmarks.NAS.util.Communicator;
import org.objectweb.proactive.benchmarks.NAS.util.NpbMath;
import org.objectweb.proactive.ext.hpc.exchange.ExchangeableDouble;
import org.objectweb.proactive.extensions.timitspmd.TimIt;
import org.objectweb.proactive.extensions.timitspmd.util.Timed;
import org.objectweb.proactive.extensions.timitspmd.util.TimerCounter;
import org.objectweb.proactive.extensions.timitspmd.util.observing.Event;
import org.objectweb.proactive.extensions.timitspmd.util.observing.EventObserver;
import org.objectweb.proactive.extensions.timitspmd.util.observing.commobserv.CommEvent;
import org.objectweb.proactive.extensions.timitspmd.util.observing.commobserv.CommEventObserver;
import org.objectweb.proactive.extensions.timitspmd.util.observing.defaultobserver.DefaultEventData;
import org.objectweb.proactive.extensions.timitspmd.util.observing.defaultobserver.DefaultEventObserver;
/**
* Kernel MG
*
* A simplified multi-grid kernel. It requires highly structured long distance communication and
* tests both short and long distance data communication. It approximates a solution to the discrete
* Poisson problem.
*/
public class WorkerMG extends Timed implements Serializable {
/*
* TimIt related variables
*/
/** Enables the observing mode */
public static final boolean COMMUNICATION_PATTERN_OBSERVING_MODE = false;
// Event observers
private EventObserver E_mflops;
private CommEventObserver nbCommObserver;
private CommEventObserver commSizeObserver;
private int reductorRank;
// Timer counters
private TimerCounter T_total = new TimerCounter("Total");
private TimerCounter T_init = new TimerCounter("Init");
private TimerCounter T_bench = new TimerCounter("Bench");
private TimerCounter T_bubble = new TimerCounter("Bubble");
private TimerCounter T_comm3 = new TimerCounter("Comm3");
private TimerCounter T_comm3_ex = new TimerCounter("Comm3Ex");
private TimerCounter T_reduce_sum = new TimerCounter("ReduceSum");
private TimerCounter T_reduce_min = new TimerCounter("ReduceMin");
private TimerCounter T_reduce_max = new TimerCounter("ReduceMax");
private TimerCounter T_reduce_max_array = new TimerCounter("ReduceMaxA");
private TimerCounter T_psinv_loop = new TimerCounter("T_psinv_loop");
/*
* MG kernel specific variables
*/
// Some MG constants
private MGProblemClass clss;
private static final int M = 1037;
private static final int MM = 10;
private static final double A = Math.pow(5.0, 13);
private static final double X = 314159265.0;
// Data for kernel computation
private double[] u;
private double[] v;
private double[] r;
private double[] a;
private double[] c;
private double rnm2;
private double rnmu;
private int n1Inst;
private int n2Inst;
private int n3Inst;
private int lb;
private int is1;
private int is2;
private int is3;
private int ie1;
private int ie2;
private int ie3;
private int[] nx;
private int[] ny;
private int[] nz;
private int[] m1;
private int[] m2;
private int[] m3;
private int[] ir;
private boolean[] dead;
private boolean[][] take_ex;
private boolean[][] give_ex;
private double[][] buff;
private int[][][] nbr;
private WorkerMG.MatrixEchanger matrixExchanger;
// Multi-dim variables
private int ud0;
private int ud01;
private int rd0;
private int rd01;
private int vd0;
private int vd01;
private int zd0;
private int zd01;
private int sd0;
private int sd01;
// ProActive
private int rank;
private int groupSize;
private boolean isLeader;
private Body body;
private Communicator communicator;
private int iter;
//
// --------------- CONSTRUCTORS ---------------------
//
public WorkerMG() {
}
public WorkerMG(MGProblemClass clss) {
E_mflops = new DefaultEventObserver("mflops", DefaultEventData.MIN, DefaultEventData.MIN);
super.activate(new TimerCounter[] { T_total, T_init, T_bench, T_bubble, T_comm3, T_comm3_ex,
T_reduce_sum, T_reduce_min, T_reduce_max, T_reduce_max_array, T_psinv_loop },
new EventObserver[] { E_mflops });
this.clss = clss;
}
public WorkerMG(MGProblemClass clss, Communicator comm) {
E_mflops = new DefaultEventObserver("mflops", DefaultEventData.MIN, DefaultEventData.MIN);
super.activate(new TimerCounter[] { T_total, T_init, T_bench, T_bubble, T_comm3, T_comm3_ex,
T_reduce_sum, T_reduce_min, T_reduce_max, T_reduce_max_array, T_psinv_loop },
new EventObserver[] { E_mflops });
this.clss = clss;
this.communicator = comm;
}
//
// --------------- PUBLIC METHODS --------------------
//
/* The entry point of the MG benchmark */
public void start() {
this.rank = PASPMD.getMyRank();
this.groupSize = PASPMD.getMySPMDGroupSize();
this.body = PAActiveObject.getBodyOnThis();
this.isLeader = (rank == 0);
this.matrixExchanger = new MatrixEchanger(this);
this.reductorRank = ((this.groupSize == 1) ? 0 : 1);
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Create a observer to observe the number of communication
this.nbCommObserver = new CommEventObserver("nbCommObserver", groupSize, rank);
// Create a observer to observe the size of the communication
this.commSizeObserver = new CommEventObserver("commSizeObserver", this.groupSize, rank);
super.activate(new EventObserver[] { nbCommObserver, commSizeObserver });
}
T_total.start();
init();
int k = clss.lt;
T_bench.start();
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
// Main iteration
for (this.iter = 0; this.iter < clss.niter; this.iter++) {
mg3P(u, 0, v, 0, r, 0, a, c, n1Inst, n2Inst, n3Inst);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
if (isLeader) {
System.out.println("iteration #" + iter);
}
}
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
T_bench.stop();
T_total.stop();
// ***** THE END *****
// ***** finalization ****
super.getEventObservable().notifyObservers(new Event(E_mflops, getMflops()));
if (isLeader) {
super.finalizeTimed(this.rank, verify() ? "" : "UNSUCCESSFUL");
} else {
super.finalizeTimed(this.rank, "");
}
} // start()
public void terminate() {
}
public void setCommunicator(Communicator comm) {
this.communicator = comm;
}
//
// --------------- PRIVATE METHODS --------------------
//
private void init() {
T_init.start();
if (isLeader) {
KernelMG.printStarted(clss.KERNEL_NAME, clss.PROBLEM_CLASS_NAME, new long[] { clss.nxSz,
clss.nySz, clss.nzSz }, clss.niter, clss.np);
}
r = new double[clss.nr + 1];
v = new double[clss.nv + 1];
u = new double[clss.nr + 1];
// Init nbr
this.nbr = new int[5][5][clss.maxLevel + 1];
this.buff = new double[6][clss.nm2 * 2];
// Init nx, ny, nz
this.nx = new int[clss.maxLevel];
this.ny = new int[clss.maxLevel];
this.nz = new int[clss.maxLevel];
this.m1 = new int[clss.maxLevel];
this.m2 = new int[clss.maxLevel];
this.m3 = new int[clss.maxLevel];
this.nx[clss.lt] = clss.nxSz;
this.ny[clss.lt] = clss.nySz;
this.nz[clss.lt] = clss.nzSz;
this.dead = new boolean[clss.maxLevel];
this.give_ex = new boolean[4][clss.maxLevel];
this.take_ex = new boolean[4][clss.maxLevel];
this.ir = new int[clss.maxLevel];
a = new double[] { -8.0 / 3.0, 0.0, 1.0 / 6.0, 1.0 / 12.0 };
if ((clss.PROBLEM_CLASS_NAME == 'S') || (clss.PROBLEM_CLASS_NAME == 'W') ||
(clss.PROBLEM_CLASS_NAME == 'A')) {
c = new double[] { -3.0 / 8.0, 1.0 / 32.0, -1.0 / 64.0, 0.0 };
} else {
c = new double[] { -3.0 / 17.0, 1.0 / 33.0, -1.0 / 61.0, 0.0 };
}
int k = clss.lt;
this.lb = 1;
// Setup
setup();
zero3(u, 0, n1Inst, n2Inst, n3Inst);
zran3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], k);
norm2u3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
// Warmup
mg3P(u, 0, v, 0, r, 0, a, c, n1Inst, n2Inst, n3Inst);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
setup();
zero3(u, 0, n1Inst, n2Inst, n3Inst);
zran3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], k);
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("warmup"));
}
PASPMD.totalBarrier("ready");
this.blockingServe();
T_init.stop();
}
private void setup() {
int dx;
int dy;
int log_p;
int dir;
int[] idi = new int[4];
int[] pi = new int[4];
int[] next = new int[4];
int[][] idin = new int[4][3];
int[][] ng = new int[4][10];
int[][] mi = new int[4][10];
int[][] mip = new int[4][10];
ng[1][clss.lt] = nx[clss.lt];
ng[2][clss.lt] = ny[clss.lt];
ng[3][clss.lt] = nz[clss.lt];
next[1] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[1][k] = ng[1][k + 1] / 2;
next[2] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[2][k] = ng[2][k + 1] / 2;
next[3] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[3][k] = ng[3][k + 1] / 2;
for (int k = clss.lt; k >= 1; k--) {
nx[k] = ng[1][k];
ny[k] = ng[2][k];
nz[k] = ng[3][k];
}
log_p = NpbMath.ilog2(clss.np);
dx = log_p / 3;
pi[1] = (int) NpbMath.ipow2(dx);
idi[1] = rank % pi[1];
dy = (log_p - dx) / 2;
pi[2] = (int) NpbMath.ipow2(dy);
idi[2] = (rank / pi[1]) % pi[2];
pi[3] = clss.np / (pi[1] * pi[2]);
idi[3] = rank / (pi[1] * pi[2]);
for (int k = clss.lt; k >= 1; k--) {
dead[k] = false;
for (int ax = 1; ax <= 3; ax++) {
take_ex[ax][k] = false;
give_ex[ax][k] = false;
mi[ax][k] = (2 + (((idi[ax] + 1) * ng[ax][k]) / pi[ax])) -
(((idi[ax] + 0) * ng[ax][k]) / pi[ax]);
mip[ax][k] = (2 + (((next[ax] + idi[ax] + 1) * ng[ax][k]) / pi[ax])) -
(((next[ax] + idi[ax] + 0) * ng[ax][k]) / pi[ax]);
if ((mip[ax][k] == 2) || (mi[ax][k] == 2)) {
next[ax] = 2 * next[ax];
}
if ((k + 1) <= clss.lt) {
if ((mip[ax][k] == 2) && (mi[ax][k] == 3)) {
give_ex[ax][k + 1] = true;
}
if ((mip[ax][k] == 3) && (mi[ax][k] == 2)) {
take_ex[ax][k + 1] = true;
}
}
}
if ((mi[1][k] == 2) || (mi[2][k] == 2) || (mi[3][k] == 2)) {
dead[k] = true;
}
m1[k] = mi[1][k];
m2[k] = mi[2][k];
m3[k] = mi[3][k];
idin[1][2] = (idi[1] + next[1] + pi[1]) % pi[1];
idin[1][0] = (idi[1] - next[1] + pi[1]) % pi[1];
idin[2][2] = (idi[2] + next[2] + pi[2]) % pi[2];
idin[2][0] = (idi[2] - next[2] + pi[2]) % pi[2];
idin[3][2] = (idi[3] + next[3] + pi[3]) % pi[3];
idin[3][0] = (idi[3] - next[3] + pi[3]) % pi[3];
for (dir = 2; dir >= 0; dir -= 2) {
nbr[1][dir][k] = idin[1][dir] + (pi[1] * (idi[2] + (pi[2] * idi[3])));
nbr[2][dir][k] = idi[1] + (pi[1] * (idin[2][dir] + (pi[2] * idi[3])));
nbr[3][dir][k] = idi[1] + (pi[1] * (idi[2] + (pi[2] * idin[3][dir])));
}
}
int k = clss.lt;
is1 = (2 + ng[1][k]) - (((pi[1] - idi[1]) * ng[1][clss.lt]) / pi[1]);
ie1 = (1 + ng[1][k]) - (((pi[1] - 1 - idi[1]) * ng[1][clss.lt]) / pi[1]);
this.n1Inst = (3 + ie1) - is1;
is2 = (2 + ng[2][k]) - (((pi[2] - idi[2]) * ng[2][clss.lt]) / pi[2]);
ie2 = (1 + ng[2][k]) - (((pi[2] - 1 - idi[2]) * ng[2][clss.lt]) / pi[2]);
this.n2Inst = (3 + ie2) - is2;
is3 = (2 + ng[3][k]) - (((pi[3] - idi[3]) * ng[3][clss.lt]) / pi[3]);
ie3 = (1 + ng[3][k]) - (((pi[3] - 1 - idi[3]) * ng[3][clss.lt]) / pi[3]);
this.n3Inst = (3 + ie3) - is3;
ir[clss.lt] = 1;
for (int j = clss.lt - 1; j >= 1; j--) {
ir[j] = ir[j + 1] + (m1[j + 1] * m2[j + 1] * m3[j + 1]);
}
k = clss.lt;
} // setup
private void mg3P(double[] u, int uoff, double[] v, int voff, double[] r, int roff, double[] a,
double[] c, int n1, int n2, int n3) {
/*---------------------------------------------------------------------
* multigrid V-cycle routine
*--------------------------------------------------------------------*/
int j;
int k;
/*---------------------------------------------------------------------
* down cycle.
* restrict the residual from the find grid to the coarse
*--------------------------------------------------------------------*/
for (k = clss.lt; k >= (lb + 1); k--) {
j = k - 1;
rprj3(r, (ir[k] + roff) - 1, m1[k], m2[k], m3[k], r, (ir[j] + roff) - 1, m1[j], m2[j], m3[j], k);
}
k = lb;
/*---------------------------------------------------------------------
* compute an approximate solution on the coarsest grid
*--------------------------------------------------------------------*/
zero3(u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k]);
psinv(r, (ir[k] + roff) - 1, u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], c, k);
for (k = lb + 1; k <= (clss.lt - 1); k++) {
j = k - 1;
/*-----------------------------------------------------------------
* prolongate from level k-1 to k
*----------------------------------------------------------------*/
zero3(u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k]);
interp(u, (ir[j] + uoff) - 1, m1[j], m2[j], m3[j], u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], k);
/*-----------------------------------------------------------------
* compute residual for level k
*----------------------------------------------------------------*/
resid(u, (ir[k] + uoff) - 1, r, (ir[k] + roff) - 1, r, (ir[k] + roff) - 1, m1[k], m2[k], m3[k],
a, k);
/*-----------------------------------------------------------------
* apply smoother
*----------------------------------------------------------------*/
psinv(r, (ir[k] + roff) - 1, u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], c, k);
}
j = clss.lt - 1;
k = clss.lt;
interp(u, (ir[j] + uoff) - 1, m1[j], m2[j], m3[j], u, uoff, n1, n2, n3, k);
resid(u, uoff, v, voff, r, roff, n1, n2, n3, a, k);
psinv(r, roff, u, uoff, n1, n2, n3, c, k);
} // mg3p
private void resid(double[] u, int uoff, double[] v, int voff, double[] r, int roff, int n1, int n2,
int n3, double[] a, int k) {
double[] u1 = new double[M];
double[] u2 = new double[M];
this.usetDimension(n1, n2, n3);
this.vsetDimension(n1, n2, n3);
this.rsetDimension(n1, n2, n3);
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u1[i1] = u[uresolve(i1, (i2 - 1), i3) + uoff] + u[uresolve(i1, (i2 + 1), i3) + uoff] +
u[uresolve(i1, i2, i3 - 1) + uoff] + u[uresolve(i1, i2, i3 + 1) + uoff];
u2[i1] = u[uresolve(i1, (i2 - 1), i3 - 1) + uoff] +
u[uresolve(i1, (i2 + 1), i3 - 1) + uoff] + u[uresolve(i1, (i2 - 1), i3 + 1) + uoff] +
u[uresolve(i1, (i2 + 1), i3 + 1) + uoff];
}
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
r[rresolve(i1, i2, i3) + roff] = v[vresolve(i1, i2, i3) + voff] -
(a[0] * u[uresolve(i1, i2, i3) + uoff]) -
(a[2] * (u2[i1] + u1[i1 - 1] + u1[i1 + 1])) - (a[3] * (u2[i1 - 1] + u2[i1 + 1]));
}
}
}
/*--------------------------------------------------------------------
* exchange boundary data
*--------------------------------------------------------------------*/
T_comm3.start();
comm3(r, roff, n1, n2, n3, k);
T_comm3.stop();
}
private void interp(double[] z, int zoff, int mm1, int mm2, int mm3, double[] u, int uoff, int n1,
int n2, int n3, int k) {
int d1;
int d2;
int d3;
int t1;
int t2;
int t3;
double[] z1 = new double[M];
double[] z2 = new double[M];
double[] z3 = new double[M];
this.zsetDimension(mm1, mm2, mm3);
this.usetDimension(n1, n2, n3);
// note that m = 1037 but for this only need to be 535 to handle up to
// 1024^3
if ((n1 != 3) && (n2 != 3) && (n3 != 3)) {
for (int i3 = 1; i3 <= (mm3 - 1); i3++) {
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = 1; i1 <= mm1; i1++) {
z1[i1] = z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(i1, i2, i3) + zoff];
z2[i1] = z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1, i2, i3) + zoff];
z3[i1] = z[zresolve(i1, i2 + 1, i3 + 1) + zoff] + z[zresolve(i1, i2, i3 + 1) + zoff] +
z1[i1];
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, (2 * i2) - 1, (2 * i3) - 1) + uoff] += z[zresolve(i1, i2, i3) +
zoff];
u[uresolve(2 * i1, (2 * i2) - 1, (2 * i3) - 1) + uoff] += (0.5 * (z[zresolve(i1 + 1,
i2, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, 2 * i2, (2 * i3) - 1) + uoff] += (0.5 * z1[i1]);
u[uresolve(2 * i1, 2 * i2, (2 * i3) - 1) + uoff] += (0.25 * (z1[i1] + z1[i1 + 1]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, (2 * i2) - 1, 2 * i3) + uoff] += (0.5 * z2[i1]);
u[uresolve(2 * i1, (2 * i2) - 1, 2 * i3) + uoff] += (0.25 * (z2[i1] + z2[i1 + 1]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, 2 * i2, 2 * i3) + uoff] += (0.25 * z3[i1]);
u[uresolve(2 * i1, 2 * i2, 2 * i3) + uoff] += (0.125 * (z3[i1] + z3[i1 + 1]));
}
}
}
} else {
d1 = (n1 == 3) ? 2 : 1;
d2 = (n2 == 3) ? 2 : 1;
d3 = (n3 == 3) ? 2 : 1;
t1 = (n1 == 3) ? 1 : 0;
t2 = (n2 == 3) ? 1 : 0;
t3 = (n3 == 3) ? 1 : 0;
for (int i3 = d3; i3 <= (mm3 - 1); i3++) {
for (int i2 = d2; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - d2, (2 * i3) - d3) + uoff] += z[zresolve(i1, i2,
i3) +
zoff];
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - d2, (2 * i3) - d3) + uoff] += (0.5 * (z[zresolve(
i1 + 1, i2, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
}
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - t2, (2 * i3) - d3) + uoff] += (0.5 * (z[zresolve(
i1, i2 + 1, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - t2, (2 * i3) - d3) + uoff] += (0.25 * (z[zresolve(
i1 + 1, i2 + 1, i3) +
zoff] +
z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
}
for (int i3 = 1; i3 <= (mm3 - 1); i3++) {
for (int i2 = d2; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - d2, (2 * i3) - t3) + uoff] += (0.5 * (z[zresolve(
i1, i2, i3 + 1) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - d2, (2 * i3) - t3) + uoff] += (0.25 * (z[zresolve(
i1 + 1, i2, i3 + 1) +
zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - t2, (2 * i3) - t3) + uoff] += (0.25 * (z[zresolve(
i1, i2 + 1, i3 + 1) +
zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - t2, (2 * i3) - t3) + uoff] += (0.125 * (z[zresolve(
i1 + 1, i2 + 1, i3 + 1) +
zoff] +
z[zresolve(i1 + 1, i2, i3 + 1) + zoff] +
z[zresolve(i1, i2 + 1, i3 + 1) + zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] +
z[zresolve(i1 + 1, i2 + 1, i3) + zoff] +
z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
}
}
T_comm3_ex.start();
comm3_ex(u, uoff, n1, n2, n3, k);
T_comm3_ex.stop();
}
/*--------------------------------------------------------------------
* psinv applies an approximate inverse as smoother: u = u + Cr
*
* This implementation costs 15A + 4M per result, where
* A and M denote the costs of Addition and Multiplication.
* Presuming coefficient c(3) is zero (the NPB assumes this,
* but it is thus not a general case), 2A + 1M may be eliminated,
* resulting in 13A + 3M.
* Note that this vectorizes, and is also fine for cache
* based machines.
*-------------------------------------------------------------------*/
private void psinv(double[] r, int roff, double[] u, int uoff, int n1, int n2, int n3, double[] c, int k) {
double[] r1 = new double[M];
double[] r2 = new double[M];
this.rsetDimension(n1, n2, n2);
this.usetDimension(n1, n2, n3);
T_psinv_loop.start();
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
r1[i1] = r[this.rresolve(i1, (i2 - 1), i3) + roff] +
r[this.rresolve(i1, (i2 + 1), i3) + roff] + r[this.rresolve(i1, i2, i3 - 1) + roff] +
r[this.rresolve(i1, i2, i3 + 1) + roff];
r2[i1] = r[this.rresolve(i1, (i2 - 1), i3 - 1) + roff] +
r[this.rresolve(i1, (i2 + 1), i3 - 1) + roff] +
r[this.rresolve(i1, (i2 - 1), i3 + 1) + roff] +
r[this.rresolve(i1, (i2 + 1), i3 + 1) + roff];
}
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
u[this.uresolve(i1, i2, i3) + uoff] = u[this.uresolve(i1, i2, i3) + uoff] +
(c[0] * r[this.rresolve(i1, i2, i3) + roff]) +
(c[1] * (r[this.rresolve(i1 - 1, i2, i3) + roff] +
r[this.rresolve(i1 + 1, i2, i3) + roff] + r1[i1])) +
(c[2] * (r2[i1] + r1[i1 - 1] + r1[i1 + 1]));
}
}
}
T_psinv_loop.stop();
/*--------------------------------------------------------------------
* exchange boundary points
*-------------------------------------------------------------------*/
T_comm3.start();
comm3(u, uoff, n1, n2, n3, k);
T_comm3.stop();
}
/*--------------------------------------------------------------------
* norm2u3 evaluates approximations to the L2 norm and the
* uniform (or L-infinity or Chebyshev) norm, under the
* assumption that the boundaries are periodic or zero. Add the
* boundaries in with half weight (quarter weight on the edges
* and eighth weight at the corners) for inhomogeneous boundaries.
*-------------------------------------------------------------------*/
private void norm2u3(double[] r, int roff, int n1, int n2, int n3, int nx, int ny, int nz) {
double a;
double[] sum_max;
double s = 0.0;
int n = nx * ny * nz;
this.rnmu = 0.0;
this.rsetDimension(n1, n2, n3);
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
double tmp = r[rresolve(i1, i2, i3) + roff];
s += (tmp * tmp);
a = Math.abs(tmp);
if (a > this.rnmu) {
this.rnmu = a;
}
}
}
}
T_reduce_sum.start();
sum_max = this.communicator.sumAndMax(s, rnmu);
T_reduce_sum.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by convention
// it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 16 /*
* the size of the message s and rnmu a
* doubles
*/);
// The communicator will compute sum and max and broadcast an
// array of double
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(sum_max));
}
}
rnmu = sum_max[1];
rnm2 = Math.sqrt(sum_max[0] / n);
}
private void comm3(double[] u, int uoff, int n1, int n2, int n3, int kk) {
if (!dead[kk]) {
for (int axis = 1; axis <= 3; axis++) {
if (clss.np != 1) {
matrixExchanger.prepare(axis, +1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("pos" + axis, nbr[axis][2][kk], matrixExchanger, matrixExchanger);
matrixExchanger.prepare(axis, -1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("neg" + axis, nbr[axis][0][kk], matrixExchanger, matrixExchanger);
} else {
comm1p(axis, u, uoff, n1, n2, n3, kk);
}
}
} else {
zero3(u, uoff, n1, n2, n3);
}
}
private void comm3_ex(double[] u, int uoff, int n1, int n2, int n3, int kk) {
for (int axis = 1; axis <= 3; axis++) {
if (clss.np != 1) {
matrixExchanger.prepare(axis, +1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("pos" + axis, nbr[axis][2][kk], matrixExchanger, matrixExchanger);
matrixExchanger.prepare(axis, -1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("neg" + axis, nbr[axis][0][kk], matrixExchanger, matrixExchanger);
} else {
comm1p_ex(axis, u, uoff, n1, n2, n3, kk);
}
}
}
private void comm1p(int axis, double[] u, int uoff, int n1, int n2, int n3, int kk) {
this.usetDimension(n1, n2, n3);
switch (axis) {
case 1:
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
u[uresolve(1, i2, i3) + uoff] = u[uresolve(n1 - 1, i2, i3) + uoff];
u[uresolve(n1, i2, i3) + uoff] = u[uresolve(2, i2, i3) + uoff];
}
}
break;
case 2:
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, 1, i3) + uoff] = u[uresolve(i1, n2 - 1, i3) + uoff];
u[uresolve(i1, n2, i3) + uoff] = u[uresolve(i1, 2, i3) + uoff];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, i2, 1) + uoff] = u[uresolve(i1, i2, n3 - 1) + uoff];
u[uresolve(i1, i2, n3) + uoff] = u[uresolve(i1, i2, 2) + uoff];
}
}
break;
}
}
private void comm1p_ex(int axis, double[] u, int uoff, int n1, int n2, int n3, int kk) {
int buff_len;
int indx;
this.usetDimension(n1, n2, n3);
if (take_ex[axis][kk]) {
buff_len = clss.nm2;
for (int i = 1; i <= buff_len; i++) {
buff[2][i] = 0;
buff[4][i] = 0;
}
indx = 0;
switch (axis) {
case 1:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
u[uresolve(n1, i2, i3) + uoff] = buff[2][++indx];
u[uresolve(1, i2, i3) + uoff] = buff[4][++indx];
u[uresolve(2, i2, i3) + uoff] = buff[4][++indx];
}
}
break;
case 2:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, n2, i3) + uoff] = buff[2][++indx];
u[uresolve(i1, 1, i3) + uoff] = buff[4][++indx];
u[uresolve(i1, 2, i3) + uoff] = buff[4][++indx];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, i2, n3) + uoff] = buff[2][++indx];
u[uresolve(i1, i2, 1) + uoff] = buff[4][++indx];
u[uresolve(i1, i2, 2) + uoff] = buff[4][++indx];
}
}
break;
}
}
if (this.give_ex[axis][kk]) {
buff_len = 0;
switch (axis) {
case 1:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
buff[3][++buff_len] = u[uresolve(n1 - 1, i2, n3 - 1) + uoff];
buff[3][++buff_len] = u[uresolve(n1, i2, n3 - 1) + uoff];
buff[1][++buff_len] = u[uresolve(2, i2, i3) + uoff];
}
}
break;
case 2:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
buff[3][++buff_len] = u[uresolve(i1, n2 - 1, i3) + uoff];
buff[3][++buff_len] = u[uresolve(i1, n2, i3) + uoff];
buff[1][++buff_len] = u[uresolve(i1, 2, i3) + uoff];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
buff[3][++buff_len] = u[uresolve(i1, i2, n3 - 1) + uoff];
buff[3][++buff_len] = u[uresolve(i1, i2, n3) + uoff];
buff[1][++buff_len] = u[uresolve(i1, i2, 2) + uoff];
}
}
}
}
for (int i = 1; i <= clss.nm2; i++) {
buff[4][i] = buff[3][i];
buff[2][i] = buff[1][i];
}
}
/*--------------------------------------------------------------------
* rprj3 projects onto the next coarser grid,
* using a trilinear Finite Element projection: s = r' = P r
*
* This implementation costs 20A + 4M per result, where
* A and M denote the costs of Addition and Multiplication.
* Note that this vectorizes, and is also fine for cache
* based machines.
*-------------------------------------------------------------------*/
private void rprj3(double[] r, int roff, int m1k, int m2k, int m3k, double[] s, int soff, int m1j,
int m2j, int m3j, int k) {
int d1;
int d2;
int d3;
double[] x1 = new double[M];
double[] y1 = new double[M];
double x2;
double y2;
this.rsetDimension(m1k, m2k, m3k);
this.ssetDimension(m1j, m2j, m3j);
d1 = (m1k == 3) ? 2 : 1;
d2 = (m2k == 3) ? 2 : 1;
d3 = (m3k == 3) ? 2 : 1;
for (int j3 = 2; j3 <= (m3j - 1); j3++) {
int i3 = (2 * j3) - d3;
for (int j2 = 2; j2 <= (m2j - 1); j2++) {
int i2 = (2 * j2) - d2;
for (int j1 = 2; j1 <= m1j; j1++) {
int i1 = (2 * j1) - d1;
x1[i1 - 1] = r[rresolve(i1 - 1, i2 - 1, i3) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3) + roff] + r[rresolve(i1 - 1, i2, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2, i3 + 1) + roff];
y1[i1 - 1] = r[rresolve(i1 - 1, i2 - 1, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2 - 1, i3 + 1) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3 + 1) + roff];
}
for (int j1 = 2; j1 <= (m1j - 1); j1++) {
int i1 = (2 * j1) - d1;
y2 = r[rresolve(i1, i2 - 1, i3 - 1) + roff] + r[rresolve(i1, i2 - 1, i3 + 1) + roff] +
r[rresolve(i1, i2 + 1, i3 - 1) + roff] + r[rresolve(i1, i2 + 1, i3 + 1) + roff];
x2 = r[rresolve(i1, i2 - 1, i3) + roff] + r[rresolve(i1, i2 + 1, i3) + roff] +
r[rresolve(i1, i2, i3 - 1) + roff] + r[rresolve(i1, i2, i3 + 1) + roff];
s[sresolve(j1, j2, j3) + soff] = (0.5 * r[rresolve(i1, i2, i3) + roff]) +
(0.25 * (r[rresolve(i1 - 1, i2, i3) + roff] + r[rresolve(i1 + 1, i2, i3) + roff] + x2)) +
(0.125 * (x1[i1 - 1] + x1[i1 + 1] + y2)) + (0.0625 * (y1[i1 - 1] + y1[i1 + 1]));
}
}
}
T_comm3.start();
comm3(s, soff, m1j, m2j, m3j, k - 1);
T_comm3.stop();
}
private void bubble(double[][] ten, int[][] j1, int[][] j2, int[][] j3, int m, int ind) {
double temp;
int j_temp;
T_bubble.start();
if (ind == 1) {
for (int i = 1; i <= (m - 1); i++) {
if (ten[i][ind] > ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
} else {
T_bubble.stop();
return;
}
}
} else {
for (int i = 1; i <= (m - 1); i++) {
if (ten[i][ind] < ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
} else {
T_bubble.stop();
return;
}
}
}
T_bubble.stop();
}
private void zero3(double[] z, int zoff, int n1, int n2, int n3) {
this.zsetDimension(n1, n2, n3);
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
z[zresolve(i1, i2, i3) + zoff] = 0.0;
}
}
}
}
/*--------------------------------------------------------------------
* zran3 loads +1 at ten randomly chosen points,
* loads -1 at a different ten random points,
* and zero elsewhere.
*--------------------------------------------------------------------*/
private void zran3(double[] z, int zoff, int n1, int n2, int n3, int nx, int ny, int k) {
int m0;
int m1;
int d1;
int e2;
int e3;
double a1;
double a2;
double ai;
double temp;
double best;
double[] xxptr = new double[1];
double[] x0ptr = new double[1];
double[] x1ptr = new double[1];
double[][] ten = new double[MM + 1][2];
int[][] j1 = new int[MM + 1][2];
int[][] j2 = new int[MM + 1][2];
int[][] j3 = new int[MM + 1][2];
int[][][] jg = new int[5][MM + 1][2];
int[] jg_temp;
this.zsetDimension(n1, n2, n3);
a1 = NpbMath.power(A, nx);
a2 = NpbMath.power(A, nx * ny);
zero3(z, zoff, n1, n2, n3);
ai = NpbMath.power(A, is1 - 2 + (nx * (is2 - 2 + (ny * (is3 - 2)))));
d1 = ie1 - is1 + 1;
e2 = ie2 - is2 + 2;
e3 = ie3 - is3 + 2;
x0ptr[0] = X;
NpbMath.randlc(x0ptr, ai);
for (int i3 = 2; i3 <= e3; i3++) {
x1ptr[0] = x0ptr[0];
for (int i2 = 2; i2 <= e2; i2++) {
xxptr[0] = x1ptr[0];
NpbMath.vranlc(d1, xxptr, A, z, zresolve(2, i2, i3) + zoff);
NpbMath.randlc(x1ptr, a1);
}
NpbMath.randlc(x0ptr, a2);
}
/*--------------------------------------------------------------------
* call comm3(z,n1,n2,n3)
* call showall(z,n1,n2,n3)
*-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
* each processor looks for twenty candidates
*-------------------------------------------------------------------*/
for (int i = 1; i <= MM; i++) {
ten[i][1] = 0.0;
j1[i][1] = 0;
j2[i][1] = 0;
j3[i][1] = 0;
ten[i][0] = 1.0;
j1[i][0] = 0;
j2[i][0] = 0;
j3[i][0] = 0;
}
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
temp = z[zresolve(i1, i2, i3) + zoff];
if (temp > ten[1][1]) {
ten[1][1] = temp;
j1[1][1] = i1;
j2[1][1] = i2;
j3[1][1] = i3;
bubble(ten, j1, j2, j3, MM, 1);
}
if (temp < ten[1][0]) {
ten[1][0] = temp;
j1[1][0] = i1;
j2[1][0] = i2;
j3[1][0] = i3;
bubble(ten, j1, j2, j3, MM, 0);
}
}
}
}
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("zran3a" + this.iter));
}
PASPMD.totalBarrier("zran3a");
this.blockingServe();
/*--------------------------------------------------------------------
* Now which of these are globally best?
*-------------------------------------------------------------------*/
int i1 = MM;
int i0 = MM;
for (int i = MM; i >= 1; i--) {
best = z[zresolve(j1[i1][1], j2[i1][1], j3[i1][1]) + zoff];
T_reduce_max.start();
temp = this.communicator.max(best);
T_reduce_max.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 8 /* the size of the message */);
// The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(8);
}
}
best = temp;
if (best == z[zresolve(j1[i1][1], j2[i1][1], j3[i1][1]) + zoff]) {
jg[0][i][1] = rank;
jg[1][i][1] = is1 - 2 + j1[i1][1];
jg[2][i][1] = is2 - 2 + j2[i1][1];
jg[3][i][1] = is3 - 2 + j3[i1][1];
i1--;
} else {
jg[0][i][1] = 0;
jg[1][i][1] = 0;
jg[2][i][1] = 0;
jg[3][i][1] = 0;
}
ten[i][1] = best;
T_reduce_max_array.start();
jg_temp = this.communicator.max(new int[] { jg[0][i][1], jg[1][i][1], jg[2][i][1], jg[3][i][1] });
T_reduce_max_array.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, TimIt.getObjectSize(jg_temp) /*
* the size
* of the
* message
*/);
// The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(jg_temp));
}
}
jg[0][i][1] = jg_temp[0];
jg[1][i][1] = jg_temp[1];
jg[2][i][1] = jg_temp[2];
jg[3][i][1] = jg_temp[3];
best = z[zresolve(j1[i0][0], j2[i0][0], j3[i0][0]) + zoff];
T_reduce_min.start();
best = this.communicator.min(best);
T_reduce_min.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 8 /* the size of the message */);
// / The communicator will compute the min and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(8);
}
}
if (best == z[zresolve(j1[i0][0], j2[i0][0], j3[i0][0]) + zoff]) {
jg[0][i][0] = rank;
jg[1][i][0] = is1 - 2 + j1[i0][0];
jg[2][i][0] = is2 - 2 + j2[i0][0];
jg[3][i][0] = is3 - 2 + j3[i0][0];
i0--;
} else {
jg[0][i][0] = 0;
jg[1][i][0] = 0;
jg[2][i][0] = 0;
jg[3][i][0] = 0;
}
ten[i][0] = best;
T_reduce_max_array.start();
jg_temp = this.communicator.max(new int[] { jg[0][i][0], jg[1][i][0], jg[2][i][0], jg[3][i][0] });
T_reduce_max_array.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, TimIt.getObjectSize(jg_temp) /*
* the size
* of the
* message
*/);
// / The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(jg_temp));
}
}
jg[0][i][0] = jg_temp[0];
jg[1][i][0] = jg_temp[1];
jg[2][i][0] = jg_temp[2];
jg[3][i][0] = jg_temp[3];
}
m1 = i1 + 1;
m0 = i0 + 1;
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("zran3b" + this.iter));
}
PASPMD.totalBarrier("zran3b");
this.blockingServe();
this.zsetDimension(n1, n2, n3);
zero3(z, zoff, n1, n2, n3);
this.zsetDimension(n1, n2, n3);
for (int i = MM; i >= m0; i--) {
z[zresolve(j1[i][0], j2[i][0], j3[i][0]) + zoff] = -1.0;
}
for (int i = MM; i >= m1; i--) {
z[zresolve(j1[i][1], j2[i][1], j3[i][1]) + zoff] = +1.0;
}
T_comm3.start();
comm3(z, zoff, n1, n2, n3, k);
T_comm3.stop();
}
private boolean verify() {
double epsilon = 0.000000001;
double verify_value = 0;
boolean verified;
switch (clss.PROBLEM_CLASS_NAME) {
case 'S':
verify_value = 0.0000530770700573;
break;
case 'W':
verify_value = 0.00000646732937534;
break;
case 'A':
verify_value = 0.00000243336530907;
break;
case 'B':
verify_value = 0.00000180056440136;
break;
case 'C':
verify_value = 0.000000570673228574;
break;
case 'D':
verify_value = 0.000000000158327506043;
}
if (Math.abs(rnm2 - verify_value) <= epsilon) {
verified = true;
System.out.println(" VERIFICATION SUCCESSFUL\n");
System.out.println(" L2 Norm is " + rnm2);
System.out.println(" Error is " + (rnm2 - verify_value));
} else {
verified = false;
System.out.println(" VERIFICATION FAILED\n");
System.out.println(" L2 Norm is " + rnm2);
System.out.println(" The correct L2 Norm is " + verify_value);
}
return verified;
}
private double getMflops() {
double time = T_total.getTotalTime() / 1000.0;
double nn = nx[clss.lt] * ny[clss.lt] * nz[clss.lt];
double mflops = (58 * clss.niter * nn * 0.000001) / time;
return mflops;
}
/*
* These methods are usefull to play with arrays as it is a 1-dim or a 3-dim
*/
private void usetDimension(int d0, int d1, int d2) {
this.ud0 = d0;
this.ud01 = ud0 * d1;
}
private final int uresolve(int a, int b, int c) {
return a + ((b - 1) * ud0) + ((c - 1) * ud01);
}
private void vsetDimension(int d0, int d1, int d2) {
this.vd0 = d0;
this.vd01 = vd0 * d1;
}
private final int vresolve(int a, int b, int c) {
return a + ((b - 1) * vd0) + ((c - 1) * vd01);
}
private void rsetDimension(int d0, int d1, int d2) {
this.rd0 = d0;
this.rd01 = rd0 * d1;
}
private final int rresolve(int a, int b, int c) {
return a + ((b - 1) * rd0) + ((c - 1) * rd01);
}
private void zsetDimension(int d0, int d1, int d2) {
this.zd0 = d0;
this.zd01 = zd0 * d1;
}
private final int zresolve(int a, int b, int c) {
return a + ((b - 1) * zd0) + ((c - 1) * zd01);
}
private void ssetDimension(int d0, int d1, int d2) {
this.sd0 = d0;
this.sd01 = sd0 * d1;
}
private final int sresolve(int a, int b, int c) {
return a + ((b - 1) * sd0) + ((c - 1) * sd01);
}
/*
* Forces the associated worker used to block the treatment of the requestQueue.
*/
private final void blockingServe() {
body.serve(body.getRequestQueue().blockingRemoveOldest());
}
/*
* Methods used to observe the number and the size of communication
*/
private void notifyOneRank(int destRank, int messageSize) {
// Notification of 1 communication with the dest rank
super.getEventObservable().notifyObservers(new CommEvent(this.nbCommObserver, destRank, 1));
// Notification
super.getEventObservable().notifyObservers(
new CommEvent(this.commSizeObserver, destRank, messageSize));
}
private void notifyAllGroupRanks(int messageSize) {
for (int i = 0; i < this.groupSize; i++) {
this.notifyOneRank(i, messageSize);
}
}
private class MatrixEchanger implements ExchangeableDouble {
private WorkerMG worker;
private int axis;
private double[] src_u;
private double[] dst_u;
private int src_uoff;
private int dst_uoff;
private int len;
private int getPos; // current position
private int putPos; // current position
private int src_x;
private int src_y;
private int src_z;
private int dst_x;
private int dst_y;
private int dst_z;
private int x0;
private int x1;
private int y0;
private int y1;
private int z0;
// private int z1; // Never used
public MatrixEchanger(WorkerMG worker) {
this.worker = worker;
}
public void prepare(int axis, int dir, double[] src_u, int src_uoff, double[] dst_u, int dst_uoff,
int n1, int n2, int n3) {
worker.usetDimension(n1, n2, n3);
this.getPos = 1;
this.putPos = 1;
this.src_u = src_u;
this.dst_u = dst_u;
this.src_uoff = src_uoff;
this.dst_uoff = dst_uoff;
this.axis = axis;
switch (axis) {
case 1:
len = ((n2 - 2) * (n3 - 2)) + 1;
x0 = 2; // neg
x1 = n1 - 1; // pos
y0 = 2;
y1 = n2 - 1;
z0 = 2;
// z1 = n3 - 1;
if (dir == -1) {
src_x = 2;
dst_x = n1;
} else {
src_x = n1 - 1;
dst_x = 1;
}
src_y = y0;
dst_y = y0;
src_z = z0;
dst_z = z0;
break;
case 2:
len = (n1 * (n3 - 2)) + 1;
x0 = 1;
x1 = n1;
y0 = 2; // neg
y1 = n2 - 1; // pos
z0 = 2;
// z1 = n3 - 1;
src_x = x0;
dst_x = x0;
if (dir == -1) {
src_y = 2;
dst_y = n2;
} else {
src_y = n2 - 1;
dst_y = 1;
}
src_z = z0;
dst_z = z0;
break;
case 3:
len = (n1 * n2) + 1;
x0 = 1;
x1 = n1;
y0 = 1;
y1 = n2;
z0 = 2; // neg
// z1 = n3 - 1; // pos
src_x = x0;
dst_x = x0;
src_y = y0;
dst_y = y0;
if (dir == -1) {
src_z = 2;
dst_z = n3;
} else {
src_z = n3 - 1;
dst_z = 1;
}
break;
}
}
public double get() {
getPos++;
double res = src_u[worker.uresolve(src_x, src_y, src_z) + src_uoff];
switch (axis) {
case 1: // x
if (src_y < y1) {
src_y++;
} else {
src_z++;
src_y = y0;
}
break;
case 2: // y
if (src_x < x1) {
src_x++;
} else {
src_z++;
src_x = x0;
}
break;
case 3: // z
if (src_x < x1) {
src_x++;
} else {
src_y++;
src_x = x0;
}
break;
}
return res;
}
public boolean hasNextGet() {
return (getPos < len);
}
public boolean hasNextPut() {
return (putPos < len);
}
public void put(double value) {
putPos++;
dst_u[worker.uresolve(dst_x, dst_y, dst_z) + dst_uoff] = value;
switch (axis) {
case 1: // x
if (dst_y < y1) {
dst_y++;
} else {
dst_z++;
dst_y = y0;
}
break;
case 2: // y
if (dst_x < x1) {
dst_x++;
} else {
dst_z++;
dst_x = x0;
}
break;
case 3: // z
if (dst_x < x1) {
dst_x++;
} else {
dst_y++;
dst_x = x0;
}
break;
}
}
}
}
|
src/Benchmarks/org/objectweb/proactive/benchmarks/NAS/MG/WorkerMG.java
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.benchmarks.NAS.MG;
import java.io.Serializable;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PASPMD;
import org.objectweb.proactive.benchmarks.NAS.util.Communicator;
import org.objectweb.proactive.benchmarks.NAS.util.NpbMath;
import org.objectweb.proactive.ext.hpc.exchange.ExchangeableDouble;
import org.objectweb.proactive.extensions.timitspmd.TimIt;
import org.objectweb.proactive.extensions.timitspmd.util.Timed;
import org.objectweb.proactive.extensions.timitspmd.util.TimerCounter;
import org.objectweb.proactive.extensions.timitspmd.util.observing.Event;
import org.objectweb.proactive.extensions.timitspmd.util.observing.EventObserver;
import org.objectweb.proactive.extensions.timitspmd.util.observing.commobserv.CommEvent;
import org.objectweb.proactive.extensions.timitspmd.util.observing.commobserv.CommEventObserver;
import org.objectweb.proactive.extensions.timitspmd.util.observing.defaultobserver.DefaultEventData;
import org.objectweb.proactive.extensions.timitspmd.util.observing.defaultobserver.DefaultEventObserver;
/**
* Kernel MG
*
* A simplified multi-grid kernel. It requires highly structured long distance communication and
* tests both short and long distance data communication. It approximates a solution to the discrete
* Poisson problem.
*/
public class WorkerMG extends Timed implements Serializable {
/*
* TimIt related variables
*/
/** Enables the observing mode */
public static final boolean COMMUNICATION_PATTERN_OBSERVING_MODE = false;
// Event observers
private EventObserver E_mflops;
private CommEventObserver nbCommObserver;
private CommEventObserver commSizeObserver;
private int reductorRank;
// Timer counters
private TimerCounter T_total = new TimerCounter("Total");
private TimerCounter T_init = new TimerCounter("Init");
private TimerCounter T_bench = new TimerCounter("Bench");
private TimerCounter T_bubble = new TimerCounter("Bubble");
private TimerCounter T_comm3 = new TimerCounter("Comm3");
private TimerCounter T_comm3_ex = new TimerCounter("Comm3Ex");
private TimerCounter T_reduce_sum = new TimerCounter("ReduceSum");
private TimerCounter T_reduce_min = new TimerCounter("ReduceMin");
private TimerCounter T_reduce_max = new TimerCounter("ReduceMax");
private TimerCounter T_reduce_max_array = new TimerCounter("ReduceMaxA");
private TimerCounter T_psinv_loop = new TimerCounter("T_psinv_loop");
/*
* MG kernel specific variables
*/
// Some MG constants
private MGProblemClass clss;
private static final int M = 1037;
private static final int MM = 10;
private static final double A = Math.pow(5.0, 13);
private static final double X = 314159265.0;
// Data for kernel computation
private double[] u;
private double[] v;
private double[] r;
private double[] a;
private double[] c;
private double rnm2;
private double rnmu;
private int n1Inst;
private int n2Inst;
private int n3Inst;
private int lb;
private int is1;
private int is2;
private int is3;
private int ie1;
private int ie2;
private int ie3;
private int[] nx;
private int[] ny;
private int[] nz;
private int[] m1;
private int[] m2;
private int[] m3;
private int[] ir;
private boolean[] dead;
private boolean[][] take_ex;
private boolean[][] give_ex;
private double[][] buff;
private int[][][] nbr;
private WorkerMG.MatrixEchanger matrixExchanger;
// Multi-dim variables
private int ud0;
private int ud01;
private int rd0;
private int rd01;
private int vd0;
private int vd01;
private int zd0;
private int zd01;
private int sd0;
private int sd01;
// ProActive
private int rank;
private int groupSize;
private boolean isLeader;
private Body body;
private Communicator communicator;
private int iter;
//
// --------------- CONSTRUCTORS ---------------------
//
public WorkerMG() {
}
public WorkerMG(MGProblemClass clss) {
E_mflops = new DefaultEventObserver("mflops", DefaultEventData.MIN, DefaultEventData.MIN);
super.activate(new TimerCounter[] { T_total, T_init, T_bench, T_bubble, T_comm3, T_comm3_ex,
T_reduce_sum, T_reduce_min, T_reduce_max, T_reduce_max_array, T_psinv_loop },
new EventObserver[] { E_mflops });
this.clss = clss;
}
public WorkerMG(MGProblemClass clss, Communicator comm) {
E_mflops = new DefaultEventObserver("mflops", DefaultEventData.MIN, DefaultEventData.MIN);
super.activate(new TimerCounter[] { T_total, T_init, T_bench, T_bubble, T_comm3, T_comm3_ex,
T_reduce_sum, T_reduce_min, T_reduce_max, T_reduce_max_array, T_psinv_loop },
new EventObserver[] { E_mflops });
this.clss = clss;
this.communicator = comm;
}
//
// --------------- PUBLIC METHODS --------------------
//
/* The entry point of the MG benchmark */
public void start() {
this.rank = PASPMD.getMyRank();
this.groupSize = PASPMD.getMySPMDGroupSize();
this.body = PAActiveObject.getBodyOnThis();
this.isLeader = (rank == 0);
this.matrixExchanger = new MatrixEchanger(this);
this.reductorRank = ((this.groupSize == 1) ? 0 : 1);
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Create a observer to observe the number of communication
this.nbCommObserver = new CommEventObserver("nbCommObserver", groupSize, rank);
// Create a observer to observe the size of the communication
this.commSizeObserver = new CommEventObserver("commSizeObserver", this.groupSize, rank);
super.activate(new EventObserver[] { nbCommObserver, commSizeObserver });
}
T_total.start();
init();
int k = clss.lt;
T_bench.start();
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
// Main iteration
for (this.iter = 0; this.iter < clss.niter; this.iter++) {
mg3P(u, 0, v, 0, r, 0, a, c, n1Inst, n2Inst, n3Inst);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
if (isLeader) {
System.out.println("iteration #" + iter);
}
}
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
T_bench.stop();
T_total.stop();
// ***** THE END *****
// ***** finalization ****
super.getEventObservable().notifyObservers(new Event(E_mflops, getMflops()));
if (isLeader) {
super.finalizeTimed(this.rank, verify() ? "" : "UNSUCCESSFUL");
} else {
super.finalizeTimed(this.rank, "");
}
} // start()
public void terminate() {
}
public void setCommunicator(Communicator comm) {
this.communicator = comm;
}
//
// --------------- PRIVATE METHODS --------------------
//
private void init() {
T_init.start();
if (isLeader) {
KernelMG.printStarted(clss.KERNEL_NAME, clss.PROBLEM_CLASS_NAME, new long[] { clss.nxSz,
clss.nySz, clss.nzSz }, clss.niter, clss.np);
}
r = new double[clss.nr + 1];
v = new double[clss.nv + 1];
u = new double[clss.nr + 1];
// Init nbr
this.nbr = new int[5][5][clss.maxLevel + 1];
this.buff = new double[6][clss.nm2 * 2];
// Init nx, ny, nz
this.nx = new int[clss.maxLevel];
this.ny = new int[clss.maxLevel];
this.nz = new int[clss.maxLevel];
this.m1 = new int[clss.maxLevel];
this.m2 = new int[clss.maxLevel];
this.m3 = new int[clss.maxLevel];
this.nx[clss.lt] = clss.nxSz;
this.ny[clss.lt] = clss.nySz;
this.nz[clss.lt] = clss.nzSz;
this.dead = new boolean[clss.maxLevel];
this.give_ex = new boolean[4][clss.maxLevel];
this.take_ex = new boolean[4][clss.maxLevel];
this.ir = new int[clss.maxLevel];
a = new double[] { -8.0 / 3.0, 0.0, 1.0 / 6.0, 1.0 / 12.0 };
if ((clss.PROBLEM_CLASS_NAME == 'S') || (clss.PROBLEM_CLASS_NAME == 'W') ||
(clss.PROBLEM_CLASS_NAME == 'A')) {
c = new double[] { -3.0 / 8.0, 1.0 / 32.0, -1.0 / 64.0, 0.0 };
} else {
c = new double[] { -3.0 / 17.0, 1.0 / 33.0, -1.0 / 61.0, 0.0 };
}
int k = clss.lt;
this.lb = 1;
// Setup
setup();
zero3(u, 0, n1Inst, n2Inst, n3Inst);
zran3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], k);
norm2u3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
norm2u3(r, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], nz[k]);
// Warmup
mg3P(u, 0, v, 0, r, 0, a, c, n1Inst, n2Inst, n3Inst);
resid(u, 0, v, 0, r, 0, n1Inst, n2Inst, n3Inst, a, k);
setup();
zero3(u, 0, n1Inst, n2Inst, n3Inst);
zran3(v, 0, n1Inst, n2Inst, n3Inst, nx[k], ny[k], k);
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("warmup"));
}
PASPMD.totalBarrier("ready");
this.blockingServe();
T_init.stop();
}
private void setup() {
int dx;
int dy;
int log_p;
int dir;
int[] idi = new int[4];
int[] pi = new int[4];
int[] next = new int[4];
int[][] idin = new int[4][3];
int[][] ng = new int[4][10];
int[][] mi = new int[4][10];
int[][] mip = new int[4][10];
ng[1][clss.lt] = nx[clss.lt];
ng[2][clss.lt] = ny[clss.lt];
ng[3][clss.lt] = nz[clss.lt];
next[1] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[1][k] = ng[1][k + 1] / 2;
next[2] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[2][k] = ng[2][k + 1] / 2;
next[3] = 1;
for (int k = clss.lt - 1; k >= 1; k--)
ng[3][k] = ng[3][k + 1] / 2;
for (int k = clss.lt; k >= 1; k--) {
nx[k] = ng[1][k];
ny[k] = ng[2][k];
nz[k] = ng[3][k];
}
log_p = NpbMath.ilog2(clss.np);
dx = log_p / 3;
pi[1] = (int) NpbMath.ipow2(dx);
idi[1] = rank % pi[1];
dy = (log_p - dx) / 2;
pi[2] = (int) NpbMath.ipow2(dy);
idi[2] = (rank / pi[1]) % pi[2];
pi[3] = clss.np / (pi[1] * pi[2]);
idi[3] = rank / (pi[1] * pi[2]);
for (int k = clss.lt; k >= 1; k--) {
dead[k] = false;
for (int ax = 1; ax <= 3; ax++) {
take_ex[ax][k] = false;
give_ex[ax][k] = false;
mi[ax][k] = (2 + (((idi[ax] + 1) * ng[ax][k]) / pi[ax])) -
(((idi[ax] + 0) * ng[ax][k]) / pi[ax]);
mip[ax][k] = (2 + (((next[ax] + idi[ax] + 1) * ng[ax][k]) / pi[ax])) -
(((next[ax] + idi[ax] + 0) * ng[ax][k]) / pi[ax]);
if ((mip[ax][k] == 2) || (mi[ax][k] == 2)) {
next[ax] = 2 * next[ax];
}
if ((k + 1) <= clss.lt) {
if ((mip[ax][k] == 2) && (mi[ax][k] == 3)) {
give_ex[ax][k + 1] = true;
}
if ((mip[ax][k] == 3) && (mi[ax][k] == 2)) {
take_ex[ax][k + 1] = true;
}
}
}
if ((mi[1][k] == 2) || (mi[2][k] == 2) || (mi[3][k] == 2)) {
dead[k] = true;
}
m1[k] = mi[1][k];
m2[k] = mi[2][k];
m3[k] = mi[3][k];
idin[1][2] = (idi[1] + next[1] + pi[1]) % pi[1];
idin[1][0] = (idi[1] - next[1] + pi[1]) % pi[1];
idin[2][2] = (idi[2] + next[2] + pi[2]) % pi[2];
idin[2][0] = (idi[2] - next[2] + pi[2]) % pi[2];
idin[3][2] = (idi[3] + next[3] + pi[3]) % pi[3];
idin[3][0] = (idi[3] - next[3] + pi[3]) % pi[3];
for (dir = 2; dir >= 0; dir -= 2) {
nbr[1][dir][k] = idin[1][dir] + (pi[1] * (idi[2] + (pi[2] * idi[3])));
nbr[2][dir][k] = idi[1] + (pi[1] * (idin[2][dir] + (pi[2] * idi[3])));
nbr[3][dir][k] = idi[1] + (pi[1] * (idi[2] + (pi[2] * idin[3][dir])));
}
}
int k = clss.lt;
is1 = (2 + ng[1][k]) - (((pi[1] - idi[1]) * ng[1][clss.lt]) / pi[1]);
ie1 = (1 + ng[1][k]) - (((pi[1] - 1 - idi[1]) * ng[1][clss.lt]) / pi[1]);
this.n1Inst = (3 + ie1) - is1;
is2 = (2 + ng[2][k]) - (((pi[2] - idi[2]) * ng[2][clss.lt]) / pi[2]);
ie2 = (1 + ng[2][k]) - (((pi[2] - 1 - idi[2]) * ng[2][clss.lt]) / pi[2]);
this.n2Inst = (3 + ie2) - is2;
is3 = (2 + ng[3][k]) - (((pi[3] - idi[3]) * ng[3][clss.lt]) / pi[3]);
ie3 = (1 + ng[3][k]) - (((pi[3] - 1 - idi[3]) * ng[3][clss.lt]) / pi[3]);
this.n3Inst = (3 + ie3) - is3;
ir[clss.lt] = 1;
for (int j = clss.lt - 1; j >= 1; j--) {
ir[j] = ir[j + 1] + (m1[j + 1] * m2[j + 1] * m3[j + 1]);
}
k = clss.lt;
} // setup
private void mg3P(double[] u, int uoff, double[] v, int voff, double[] r, int roff, double[] a,
double[] c, int n1, int n2, int n3) {
/*---------------------------------------------------------------------
* multigrid V-cycle routine
*--------------------------------------------------------------------*/
int j;
int k;
/*---------------------------------------------------------------------
* down cycle.
* restrict the residual from the find grid to the coarse
*--------------------------------------------------------------------*/
for (k = clss.lt; k >= (lb + 1); k--) {
j = k - 1;
rprj3(r, (ir[k] + roff) - 1, m1[k], m2[k], m3[k], r, (ir[j] + roff) - 1, m1[j], m2[j], m3[j], k);
}
k = lb;
/*---------------------------------------------------------------------
* compute an approximate solution on the coarsest grid
*--------------------------------------------------------------------*/
zero3(u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k]);
psinv(r, (ir[k] + roff) - 1, u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], c, k);
for (k = lb + 1; k <= (clss.lt - 1); k++) {
j = k - 1;
/*-----------------------------------------------------------------
* prolongate from level k-1 to k
*----------------------------------------------------------------*/
zero3(u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k]);
interp(u, (ir[j] + uoff) - 1, m1[j], m2[j], m3[j], u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], k);
/*-----------------------------------------------------------------
* compute residual for level k
*----------------------------------------------------------------*/
resid(u, (ir[k] + uoff) - 1, r, (ir[k] + roff) - 1, r, (ir[k] + roff) - 1, m1[k], m2[k], m3[k],
a, k);
/*-----------------------------------------------------------------
* apply smoother
*----------------------------------------------------------------*/
psinv(r, (ir[k] + roff) - 1, u, (ir[k] + uoff) - 1, m1[k], m2[k], m3[k], c, k);
}
j = clss.lt - 1;
k = clss.lt;
interp(u, (ir[j] + uoff) - 1, m1[j], m2[j], m3[j], u, uoff, n1, n2, n3, k);
resid(u, uoff, v, voff, r, roff, n1, n2, n3, a, k);
psinv(r, roff, u, uoff, n1, n2, n3, c, k);
} // mg3p
private void resid(double[] u, int uoff, double[] v, int voff, double[] r, int roff, int n1, int n2,
int n3, double[] a, int k) {
double[] u1 = new double[M];
double[] u2 = new double[M];
this.usetDimension(n1, n2, n3);
this.vsetDimension(n1, n2, n3);
this.rsetDimension(n1, n2, n3);
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u1[i1] = u[uresolve(i1, (i2 - 1), i3) + uoff] + u[uresolve(i1, (i2 + 1), i3) + uoff] +
u[uresolve(i1, i2, i3 - 1) + uoff] + u[uresolve(i1, i2, i3 + 1) + uoff];
u2[i1] = u[uresolve(i1, (i2 - 1), i3 - 1) + uoff] +
u[uresolve(i1, (i2 + 1), i3 - 1) + uoff] + u[uresolve(i1, (i2 - 1), i3 + 1) + uoff] +
u[uresolve(i1, (i2 + 1), i3 + 1) + uoff];
}
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
r[rresolve(i1, i2, i3) + roff] = v[vresolve(i1, i2, i3) + voff] -
(a[0] * u[uresolve(i1, i2, i3) + uoff]) -
(a[2] * (u2[i1] + u1[i1 - 1] + u1[i1 + 1])) - (a[3] * (u2[i1 - 1] + u2[i1 + 1]));
}
}
}
/*--------------------------------------------------------------------
* exchange boundary data
*--------------------------------------------------------------------*/
T_comm3.start();
comm3(r, roff, n1, n2, n3, k);
T_comm3.stop();
}
private void interp(double[] z, int zoff, int mm1, int mm2, int mm3, double[] u, int uoff, int n1,
int n2, int n3, int k) {
int d1;
int d2;
int d3;
int t1;
int t2;
int t3;
double[] z1 = new double[M];
double[] z2 = new double[M];
double[] z3 = new double[M];
this.zsetDimension(mm1, mm2, mm3);
this.usetDimension(n1, n2, n3);
// note that m = 1037 but for this only need to be 535 to handle up to
// 1024^3
if ((n1 != 3) && (n2 != 3) && (n3 != 3)) {
for (int i3 = 1; i3 <= (mm3 - 1); i3++) {
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = 1; i1 <= mm1; i1++) {
z1[i1] = z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(i1, i2, i3) + zoff];
z2[i1] = z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1, i2, i3) + zoff];
z3[i1] = z[zresolve(i1, i2 + 1, i3 + 1) + zoff] + z[zresolve(i1, i2, i3 + 1) + zoff] +
z1[i1];
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, (2 * i2) - 1, (2 * i3) - 1) + uoff] += z[zresolve(i1, i2, i3) +
zoff];
u[uresolve(2 * i1, (2 * i2) - 1, (2 * i3) - 1) + uoff] += (0.5 * (z[zresolve(i1 + 1,
i2, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, 2 * i2, (2 * i3) - 1) + uoff] += (0.5 * z1[i1]);
u[uresolve(2 * i1, 2 * i2, (2 * i3) - 1) + uoff] += (0.25 * (z1[i1] + z1[i1 + 1]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, (2 * i2) - 1, 2 * i3) + uoff] += (0.5 * z2[i1]);
u[uresolve(2 * i1, (2 * i2) - 1, 2 * i3) + uoff] += (0.25 * (z2[i1] + z2[i1 + 1]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - 1, 2 * i2, 2 * i3) + uoff] += (0.25 * z3[i1]);
u[uresolve(2 * i1, 2 * i2, 2 * i3) + uoff] += (0.125 * (z3[i1] + z3[i1 + 1]));
}
}
}
} else {
d1 = (n1 == 3) ? 2 : 1;
d2 = (n2 == 3) ? 2 : 1;
d3 = (n3 == 3) ? 2 : 1;
t1 = (n1 == 3) ? 1 : 0;
t2 = (n2 == 3) ? 1 : 0;
t3 = (n3 == 3) ? 1 : 0;
for (int i3 = d3; i3 <= (mm3 - 1); i3++) {
for (int i2 = d2; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - d2, (2 * i3) - d3) + uoff] += z[zresolve(i1, i2,
i3) +
zoff];
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - d2, (2 * i3) - d3) + uoff] += (0.5 * (z[zresolve(
i1 + 1, i2, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
}
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - t2, (2 * i3) - d3) + uoff] += (0.5 * (z[zresolve(
i1, i2 + 1, i3) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - t2, (2 * i3) - d3) + uoff] += (0.25 * (z[zresolve(
i1 + 1, i2 + 1, i3) +
zoff] +
z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
}
for (int i3 = 1; i3 <= (mm3 - 1); i3++) {
for (int i2 = d2; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - d2, (2 * i3) - t3) + uoff] += (0.5 * (z[zresolve(
i1, i2, i3 + 1) +
zoff] + z[zresolve(i1, i2, i3) + zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - d2, (2 * i3) - t3) + uoff] += (0.25 * (z[zresolve(
i1 + 1, i2, i3 + 1) +
zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
for (int i2 = 1; i2 <= (mm2 - 1); i2++) {
for (int i1 = d1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - d1, (2 * i2) - t2, (2 * i3) - t3) + uoff] += (0.25 * (z[zresolve(
i1, i2 + 1, i3 + 1) +
zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
for (int i1 = 1; i1 <= (mm1 - 1); i1++) {
u[uresolve((2 * i1) - t1, (2 * i2) - t2, (2 * i3) - t3) + uoff] += (0.125 * (z[zresolve(
i1 + 1, i2 + 1, i3 + 1) +
zoff] +
z[zresolve(i1 + 1, i2, i3 + 1) + zoff] +
z[zresolve(i1, i2 + 1, i3 + 1) + zoff] +
z[zresolve(i1, i2, i3 + 1) + zoff] +
z[zresolve(i1 + 1, i2 + 1, i3) + zoff] +
z[zresolve(i1 + 1, i2, i3) + zoff] + z[zresolve(i1, i2 + 1, i3) + zoff] + z[zresolve(
i1, i2, i3) +
zoff]));
}
}
}
}
T_comm3_ex.start();
comm3_ex(u, uoff, n1, n2, n3, k);
T_comm3_ex.stop();
}
/*--------------------------------------------------------------------
* psinv applies an approximate inverse as smoother: u = u + Cr
*
* This implementation costs 15A + 4M per result, where
* A and M denote the costs of Addition and Multiplication.
* Presuming coefficient c(3) is zero (the NPB assumes this,
* but it is thus not a general case), 2A + 1M may be eliminated,
* resulting in 13A + 3M.
* Note that this vectorizes, and is also fine for cache
* based machines.
*-------------------------------------------------------------------*/
private void psinv(double[] r, int roff, double[] u, int uoff, int n1, int n2, int n3, double[] c, int k) {
double[] r1 = new double[M];
double[] r2 = new double[M];
this.rsetDimension(n1, n2, n2);
this.usetDimension(n1, n2, n3);
T_psinv_loop.start();
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
r1[i1] = r[this.rresolve(i1, (i2 - 1), i3) + roff] +
r[this.rresolve(i1, (i2 + 1), i3) + roff] + r[this.rresolve(i1, i2, i3 - 1) + roff] +
r[this.rresolve(i1, i2, i3 + 1) + roff];
r2[i1] = r[this.rresolve(i1, (i2 - 1), i3 - 1) + roff] +
r[this.rresolve(i1, (i2 + 1), i3 - 1) + roff] +
r[this.rresolve(i1, (i2 - 1), i3 + 1) + roff] +
r[this.rresolve(i1, (i2 + 1), i3 + 1) + roff];
}
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
u[this.uresolve(i1, i2, i3) + uoff] = u[this.uresolve(i1, i2, i3) + uoff] +
(c[0] * r[this.rresolve(i1, i2, i3) + roff]) +
(c[1] * (r[this.rresolve(i1 - 1, i2, i3) + roff] +
r[this.rresolve(i1 + 1, i2, i3) + roff] + r1[i1])) +
(c[2] * (r2[i1] + r1[i1 - 1] + r1[i1 + 1]));
}
}
}
T_psinv_loop.stop();
/*--------------------------------------------------------------------
* exchange boundary points
*-------------------------------------------------------------------*/
T_comm3.start();
comm3(u, uoff, n1, n2, n3, k);
T_comm3.stop();
}
/*--------------------------------------------------------------------
* norm2u3 evaluates approximations to the L2 norm and the
* uniform (or L-infinity or Chebyshev) norm, under the
* assumption that the boundaries are periodic or zero. Add the
* boundaries in with half weight (quarter weight on the edges
* and eighth weight at the corners) for inhomogeneous boundaries.
*-------------------------------------------------------------------*/
private void norm2u3(double[] r, int roff, int n1, int n2, int n3, int nx, int ny, int nz) {
double a;
double[] sum_max;
double s = 0.0;
int n = nx * ny * nz;
this.rnmu = 0.0;
this.rsetDimension(n1, n2, n3);
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
double tmp = r[rresolve(i1, i2, i3) + roff];
s += (tmp * tmp);
a = Math.abs(tmp);
if (a > this.rnmu) {
this.rnmu = a;
}
}
}
}
T_reduce_sum.start();
sum_max = this.communicator.sumAndMax(s, rnmu); // XXX sumAndMax
T_reduce_sum.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by convention
// it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 16 /*
* the size of the message s and rnmu a
* doubles
*/);
// The communicator will compute sum and max and broadcast an
// array of double
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(sum_max));
}
}
rnmu = sum_max[1];
rnm2 = Math.sqrt(sum_max[0] / n);
}
private void comm3(double[] u, int uoff, int n1, int n2, int n3, int kk) {
if (!dead[kk]) {
for (int axis = 1; axis <= 3; axis++) {
if (clss.np != 1) {
matrixExchanger.prepare(axis, +1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("pos" + axis, nbr[axis][2][kk], matrixExchanger, matrixExchanger);
matrixExchanger.prepare(axis, -1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("neg" + axis, nbr[axis][0][kk], matrixExchanger, matrixExchanger);
} else {
comm1p(axis, u, uoff, n1, n2, n3, kk);
}
}
} else {
zero3(u, uoff, n1, n2, n3);
}
}
private void comm3_ex(double[] u, int uoff, int n1, int n2, int n3, int kk) {
for (int axis = 1; axis <= 3; axis++) {
if (clss.np != 1) {
matrixExchanger.prepare(axis, +1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("pos" + axis, nbr[axis][2][kk], matrixExchanger, matrixExchanger);
matrixExchanger.prepare(axis, -1, u, uoff, u, uoff, n1, n2, n3);
PASPMD.exchange("neg" + axis, nbr[axis][0][kk], matrixExchanger, matrixExchanger);
} else {
comm1p_ex(axis, u, uoff, n1, n2, n3, kk);
}
}
}
private void comm1p(int axis, double[] u, int uoff, int n1, int n2, int n3, int kk) {
this.usetDimension(n1, n2, n3);
switch (axis) {
case 1:
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
u[uresolve(1, i2, i3) + uoff] = u[uresolve(n1 - 1, i2, i3) + uoff];
u[uresolve(n1, i2, i3) + uoff] = u[uresolve(2, i2, i3) + uoff];
}
}
break;
case 2:
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, 1, i3) + uoff] = u[uresolve(i1, n2 - 1, i3) + uoff];
u[uresolve(i1, n2, i3) + uoff] = u[uresolve(i1, 2, i3) + uoff];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, i2, 1) + uoff] = u[uresolve(i1, i2, n3 - 1) + uoff];
u[uresolve(i1, i2, n3) + uoff] = u[uresolve(i1, i2, 2) + uoff];
}
}
break;
}
}
private void comm1p_ex(int axis, double[] u, int uoff, int n1, int n2, int n3, int kk) {
int buff_len;
int indx;
this.usetDimension(n1, n2, n3);
if (take_ex[axis][kk]) {
buff_len = clss.nm2;
for (int i = 1; i <= buff_len; i++) {
buff[2][i] = 0;
buff[4][i] = 0;
}
indx = 0;
switch (axis) {
case 1:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
u[uresolve(n1, i2, i3) + uoff] = buff[2][++indx];
u[uresolve(1, i2, i3) + uoff] = buff[4][++indx];
u[uresolve(2, i2, i3) + uoff] = buff[4][++indx];
}
}
break;
case 2:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, n2, i3) + uoff] = buff[2][++indx];
u[uresolve(i1, 1, i3) + uoff] = buff[4][++indx];
u[uresolve(i1, 2, i3) + uoff] = buff[4][++indx];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
u[uresolve(i1, i2, n3) + uoff] = buff[2][++indx];
u[uresolve(i1, i2, 1) + uoff] = buff[4][++indx];
u[uresolve(i1, i2, 2) + uoff] = buff[4][++indx];
}
}
break;
}
}
if (this.give_ex[axis][kk]) {
buff_len = 0;
switch (axis) {
case 1:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
buff[3][++buff_len] = u[uresolve(n1 - 1, i2, n3 - 1) + uoff];
buff[3][++buff_len] = u[uresolve(n1, i2, n3 - 1) + uoff];
buff[1][++buff_len] = u[uresolve(2, i2, i3) + uoff];
}
}
break;
case 2:
for (int i3 = 1; i3 <= n3; i3++) {
for (int i1 = 1; i1 <= n1; i1++) {
buff[3][++buff_len] = u[uresolve(i1, n2 - 1, i3) + uoff];
buff[3][++buff_len] = u[uresolve(i1, n2, i3) + uoff];
buff[1][++buff_len] = u[uresolve(i1, 2, i3) + uoff];
}
}
break;
case 3:
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
buff[3][++buff_len] = u[uresolve(i1, i2, n3 - 1) + uoff];
buff[3][++buff_len] = u[uresolve(i1, i2, n3) + uoff];
buff[1][++buff_len] = u[uresolve(i1, i2, 2) + uoff];
}
}
}
}
for (int i = 1; i <= clss.nm2; i++) {
buff[4][i] = buff[3][i];
buff[2][i] = buff[1][i];
}
}
/*--------------------------------------------------------------------
* rprj3 projects onto the next coarser grid,
* using a trilinear Finite Element projection: s = r' = P r
*
* This implementation costs 20A + 4M per result, where
* A and M denote the costs of Addition and Multiplication.
* Note that this vectorizes, and is also fine for cache
* based machines.
*-------------------------------------------------------------------*/
private void rprj3(double[] r, int roff, int m1k, int m2k, int m3k, double[] s, int soff, int m1j,
int m2j, int m3j, int k) {
int d1;
int d2;
int d3;
double[] x1 = new double[M];
double[] y1 = new double[M];
double x2;
double y2;
this.rsetDimension(m1k, m2k, m3k);
this.ssetDimension(m1j, m2j, m3j);
d1 = (m1k == 3) ? 2 : 1;
d2 = (m2k == 3) ? 2 : 1;
d3 = (m3k == 3) ? 2 : 1;
for (int j3 = 2; j3 <= (m3j - 1); j3++) {
int i3 = (2 * j3) - d3;
for (int j2 = 2; j2 <= (m2j - 1); j2++) {
int i2 = (2 * j2) - d2;
for (int j1 = 2; j1 <= m1j; j1++) {
int i1 = (2 * j1) - d1;
x1[i1 - 1] = r[rresolve(i1 - 1, i2 - 1, i3) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3) + roff] + r[rresolve(i1 - 1, i2, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2, i3 + 1) + roff];
y1[i1 - 1] = r[rresolve(i1 - 1, i2 - 1, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2 - 1, i3 + 1) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3 - 1) + roff] +
r[rresolve(i1 - 1, i2 + 1, i3 + 1) + roff];
}
for (int j1 = 2; j1 <= (m1j - 1); j1++) {
int i1 = (2 * j1) - d1;
y2 = r[rresolve(i1, i2 - 1, i3 - 1) + roff] + r[rresolve(i1, i2 - 1, i3 + 1) + roff] +
r[rresolve(i1, i2 + 1, i3 - 1) + roff] + r[rresolve(i1, i2 + 1, i3 + 1) + roff];
x2 = r[rresolve(i1, i2 - 1, i3) + roff] + r[rresolve(i1, i2 + 1, i3) + roff] +
r[rresolve(i1, i2, i3 - 1) + roff] + r[rresolve(i1, i2, i3 + 1) + roff];
s[sresolve(j1, j2, j3) + soff] = (0.5 * r[rresolve(i1, i2, i3) + roff]) +
(0.25 * (r[rresolve(i1 - 1, i2, i3) + roff] + r[rresolve(i1 + 1, i2, i3) + roff] + x2)) +
(0.125 * (x1[i1 - 1] + x1[i1 + 1] + y2)) + (0.0625 * (y1[i1 - 1] + y1[i1 + 1]));
}
}
}
T_comm3.start();
comm3(s, soff, m1j, m2j, m3j, k - 1);
T_comm3.stop();
}
private void bubble(double[][] ten, int[][] j1, int[][] j2, int[][] j3, int m, int ind) {
double temp;
int j_temp;
T_bubble.start();
if (ind == 1) {
for (int i = 1; i <= (m - 1); i++) {
if (ten[i][ind] > ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
} else {
T_bubble.stop();
return;
}
}
} else {
for (int i = 1; i <= (m - 1); i++) {
if (ten[i][ind] < ten[i + 1][ind]) {
temp = ten[i + 1][ind];
ten[i + 1][ind] = ten[i][ind];
ten[i][ind] = temp;
j_temp = j1[i + 1][ind];
j1[i + 1][ind] = j1[i][ind];
j1[i][ind] = j_temp;
j_temp = j2[i + 1][ind];
j2[i + 1][ind] = j2[i][ind];
j2[i][ind] = j_temp;
j_temp = j3[i + 1][ind];
j3[i + 1][ind] = j3[i][ind];
j3[i][ind] = j_temp;
} else {
T_bubble.stop();
return;
}
}
}
T_bubble.stop();
}
private void zero3(double[] z, int zoff, int n1, int n2, int n3) {
this.zsetDimension(n1, n2, n3);
for (int i3 = 1; i3 <= n3; i3++) {
for (int i2 = 1; i2 <= n2; i2++) {
for (int i1 = 1; i1 <= n1; i1++) {
z[zresolve(i1, i2, i3) + zoff] = 0.0;
}
}
}
}
/*--------------------------------------------------------------------
* zran3 loads +1 at ten randomly chosen points,
* loads -1 at a different ten random points,
* and zero elsewhere.
*--------------------------------------------------------------------*/
private void zran3(double[] z, int zoff, int n1, int n2, int n3, int nx, int ny, int k) {
int m0;
int m1;
int d1;
int e2;
int e3;
double a1;
double a2;
double ai;
double temp;
double best;
double[] xxptr = new double[1];
double[] x0ptr = new double[1];
double[] x1ptr = new double[1];
double[][] ten = new double[MM + 1][2];
int[][] j1 = new int[MM + 1][2];
int[][] j2 = new int[MM + 1][2];
int[][] j3 = new int[MM + 1][2];
int[][][] jg = new int[5][MM + 1][2];
int[] jg_temp;
this.zsetDimension(n1, n2, n3);
a1 = NpbMath.power(A, nx);
a2 = NpbMath.power(A, nx * ny);
zero3(z, zoff, n1, n2, n3);
ai = NpbMath.power(A, is1 - 2 + (nx * (is2 - 2 + (ny * (is3 - 2)))));
d1 = ie1 - is1 + 1;
e2 = ie2 - is2 + 2;
e3 = ie3 - is3 + 2;
x0ptr[0] = X;
NpbMath.randlc(x0ptr, ai);
for (int i3 = 2; i3 <= e3; i3++) {
x1ptr[0] = x0ptr[0];
for (int i2 = 2; i2 <= e2; i2++) {
xxptr[0] = x1ptr[0];
NpbMath.vranlc(d1, xxptr, A, z, zresolve(2, i2, i3) + zoff);
NpbMath.randlc(x1ptr, a1);
}
NpbMath.randlc(x0ptr, a2);
}
/*--------------------------------------------------------------------
* call comm3(z,n1,n2,n3)
* call showall(z,n1,n2,n3)
*-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
* each processor looks for twenty candidates
*-------------------------------------------------------------------*/
for (int i = 1; i <= MM; i++) {
ten[i][1] = 0.0;
j1[i][1] = 0;
j2[i][1] = 0;
j3[i][1] = 0;
ten[i][0] = 1.0;
j1[i][0] = 0;
j2[i][0] = 0;
j3[i][0] = 0;
}
for (int i3 = 2; i3 <= (n3 - 1); i3++) {
for (int i2 = 2; i2 <= (n2 - 1); i2++) {
for (int i1 = 2; i1 <= (n1 - 1); i1++) {
temp = z[zresolve(i1, i2, i3) + zoff];
if (temp > ten[1][1]) {
ten[1][1] = temp;
j1[1][1] = i1;
j2[1][1] = i2;
j3[1][1] = i3;
bubble(ten, j1, j2, j3, MM, 1);
}
if (temp < ten[1][0]) {
ten[1][0] = temp;
j1[1][0] = i1;
j2[1][0] = i2;
j3[1][0] = i3;
bubble(ten, j1, j2, j3, MM, 0);
}
}
}
}
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("zran3a" + this.iter));
}
PASPMD.totalBarrier("zran3a");
this.blockingServe();
/*--------------------------------------------------------------------
* Now which of these are globally best?
*-------------------------------------------------------------------*/
int i1 = MM;
int i0 = MM;
for (int i = MM; i >= 1; i--) {
best = z[zresolve(j1[i1][1], j2[i1][1], j3[i1][1]) + zoff];
T_reduce_max.start();
temp = this.communicator.max(best); // XXX REDUCES MAX
T_reduce_max.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 8 /* the size of the message */);
// The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(8);
}
}
best = temp;
if (best == z[zresolve(j1[i1][1], j2[i1][1], j3[i1][1]) + zoff]) {
jg[0][i][1] = rank;
jg[1][i][1] = is1 - 2 + j1[i1][1];
jg[2][i][1] = is2 - 2 + j2[i1][1];
jg[3][i][1] = is3 - 2 + j3[i1][1];
i1--;
} else {
jg[0][i][1] = 0;
jg[1][i][1] = 0;
jg[2][i][1] = 0;
jg[3][i][1] = 0;
}
ten[i][1] = best;
// XXX Reduce Max array
T_reduce_max_array.start();
jg_temp = this.communicator.max(new int[] { jg[0][i][1], jg[1][i][1], jg[2][i][1], jg[3][i][1] });
T_reduce_max_array.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, TimIt.getObjectSize(jg_temp) /*
* the size
* of the
* message
*/);
// The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(jg_temp));
}
}
jg[0][i][1] = jg_temp[0];
jg[1][i][1] = jg_temp[1];
jg[2][i][1] = jg_temp[2];
jg[3][i][1] = jg_temp[3];
best = z[zresolve(j1[i0][0], j2[i0][0], j3[i0][0]) + zoff];
// XXX Reduce Min
T_reduce_min.start();
best = this.communicator.min(best);
T_reduce_min.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, 8 /* the size of the message */);
// / The communicator will compute the min and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(8);
}
}
if (best == z[zresolve(j1[i0][0], j2[i0][0], j3[i0][0]) + zoff]) {
jg[0][i][0] = rank;
jg[1][i][0] = is1 - 2 + j1[i0][0];
jg[2][i][0] = is2 - 2 + j2[i0][0];
jg[3][i][0] = is3 - 2 + j3[i0][0];
i0--;
} else {
jg[0][i][0] = 0;
jg[1][i][0] = 0;
jg[2][i][0] = 0;
jg[3][i][0] = 0;
}
ten[i][0] = best;
// XXX Reduce Max array
T_reduce_max_array.start();
jg_temp = this.communicator.max(new int[] { jg[0][i][0], jg[1][i][0], jg[2][i][0], jg[3][i][0] });
T_reduce_max_array.stop();
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a communication to the reductor ( by
// convention it's the rank 1 ) to the communicator
this.notifyOneRank(this.reductorRank, TimIt.getObjectSize(jg_temp) /*
* the size
* of the
* message
*/);
// / The communicator will compute the max and broadcast it
if (this.rank == 1) {
this.notifyAllGroupRanks(TimIt.getObjectSize(jg_temp));
}
}
jg[0][i][0] = jg_temp[0];
jg[1][i][0] = jg_temp[1];
jg[2][i][0] = jg_temp[2];
jg[3][i][0] = jg_temp[3];
}
m1 = i1 + 1;
m0 = i0 + 1;
if (WorkerMG.COMMUNICATION_PATTERN_OBSERVING_MODE) {
// Notification of a global barrier synchronization
this.notifyAllGroupRanks(TimIt.getObjectSize("zran3b" + this.iter));
}
PASPMD.totalBarrier("zran3b");
this.blockingServe();
this.zsetDimension(n1, n2, n3);
zero3(z, zoff, n1, n2, n3);
this.zsetDimension(n1, n2, n3);
for (int i = MM; i >= m0; i--) {
z[zresolve(j1[i][0], j2[i][0], j3[i][0]) + zoff] = -1.0;
}
for (int i = MM; i >= m1; i--) {
z[zresolve(j1[i][1], j2[i][1], j3[i][1]) + zoff] = +1.0;
}
T_comm3.start();
comm3(z, zoff, n1, n2, n3, k);
T_comm3.stop();
}
private boolean verify() {
double epsilon = 0.000000001;
double verify_value = 0;
boolean verified;
switch (clss.PROBLEM_CLASS_NAME) {
case 'S':
verify_value = 0.0000530770700573;
break;
case 'W':
verify_value = 0.00000646732937534;
break;
case 'A':
verify_value = 0.00000243336530907;
break;
case 'B':
verify_value = 0.00000180056440136;
break;
case 'C':
verify_value = 0.000000570673228574;
break;
case 'D':
verify_value = 0.000000000158327506043;
}
if (Math.abs(rnm2 - verify_value) <= epsilon) {
verified = true;
System.out.println(" VERIFICATION SUCCESSFUL\n");
System.out.println(" L2 Norm is " + rnm2);
System.out.println(" Error is " + (rnm2 - verify_value));
} else {
verified = false;
System.out.println(" VERIFICATION FAILED\n");
System.out.println(" L2 Norm is " + rnm2);
System.out.println(" The correct L2 Norm is " + verify_value);
}
return verified;
}
private double getMflops() {
double time = T_total.getTotalTime() / 1000.0;
double nn = nx[clss.lt] * ny[clss.lt] * nz[clss.lt];
double mflops = (58 * clss.niter * nn * 0.000001) / time;
return mflops;
}
/*
* These methods are usefull to play with arrays as it is a 1-dim or a 3-dim
*/
private void usetDimension(int d0, int d1, int d2) {
this.ud0 = d0;
this.ud01 = ud0 * d1;
}
private final int uresolve(int a, int b, int c) {
return a + ((b - 1) * ud0) + ((c - 1) * ud01);
}
private void vsetDimension(int d0, int d1, int d2) {
this.vd0 = d0;
this.vd01 = vd0 * d1;
}
private final int vresolve(int a, int b, int c) {
return a + ((b - 1) * vd0) + ((c - 1) * vd01);
}
private void rsetDimension(int d0, int d1, int d2) {
this.rd0 = d0;
this.rd01 = rd0 * d1;
}
private final int rresolve(int a, int b, int c) {
return a + ((b - 1) * rd0) + ((c - 1) * rd01);
}
private void zsetDimension(int d0, int d1, int d2) {
this.zd0 = d0;
this.zd01 = zd0 * d1;
}
private final int zresolve(int a, int b, int c) {
return a + ((b - 1) * zd0) + ((c - 1) * zd01);
}
private void ssetDimension(int d0, int d1, int d2) {
this.sd0 = d0;
this.sd01 = sd0 * d1;
}
private final int sresolve(int a, int b, int c) {
return a + ((b - 1) * sd0) + ((c - 1) * sd01);
}
/*
* Forces the associated worker used to block the treatment of the requestQueue.
*/
private final void blockingServe() {
body.serve(body.getRequestQueue().blockingRemoveOldest());
}
/*
* Methods used to observe the number and the size of communication
*/
private void notifyOneRank(int destRank, int messageSize) {
// Notification of 1 communication with the dest rank
super.getEventObservable().notifyObservers(new CommEvent(this.nbCommObserver, destRank, 1));
// Notification
super.getEventObservable().notifyObservers(
new CommEvent(this.commSizeObserver, destRank, messageSize));
}
private void notifyAllGroupRanks(int messageSize) {
for (int i = 0; i < this.groupSize; i++) {
this.notifyOneRank(i, messageSize);
}
}
private class MatrixEchanger implements ExchangeableDouble {
private WorkerMG worker;
private int axis;
private double[] src_u;
private double[] dst_u;
private int src_uoff;
private int dst_uoff;
private int len;
private int getPos; // current position
private int putPos; // current position
private int src_x;
private int src_y;
private int src_z;
private int dst_x;
private int dst_y;
private int dst_z;
private int x0;
private int x1;
private int y0;
private int y1;
private int z0;
// private int z1; // Never used
public MatrixEchanger(WorkerMG worker) {
this.worker = worker;
}
public void prepare(int axis, int dir, double[] src_u, int src_uoff, double[] dst_u, int dst_uoff,
int n1, int n2, int n3) {
worker.usetDimension(n1, n2, n3);
this.getPos = 1;
this.putPos = 1;
this.src_u = src_u;
this.dst_u = dst_u;
this.src_uoff = src_uoff;
this.dst_uoff = dst_uoff;
this.axis = axis;
switch (axis) {
case 1:
len = ((n2 - 2) * (n3 - 2)) + 1;
x0 = 2; // neg
x1 = n1 - 1; // pos
y0 = 2;
y1 = n2 - 1;
z0 = 2;
// z1 = n3 - 1;
if (dir == -1) {
src_x = 2;
dst_x = n1;
} else {
src_x = n1 - 1;
dst_x = 1;
}
src_y = y0;
dst_y = y0;
src_z = z0;
dst_z = z0;
break;
case 2:
len = (n1 * (n3 - 2)) + 1;
x0 = 1;
x1 = n1;
y0 = 2; // neg
y1 = n2 - 1; // pos
z0 = 2;
// z1 = n3 - 1;
src_x = x0;
dst_x = x0;
if (dir == -1) {
src_y = 2;
dst_y = n2;
} else {
src_y = n2 - 1;
dst_y = 1;
}
src_z = z0;
dst_z = z0;
break;
case 3:
len = (n1 * n2) + 1;
x0 = 1;
x1 = n1;
y0 = 1;
y1 = n2;
z0 = 2; // neg
// z1 = n3 - 1; // pos
src_x = x0;
dst_x = x0;
src_y = y0;
dst_y = y0;
if (dir == -1) {
src_z = 2;
dst_z = n3;
} else {
src_z = n3 - 1;
dst_z = 1;
}
break;
}
}
public double get() {
getPos++;
double res = src_u[worker.uresolve(src_x, src_y, src_z) + src_uoff];
switch (axis) {
case 1: // x
if (src_y < y1) {
src_y++;
} else {
src_z++;
src_y = y0;
}
break;
case 2: // y
if (src_x < x1) {
src_x++;
} else {
src_z++;
src_x = x0;
}
break;
case 3: // z
if (src_x < x1) {
src_x++;
} else {
src_y++;
src_x = x0;
}
break;
}
return res;
}
public boolean hasNextGet() {
return (getPos < len);
}
public boolean hasNextPut() {
return (putPos < len);
}
public void put(double value) {
putPos++;
dst_u[worker.uresolve(dst_x, dst_y, dst_z) + dst_uoff] = value;
switch (axis) {
case 1: // x
if (dst_y < y1) {
dst_y++;
} else {
dst_z++;
dst_y = y0;
}
break;
case 2: // y
if (dst_x < x1) {
dst_x++;
} else {
dst_z++;
dst_x = x0;
}
break;
case 3: // z
if (dst_x < x1) {
dst_x++;
} else {
dst_y++;
dst_x = x0;
}
break;
}
}
}
}
|
Removing some unuseful XXX comments
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@10649 28e8926c-6b08-0410-baaa-805c5e19b8d6
|
src/Benchmarks/org/objectweb/proactive/benchmarks/NAS/MG/WorkerMG.java
|
Removing some unuseful XXX comments
|
|
Java
|
agpl-3.0
|
c9d18b86dc2c471b6176b87c9a586b323d6bfa04
| 0
|
animotron/core,animotron/core
|
/*
* Copyright (C) 2011-2012 The Animo Project
* http://animotron.org
*
* This file is part of Animotron.
*
* Animotron is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Animotron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of
* the GNU Affero General Public License along with Animotron.
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.animotron.games.web;
import org.animotron.ATest;
import org.animotron.expression.Expression;
import org.junit.Test;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class ResourceTest extends ATest {
@Test
public void test1() throws Throwable {
tAnimo("def service ^resource.");
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest any resource.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest root-service (service resource) (root) (title \"root\").");
assertAnimoResult(s, "s rest root-service (service resource) (root) (title).");
}
@Test
public void test2() throws Throwable {
tAnimo("def service ^resource.");
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def root-service1 (service) (root) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all resource.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title \"root\")) (root-service1 (service resource) (root) (title \"root1\")).");
assertAnimoResult(s, "s rest (root-service (service resource) (root) (title)) (root-service1 (service resource) (root) (title)).");
}
@Test
public void test3() throws Throwable {
tAnimo("def service ^resource.");
tAnimo("def root-service (^service) (root) (title 'root').");
tAnimo("def root-service1 (root-service) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all resource.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title \"root\")) (root-service1 (root-service (service resource) (root) (title \"root\")) (title)) (title \"root1\")).");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title)) (root-service1 (root-service (service resource) (root) (title)) (title)).");
assertAnimoResult(s, "s rest " +
"(root-service (service resource) (root) (title)) " +
"(root-service1 (root-service (service resource) (root) (title)) (title)).");
}
@Test
public void test4() throws Throwable {
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest any service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest root-service (service) (root) (title \"root\").");
assertAnimoResult(s, "s rest root-service (service) (root) (title).");
}
@Test
public void test5() throws Throwable {
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def root-service1 (service) (root) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title \"root\")) (root-service1 (service) (root) (title \"root1\")).");
assertAnimoResult(s, "s rest (root-service (service) (root) (title)) (root-service1 (service) (root) (title)).");
}
@Test
public void test6() throws Throwable {
tAnimo("def root-service (^service) (root) (title 'root').");
tAnimo("def root-service1 (root-service) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title \"root\")) (root-service1 (root-service) (title \"root1\")).");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title)) (root-service1 (root-service (service) (root) (title)) (title)).");
assertAnimoResult(s, "s rest " +
"(root-service (service) (root) (title)) " +
"(root-service1 (root-service (service) (root) (title)) (title)).");
}
}
|
src/test/java/org/animotron/games/web/ResourceTest.java
|
/*
* Copyright (C) 2011-2012 The Animo Project
* http://animotron.org
*
* This file is part of Animotron.
*
* Animotron is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Animotron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of
* the GNU Affero General Public License along with Animotron.
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.animotron.games.web;
import org.animotron.ATest;
import org.animotron.expression.Expression;
import org.junit.Test;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class ResourceTest extends ATest {
@Test
public void test1() throws Throwable {
tAnimo("def service resource.");
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest any resource.");
Expression s = tAnimo("def rest use root.");
//assertAnimoResult(s, "s rest root-service (service resource) (root) (title \"root\").");
assertAnimoResult(s, "s rest root-service (service resource) (root) (title).");
}
@Test
public void test2() throws Throwable {
tAnimo("def service ^resource.");
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def root-service1 (service) (root) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all resource.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title \"root\")) (root-service1 (service resource) (root) (title \"root1\")).");
assertAnimoResult(s, "s rest (root-service (service resource) (root) (title)) (root-service1 (service resource) (root) (title)).");
}
@Test
public void test3() throws Throwable {
tAnimo("def service ^resource.");
tAnimo("def root-service (^service) (root) (title 'root').");
tAnimo("def root-service1 (root-service) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all resource.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title \"root\")) (root-service1 (root-service (service resource) (root) (title \"root\")) (title)) (title \"root1\")).");
//assertAnimoResult(s, "s rest (root-service (service resource) (root) (title)) (root-service1 (root-service (service resource) (root) (title)) (title)).");
assertAnimoResult(s, "s rest " +
"(root-service (service resource) (root) (title)) " +
"(root-service1 (root-service (service resource) (root) (title)) (title)).");
}
@Test
public void test4() throws Throwable {
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest any service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest root-service (service) (root) (title \"root\").");
assertAnimoResult(s, "s rest root-service (service) (root) (title).");
}
@Test
public void test5() throws Throwable {
tAnimo("def root-service (service) (root) (title 'root').");
tAnimo("def root-service1 (service) (root) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title \"root\")) (root-service1 (service) (root) (title \"root1\")).");
assertAnimoResult(s, "s rest (root-service (service) (root) (title)) (root-service1 (service) (root) (title)).");
}
@Test
public void test6() throws Throwable {
tAnimo("def root-service (^service) (root) (title 'root').");
tAnimo("def root-service1 (root-service) (title 'root1').");
tAnimo("def not-found-service (service) (not-found) (title 404).");
tAnimo("def rest all service.");
Expression s = tAnimo("def s rest use root.");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title \"root\")) (root-service1 (root-service) (title \"root1\")).");
//assertAnimoResult(s, "s rest (root-service (service) (root) (title)) (root-service1 (root-service (service) (root) (title)) (title)).");
assertAnimoResult(s, "s rest " +
"(root-service (service) (root) (title)) " +
"(root-service1 (root-service (service) (root) (title)) (title)).");
}
}
|
testfix
|
src/test/java/org/animotron/games/web/ResourceTest.java
|
testfix
|
|
Java
|
agpl-3.0
|
95ffe7ad489d8c94a587001d13834d99d530127c
| 0
|
adakitesystems/droplauncher
|
package droplauncher.util.windows;
import adakite.utils.AdakiteUtils;
import droplauncher.util.Constants;
import droplauncher.util.SimpleProcess;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.logging.Logger;
/**
* Class for getting and storing a list of processes using
* the Windows Tasklist program.
*/
public class Tasklist {
private static final Logger LOGGER = Logger.getLogger(Tasklist.class.getName());
private static final boolean CLASS_DEBUG = (Constants.DEBUG && true);
public static File TASKLIST_EXE = new File("C:\\Windows\\System32\\tasklist.exe");
public static String[] DEFAULT_TASKLIST_ARGS = {"/v"};
public static File TASKKILL_EXE = new File("C:\\Windows\\System32\\taskkill.exe");
public static String[] DEFAULT_TASKKILL_ARGS = {"/f", "/pid"}; /* /PID requires a second string */
private ArrayList<Task> tasks;
public Tasklist() {
this.tasks = new ArrayList<>();
}
public void kill(String pid) {
String[] args = new String[DEFAULT_TASKKILL_ARGS.length + 1];
System.arraycopy(DEFAULT_TASKKILL_ARGS, 0, args, 0, DEFAULT_TASKKILL_ARGS.length);
args[args.length - 1] = pid;
SimpleProcess process = new SimpleProcess();
process.run(TASKKILL_EXE, args);
}
/**
* Returns a list of Task objects.
*
* @param update whether to update the list before returning
* @return
* a list of Task objects
*/
public ArrayList<Task> getTasks(boolean update) {
if (update) {
update();
}
return this.tasks;
}
/**
* Returns a list of Task objects. Does NOT update the task list
* before returning.
*
* @see #getTasks(boolean)
* @return
* a list of Task objects
*/
public ArrayList<Task> getTasks() {
return getTasks(false);
}
public boolean update() {
this.tasks.clear();
SimpleProcess process = new SimpleProcess();
process.run(TASKLIST_EXE, DEFAULT_TASKLIST_ARGS);
/* Find beginning of process list. */
int index;
for (index = 0; index < process.getLog().size(); index++) {
String line = process.getLog().get(index);
if (line.startsWith("=")) {
break;
}
}
if (index >= process.getLog().size()) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, "error parsing Tasklist output");
}
return false;
}
/* Determine length of each column. */
ArrayList<Integer> colLengths = new ArrayList<>();
String colLine = process.getLog().get(index);
StringTokenizer st = new StringTokenizer(colLine);
while (st.hasMoreTokens()) {
String token = st.nextToken();
colLengths.add(token.length());
}
/* Go to first line with a task entry. */
index++;
/* Parse remaining lines. */
for (int i = index; i < process.getLog().size(); i++) {
String line = process.getLog().get(i);
if (AdakiteUtils.isNullOrEmpty(line)) {
continue;
}
/* Tokenize line using the column lengths. */
ArrayList<String> tokens = tokenizeTaskEntry(line, colLengths);
if (tokens.size() < TasklistTitle.values().length) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, "error parsing task entry line");
}
return false;
}
/* Set task information. */
Task task = new Task();
int tokenIndex = 0;
task.setImageName(tokens.get(tokenIndex++));
task.setPID(tokens.get(tokenIndex++));
task.setSessionName(tokens.get(tokenIndex++));
task.setSessionNumber(tokens.get(tokenIndex++));
task.setMemUsage(tokens.get(tokenIndex++));
task.setStatus(tokens.get(tokenIndex++));
task.setUsername(tokens.get(tokenIndex++));
task.setCpuTime(tokens.get(tokenIndex++));
task.setWindowTitle(tokens.get(tokenIndex++));
/* Add task to main task list. */
this.tasks.add(task);
}
return true;
}
private ArrayList<String> tokenizeTaskEntry(String str, ArrayList<Integer> colLengths) {
ArrayList<String> ret = new ArrayList<>();
int colIndex = 0;
for (int i = 0; i < colLengths.size(); i++) {
String tmp = str.substring(colIndex, colIndex + colLengths.get(i)).trim();
ret.add(tmp);
colIndex += colLengths.get(i) + 1;
}
return ret;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Tasklist)) {
return false;
} else if (obj == this) {
return true;
} else {
Tasklist tasklist = (Tasklist) obj;
for (Task task1 : tasklist.getTasks()) {
boolean isFound = false;
for (Task task2 : this.getTasks()) {
if (task1.getPID().equals(task2.getPID())) {
isFound = true;
break;
}
}
if (!isFound) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(this.tasks);
}
}
|
src/droplauncher/util/windows/Tasklist.java
|
package droplauncher.util.windows;
import adakite.utils.AdakiteUtils;
import droplauncher.util.Constants;
import droplauncher.util.SimpleProcess;
import java.io.File;
import java.util.ArrayList;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.logging.Logger;
/**
* Class for getting and storing a list of processes using
* the Windows Tasklist program.
*/
public class Tasklist {
private static final Logger LOGGER = Logger.getLogger(Tasklist.class.getName());
private static final boolean CLASS_DEBUG = (Constants.DEBUG && true);
public static File TASKLIST_EXE = new File("C:\\Windows\\System32\\tasklist.exe");
public static String[] DEFAULT_TASKLIST_ARGS = {"/v"};
public static File TASKKILL_EXE = new File("C:\\Windows\\System32\\taskkill.exe");
private ArrayList<Task> tasks;
public Tasklist() {
this.tasks = new ArrayList<>();
}
/**
* Returns a list of Task objects.
*
* @param update whether to update the list before returning
* @return
* a list of Task objects
*/
public ArrayList<Task> getTasks(boolean update) {
if (update) {
update();
}
return this.tasks;
}
/**
* Returns a list of Task objects. Does NOT update the task list
* before returning.
*
* @see #getTasks(boolean)
* @return
* a list of Task objects
*/
public ArrayList<Task> getTasks() {
return getTasks(false);
}
public boolean update() {
this.tasks.clear();
SimpleProcess process = new SimpleProcess();
process.run(TASKLIST_EXE, DEFAULT_TASKLIST_ARGS);
/* Find beginning of process list. */
int index;
for (index = 0; index < process.getLog().size(); index++) {
String line = process.getLog().get(index);
if (line.startsWith("=")) {
break;
}
}
if (index >= process.getLog().size()) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, "error parsing Tasklist output");
}
return false;
}
/* Determine length of each column. */
ArrayList<Integer> colLengths = new ArrayList<>();
String colLine = process.getLog().get(index);
StringTokenizer st = new StringTokenizer(colLine);
while (st.hasMoreTokens()) {
String token = st.nextToken();
colLengths.add(token.length());
}
/* Go to first line with a task entry. */
index++;
/* Parse remaining lines. */
for (int i = index; i < process.getLog().size(); i++) {
String line = process.getLog().get(i);
if (AdakiteUtils.isNullOrEmpty(line)) {
continue;
}
/* Tokenize line using the column lengths. */
ArrayList<String> tokens = tokenizeTaskEntry(line, colLengths);
if (tokens.size() < TasklistTitle.values().length) {
if (CLASS_DEBUG) {
LOGGER.log(Constants.DEFAULT_LOG_LEVEL, "error parsing task entry line");
}
return false;
}
/* Set task information. */
Task task = new Task();
int tokenIndex = 0;
task.setImageName(tokens.get(tokenIndex++));
task.setPID(tokens.get(tokenIndex++));
task.setSessionName(tokens.get(tokenIndex++));
task.setSessionNumber(tokens.get(tokenIndex++));
task.setMemUsage(tokens.get(tokenIndex++));
task.setStatus(tokens.get(tokenIndex++));
task.setUsername(tokens.get(tokenIndex++));
task.setCpuTime(tokens.get(tokenIndex++));
task.setWindowTitle(tokens.get(tokenIndex++));
/* Add task to main task list. */
this.tasks.add(task);
}
return true;
}
private ArrayList<String> tokenizeTaskEntry(String str, ArrayList<Integer> colLengths) {
ArrayList<String> ret = new ArrayList<>();
int colIndex = 0;
for (int i = 0; i < colLengths.size(); i++) {
String tmp = str.substring(colIndex, colIndex + colLengths.get(i)).trim();
ret.add(tmp);
colIndex += colLengths.get(i) + 1;
}
return ret;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Tasklist)) {
return false;
} else if (obj == this) {
return true;
} else {
Tasklist tasklist = (Tasklist) obj;
for (Task task1 : tasklist.getTasks()) {
boolean isFound = false;
for (Task task2 : this.getTasks()) {
if (task1.getPID().equals(task2.getPID())) {
isFound = true;
break;
}
}
if (!isFound) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(this.tasks);
}
}
|
Implement "public void kill(String pid)" in "Tasklist.java"
|
src/droplauncher/util/windows/Tasklist.java
|
Implement "public void kill(String pid)" in "Tasklist.java"
|
|
Java
|
lgpl-2.1
|
822ad196a83ed9ea858987c7beb512ea0fcc8e5e
| 0
|
windauer/exist,dizzzz/exist,adamretter/exist,eXist-db/exist,adamretter/exist,ambs/exist,lcahlander/exist,windauer/exist,ambs/exist,eXist-db/exist,wolfgangmm/exist,ambs/exist,ambs/exist,wolfgangmm/exist,lcahlander/exist,windauer/exist,dizzzz/exist,lcahlander/exist,dizzzz/exist,dizzzz/exist,eXist-db/exist,windauer/exist,lcahlander/exist,adamretter/exist,ambs/exist,ambs/exist,windauer/exist,lcahlander/exist,windauer/exist,wolfgangmm/exist,dizzzz/exist,dizzzz/exist,wolfgangmm/exist,wolfgangmm/exist,lcahlander/exist,adamretter/exist,eXist-db/exist,wolfgangmm/exist,adamretter/exist,adamretter/exist,eXist-db/exist,eXist-db/exist
|
/*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.client.security;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
/**
* Provides Auto Completion for JComboBox's.
* See {@link #enable(JComboBox)}.
*
* The original code for this class was Public Domain
* code by Thomas Bierhance, and was downloaded
* from http://www.orbital-computer.de/JComboBox/.
*/
public class AutoCompletion<E> extends PlainDocument {
private final JComboBox<E> comboBox;
private ComboBoxModel<E> model;
private JTextComponent editor;
// flag to indicate if setSelectedItem has been called
// subsequent calls to remove/insertString should be ignored
private boolean selecting = false;
private final boolean hidePopupOnFocusLoss;
private boolean hitBackspace = false;
private boolean hitBackspaceOnSelection;
private final KeyListener editorKeyListener;
private final FocusListener editorFocusListener;
@SuppressWarnings("unchecked")
public AutoCompletion(final JComboBox<E> comboBox) {
this.comboBox = comboBox;
this.model = comboBox.getModel();
comboBox.addActionListener(e -> {
if (!selecting) {
highlightCompletedText(0);
}
});
comboBox.addPropertyChangeListener(e -> {
if ("editor".equals(e.getPropertyName())) {
configureEditor((ComboBoxEditor) e.getNewValue());
}
if ("model".equals(e.getPropertyName())) {
this.model = (ComboBoxModel<E>) e.getNewValue();
}
});
this.editorKeyListener = new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
if (comboBox.isDisplayable()) {
comboBox.setPopupVisible(true);
}
hitBackspace = false;
switch (e.getKeyCode()) {
// determine if the pressed key is backspace (needed by the remove method)
case KeyEvent.VK_BACK_SPACE:
hitBackspace = true;
hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd();
break;
// ignore delete key
case KeyEvent.VK_DELETE:
e.consume();
comboBox.getToolkit().beep();
break;
}
}
};
// Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
this.hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
// Highlight whole text when gaining focus
this.editorFocusListener = new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
highlightCompletedText(0);
}
@Override
public void focusLost(final FocusEvent e) {
// Workaround for Bug 5100422 - Hide Popup on focus loss
if (hidePopupOnFocusLoss) {
comboBox.setPopupVisible(false);
}
}
};
configureEditor(comboBox.getEditor());
// Handle initially selected object
final E selected = (E) comboBox.getSelectedItem();
if (selected != null) {
setText(selected.toString());
}
highlightCompletedText(0);
}
public static <T> AutoCompletion<T> enable(final JComboBox<T> comboBox) {
// has to be editable
comboBox.setEditable(true);
// change the editor's document
return new AutoCompletion<>(comboBox);
}
void configureEditor(final ComboBoxEditor newEditor) {
if (editor != null) {
editor.removeKeyListener(editorKeyListener);
editor.removeFocusListener(editorFocusListener);
}
if (newEditor != null) {
editor = (JTextComponent) newEditor.getEditorComponent();
editor.addKeyListener(editorKeyListener);
editor.addFocusListener(editorFocusListener);
editor.setDocument(this);
}
}
@Override
public void remove(int offs, final int len) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
if (hitBackspace) {
// user hit backspace => move the selection backwards
// old item keeps being selected
if (offs > 0) {
if (hitBackspaceOnSelection) {
offs--;
}
} else {
// User hit backspace with the cursor positioned on the start => beep
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
highlightCompletedText(offs);
} else {
super.remove(offs, len);
}
}
@SuppressWarnings("unchecked")
@Override
public void insertString(int offs, final String str, final AttributeSet a) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
// insert the string into the document
super.insertString(offs, str, a);
// lookup and select a matching item
E item = lookupItem(getText(0, getLength()));
if (item != null) {
setSelectedItem(item);
} else {
// keep old item selected if there is no match
item = (E) comboBox.getSelectedItem();
// imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
offs = offs - str.length();
// provide feedback to the user that his input has been received but can not be accepted
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
setText(item != null ? item.toString() : null);
// select the completed part
highlightCompletedText(offs + str.length());
}
private void setText(final String text) {
try {
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, text, null);
} catch (final BadLocationException e) {
throw new RuntimeException(e.toString());
}
}
private void highlightCompletedText(final int start) {
editor.setCaretPosition(getLength());
editor.moveCaretPosition(start);
}
private void setSelectedItem(final E item) {
selecting = true;
model.setSelectedItem(item);
selecting = false;
}
@SuppressWarnings("unchecked")
private E lookupItem(final String pattern) {
final E selectedItem = (E) model.getSelectedItem();
// only search for a different item if the currently selected does not match
if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) {
return selectedItem;
} else {
// iterate over all items
for (int i = 0, n = model.getSize(); i < n; i++) {
final E currentItem = model.getElementAt(i);
// current item starts with the pattern?
if (currentItem != null && startsWithIgnoreCase(currentItem.toString(), pattern)) {
return currentItem;
}
}
}
// no item starts with the pattern => return null
return null;
}
// checks if str1 starts with str2 - ignores case
private boolean startsWithIgnoreCase(final String str1, final String str2) {
return str1.toUpperCase().startsWith(str2.toUpperCase());
}
}
|
exist-core/src/main/java/org/exist/client/security/AutoCompletion.java
|
/*
* Public Domain Code
* Taken from: http://www.orbital-computer.de/JComboBox/
* Original Author: Thomas Bierhance
*
* Accompanying statement from Thomas:
*
* This work is hereby released into the Public Domain.
* To view a copy of the public domain dedication, visit
* http://creativecommons.org/licenses/publicdomain/
*/
package org.exist.client.security;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class AutoCompletion<E> extends PlainDocument {
private final JComboBox<E> comboBox;
private ComboBoxModel<E> model;
private JTextComponent editor;
// flag to indicate if setSelectedItem has been called
// subsequent calls to remove/insertString should be ignored
private boolean selecting = false;
private final boolean hidePopupOnFocusLoss;
private boolean hitBackspace = false;
private boolean hitBackspaceOnSelection;
private final KeyListener editorKeyListener;
private final FocusListener editorFocusListener;
@SuppressWarnings("unchecked")
public AutoCompletion(final JComboBox<E> comboBox) {
this.comboBox = comboBox;
this.model = comboBox.getModel();
comboBox.addActionListener(e -> {
if (!selecting) {
highlightCompletedText(0);
}
});
comboBox.addPropertyChangeListener(e -> {
if ("editor".equals(e.getPropertyName())) {
configureEditor((ComboBoxEditor) e.getNewValue());
}
if ("model".equals(e.getPropertyName())) {
this.model = (ComboBoxModel<E>) e.getNewValue();
}
});
this.editorKeyListener = new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
if (comboBox.isDisplayable()) {
comboBox.setPopupVisible(true);
}
hitBackspace = false;
switch (e.getKeyCode()) {
// determine if the pressed key is backspace (needed by the remove method)
case KeyEvent.VK_BACK_SPACE:
hitBackspace = true;
hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd();
break;
// ignore delete key
case KeyEvent.VK_DELETE:
e.consume();
comboBox.getToolkit().beep();
break;
}
}
};
// Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
this.hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
// Highlight whole text when gaining focus
this.editorFocusListener = new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
highlightCompletedText(0);
}
@Override
public void focusLost(final FocusEvent e) {
// Workaround for Bug 5100422 - Hide Popup on focus loss
if (hidePopupOnFocusLoss) {
comboBox.setPopupVisible(false);
}
}
};
configureEditor(comboBox.getEditor());
// Handle initially selected object
final E selected = (E) comboBox.getSelectedItem();
if (selected != null) {
setText(selected.toString());
}
highlightCompletedText(0);
}
public static <T> AutoCompletion<T> enable(final JComboBox<T> comboBox) {
// has to be editable
comboBox.setEditable(true);
// change the editor's document
return new AutoCompletion<>(comboBox);
}
void configureEditor(final ComboBoxEditor newEditor) {
if (editor != null) {
editor.removeKeyListener(editorKeyListener);
editor.removeFocusListener(editorFocusListener);
}
if (newEditor != null) {
editor = (JTextComponent) newEditor.getEditorComponent();
editor.addKeyListener(editorKeyListener);
editor.addFocusListener(editorFocusListener);
editor.setDocument(this);
}
}
@Override
public void remove(int offs, final int len) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
if (hitBackspace) {
// user hit backspace => move the selection backwards
// old item keeps being selected
if (offs > 0) {
if (hitBackspaceOnSelection) {
offs--;
}
} else {
// User hit backspace with the cursor positioned on the start => beep
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
highlightCompletedText(offs);
} else {
super.remove(offs, len);
}
}
@SuppressWarnings("unchecked")
@Override
public void insertString(int offs, final String str, final AttributeSet a) throws BadLocationException {
// return immediately when selecting an item
if (selecting) {
return;
}
// insert the string into the document
super.insertString(offs, str, a);
// lookup and select a matching item
E item = lookupItem(getText(0, getLength()));
if (item != null) {
setSelectedItem(item);
} else {
// keep old item selected if there is no match
item = (E) comboBox.getSelectedItem();
// imitate no insert (later on offs will be incremented by str.length(): selection won't move forward)
offs = offs - str.length();
// provide feedback to the user that his input has been received but can not be accepted
comboBox.getToolkit().beep(); // when available use: UIManager.getLookAndFeel().provideErrorFeedback(comboBox);
}
setText(item != null ? item.toString() : null);
// select the completed part
highlightCompletedText(offs + str.length());
}
private void setText(final String text) {
try {
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, text, null);
} catch (final BadLocationException e) {
throw new RuntimeException(e.toString());
}
}
private void highlightCompletedText(final int start) {
editor.setCaretPosition(getLength());
editor.moveCaretPosition(start);
}
private void setSelectedItem(final E item) {
selecting = true;
model.setSelectedItem(item);
selecting = false;
}
@SuppressWarnings("unchecked")
private E lookupItem(final String pattern) {
final E selectedItem = (E) model.getSelectedItem();
// only search for a different item if the currently selected does not match
if (selectedItem != null && startsWithIgnoreCase(selectedItem.toString(), pattern)) {
return selectedItem;
} else {
// iterate over all items
for (int i = 0, n = model.getSize(); i < n; i++) {
final E currentItem = model.getElementAt(i);
// current item starts with the pattern?
if (currentItem != null && startsWithIgnoreCase(currentItem.toString(), pattern)) {
return currentItem;
}
}
}
// no item starts with the pattern => return null
return null;
}
// checks if str1 starts with str2 - ignores case
private boolean startsWithIgnoreCase(final String str1, final String str2) {
return str1.toUpperCase().startsWith(str2.toUpperCase());
}
}
|
[license] Public domain code can be freely relicensed
|
exist-core/src/main/java/org/exist/client/security/AutoCompletion.java
|
[license] Public domain code can be freely relicensed
|
|
Java
|
lgpl-2.1
|
be1510acc0fbe022d322807fb4cb15007bcf1da6
| 0
|
benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc
|
package dr.app.tools;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.evolution.io.Importer;
import dr.evolution.io.NewickImporter;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.util.Version;
import dr.math.distributions.MultivariateNormalDistribution;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author Marc A. Suchard
* @author Philippe Lemey
*/
public class TimeSlicer {
public static final String sep = "\t";
public static final String PRECISION_STRING = "precision";
public static final String RATE_STRING = "rate";
public TimeSlicer(String treeFileName, String outFileName, int burnin, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
List<Tree> trees = null;
try {
trees = importTrees(treeFileName, burnin);
} catch (IOException e) {
System.err.println("Error reading file: " + treeFileName);
System.exit(-1);
} catch (Importer.ImportException e) {
System.err.println("Error parsing trees in file: " + treeFileName);
System.exit(-1);
}
if (trees == null || trees.size() == 0) {
System.err.println("No trees read from file: " + treeFileName);
System.exit(-1);
}
run(trees, traits, slices, impute, trueNoise);
resultsStream = System.out;
if (outFileName != null) {
try {
resultsStream = new PrintStream(new File(outFileName));
} catch (IOException e) {
System.err.println("Error opening file: "+outFileName);
System.exit(-1);
}
}
outputHeader(traits);
if (slices == null)
outputSlice(0,Double.NaN);
else {
for(int i=0; i<slices.length; i++)
outputSlice(i,slices[i]);
}
}
private void outputHeader(String[] traits) {
StringBuffer sb = new StringBuffer("slice");
for(int i=0; i<traits.length; i++) {
// Load first value to check dimensionality
Trait trait = values.get(0).get(i).get(0);
if (trait.isMultivariate()) {
int dim = trait.getDim();
for(int j=1; j<=dim; j++)
sb.append(sep).append(traits[i]).append(j);
} else
sb.append(sep).append(traits[i]);
}
sb.append("\n");
resultsStream.print(sb);
}
private List<Tree> importTrees(String treeFileName, int burnin) throws IOException, Importer.ImportException {
int totalTrees = 10000;
progressStream.println("Reading trees (bar assumes 10,000 trees)...");
progressStream.println("0 25 50 75 100");
progressStream.println("|--------------|--------------|--------------|--------------|");
int stepSize = totalTrees / 60;
if (stepSize < 1) stepSize = 1;
List<Tree> treeList = new ArrayList<Tree>();
BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
String line1 = reader1.readLine();
TreeImporter importer1;
if (line1.toUpperCase().startsWith("#NEXUS")) {
importer1 = new NexusImporter(new FileReader(treeFileName));
} else {
importer1 = new NewickImporter(new FileReader(treeFileName));
}
totalTrees = 0;
while (importer1.hasTree()) {
Tree treeTime = importer1.importNextTree();
if (totalTrees > burnin)
treeList.add(treeTime);
if (totalTrees > 0 && totalTrees % stepSize == 0) {
progressStream.print("*");
progressStream.flush();
}
totalTrees++;
}
return treeList;
}
class Trait {
Trait(Object obj) {
this.obj = obj;
if (obj instanceof Object[]) {
isMultivariate = true;
array = (Object[])obj;
}
}
public boolean isMultivariate() { return isMultivariate; }
public boolean isNumber() {
if (!isMultivariate)
return (obj instanceof Double);
return (array[0] instanceof Double);
}
public int getDim() {
if (isMultivariate) {
return array.length;
}
return 1;
}
public double[] getValue() {
int dim = getDim();
double[] result = new double[dim];
for(int i=0; i<dim; i++)
result[i] = (Double)array[i];
return result;
}
private Object obj;
private Object[] array;
private boolean isMultivariate = false;
public String toString() {
if (!isMultivariate)
return obj.toString();
StringBuffer sb = new StringBuffer(array[0].toString());
for(int i=1; i<array.length; i++)
sb.append(sep).append(array[i]);
return sb.toString();
}
}
private List<List<List<Trait>>> values;
private void outputSlice(int slice, double sliceValue) {
List<List<Trait>> thisSlice = values.get(slice);
int traitCount = thisSlice.size();
int valueCount = thisSlice.get(0).size();
StringBuffer sb = new StringBuffer();
for(int v=0; v<valueCount; v++) {
if (Double.isNaN(sliceValue))
sb.append("All");
else
sb.append(sliceValue);
for(int t=0; t<traitCount; t++) {
sb.append(sep);
sb.append(thisSlice.get(t).get(v));
}
sb.append("\n");
}
resultsStream.print(sb);
}
private void run(List<Tree> trees, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
int traitCount = traits.length;
int sliceCount = 1;
boolean doSlices = false;
if (slices != null) {
sliceCount = slices.length;
doSlices = true;
}
values = new ArrayList<List<List<Trait>>>(sliceCount);
for (int i = 0; i < sliceCount; i++) {
List<List<Trait>> thisSlice = new ArrayList<List<Trait>>(traitCount);
values.add(thisSlice);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = new ArrayList<Trait>();
thisSlice.add(thisTraitSlice);
}
}
for (Tree treeTime : trees) {
double[][] precision = null;
if (impute) {
Object o = treeTime.getAttribute("precision");
if (o != null) {
Object[] array = (Object[])o;
int dim = (int) Math.sqrt(1+8*array.length) / 2;
precision = new double[dim][dim];
int c = 0;
for(int i=0; i<dim; i++) {
for(int j=i; j<dim; j++) {
precision[j][i] = precision[i][j] = (Double)array[c++];
}
}
}
}
for (int x = 0; x < treeTime.getNodeCount(); x++) {
NodeRef node = treeTime.getNode(x);
if (!(treeTime.isRoot(node))) {
double nodeHeight = treeTime.getNodeHeight(node);
double parentHeight = treeTime.getNodeHeight(treeTime.getParent(node));
for (int i = 0; i < sliceCount; i++) {
if (!doSlices ||
(slices[i] >= nodeHeight && slices[i] < parentHeight)
) {
List<List<Trait>> thisSlice = values.get(i);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = thisSlice.get(j);
Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
if (tmpTrait == null) {
System.err.println("Trait '"+traits[j]+"' not found on branch.");
System.exit(-1);
}
Trait trait = new Trait(tmpTrait);
if (impute) {
Double rateAttribute = (Double) treeTime.getNodeAttribute(node,RATE_STRING);
double rate = 1.0;
if (rateAttribute != null) {
rate = rateAttribute;
if (outputRateWarning) {
progressStream.println("Warning: using a rate attribute during imputation!");
outputRateWarning = false;
}
}
trait = imputeValue(trait,new Trait(treeTime.getNodeAttribute(treeTime.getParent(node),traits[j])),
slices[i],nodeHeight, parentHeight,precision, rate, trueNoise);
}
thisTraitSlice.add(trait);
}
}
}
}
}
}
}
private boolean outputRateWarning = true;
private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) {
if (!nodeTrait.isNumber()) {
System.err.println("Can only impute numbers!");
System.exit(-1);
}
int dim = precision.length;
double[] nodeValue = nodeTrait.getValue();
double[] parentValue = parentTrait.getValue();
final double timeTotal = parentHeight - nodeHeight;
final double timeChild = (time - nodeHeight);
final double timeParent = (parentHeight - time);
final double weightTotal = 1.0 / timeChild + 1.0 / timeParent;
if (timeChild == 0)
return nodeTrait;
if (timeParent == 0)
return parentTrait;
// Find mean value, weighted average
double[] mean = new double[dim];
double[][] scaledPrecision = new double[dim][dim];
for(int i=0; i<dim; i++) {
mean[i] = (nodeValue[i] / timeChild + parentValue[i] / timeParent) / weightTotal;
if (trueNoise) {
for(int j=i; j<dim; j++)
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] / timeTotal / rate;
}
}
if (trueNoise)
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, precision);
Object[] result = new Object[dim];
for(int i=0; i<dim; i++)
result[i] = mean[i];
return new Trait(result);
}
// Messages to stderr, output to stdout
private static PrintStream progressStream = System.err;
private PrintStream resultsStream;
private final static Version version = new BeastVersion();
private static final String commandName = "timeslicer";
public static void printUsage(Arguments arguments) {
arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: " + commandName + " test.trees out.txt");
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printTitle() {
progressStream.println();
centreLine("TimeSlicer " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC Output analysis", 60);
centreLine("by", 60);
centreLine("Marc A. Suchard, Philippe Lemey,", 60);
centreLine("Alexei J. Drummond and Andrew Rambaut", 60);
progressStream.println();
centreLine("Department of Biomathematics", 60);
centreLine("University of California, Los Angeles", 60);
centreLine("msuchard@ucla.edu", 60);
progressStream.println();
centreLine("Rega Institute for Medical Research", 60);
centreLine("Katholieke Unversiteit Leuven", 60);
centreLine("philippe.lemey@gmail.com", 60);
progressStream.println();
centreLine("Department of Computer Science", 60);
centreLine("University of Auckland", 60);
centreLine("alexei@cs.auckland.ac.nz", 60);
progressStream.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
progressStream.println();
progressStream.println();
}
private static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
List<Double> returnList = new ArrayList<Double>();
StringTokenizer st = new StringTokenizer(inString,",");
while(st.hasMoreTokens()) {
try {
returnList.add(Double.parseDouble(st.nextToken()));
} catch (NumberFormatException e) {
throw new Arguments.ArgumentException();
}
}
if (returnList.size()>0) {
double[] doubleArray = new double[returnList.size()];
for(int i=0; i<doubleArray.length; i++)
doubleArray[i] = returnList.get(i);
return doubleArray;
}
return null;
}
private static String[] parseVariableLengthStringArray(String inString) {
List<String> returnList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(inString,",");
while(st.hasMoreTokens()) {
returnList.add(st.nextToken());
}
if (returnList.size()>0) {
String[] stringArray = new String[returnList.size()];
stringArray = returnList.toArray(stringArray);
return stringArray;
}
return null;
}
public static void main(String[] args) throws IOException {
String inputFileName = null;
String outputFileName = null;
// if (args.length == 0) {
// // TODO Make flash GUI
// }
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in' [default = 0]"),
new Arguments.StringOption("trait", "trait_name", "specifies an attribute-list to use to create a density map [default = location.angle]"),
new Arguments.StringOption("slice","time","specifies an slice time-list [default=none]"),
new Arguments.Option("help", "option to print this message"),
new Arguments.StringOption("noise", new String[]{"false","true"}, false,
"add true noise [default = true])"),
new Arguments.StringOption("impute", new String[]{"false", "true"}, false,
"impute trait at time-slice [default = false])"),
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
int burnin = -1;
if (arguments.hasOption("burnin")) {
burnin = arguments.getIntegerOption("burnin");
}
String[] traitNames = null;
double[] sliceTimes = null;
try {
String traitString = arguments.getStringOption("trait");
if (traitString != null) {
traitNames = parseVariableLengthStringArray(traitString);
}
if (traitNames == null) {
traitNames = new String[1];
traitNames[0] = "location.rate";
}
String sliceString = arguments.getStringOption("slice");
if (sliceString != null) {
sliceTimes = parseVariableLengthDoubleArray(sliceString);
}
} catch (Arguments.ArgumentException e) {
progressStream.println(e);
printUsage(arguments);
System.exit(-1);
}
String imputeString = arguments.getStringOption("impute");
boolean impute = false;
if (imputeString != null && imputeString.compareToIgnoreCase("true") == 0)
impute = true;
String noiseString = arguments.getStringOption("noise");
boolean trueNoise = true;
if (noiseString != null && noiseString.compareToIgnoreCase("false") == 0)
trueNoise = false;
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 0:
printUsage(arguments);
System.exit(1);
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
System.err.println("Unknown option: " + args2[2]);
System.err.println();
printUsage(arguments);
System.exit(1);
}
}
new TimeSlicer(inputFileName, outputFileName, burnin, traitNames, sliceTimes, impute, trueNoise);
System.exit(0);
}
}
|
src/dr/app/tools/TimeSlicer.java
|
package dr.app.tools;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.evolution.io.Importer;
import dr.evolution.io.NewickImporter;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.TreeImporter;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.util.Version;
import dr.math.distributions.MultivariateNormalDistribution;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author Marc A. Suchard
* @author Philippe Lemey
*/
public class TimeSlicer {
public static final String sep = "\t";
public static final String PRECISION_STRING = "precision";
public TimeSlicer(String treeFileName, String outFileName, int burnin, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
List<Tree> trees = null;
try {
trees = importTrees(treeFileName, burnin);
} catch (IOException e) {
System.err.println("Error reading file: " + treeFileName);
System.exit(-1);
} catch (Importer.ImportException e) {
System.err.println("Error parsing trees in file: " + treeFileName);
System.exit(-1);
}
if (trees == null || trees.size() == 0) {
System.err.println("No trees read from file: " + treeFileName);
System.exit(-1);
}
run(trees, traits, slices, impute, trueNoise);
resultsStream = System.out;
if (outFileName != null) {
try {
resultsStream = new PrintStream(new File(outFileName));
} catch (IOException e) {
System.err.println("Error opening file: "+outFileName);
System.exit(-1);
}
}
outputHeader(traits);
if (slices == null)
outputSlice(0,Double.NaN);
else {
for(int i=0; i<slices.length; i++)
outputSlice(i,slices[i]);
}
}
private void outputHeader(String[] traits) {
StringBuffer sb = new StringBuffer("slice");
for(int i=0; i<traits.length; i++) {
// Load first value to check dimensionality
Trait trait = values.get(0).get(i).get(0);
if (trait.isMultivariate()) {
int dim = trait.getDim();
for(int j=1; j<=dim; j++)
sb.append(sep).append(traits[i]).append(j);
} else
sb.append(sep).append(traits[i]);
}
sb.append("\n");
resultsStream.print(sb);
}
private List<Tree> importTrees(String treeFileName, int burnin) throws IOException, Importer.ImportException {
int totalTrees = 10000;
// int totalTreesUsed = 0;
progressStream.println("Reading trees (bar assumes 10,000 trees)...");
progressStream.println("0 25 50 75 100");
progressStream.println("|--------------|--------------|--------------|--------------|");
int stepSize = totalTrees / 60;
if (stepSize < 1) stepSize = 1;
List<Tree> treeList = new ArrayList<Tree>();
BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
String line1 = reader1.readLine();
TreeImporter importer1;
if (line1.toUpperCase().startsWith("#NEXUS")) {
importer1 = new NexusImporter(new FileReader(treeFileName));
} else {
importer1 = new NewickImporter(new FileReader(treeFileName));
}
totalTrees = 0;
while (importer1.hasTree()) {
Tree treeTime = importer1.importNextTree();
if (totalTrees > burnin)
treeList.add(treeTime);
if (totalTrees > 0 && totalTrees % stepSize == 0) {
progressStream.print("*");
progressStream.flush();
}
totalTrees++;
}
return treeList;
}
class Trait {
Trait(Object obj) {
this.obj = obj;
if (obj instanceof Object[]) {
isMultivariate = true;
array = (Object[])obj;
}
}
public boolean isMultivariate() { return isMultivariate; }
public boolean isNumber() {
if (!isMultivariate)
return (obj instanceof Double);
return (array[0] instanceof Double);
}
public int getDim() {
if (isMultivariate) {
return array.length;
}
return 1;
}
public double[] getValue() {
int dim = getDim();
double[] result = new double[dim];
for(int i=0; i<dim; i++)
result[i] = (Double)array[i];
return result;
}
private Object obj;
private Object[] array;
private boolean isMultivariate = false;
public String toString() {
if (!isMultivariate)
return obj.toString();
StringBuffer sb = new StringBuffer(array[0].toString());
for(int i=1; i<array.length; i++)
sb.append(sep).append(array[i]);
return sb.toString();
}
}
private List<List<List<Trait>>> values;
private void outputSlice(int slice, double sliceValue) {
List<List<Trait>> thisSlice = values.get(slice);
int traitCount = thisSlice.size();
int valueCount = thisSlice.get(0).size();
StringBuffer sb = new StringBuffer();
for(int v=0; v<valueCount; v++) {
if (Double.isNaN(sliceValue))
sb.append("All");
else
sb.append(sliceValue);
for(int t=0; t<traitCount; t++) {
sb.append(sep);
sb.append(thisSlice.get(t).get(v));
}
sb.append("\n");
}
resultsStream.print(sb);
}
private void run(List<Tree> trees, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
int traitCount = traits.length;
int sliceCount = 1;
boolean doSlices = false;
if (slices != null) {
sliceCount = slices.length;
doSlices = true;
}
values = new ArrayList<List<List<Trait>>>(sliceCount);
for (int i = 0; i < sliceCount; i++) {
List<List<Trait>> thisSlice = new ArrayList<List<Trait>>(traitCount);
values.add(thisSlice);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = new ArrayList<Trait>();
thisSlice.add(thisTraitSlice);
}
}
for (Tree treeTime : trees) {
double[][] precision = null;
if (impute) {
Object o = treeTime.getAttribute("precision");
if (o != null) {
Object[] array = (Object[])o;
int dim = (int) Math.sqrt(1+8*array.length) / 2;
precision = new double[dim][dim];
int c = 0;
for(int i=0; i<dim; i++) {
for(int j=i; j<dim; j++) {
precision[j][i] = precision[i][j] = (Double)array[c++];
}
}
}
}
for (int x = 0; x < treeTime.getNodeCount(); x++) {
NodeRef node = treeTime.getNode(x);
if (!(treeTime.isRoot(node))) {
double nodeHeight = treeTime.getNodeHeight(node);
double parentHeight = treeTime.getNodeHeight(treeTime.getParent(node));
for (int i = 0; i < sliceCount; i++) {
if (!doSlices ||
(slices[i] >= nodeHeight && slices[i] < parentHeight)
) {
List<List<Trait>> thisSlice = values.get(i);
for (int j = 0; j < traitCount; j++) {
List<Trait> thisTraitSlice = thisSlice.get(j);
Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
if (tmpTrait == null) {
System.err.println("Trait '"+traits[j]+"' not found on branch.");
System.exit(-1);
}
Trait trait = new Trait(tmpTrait);
if (impute) {
trait = imputeValue(trait,new Trait(treeTime.getNodeAttribute(treeTime.getParent(node),traits[j])),
slices[i],nodeHeight, parentHeight,precision, 1.0, trueNoise); // TODO Fix for inhomogeneous model
}
thisTraitSlice.add(trait);
}
}
}
}
}
}
}
private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) {
if (!nodeTrait.isNumber()) {
System.err.println("Can only impute numbers!");
System.exit(-1);
}
int dim = precision.length;
double[] nodeValue = nodeTrait.getValue();
double[] parentValue = parentTrait.getValue();
final double timeTotal = parentHeight - nodeHeight;
final double timeChild = (time - nodeHeight);
final double timeParent = (parentHeight - time);
final double weightTotal = 1.0 / timeChild + 1.0 / timeParent;
if (timeChild == 0)
return nodeTrait;
if (timeParent == 0)
return parentTrait;
// Find mean value, weighted average
double[] mean = new double[dim];
double[][] scaledPrecision = new double[dim][dim];
for(int i=0; i<dim; i++) {
mean[i] = (nodeValue[i] / timeChild + parentValue[i] / timeParent) / weightTotal;
if (trueNoise) {
for(int j=i; j<dim; j++)
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] / timeTotal / rate;
}
}
if (trueNoise)
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, precision);
Object[] result = new Object[dim];
for(int i=0; i<dim; i++)
result[i] = mean[i];
return new Trait(result);
}
// Messages to stderr, output to stdout
private static PrintStream progressStream = System.err;
private PrintStream resultsStream;
private final static Version version = new BeastVersion();
private static final String commandName = "treeslicer";
public static void printUsage(Arguments arguments) {
arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]");
progressStream.println();
progressStream.println(" Example: " + commandName + " test.trees out.txt");
progressStream.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
progressStream.print(" ");
}
progressStream.println(line);
}
public static void printTitle() {
progressStream.println();
centreLine("TimeSlicer " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC Output analysis", 60);
centreLine("by", 60);
centreLine("Marc A. Suchard, Philippe Lemey,", 60);
centreLine("Alexei J. Drummond and Andrew Rambaut", 60);
progressStream.println();
centreLine("Department of Biomathematics", 60);
centreLine("University of California, Los Angeles", 60);
centreLine("msuchard@ucla.edu", 60);
progressStream.println();
centreLine("DEPARTMENT", 60);
centreLine("UNIVERSITY", 60);
centreLine("EMAIL", 60);
progressStream.println();
centreLine("Department of Computer Science", 60);
centreLine("University of Auckland", 60);
centreLine("alexei@cs.auckland.ac.nz", 60);
progressStream.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
progressStream.println();
progressStream.println();
}
private static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
List<Double> returnList = new ArrayList<Double>();
StringTokenizer st = new StringTokenizer(inString,",");
while(st.hasMoreTokens()) {
try {
returnList.add(Double.parseDouble(st.nextToken()));
} catch (NumberFormatException e) {
throw new Arguments.ArgumentException();
}
}
if (returnList.size()>0) {
double[] doubleArray = new double[returnList.size()];
for(int i=0; i<doubleArray.length; i++)
doubleArray[i] = returnList.get(i);
return doubleArray;
}
return null;
}
private static String[] parseVariableLengthStringArray(String inString) {
List<String> returnList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(inString,",");
while(st.hasMoreTokens()) {
returnList.add(st.nextToken());
}
if (returnList.size()>0) {
String[] stringArray = new String[returnList.size()];
stringArray = returnList.toArray(stringArray);
return stringArray;
}
return null;
}
public static void main(String[] args) throws IOException {
String inputFileName = null;
String outputFileName = null;
// if (args.length == 0) {
// // TODO Make flash GUI
// }
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in' [default = 0]"),
new Arguments.StringOption("trait", "trait_name", "specifies an attribute-list to use to create a density map [default = location.angle]"),
new Arguments.StringOption("slice","time","specifies an slice time-list [default=none]"),
new Arguments.Option("help", "option to print this message"),
new Arguments.StringOption("noise", new String[]{"false","true"}, false,
"add true noise [default = true])"),
new Arguments.StringOption("impute", new String[]{"false", "true"}, false,
"impute trait at time-slice [default = false])"),
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
progressStream.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
int burnin = -1;
if (arguments.hasOption("burnin")) {
burnin = arguments.getIntegerOption("burnin");
}
String[] traitNames = null;
double[] sliceTimes = null;
try {
String traitString = arguments.getStringOption("trait");
if (traitString != null) {
traitNames = parseVariableLengthStringArray(traitString);
}
if (traitNames == null) {
traitNames = new String[1];
traitNames[0] = "location.rate";
}
String sliceString = arguments.getStringOption("slice");
if (sliceString != null) {
sliceTimes = parseVariableLengthDoubleArray(sliceString);
}
} catch (Arguments.ArgumentException e) {
progressStream.println(e);
printUsage(arguments);
System.exit(-1);
}
String imputeString = arguments.getStringOption("impute");
boolean impute = false;
if (imputeString != null && imputeString.compareToIgnoreCase("true") == 0)
impute = true;
String noiseString = arguments.getStringOption("noise");
boolean trueNoise = true;
if (noiseString != null && noiseString.compareToIgnoreCase("false") == 0)
trueNoise = false;
final String[] args2 = arguments.getLeftoverArguments();
switch (args2.length) {
case 0:
printUsage(arguments);
System.exit(1);
case 2:
outputFileName = args2[1];
// fall to
case 1:
inputFileName = args2[0];
break;
default: {
System.err.println("Unknown option: " + args2[2]);
System.err.println();
printUsage(arguments);
System.exit(1);
}
}
new TimeSlicer(inputFileName, outputFileName, burnin, traitNames, sliceTimes, impute, trueNoise);
System.exit(0);
}
}
|
TimeSlicer now works for branch-specific rate variation models.
|
src/dr/app/tools/TimeSlicer.java
|
TimeSlicer now works for branch-specific rate variation models.
|
|
Java
|
lgpl-2.1
|
c137cdba2f7fb3dfbecefd04ca5c976e52ae67d2
| 0
|
juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle,cwarden/kettle,cwarden/kettle,juanmjacobs/kettle
|
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.pentaho.di.core.gui;
public final class Rectangle extends org.eclipse.swt.graphics.Rectangle
{
public Rectangle(int x, int y, int width, int height)
{
super(x, y, width, height);
}
/**
* Returns <code>true</code> if the given point is inside the area specified by the receiver, and
* <code>false</code> otherwise.
*
* @param pt the point to test for containment
* @return <code>true</code> if the rectangle contains the point and <code>false</code> otherwise
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*/
public boolean contains(Point pt)
{
return contains(pt.x, pt.y);
}
}
|
src/org/pentaho/di/core/gui/Rectangle.java
|
package org.pentaho.di.core.gui;
public final class Rectangle
{
/**
* the x coordinate of the rectangle
*/
public int x;
/**
* the y coordinate of the rectangle
*/
public int y;
/**
* the width of the rectangle
*/
public int width;
/**
* the height of the rectangle
*/
public int height;
/**
* Construct a new instance of this class given the x, y, width and height values.
*
* @param x the x coordinate of the origin of the rectangle
* @param y the y coordinate of the origin of the rectangle
* @param width the width of the rectangle
* @param height the height of the rectangle
*/
public Rectangle(int x, int y, int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* Returns <code>true</code> if the point specified by the arguments is inside the area specified by the receiver,
* and <code>false</code> otherwise.
*
* @param x the x coordinate of the point to test for containment
* @param y the y coordinate of the point to test for containment
* @return <code>true</code> if the rectangle contains the point and <code>false</code> otherwise
*/
public boolean contains(int x, int y)
{
return (x >= this.x) && (y >= this.y) && ((x - this.x) < width) && ((y - this.y) < height);
}
/**
* Returns <code>true</code> if the given point is inside the area specified by the receiver, and
* <code>false</code> otherwise.
*
* @param pt the point to test for containment
* @return <code>true</code> if the rectangle contains the point and <code>false</code> otherwise
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*/
public boolean contains(Point pt)
{
return contains(pt.x, pt.y);
}
/**
* Compares the argument to the receiver, and returns true if they represent the <em>same</em> object using a
* class specific comparison.
*
* @param object the object to compare with this object
* @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise
*
* @see #hashCode()
*/
public boolean equals(Object object)
{
if (object == this) return true;
if (!(object instanceof Rectangle)) return false;
Rectangle r = (Rectangle) object;
return (r.x == this.x) && (r.y == this.y) && (r.width == this.width) && (r.height == this.height);
}
/**
* Returns an integer hash code for the receiver. Any two objects which return <code>true</code> when passed to
* <code>equals</code> must return the same value for this method.
*
* @return the receiver's hash
*
* @see #equals(Object)
*/
public int hashCode()
{
return x ^ y ^ width ^ height;
}
/**
* Destructively replaces the x, y, width and height values in the receiver with ones which represent the
* intersection of the rectangles specified by the receiver and the given rectangle.
*
* @param rect the rectangle to intersect with the receiver
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*
* since 3.0
*/
public void intersect(Rectangle rect)
{
if (this == rect) return;
int left = x > rect.x ? x : rect.x;
int top = y > rect.y ? y : rect.y;
int lhs = x + width;
int rhs = rect.x + rect.width;
int right = lhs < rhs ? lhs : rhs;
lhs = y + height;
rhs = rect.y + rect.height;
int bottom = lhs < rhs ? lhs : rhs;
x = right < left ? 0 : left;
y = bottom < top ? 0 : top;
width = right < left ? 0 : right - left;
height = bottom < top ? 0 : bottom - top;
}
/**
* Returns a new rectangle which represents the intersection of the receiver and the given rectangle.
* <p>
* The intersection of two rectangles is the rectangle that covers the area which is contained within both
* rectangles.
* </p>
*
* @param rect the rectangle to intersect with the receiver
* @return the intersection of the receiver and the argument
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*/
public Rectangle intersection(Rectangle rect)
{
if (this == rect) return new Rectangle(x, y, width, height);
int left = x > rect.x ? x : rect.x;
int top = y > rect.y ? y : rect.y;
int lhs = x + width;
int rhs = rect.x + rect.width;
int right = lhs < rhs ? lhs : rhs;
lhs = y + height;
rhs = rect.y + rect.height;
int bottom = lhs < rhs ? lhs : rhs;
return new Rectangle(right < left ? 0 : left, bottom < top ? 0 : top, right < left ? 0 : right - left, bottom < top ? 0 : bottom - top);
}
/**
* Returns <code>true</code> if the rectangle described by the arguments intersects with the receiver and
* <code>false</code> otherwise.
* <p>
* Two rectangles intersect if the area of the rectangle representing their intersection is not empty.
* </p>
*
* @param x the x coordinate of the origin of the rectangle
* @param y the y coordinate of the origin of the rectangle
* @param width the width of the rectangle
* @param height the height of the rectangle
* @return <code>true</code> if the rectangle intersects with the receiver, and <code>false</code> otherwise
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*
* @see #intersection(Rectangle)
* @see #isEmpty()
*
* @since 3.0
*/
public boolean intersects(int x, int y, int width, int height)
{
return (x < this.x + this.width) && (y < this.y + this.height) && (x + width > this.x) && (y + height > this.y);
}
/**
* Returns <code>true</code> if the given rectangle intersects with the receiver and <code>false</code>
* otherwise.
* <p>
* Two rectangles intersect if the area of the rectangle representing their intersection is not empty.
* </p>
*
* @param rect the rectangle to test for intersection
* @return <code>true</code> if the rectangle intersects with the receiver, and <code>false</code> otherwise
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*
* @see #intersection(Rectangle)
* @see #isEmpty()
*/
public boolean intersects(Rectangle rect)
{
return rect == this || intersects(rect.x, rect.y, rect.width, rect.height);
}
/**
* Returns <code>true</code> if the receiver does not cover any area in the (x, y) coordinate plane, and
* <code>false</code> if the receiver does cover some area in the plane.
* <p>
* A rectangle is considered to <em>cover area</em> in the (x, y) coordinate plane if both its width and height
* are non-zero.
* </p>
*
* @return <code>true</code> if the receiver is empty, and <code>false</code> otherwise
*/
public boolean isEmpty()
{
return (width <= 0) || (height <= 0);
}
/**
* Returns a string containing a concise, human-readable description of the receiver.
*
* @return a string representation of the rectangle
*/
public String toString()
{
return "Rectangle {" + x + ", " + y + ", " + width + ", " + height + "}"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
/**
* Returns a new rectangle which represents the union of the receiver and the given rectangle.
* <p>
* The union of two rectangles is the smallest single rectangle that completely covers both of the areas covered by
* the two given rectangles.
* </p>
*
* @param rect the rectangle to perform union with
* @return the union of the receiver and the argument
*
* @exception IllegalArgumentException
* <ul>
* <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
* </ul>
*
*/
public Rectangle union(Rectangle rect)
{
int left = x < rect.x ? x : rect.x;
int top = y < rect.y ? y : rect.y;
int lhs = x + width;
int rhs = rect.x + rect.width;
int right = lhs > rhs ? lhs : rhs;
lhs = y + height;
rhs = rect.y + rect.height;
int bottom = lhs > rhs ? lhs : rhs;
return new Rectangle(left, top, right - left, bottom - top);
}
}
|
Cleanup of dependencies on SWT code
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@3792 5fb7f6ec-07c1-534a-b4ca-9155e429e800
|
src/org/pentaho/di/core/gui/Rectangle.java
|
Cleanup of dependencies on SWT code
|
|
Java
|
unlicense
|
7843277ee42f0c2c877263ec6b2924398e7003d1
| 0
|
janlep47/nurseHelper
|
package com.android.janice.nursehelper;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.janice.nursehelper.data.ResidentContract;
import com.squareup.picasso.Picasso;
//import com.android.janice.nursehelper.sync.NurseHelperSyncAdapter;
/**
* Created by janicerichards on 2/2/17.
*/
public class AssessmentFragment extends Fragment {
public static final String LOG_TAG = AssessmentFragment.class.getSimpleName();
private NumberPicker mSystolicBP_picker;
private NumberPicker mDiastolicBP_picker;
private NumberPicker mTemp_int_picker;
private NumberPicker mTemp_decimal_picker;
private NumberPicker mPulse_picker;
private NumberPicker mRR_picker;
private Spinner mEdema_spinner;
private Spinner mEdema_location_spinner;
private NumberPicker mPain_picker;
private TextView mSystolicBP_textView;
private TextView mDiastolicBP_textView;
private TextView mTemperature_textView;
private TextView mPulse_textView;
private TextView mRR_textView;
private TextView mEdema_textView;
private TextView mEdemaLocation_textView;
private TextView mPain_textView;
private EditText mFindings_editText;
private Button mDone_button;
String mRoomNumber;
String mPortraitFilePath;
public static final int DEFAULT_ACTION_BAR_HEIGHT = 60;
private static final String[] ASSESSMENT_COLUMNS = {
ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER,
ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE,
ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE,
ResidentContract.AssessmentEntry.COLUMN_PULSE,
ResidentContract.AssessmentEntry.COLUMN_RR,
ResidentContract.AssessmentEntry.COLUMN_EDEMA,
ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS,
ResidentContract.AssessmentEntry.COLUMN_TIME
};
public AssessmentFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mRoomNumber = arguments.getString(MainActivity.ITEM_ROOM_NUMBER);
mPortraitFilePath = arguments.getString(MainActivity.ITEM_PORTRAIT_FILEPATH);
Log.e(LOG_TAG, "mPortraitFilePath is "+mPortraitFilePath);
}
//View rootView = inflater.inflate(R.layout.fragment_assessment, container, false);
View rootView = inflater.inflate(R.layout.item_assessment, container, false);
mSystolicBP_textView = (TextView) rootView.findViewById(R.id.bp_systolic_textview);
mDiastolicBP_textView = (TextView) rootView.findViewById(R.id.bp_diastolic_textview);
mTemperature_textView = (TextView) rootView.findViewById(R.id.temperature_textview);
mPulse_textView = (TextView) rootView.findViewById(R.id.pulse_textview);
mRR_textView = (TextView) rootView.findViewById(R.id.rr_textview);
mEdema_textView = (TextView) rootView.findViewById(R.id.edema_textview);
mPain_textView = (TextView) rootView.findViewById(R.id.pain_textview);
mFindings_editText = (EditText) rootView.findViewById(R.id.findings_edittext);
mSystolicBP_picker = (NumberPicker) rootView.findViewById(R.id.bp_systolic_numberpicker);
mDiastolicBP_picker = (NumberPicker) rootView.findViewById(R.id.bp_diastolic_numberpicker);
mTemp_int_picker = (NumberPicker) rootView.findViewById(R.id.temp_int_numberpicker);
mTemp_decimal_picker = (NumberPicker) rootView.findViewById(R.id.temp_decimal_numberpicker);
mPulse_picker = (NumberPicker) rootView.findViewById(R.id.pulse_numberpicker);
mRR_picker = (NumberPicker) rootView.findViewById(R.id.rr_numberpicker);
mEdema_spinner = (Spinner) rootView.findViewById(R.id.edema_spinner);
mEdema_location_spinner = (Spinner) rootView.findViewById(R.id.edema_locn_spinner);
mPain_picker = (NumberPicker) rootView.findViewById(R.id.pain_picker);
mDone_button = (Button) rootView.findViewById(R.id.done_button);
mSystolicBP_picker.setMinValue(60);
mSystolicBP_picker.setMaxValue(250);
mSystolicBP_picker.setValue(120);
mSystolicBP_textView.setText(String.valueOf(mSystolicBP_picker.getValue()));
mSystolicBP_picker.setWrapSelectorWheel(false);
mDiastolicBP_picker.setMinValue(40);
mDiastolicBP_picker.setMaxValue(160);
mDiastolicBP_textView.setText(String.valueOf(mDiastolicBP_picker.getValue()));
mDiastolicBP_picker.setValue(80);
mDiastolicBP_picker.setWrapSelectorWheel(false);
mSystolicBP_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mSystolicBP_textView.setText(String.valueOf(mSystolicBP_picker.getValue()));
}
});
mDiastolicBP_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mDiastolicBP_textView.setText(String.valueOf(mDiastolicBP_picker.getValue()));
}
});
mTemp_int_picker.setMinValue(95);
mTemp_int_picker.setMaxValue(106);
mTemp_int_picker.setValue(98);
mTemp_int_picker.setWrapSelectorWheel(false);
mTemp_decimal_picker.setMinValue(0);
mTemp_decimal_picker.setMaxValue(9);
mTemp_decimal_picker.setValue(7);
mTemp_decimal_picker.setWrapSelectorWheel(false);
mTemperature_textView.setText("98.7");
NumberPicker.OnScrollListener tempScrollListener = new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mTemperature_textView.setText(String.valueOf(mTemp_int_picker.getValue())+"."+
String.valueOf(mTemp_decimal_picker.getValue()));
}
};
mTemp_int_picker.setOnScrollListener(tempScrollListener);
mTemp_decimal_picker.setOnScrollListener(tempScrollListener);
mPulse_picker.setMinValue(20);
mPulse_picker.setMaxValue(200);
mPulse_picker.setValue(60);
mPulse_textView.setText(String.valueOf(mPulse_picker.getValue()));
mPulse_picker.setWrapSelectorWheel(false);
mPulse_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mPulse_textView.setText(String.valueOf(mPulse_picker.getValue()));
}
});
mRR_picker.setMinValue(6);
mRR_picker.setMaxValue(70);
mRR_picker.setValue(14);
mRR_textView.setText(String.valueOf(mRR_picker.getValue()));
mRR_picker.setWrapSelectorWheel(false);
mRR_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mRR_textView.setText(String.valueOf(mRR_picker.getValue()));
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.edema_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mEdema_spinner.setAdapter(adapter);
// Do the same for the edemaLocationSpinner:
adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.edema_locn_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mEdema_location_spinner.setAdapter(adapter);
mPain_picker.setMinValue(0);
mPain_picker.setMaxValue(10);
mPain_picker.setValue(0);
mPain_textView.setText(String.valueOf(mPain_picker.getValue()));
mPain_picker.setWrapSelectorWheel(false);
mPain_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mPain_textView.setText(String.valueOf(mPain_picker.getValue()));
}
});
rootView.invalidate();
//mEdemaLocation_textView;
mDone_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int systolicBP, diastolicBP, pulse, rr, pain;
float temp;
systolicBP = Integer.parseInt((String) mSystolicBP_textView.getText());
diastolicBP = Integer.parseInt((String) mDiastolicBP_textView.getText());
temp = Float.parseFloat((String) mTemperature_textView.getText());
pulse = Integer.parseInt((String) mPulse_textView.getText());
rr = Integer.parseInt((String) mRR_textView.getText());
pain = Integer.parseInt((String) mPain_textView.getText());
String findings = mFindings_editText.getText().toString();
AssessmentItem.saveAssessment(getActivity(), mRoomNumber, systolicBP, diastolicBP, temp, pulse, rr,
(String) mEdema_spinner.getSelectedItem(), (String) mEdema_location_spinner.getSelectedItem(),
pain, findings);
getActivity().finish();
}
});
AppCompatActivity activity = (AppCompatActivity) getActivity();
// We need to start the enter transition after the data has loaded
//if ( mTransitionAnimation ) {
activity.supportStartPostponedEnterTransition();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setSubtitle("room: "+mRoomNumber);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
// Calculate ActionBar height
int actionBarHeight = DEFAULT_ACTION_BAR_HEIGHT;
TypedValue tv = new TypedValue();
if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
Picasso.with(getActivity())
.load("file:///android_asset/"+mPortraitFilePath)
.placeholder(R.drawable.blank_portrait)
//.noFade().resize(actionBar.getHeight(), actionBar.getHeight())
.noFade().resize(actionBarHeight, actionBarHeight)
.error(R.drawable.blank_portrait)
.into(imageView);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
// When tablets rotate, the currently selected list item needs to be saved.
super.onSaveInstanceState(outState);
}
}
|
app/src/main/java/com/android/janice/nursehelper/AssessmentFragment.java
|
package com.android.janice.nursehelper;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.janice.nursehelper.data.ResidentContract;
import com.squareup.picasso.Picasso;
//import com.android.janice.nursehelper.sync.NurseHelperSyncAdapter;
/**
* Created by janicerichards on 2/2/17.
*/
public class AssessmentFragment extends Fragment {
public static final String LOG_TAG = AssessmentFragment.class.getSimpleName();
private NumberPicker mSystolicBP_picker;
private NumberPicker mDiastolicBP_picker;
private NumberPicker mTemp_int_picker;
private NumberPicker mTemp_decimal_picker;
private NumberPicker mPulse_picker;
private NumberPicker mRR_picker;
private Spinner mEdema_spinner;
private Spinner mEdema_location_spinner;
private NumberPicker mPain_picker;
private TextView mSystolicBP_textView;
private TextView mDiastolicBP_textView;
private TextView mTemperature_textView;
private TextView mPulse_textView;
private TextView mRR_textView;
private TextView mEdema_textView;
private TextView mEdemaLocation_textView;
private TextView mPain_textView;
private EditText mFindings_editText;
private Button mDone_button;
String mRoomNumber;
String mPortraitFilePath;
public static final int DEFAULT_ACTION_BAR_HEIGHT = 60;
private static final String[] ASSESSMENT_COLUMNS = {
ResidentContract.AssessmentEntry.COLUMN_ROOM_NUMBER,
ResidentContract.AssessmentEntry.COLUMN_BLOOD_PRESSURE,
ResidentContract.AssessmentEntry.COLUMN_TEMPERATURE,
ResidentContract.AssessmentEntry.COLUMN_PULSE,
ResidentContract.AssessmentEntry.COLUMN_RR,
ResidentContract.AssessmentEntry.COLUMN_EDEMA,
ResidentContract.AssessmentEntry.COLUMN_SIGNIFICANT_FINDINGS,
ResidentContract.AssessmentEntry.COLUMN_TIME
};
public AssessmentFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mRoomNumber = arguments.getString(MainActivity.ITEM_ROOM_NUMBER);
mPortraitFilePath = arguments.getString(MainActivity.ITEM_PORTRAIT_FILEPATH);
Log.e(LOG_TAG, "mPortraitFilePath is "+mPortraitFilePath);
}
//View rootView = inflater.inflate(R.layout.fragment_assessment, container, false);
View rootView = inflater.inflate(R.layout.item_assessment, container, false);
mSystolicBP_textView = (TextView) rootView.findViewById(R.id.bp_systolic_textview);
mDiastolicBP_textView = (TextView) rootView.findViewById(R.id.bp_diastolic_textview);
mTemperature_textView = (TextView) rootView.findViewById(R.id.temperature_textview);
mPulse_textView = (TextView) rootView.findViewById(R.id.pulse_textview);
mRR_textView = (TextView) rootView.findViewById(R.id.rr_textview);
mEdema_textView = (TextView) rootView.findViewById(R.id.edema_textview);
mPain_textView = (TextView) rootView.findViewById(R.id.pain_textview);
mFindings_editText = (EditText) rootView.findViewById(R.id.findings_edittext);
mSystolicBP_picker = (NumberPicker) rootView.findViewById(R.id.bp_systolic_numberpicker);
mDiastolicBP_picker = (NumberPicker) rootView.findViewById(R.id.bp_diastolic_numberpicker);
mTemp_int_picker = (NumberPicker) rootView.findViewById(R.id.temp_int_numberpicker);
mTemp_decimal_picker = (NumberPicker) rootView.findViewById(R.id.temp_decimal_numberpicker);
mPulse_picker = (NumberPicker) rootView.findViewById(R.id.pulse_numberpicker);
mRR_picker = (NumberPicker) rootView.findViewById(R.id.rr_numberpicker);
mEdema_spinner = (Spinner) rootView.findViewById(R.id.edema_spinner);
mEdema_location_spinner = (Spinner) rootView.findViewById(R.id.edema_locn_spinner);
mPain_picker = (NumberPicker) rootView.findViewById(R.id.pain_picker);
mDone_button = (Button) rootView.findViewById(R.id.done_button);
mSystolicBP_picker.setMinValue(60);
mSystolicBP_picker.setMaxValue(250);
mSystolicBP_picker.setValue(120);
mSystolicBP_textView.setText(String.valueOf(mSystolicBP_picker.getValue()));
mDiastolicBP_picker.setMinValue(40);
mDiastolicBP_picker.setMaxValue(160);
mDiastolicBP_textView.setText(String.valueOf(mDiastolicBP_picker.getValue()));
mDiastolicBP_picker.setValue(80);
mSystolicBP_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mSystolicBP_textView.setText(String.valueOf(mSystolicBP_picker.getValue()));
}
});
mDiastolicBP_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mDiastolicBP_textView.setText(String.valueOf(mDiastolicBP_picker.getValue()));
}
});
mTemp_int_picker.setMinValue(95);
mTemp_int_picker.setMaxValue(106);
mTemp_int_picker.setValue(98);
mTemp_decimal_picker.setMinValue(0);
mTemp_decimal_picker.setMaxValue(9);
mTemp_decimal_picker.setValue(7);
mTemperature_textView.setText("98.7");
NumberPicker.OnScrollListener tempScrollListener = new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mTemperature_textView.setText(String.valueOf(mTemp_int_picker.getValue())+"."+
String.valueOf(mTemp_decimal_picker.getValue()));
}
};
mTemp_int_picker.setOnScrollListener(tempScrollListener);
mTemp_decimal_picker.setOnScrollListener(tempScrollListener);
mPulse_picker.setMinValue(20);
mPulse_picker.setMaxValue(200);
mPulse_picker.setValue(60);
mPulse_textView.setText(String.valueOf(mPulse_picker.getValue()));
mPulse_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mPulse_textView.setText(String.valueOf(mPulse_picker.getValue()));
}
});
mRR_picker.setMinValue(6);
mRR_picker.setMaxValue(70);
mRR_picker.setValue(14);
mRR_textView.setText(String.valueOf(mRR_picker.getValue()));
mRR_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mRR_textView.setText(String.valueOf(mRR_picker.getValue()));
}
});
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.edema_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mEdema_spinner.setAdapter(adapter);
// Do the same for the edemaLocationSpinner:
adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.edema_locn_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mEdema_location_spinner.setAdapter(adapter);
mPain_picker.setMinValue(0);
mPain_picker.setMaxValue(10);
mPain_picker.setValue(0);
mPain_textView.setText(String.valueOf(mPain_picker.getValue()));
mPain_picker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int i) {
if (i == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
mPain_textView.setText(String.valueOf(mPain_picker.getValue()));
}
});
rootView.invalidate();
//mEdemaLocation_textView;
mDone_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int systolicBP, diastolicBP, pulse, rr, pain;
float temp;
systolicBP = Integer.parseInt((String) mSystolicBP_textView.getText());
diastolicBP = Integer.parseInt((String) mDiastolicBP_textView.getText());
temp = Float.parseFloat((String) mTemperature_textView.getText());
pulse = Integer.parseInt((String) mPulse_textView.getText());
rr = Integer.parseInt((String) mRR_textView.getText());
pain = Integer.parseInt((String) mPain_textView.getText());
String findings = mFindings_editText.getText().toString();
AssessmentItem.saveAssessment(getActivity(), mRoomNumber, systolicBP, diastolicBP, temp, pulse, rr,
(String) mEdema_spinner.getSelectedItem(), (String) mEdema_location_spinner.getSelectedItem(),
pain, findings);
getActivity().finish();
}
});
AppCompatActivity activity = (AppCompatActivity) getActivity();
// We need to start the enter transition after the data has loaded
//if ( mTransitionAnimation ) {
activity.supportStartPostponedEnterTransition();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setSubtitle("room: "+mRoomNumber);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
// Calculate ActionBar height
int actionBarHeight = DEFAULT_ACTION_BAR_HEIGHT;
TypedValue tv = new TypedValue();
if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
Picasso.with(getActivity())
.load("file:///android_asset/"+mPortraitFilePath)
.placeholder(R.drawable.blank_portrait)
//.noFade().resize(actionBar.getHeight(), actionBar.getHeight())
.noFade().resize(actionBarHeight, actionBarHeight)
.error(R.drawable.blank_portrait)
.into(imageView);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
// When tablets rotate, the currently selected list item needs to be saved.
super.onSaveInstanceState(outState);
}
}
|
Change NumberPickers to not wrap-around from min <-> max values
|
app/src/main/java/com/android/janice/nursehelper/AssessmentFragment.java
|
Change NumberPickers to not wrap-around from min <-> max values
|
|
Java
|
apache-2.0
|
88fcf5381d78aa60a2ad71045ab11194ae74d36d
| 0
|
rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy
|
/*
* Autopsy
*
* Copyright 2020 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.discovery;
import static java.awt.BorderLayout.CENTER;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.discovery.FileGroup.GroupSortingAlgorithm;
import org.sleuthkit.autopsy.discovery.FileSearch.GroupingAttributeType;
import org.sleuthkit.autopsy.discovery.FileSorter.SortingMethod;
/**
* Dialog for displaying the controls and filters for configuration of a
* Discovery search.
*/
final class DiscoveryDialog extends javax.swing.JDialog {
private static final Set<Case.Events> CASE_EVENTS_OF_INTEREST = EnumSet.of(Case.Events.CURRENT_CASE,
Case.Events.DATA_SOURCE_ADDED, Case.Events.DATA_SOURCE_DELETED);
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(DiscoveryDialog.class.getName());
private ImageFilterPanel imageFilterPanel = null;
private VideoFilterPanel videoFilterPanel = null;
private DocumentFilterPanel documentFilterPanel = null;
private static final Color SELECTED_COLOR = new Color(216, 230, 242);
private static final Color UNSELECTED_COLOR = new Color(240, 240, 240);
private SearchWorker searchWorker = null;
private static DiscoveryDialog discDialog;
private FileSearchData.FileType fileType = FileSearchData.FileType.IMAGE;
private final PropertyChangeListener listener;
/**
* Get the Discovery dialog instance.
*
* @return The instance of the Discovery Dialog.
*/
static synchronized DiscoveryDialog getDiscoveryDialogInstance() {
if (discDialog == null) {
discDialog = new DiscoveryDialog();
}
return discDialog;
}
/**
* Private constructor to construct a new DiscoveryDialog
*/
@Messages("DiscoveryDialog.name.text=Discovery")
private DiscoveryDialog() {
super(WindowManager.getDefault().getMainWindow(), Bundle.DiscoveryDialog_name_text(), true);
initComponents();
listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("FilterError") && evt.getNewValue() != null) {
setValid(evt.getNewValue().toString());
}
}
};
for (GroupSortingAlgorithm groupSortAlgorithm : GroupSortingAlgorithm.values()) {
groupSortingComboBox.addItem(groupSortAlgorithm);
}
updateSearchSettings();
Case.addEventTypeSubscriber(CASE_EVENTS_OF_INTEREST, this.new CasePropertyChangeListener());
}
/**
* Update the search settings to a default state.
*/
void updateSearchSettings() {
removeAllPanels();
imageFilterPanel = null;
videoFilterPanel = null;
documentFilterPanel = null;
imageFilterPanel = new ImageFilterPanel();
videoFilterPanel = new VideoFilterPanel();
documentFilterPanel = new DocumentFilterPanel();
imagesButton.setSelected(true);
imagesButton.setEnabled(false);
imagesButton.setBackground(SELECTED_COLOR);
imagesButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.IMAGE;
add(imageFilterPanel, CENTER);
imageFilterPanel.addPropertyChangeListener(listener);
updateGroupByComboBox();
updateOrderByComboBox();
groupSortingComboBox.setSelectedIndex(0);
pack();
repaint();
}
/**
* Private helper method to perform groupByComboBox update.
*/
private void updateGroupByComboBox() {
groupByCombobox.removeAllItems();
// Set up the grouping attributes
for (FileSearch.GroupingAttributeType type : FileSearch.GroupingAttributeType.getOptionsForGrouping()) {
switch (type) {
case FREQUENCY:
if (!CentralRepository.isEnabled()) {
continue;
}
break;
case OBJECT_DETECTED:
if (!imageFilterPanel.isObjectsFilterSupported()) {
continue;
}
break;
case INTERESTING_ITEM_SET:
if (!imageFilterPanel.isInterestingItemsFilterSupported()) {
continue;
}
break;
case HASH_LIST_NAME:
if (!imageFilterPanel.isHashSetFilterSupported()) {
continue;
}
break;
default:
break;
}
groupByCombobox.addItem(type);
}
}
/**
* Private helper method to perform orderByComboBox update.
*/
private void updateOrderByComboBox() {
orderByCombobox.removeAllItems();
// Set up the file order list
for (FileSorter.SortingMethod method : FileSorter.SortingMethod.getOptionsForOrdering()) {
if (method != SortingMethod.BY_FREQUENCY || CentralRepository.isEnabled()) {
orderByCombobox.addItem(method);
}
}
}
/**
* Validate the current filter settings of the selected type.
*/
synchronized void validateDialog() {
switch (fileType) {
case IMAGE:
if (imageFilterPanel != null) {
imageFilterPanel.validateFields();
}
return;
case VIDEO:
if (videoFilterPanel != null) {
videoFilterPanel.validateFields();
}
return;
case DOCUMENTS:
if (documentFilterPanel != null) {
documentFilterPanel.validateFields();
}
break;
default:
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.JPanel toolBarPanel = new javax.swing.JPanel();
imagesButton = new javax.swing.JButton();
videosButton = new javax.swing.JButton();
documentsButton = new javax.swing.JButton();
javax.swing.JLabel step1Label = new javax.swing.JLabel();
javax.swing.Box.Filler filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 32767));
javax.swing.JPanel displaySettingsPanel = new javax.swing.JPanel();
searchButton = new javax.swing.JButton();
errorLabel = new javax.swing.JLabel();
javax.swing.JButton cancelButton = new javax.swing.JButton();
javax.swing.JPanel sortingPanel = new javax.swing.JPanel();
groupByCombobox = new javax.swing.JComboBox<>();
orderByCombobox = new javax.swing.JComboBox<>();
javax.swing.JLabel orderGroupsByLabel = new javax.swing.JLabel();
javax.swing.JLabel orderByLabel = new javax.swing.JLabel();
javax.swing.JLabel groupByLabel = new javax.swing.JLabel();
groupSortingComboBox = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(600, 300));
setPreferredSize(new java.awt.Dimension(1000, 650));
imagesButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(imagesButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.imagesButton.text")); // NOI18N
imagesButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
imagesButton.setFocusable(false);
imagesButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
imagesButton.setMaximumSize(new java.awt.Dimension(90, 43));
imagesButton.setMinimumSize(new java.awt.Dimension(90, 43));
imagesButton.setPreferredSize(new java.awt.Dimension(90, 43));
imagesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
imagesButtonActionPerformed(evt);
}
});
videosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(videosButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.videosButton.text")); // NOI18N
videosButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
videosButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
videosButton.setFocusable(false);
videosButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
videosButton.setMaximumSize(new java.awt.Dimension(90, 43));
videosButton.setMinimumSize(new java.awt.Dimension(90, 43));
videosButton.setPreferredSize(new java.awt.Dimension(90, 43));
videosButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
videosButtonActionPerformed(evt);
}
});
documentsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(documentsButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.documentsButton.text")); // NOI18N
documentsButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
documentsButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
documentsButton.setFocusable(false);
documentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
documentsButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(step1Label, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.step1Label.text")); // NOI18N
javax.swing.GroupLayout toolBarPanelLayout = new javax.swing.GroupLayout(toolBarPanel);
toolBarPanel.setLayout(toolBarPanelLayout);
toolBarPanelLayout.setHorizontalGroup(
toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addContainerGap(196, Short.MAX_VALUE)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, toolBarPanelLayout.createSequentialGroup()
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(step1Label, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(documentsButton)))
.addContainerGap(196, Short.MAX_VALUE))
);
toolBarPanelLayout.setVerticalGroup(
toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(step1Label))
.addGap(8, 8, 8)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(documentsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8))
);
getContentPane().add(toolBarPanel, java.awt.BorderLayout.PAGE_START);
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.searchButton.text")); // NOI18N
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.cancelButton.text")); // NOI18N
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
sortingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.sortingPanel.border.title"))); // NOI18N
sortingPanel.setPreferredSize(new java.awt.Dimension(345, 112));
org.openide.awt.Mnemonics.setLocalizedText(orderGroupsByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderGroupsByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(groupByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.groupByLabel.text")); // NOI18N
javax.swing.GroupLayout sortingPanelLayout = new javax.swing.GroupLayout(sortingPanel);
sortingPanel.setLayout(sortingPanelLayout);
sortingPanelLayout.setHorizontalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(orderGroupsByLabel)
.addComponent(groupByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(groupSortingComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(groupByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(orderByLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
sortingPanelLayout.setVerticalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupByLabel)
.addComponent(orderByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderByLabel))
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupSortingComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderGroupsByLabel))
.addGap(8, 8, 8))
);
javax.swing.GroupLayout displaySettingsPanelLayout = new javax.swing.GroupLayout(displaySettingsPanel);
displaySettingsPanel.setLayout(displaySettingsPanelLayout);
displaySettingsPanelLayout.setHorizontalGroup(
displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(sortingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE)
.addGroup(displaySettingsPanelLayout.createSequentialGroup()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(cancelButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(searchButton)))
.addGap(8, 8, 8))
);
displaySettingsPanelLayout.setVerticalGroup(
displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(sortingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)))
.addGap(8, 8, 8))
);
getContentPane().add(displaySettingsPanel, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>//GEN-END:initComponents
private void imagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagesButtonActionPerformed
removeAllPanels();
add(imageFilterPanel, CENTER);
imagesButton.setSelected(true);
imagesButton.setEnabled(false);
imagesButton.setBackground(SELECTED_COLOR);
imagesButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.IMAGE;
imageFilterPanel.addPropertyChangeListener(listener);
validateDialog();
pack();
repaint();
}//GEN-LAST:event_imagesButtonActionPerformed
private void videosButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_videosButtonActionPerformed
removeAllPanels();
add(videoFilterPanel, CENTER);
imagesButton.setSelected(false);
imagesButton.setEnabled(true);
imagesButton.setBackground(UNSELECTED_COLOR);
videosButton.setSelected(true);
videosButton.setEnabled(false);
videosButton.setBackground(SELECTED_COLOR);
videosButton.setForeground(Color.BLACK);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
videoFilterPanel.addPropertyChangeListener(listener);
fileType = FileSearchData.FileType.VIDEO;
validateDialog();
pack();
repaint();
}//GEN-LAST:event_videosButtonActionPerformed
private void documentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_documentsButtonActionPerformed
removeAllPanels();
add(documentFilterPanel, CENTER);
documentsButton.setSelected(true);
documentsButton.setEnabled(false);
documentsButton.setBackground(SELECTED_COLOR);
documentsButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
imagesButton.setSelected(false);
imagesButton.setEnabled(true);
imagesButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.DOCUMENTS;
documentFilterPanel.addPropertyChangeListener(listener);
validateDialog();
pack();
repaint();
}//GEN-LAST:event_documentsButtonActionPerformed
/**
* Helper method to remove all filter panels and their listeners
*/
private void removeAllPanels() {
if (imageFilterPanel != null) {
remove(imageFilterPanel);
imageFilterPanel.removePropertyChangeListener(listener);
}
if (documentFilterPanel != null) {
remove(documentFilterPanel);
documentFilterPanel.removePropertyChangeListener(listener);
}
if (videoFilterPanel != null) {
remove(videoFilterPanel);
videoFilterPanel.removePropertyChangeListener(listener);
}
}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
// Get the selected filters
final DiscoveryTopComponent tc = DiscoveryTopComponent.getTopComponent();
if (tc == null) {
setValid("No Top Component Found");
return;
}
if (tc.isOpened() == false) {
tc.open();
}
tc.resetTopComponent();
List<FileSearchFiltering.FileFilter> filters;
if (videosButton.isSelected()) {
filters = videoFilterPanel.getFilters();
} else if (documentsButton.isSelected()) {
filters = documentFilterPanel.getFilters();
} else {
filters = imageFilterPanel.getFilters();
}
DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.SearchStartedEvent(fileType));
// Get the grouping attribute and group sorting method
FileSearch.AttributeType groupingAttr = groupByCombobox.getItemAt(groupByCombobox.getSelectedIndex()).getAttributeType();
FileGroup.GroupSortingAlgorithm groupSortAlgorithm = groupSortingComboBox.getItemAt(groupSortingComboBox.getSelectedIndex());
// Get the file sorting method
FileSorter.SortingMethod fileSort = (FileSorter.SortingMethod) orderByCombobox.getSelectedItem();
CentralRepository centralRepoDb = null;
if (CentralRepository.isEnabled()) {
try {
centralRepoDb = CentralRepository.getInstance();
} catch (CentralRepoException ex) {
centralRepoDb = null;
logger.log(Level.SEVERE, "Error loading central repository database, no central repository options will be available for Discovery", ex);
}
}
searchWorker = new SearchWorker(centralRepoDb, filters, groupingAttr, groupSortAlgorithm, fileSort);
searchWorker.execute();
dispose();
tc.toFront();
tc.requestActive();
}//GEN-LAST:event_searchButtonActionPerformed
@Override
public void dispose() {
setVisible(false);
}
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
/**
* Cancel the searchWorker if it exists.
*/
void cancelSearch() {
if (searchWorker != null) {
searchWorker.cancel(true);
}
}
/**
* The adjust the controls to reflect whether the settings are valid based
* on the error.
*
* @param error The error message to display, null if there is no error.
*/
private void setValid(String error) {
if (StringUtils.isBlank(error)) {
errorLabel.setText("");
searchButton.setEnabled(true);
} else {
errorLabel.setText(error);
searchButton.setEnabled(false);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton documentsButton;
private javax.swing.JLabel errorLabel;
private javax.swing.JComboBox<GroupingAttributeType> groupByCombobox;
private javax.swing.JComboBox<GroupSortingAlgorithm> groupSortingComboBox;
private javax.swing.JButton imagesButton;
private javax.swing.JComboBox<SortingMethod> orderByCombobox;
private javax.swing.JButton searchButton;
private javax.swing.JButton videosButton;
// End of variables declaration//GEN-END:variables
/**
* PropertyChangeListener to listen to case level events that may modify the
* filters available.
*/
private class CasePropertyChangeListener implements PropertyChangeListener {
@Override
@SuppressWarnings("fallthrough")
public void propertyChange(PropertyChangeEvent evt) {
switch (Case.Events.valueOf(evt.getPropertyName())) {
case CURRENT_CASE: {
if (evt.getNewValue() == null) {
//do not refresh when a case is closed only when it is opened.
break;
}
//else fallthrough
}
case DATA_SOURCE_ADDED:
//fallthrough
case DATA_SOURCE_DELETED:
updateSearchSettings();
break;
default:
//do nothing if the event is not one of the above events.
break;
}
}
}
}
|
Core/src/org/sleuthkit/autopsy/discovery/DiscoveryDialog.java
|
/*
* Autopsy
*
* Copyright 2020 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.discovery;
import static java.awt.BorderLayout.CENTER;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.discovery.FileGroup.GroupSortingAlgorithm;
import org.sleuthkit.autopsy.discovery.FileSearch.GroupingAttributeType;
import org.sleuthkit.autopsy.discovery.FileSorter.SortingMethod;
/**
* Dialog for displaying the controls and filters for configuration of a
* Discovery search.
*/
final class DiscoveryDialog extends javax.swing.JDialog {
private static final Set<Case.Events> CASE_EVENTS_OF_INTEREST = EnumSet.of(Case.Events.CURRENT_CASE,
Case.Events.DATA_SOURCE_ADDED, Case.Events.DATA_SOURCE_DELETED);
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(DiscoveryDialog.class.getName());
private ImageFilterPanel imageFilterPanel = null;
private VideoFilterPanel videoFilterPanel = null;
private DocumentFilterPanel documentFilterPanel = null;
private static final Color SELECTED_COLOR = new Color(216, 230, 242);
private static final Color UNSELECTED_COLOR = new Color(240, 240, 240);
private SearchWorker searchWorker = null;
private static DiscoveryDialog discDialog;
private FileSearchData.FileType fileType = FileSearchData.FileType.IMAGE;
private final PropertyChangeListener listener;
/**
* Get the Discovery dialog instance.
*
* @return The instance of the Discovery Dialog.
*/
static synchronized DiscoveryDialog getDiscoveryDialogInstance() {
if (discDialog == null) {
discDialog = new DiscoveryDialog();
}
return discDialog;
}
/**
* Private constructor to construct a new DiscoveryDialog
*/
@Messages("DiscoveryDialog.name.text=Discovery")
private DiscoveryDialog() {
super(WindowManager.getDefault().getMainWindow(), Bundle.DiscoveryDialog_name_text(), true);
initComponents();
listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("FilterError") && evt.getNewValue() != null) {
setValid(evt.getNewValue().toString());
}
}
};
for (GroupSortingAlgorithm groupSortAlgorithm : GroupSortingAlgorithm.values()) {
groupSortingComboBox.addItem(groupSortAlgorithm);
}
updateSearchSettings();
Case.addEventTypeSubscriber(CASE_EVENTS_OF_INTEREST, this.new CasePropertyChangeListener());
}
/**
* Update the search settings to a default state.
*/
void updateSearchSettings() {
removeAllPanels();
imageFilterPanel = null;
videoFilterPanel = null;
documentFilterPanel = null;
imageFilterPanel = new ImageFilterPanel();
videoFilterPanel = new VideoFilterPanel();
documentFilterPanel = new DocumentFilterPanel();
imagesButton.setSelected(true);
imagesButton.setEnabled(false);
imagesButton.setBackground(SELECTED_COLOR);
imagesButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.IMAGE;
add(imageFilterPanel, CENTER);
imageFilterPanel.addPropertyChangeListener(listener);
updateGroupByComboBox();
updateOrderByComboBox();
groupSortingComboBox.setSelectedIndex(0);
pack();
repaint();
}
/**
* Private helper method to perform groupByComboBox update.
*/
private void updateGroupByComboBox() {
groupByCombobox.removeAllItems();
// Set up the grouping attributes
for (FileSearch.GroupingAttributeType type : FileSearch.GroupingAttributeType.getOptionsForGrouping()) {
if ((type != GroupingAttributeType.FREQUENCY || CentralRepository.isEnabled())
&& (type != GroupingAttributeType.OBJECT_DETECTED || imageFilterPanel.isObjectsFilterSupported())
&& (type != GroupingAttributeType.INTERESTING_ITEM_SET || imageFilterPanel.isInterestingItemsFilterSupported())
&& (type != GroupingAttributeType.HASH_LIST_NAME || imageFilterPanel.isHashSetFilterSupported())) {
groupByCombobox.addItem(type);
}
}
}
/**
* Private helper method to perform orderByComboBox update.
*/
private void updateOrderByComboBox() {
orderByCombobox.removeAllItems();
// Set up the file order list
for (FileSorter.SortingMethod method : FileSorter.SortingMethod.getOptionsForOrdering()) {
if (method != SortingMethod.BY_FREQUENCY || CentralRepository.isEnabled()) {
orderByCombobox.addItem(method);
}
}
}
/**
* Validate the current filter settings of the selected type.
*/
synchronized void validateDialog() {
switch (fileType) {
case IMAGE:
if (imageFilterPanel != null) {
imageFilterPanel.validateFields();
}
return;
case VIDEO:
if (videoFilterPanel != null) {
videoFilterPanel.validateFields();
}
return;
case DOCUMENTS:
if (documentFilterPanel != null) {
documentFilterPanel.validateFields();
}
break;
default:
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.JPanel toolBarPanel = new javax.swing.JPanel();
imagesButton = new javax.swing.JButton();
videosButton = new javax.swing.JButton();
documentsButton = new javax.swing.JButton();
javax.swing.JLabel step1Label = new javax.swing.JLabel();
javax.swing.Box.Filler filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 0), new java.awt.Dimension(104, 32767));
javax.swing.JPanel displaySettingsPanel = new javax.swing.JPanel();
searchButton = new javax.swing.JButton();
errorLabel = new javax.swing.JLabel();
javax.swing.JButton cancelButton = new javax.swing.JButton();
javax.swing.JPanel sortingPanel = new javax.swing.JPanel();
groupByCombobox = new javax.swing.JComboBox<>();
orderByCombobox = new javax.swing.JComboBox<>();
javax.swing.JLabel orderGroupsByLabel = new javax.swing.JLabel();
javax.swing.JLabel orderByLabel = new javax.swing.JLabel();
javax.swing.JLabel groupByLabel = new javax.swing.JLabel();
groupSortingComboBox = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(600, 300));
setPreferredSize(new java.awt.Dimension(1000, 650));
imagesButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(imagesButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.imagesButton.text")); // NOI18N
imagesButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/pictures-icon.png"))); // NOI18N
imagesButton.setFocusable(false);
imagesButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
imagesButton.setMaximumSize(new java.awt.Dimension(90, 43));
imagesButton.setMinimumSize(new java.awt.Dimension(90, 43));
imagesButton.setPreferredSize(new java.awt.Dimension(90, 43));
imagesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
imagesButtonActionPerformed(evt);
}
});
videosButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(videosButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.videosButton.text")); // NOI18N
videosButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
videosButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/video-icon.png"))); // NOI18N
videosButton.setFocusable(false);
videosButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
videosButton.setMaximumSize(new java.awt.Dimension(90, 43));
videosButton.setMinimumSize(new java.awt.Dimension(90, 43));
videosButton.setPreferredSize(new java.awt.Dimension(90, 43));
videosButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
videosButtonActionPerformed(evt);
}
});
documentsButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(documentsButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.documentsButton.text")); // NOI18N
documentsButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
documentsButton.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/images/documents-icon.png"))); // NOI18N
documentsButton.setFocusable(false);
documentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
documentsButtonActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(step1Label, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.step1Label.text")); // NOI18N
javax.swing.GroupLayout toolBarPanelLayout = new javax.swing.GroupLayout(toolBarPanel);
toolBarPanel.setLayout(toolBarPanelLayout);
toolBarPanelLayout.setHorizontalGroup(
toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addContainerGap(196, Short.MAX_VALUE)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, toolBarPanelLayout.createSequentialGroup()
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(step1Label, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(documentsButton)))
.addContainerGap(196, Short.MAX_VALUE))
);
toolBarPanelLayout.setVerticalGroup(
toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(toolBarPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(step1Label))
.addGap(8, 8, 8)
.addGroup(toolBarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(videosButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(imagesButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(documentsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8))
);
getContentPane().add(toolBarPanel, java.awt.BorderLayout.PAGE_START);
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.searchButton.text")); // NOI18N
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
errorLabel.setForeground(new java.awt.Color(255, 0, 0));
org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.cancelButton.text")); // NOI18N
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
sortingPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.sortingPanel.border.title"))); // NOI18N
sortingPanel.setPreferredSize(new java.awt.Dimension(345, 112));
org.openide.awt.Mnemonics.setLocalizedText(orderGroupsByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderGroupsByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(orderByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.orderByLabel.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(groupByLabel, org.openide.util.NbBundle.getMessage(DiscoveryDialog.class, "DiscoveryDialog.groupByLabel.text")); // NOI18N
javax.swing.GroupLayout sortingPanelLayout = new javax.swing.GroupLayout(sortingPanel);
sortingPanel.setLayout(sortingPanelLayout);
sortingPanelLayout.setHorizontalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(orderGroupsByLabel)
.addComponent(groupByLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(groupSortingComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(groupByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(orderByLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderByCombobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
sortingPanelLayout.setVerticalGroup(
sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(sortingPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(groupByLabel)
.addComponent(orderByCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderByLabel))
.addGap(8, 8, 8)
.addGroup(sortingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(groupSortingComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderGroupsByLabel))
.addGap(8, 8, 8))
);
javax.swing.GroupLayout displaySettingsPanelLayout = new javax.swing.GroupLayout(displaySettingsPanel);
displaySettingsPanel.setLayout(displaySettingsPanelLayout);
displaySettingsPanelLayout.setHorizontalGroup(
displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(sortingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 741, Short.MAX_VALUE)
.addGroup(displaySettingsPanelLayout.createSequentialGroup()
.addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(cancelButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(searchButton)))
.addGap(8, 8, 8))
);
displaySettingsPanelLayout.setVerticalGroup(
displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, displaySettingsPanelLayout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(sortingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(displaySettingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(searchButton)))
.addGap(8, 8, 8))
);
getContentPane().add(displaySettingsPanel, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>//GEN-END:initComponents
private void imagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagesButtonActionPerformed
removeAllPanels();
add(imageFilterPanel, CENTER);
imagesButton.setSelected(true);
imagesButton.setEnabled(false);
imagesButton.setBackground(SELECTED_COLOR);
imagesButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.IMAGE;
imageFilterPanel.addPropertyChangeListener(listener);
validateDialog();
pack();
repaint();
}//GEN-LAST:event_imagesButtonActionPerformed
private void videosButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_videosButtonActionPerformed
removeAllPanels();
add(videoFilterPanel, CENTER);
imagesButton.setSelected(false);
imagesButton.setEnabled(true);
imagesButton.setBackground(UNSELECTED_COLOR);
videosButton.setSelected(true);
videosButton.setEnabled(false);
videosButton.setBackground(SELECTED_COLOR);
videosButton.setForeground(Color.BLACK);
documentsButton.setSelected(false);
documentsButton.setEnabled(true);
documentsButton.setBackground(UNSELECTED_COLOR);
videoFilterPanel.addPropertyChangeListener(listener);
fileType = FileSearchData.FileType.VIDEO;
validateDialog();
pack();
repaint();
}//GEN-LAST:event_videosButtonActionPerformed
private void documentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_documentsButtonActionPerformed
removeAllPanels();
add(documentFilterPanel, CENTER);
documentsButton.setSelected(true);
documentsButton.setEnabled(false);
documentsButton.setBackground(SELECTED_COLOR);
documentsButton.setForeground(Color.BLACK);
videosButton.setSelected(false);
videosButton.setEnabled(true);
videosButton.setBackground(UNSELECTED_COLOR);
imagesButton.setSelected(false);
imagesButton.setEnabled(true);
imagesButton.setBackground(UNSELECTED_COLOR);
fileType = FileSearchData.FileType.DOCUMENTS;
documentFilterPanel.addPropertyChangeListener(listener);
validateDialog();
pack();
repaint();
}//GEN-LAST:event_documentsButtonActionPerformed
/**
* Helper method to remove all filter panels and their listeners
*/
private void removeAllPanels() {
if (imageFilterPanel != null) {
remove(imageFilterPanel);
imageFilterPanel.removePropertyChangeListener(listener);
}
if (documentFilterPanel != null) {
remove(documentFilterPanel);
documentFilterPanel.removePropertyChangeListener(listener);
}
if (videoFilterPanel != null) {
remove(videoFilterPanel);
videoFilterPanel.removePropertyChangeListener(listener);
}
}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
// Get the selected filters
final DiscoveryTopComponent tc = DiscoveryTopComponent.getTopComponent();
if (tc == null) {
setValid("No Top Component Found");
return;
}
if (tc.isOpened() == false) {
tc.open();
}
tc.resetTopComponent();
List<FileSearchFiltering.FileFilter> filters;
if (videosButton.isSelected()) {
filters = videoFilterPanel.getFilters();
} else if (documentsButton.isSelected()) {
filters = documentFilterPanel.getFilters();
} else {
filters = imageFilterPanel.getFilters();
}
DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.SearchStartedEvent(fileType));
// Get the grouping attribute and group sorting method
FileSearch.AttributeType groupingAttr = groupByCombobox.getItemAt(groupByCombobox.getSelectedIndex()).getAttributeType();
FileGroup.GroupSortingAlgorithm groupSortAlgorithm = groupSortingComboBox.getItemAt(groupSortingComboBox.getSelectedIndex());
// Get the file sorting method
FileSorter.SortingMethod fileSort = (FileSorter.SortingMethod) orderByCombobox.getSelectedItem();
CentralRepository centralRepoDb = null;
if (CentralRepository.isEnabled()) {
try {
centralRepoDb = CentralRepository.getInstance();
} catch (CentralRepoException ex) {
centralRepoDb = null;
logger.log(Level.SEVERE, "Error loading central repository database, no central repository options will be available for Discovery", ex);
}
}
searchWorker = new SearchWorker(centralRepoDb, filters, groupingAttr, groupSortAlgorithm, fileSort);
searchWorker.execute();
dispose();
tc.toFront();
tc.requestActive();
}//GEN-LAST:event_searchButtonActionPerformed
@Override
public void dispose() {
setVisible(false);
}
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
/**
* Cancel the searchWorker if it exists.
*/
void cancelSearch() {
if (searchWorker != null) {
searchWorker.cancel(true);
}
}
/**
* The adjust the controls to reflect whether the settings are valid based
* on the error.
*
* @param error The error message to display, null if there is no error.
*/
private void setValid(String error) {
if (StringUtils.isBlank(error)) {
errorLabel.setText("");
searchButton.setEnabled(true);
} else {
errorLabel.setText(error);
searchButton.setEnabled(false);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton documentsButton;
private javax.swing.JLabel errorLabel;
private javax.swing.JComboBox<GroupingAttributeType> groupByCombobox;
private javax.swing.JComboBox<GroupSortingAlgorithm> groupSortingComboBox;
private javax.swing.JButton imagesButton;
private javax.swing.JComboBox<SortingMethod> orderByCombobox;
private javax.swing.JButton searchButton;
private javax.swing.JButton videosButton;
// End of variables declaration//GEN-END:variables
/**
* PropertyChangeListener to listen to case level events that may modify the
* filters available.
*/
private class CasePropertyChangeListener implements PropertyChangeListener {
@Override
@SuppressWarnings("fallthrough")
public void propertyChange(PropertyChangeEvent evt) {
switch (Case.Events.valueOf(evt.getPropertyName())) {
case CURRENT_CASE: {
if (evt.getNewValue() == null) {
//do not refresh when a case is closed only when it is opened.
break;
}
//else fallthrough
}
case DATA_SOURCE_ADDED:
//fallthrough
case DATA_SOURCE_DELETED:
updateSearchSettings();
break;
default:
//do nothing if the event is not one of the above events.
break;
}
}
}
}
|
6305 third try on codacy
|
Core/src/org/sleuthkit/autopsy/discovery/DiscoveryDialog.java
|
6305 third try on codacy
|
|
Java
|
apache-2.0
|
e13a520d0612b1b76852c1549a0b9f0637816949
| 0
|
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
|
/*****************************************************************************
* Copyright 2011-2012 INRIA
* Copyright 2011-2012 Universidade Nova de Lisboa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
package sys.net.impl;
public interface NetworkingConstants {
static final int TCP_CONNECTION_TIMEOUT = 10000;
static final int NETTY_EXECUTOR_THREADS = 64;
static final int RPC_DEFAULT_TIMEOUT = 1000 * 30;
static final long RPC_MAX_SERVICE_ID = 1L << 16;
static final long RPC_MAX_SERVICE_ID_MASK = (1L << 16) - 1L;
static final int RPC_GC_STALE_HANDLERS_TIMEOUT = 20 * 60;
static final int RPC_GC_STALE_HANDLERS_PERIOD = 60;
static final int RPC_CONNECTION_RETRIES = 3;
static final int RPC_CONNECTION_RETRY_DELAY = 250;
static final int DHT_CLIENT_RETRIES = 3;
static final int DHT_CLIENT_TIMEOUT = 250;
}
|
src-core/sys/net/impl/NetworkingConstants.java
|
/*****************************************************************************
* Copyright 2011-2012 INRIA
* Copyright 2011-2012 Universidade Nova de Lisboa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
package sys.net.impl;
public interface NetworkingConstants {
static final int TCP_CONNECTION_TIMEOUT = 10000;
static final int NETTY_CORE_THREADS = 64;
static final int NETTY_MAX_TOTAL_MEMORY = 128 * (1 << 20);
static final int NETTY_MAX_MEMORY_PER_CHANNEL = 1 * (1 << 20);
static final int NETTY_CONNECTION_TIMEOUT = 20000;
static final int NETTY_WRITEBUFFER_DEFAULTSIZE = 1024;
// static final int KRYOBUFFER_INITIAL_CAPACITY = 2048;
// static final int KRYOBUFFERPOOL_CLT_MAXSIZE = 8;
// static final int KRYOBUFFERPOOL_SRV_MAXSIZE = 1024;
// static final int KRYOBUFFERPOOL_DELAY = 100;
// static final int KRYOBUFFERPOOL_MAXUSES = 100;
static final int RPC_DEFAULT_TIMEOUT = 1000 * 30;
static final long RPC_MAX_SERVICE_ID = 1L << 16;
static final long RPC_MAX_SERVICE_ID_MASK = (1L << 16) - 1L;
static final int RPC_GC_STALE_HANDLERS_TIMEOUT = 20 * 60;
static final int RPC_GC_STALE_HANDLERS_PERIOD = 60;
static final int RPC_CONNECTION_RETRIES = 3;
static final int RPC_CONNECTION_RETRY_DELAY = 250;
static final int DHT_CLIENT_RETRIES = 3;
static final int DHT_CLIENT_TIMEOUT = 250;
}
|
Removed obsolete constants...
|
src-core/sys/net/impl/NetworkingConstants.java
|
Removed obsolete constants...
|
|
Java
|
apache-2.0
|
441af8dd76ced6cfaaa7442e3c07c4d6d8b885a1
| 0
|
enternoescape/opendct,enternoescape/opendct,enternoescape/opendct
|
/*
* Copyright 2015 The OpenDCT Authors. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opendct.config;
import opendct.config.options.DeviceOption;
import opendct.config.options.DeviceOptionException;
import opendct.config.options.IntegerDeviceOption;
import opendct.util.Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
public class ConfigBag {
private static final Logger logger = LogManager.getLogger(ConfigBag.class);
public final String CONFIG_NAME;
public final String CONFIG_CATEGORY;
public final String FILE_NAME;
public final String DIR_NAME;
private final Properties properties;
private final boolean setOnGet;
public ConfigBag(String configName, boolean setOnGet) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = "";
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + configName + ".properties";
DIR_NAME = Config.getConfigDirectory();
this.setOnGet = setOnGet;
properties = new Properties();
}
public ConfigBag(String configName, boolean setOnGet, Properties properties) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = "";
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + configName + ".properties";
DIR_NAME = Config.getConfigDirectory();
this.setOnGet = setOnGet;
this.properties = properties;
}
public ConfigBag(String configName, String category, boolean setOnGet) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = category;
DIR_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category;
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category +
Config.DIR_SEPARATOR + configName + ".properties";
this.setOnGet = setOnGet;
properties = new Properties();
}
public ConfigBag(String configName, String category, boolean setOnGet, Properties properties) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = category;
DIR_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category;
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category +
Config.DIR_SEPARATOR + configName + ".properties";
this.setOnGet = setOnGet;
this.properties = properties;
}
/**
* Loads the configuration from the pre-defined configuration directory.
* <p/>
* The filename is created based on the value of <b>CONFIG_NAME</b>.
*
* @return <i>true</i> if the configuration was loaded successfully or if the configuration is new.
*/
public synchronized boolean loadConfig() {
logger.entry();
if (Config.getConfigDirectory() == null) {
logger.fatal("The configuration directory must be defined before any properties can be loaded.");
return logger.exit(false);
} else if (!Util.createDirectory(DIR_NAME)) {
logger.fatal("Unable to create required directories.");
return logger.exit(false);
}
if (new File(FILE_NAME).exists()) {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(FILE_NAME);
} catch (FileNotFoundException e) {
logger.fatal("Unable to open the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
properties.clear();
try {
properties.load(fileInputStream);
} catch (IOException e) {
logger.fatal("Unable to read the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
} else {
logger.info("'{}' was not found. A new configuration file will be created with that name on the next save.", FILE_NAME);
}
return logger.exit(true);
}
/**
* Clears the current configuration.
*/
public synchronized void clearConfig() {
logger.entry();
logger.debug("Clearing '{}' configuration...", CONFIG_NAME);
properties.clear();
logger.exit();
}
/**
* Sorts the properties alphabetically, then saves them.
*
* @return <i>true</i> if the properties were successfully saved.
*/
public synchronized boolean saveConfig() {
logger.entry();
if (Config.getConfigDirectory() == null) {
logger.fatal("The configuration directory must be defined before any properties can be saved.");
return logger.exit(false);
} else if (!Util.createDirectory(DIR_NAME)) {
logger.fatal("Unable to create required directories.");
return logger.exit(false);
}
File file = new File(FILE_NAME);
File fileBackup = new File(FILE_NAME + ".backup");
try {
Util.copyFile(file, fileBackup, true);
} catch (IOException e) {
file.renameTo(fileBackup);
}
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(FILE_NAME);
} catch (FileNotFoundException e) {
logger.error("Unable to open the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
try {
Properties sortedProperties = new Properties() {
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
sortedProperties.putAll(properties);
sortedProperties.store(fileOutputStream, CONFIG_NAME + " Configuration File");
fileOutputStream.close();
} catch (IOException e) {
logger.error("Unable to write the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
return logger.exit(true);
}
// This will be used to set all string properties so we can do trace logging if there is any
// configuration related weirdness.
public void setString(String key, String value) {
logger.entry(key, value);
properties.setProperty(key, value);
logger.exit();
}
// This will be used to request all string properties so we can do trace logging if there is
// any configuration related weirdness.
public String getString(String key, String defaultValue) {
logger.entry(key, defaultValue);
String returnValue = properties.getProperty(key, defaultValue);
if (setOnGet) {
setString(key, returnValue);
}
return logger.exit(returnValue);
}
public String getString(String key) {
logger.entry(key);
String returnValue = properties.getProperty(key);
return logger.exit(returnValue);
}
public void setBoolean(String key, boolean value) {
logger.entry(key, value);
properties.setProperty(key, Boolean.toString(value));
logger.exit();
}
public void setShort(String key, short value) {
logger.entry(key, value);
properties.setProperty(key, Short.toString(value));
logger.exit();
}
public void setInteger(String key, int value) {
logger.entry(key, value);
properties.setProperty(key, Integer.toString(value));
logger.exit();
}
public void setLong(String key, long value) {
logger.entry(key, value);
properties.setProperty(key, Long.toString(value));
logger.exit();
}
public void setFloat(String key, float value) {
logger.entry(key, value);
properties.setProperty(key, Float.toString(value));
logger.exit();
}
public void setDouble(String key, double value) {
logger.entry(key, value);
properties.setProperty(key, Double.toString(value));
logger.exit();
}
public boolean getBoolean(String key, boolean defaultValue) {
logger.entry(key, defaultValue);
boolean returnValue = defaultValue;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
try {
returnValue = Boolean.valueOf(stringValue.toLowerCase());
} catch (Exception e) {
logger.error("The property '{}' should be boolean, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setBoolean(key, returnValue);
}
return logger.exit(returnValue);
}
public short getShort(String key, short defaultValue) {
logger.entry(key, defaultValue);
short returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
try {
returnValue = Short.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a short, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setShort(key, returnValue);
}
return logger.exit(returnValue);
}
public int getInteger(String key, int defaultValue) {
logger.entry(key, defaultValue);
int returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Integer.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be an integer, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setInteger(key, returnValue);
}
return logger.exit(returnValue);
}
public long getLong(String key, long defaultValue) {
logger.entry(key, defaultValue);
long returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Long.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a long, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setLong(key, returnValue);
}
return logger.exit(returnValue);
}
public float getFloat(String key, float defaultValue) {
logger.entry(key, defaultValue);
float returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Float.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a float, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setFloat(key, returnValue);
}
return logger.exit(returnValue);
}
public double getDouble(String key, double defaultValue) {
logger.entry(key, defaultValue);
double returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Double.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a float, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setDouble(key, returnValue);
}
return logger.exit(returnValue);
}
public String[] getStringArray(String key, String... defaultValues) {
logger.entry();
String returnValue[];
String stringValue;
if ((stringValue = properties.getProperty(key)) != null) {
if (stringValue.equals("")) {
returnValue = new String[0];
} else {
// The parsing regex will tolerate white space between commas.
returnValue = stringValue.split("\\s*,\\s*");
}
} else {
StringBuilder mergedArray = new StringBuilder();
for (String value : defaultValues) {
mergedArray.append(value + ",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
if (setOnGet) {
properties.setProperty(key, mergedArray.toString());
}
returnValue = defaultValues;
}
return logger.exit(returnValue);
}
/**
* Gets a comma separated string array.
*
* @param key This is the property name.
* @param defaultValue This is the default value to be returned if the property does not already
* exist.
* @return This will return an empty array if the property is present, but does not contain
* anything. This will return <i>null</i> only if the property does not already exist
* and <b>defaultValue</b> was set to <i>null</i>.
*/
public String[] getStringArray(String key, String defaultValue) {
logger.entry(key, defaultValue);
String stringValue = properties.getProperty(key, defaultValue);
String returnValue[] = new String[0];
if (stringValue != null) {
if (!stringValue.equals("")) {
// The parsing regex will tolerate white space between commas.
returnValue = stringValue.split("\\s*,\\s*");
}
} else if (defaultValue == null) {
returnValue = null;
}
if (setOnGet) {
if (returnValue != null) {
setStringArray(key, returnValue);
} else {
setStringArray(key, "");
}
}
return logger.exit(returnValue);
}
public void setStringArray(String key, String... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (String value : values) {
mergedArray.append(value + ",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setIntegerArray(String key, int... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (int value : values) {
mergedArray.append(Integer.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setIntegerArray(String key, Integer... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (int value : values) {
mergedArray.append(Integer.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
/**
* This method will convert numbers with commas and hyphens into an array with all of the
* in-between numbers added.
*
* @param key This is the property name.
* @param defaultValues This is returns if this property is not yet defined.
* @return The fully expanded integer array.
*/
public int[] getIntegerRanges(String key, int... defaultValues) {
logger.entry(key, defaultValues);
int returnValue[] = defaultValues;
// Be sure to use the getStringArray() method that supports null.
String values[] = getStringArray(key, (String) null);
boolean errors = false;
if (values != null) {
ArrayList<Integer> intArray = new ArrayList<Integer>();
for (String value : values) {
// Ensure that the hyphen is not just the start of a negative number.
if (value.lastIndexOf("-") > 0) {
// The parsing regex will tolerate white space between the integers and the hyphen and allows for negative numbers.
String split[] = value.split("[0-9]*\\s*-\\s*[-0-9]*");
// You could have multiple hyphens, but why?
if (split.length > 1) {
int start;
int end;
try {
start = Integer.valueOf(split[0]);
} catch (Exception e) {
logger.error("The property '{}' should be an integer range beginning, but '{}' was returned. Using the default value of '{}'", key, split[0], defaultValues);
errors = true;
break;
}
try {
end = Integer.valueOf(split[split.length - 1]);
} catch (Exception e) {
logger.error("The property '{}' should be an integer range ending, but '{}' was returned. Using the default value of '{}'", key, split[split.length - 1], defaultValues);
errors = true;
break;
}
if (start > end) {
errors = true;
break;
}
// The range is inclusive.
for (int i = start; i <= end; i++) {
intArray.add(i);
}
} else {
logger.error("The property '{}' should be an integer range, but '{}' was returned. Using the default value of '{}'", key, value, defaultValues);
errors = true;
break;
}
} else {
try {
intArray.add(Integer.valueOf(value));
} catch (Exception e) {
logger.error("The property '{}' should be an integer, but '{}' was returned. Using the default value of '{}'", key, value, defaultValues);
errors = true;
break;
}
}
}
returnValue = new int[intArray.size()];
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = intArray.get(i);
}
}
if (errors) {
returnValue = defaultValues;
}
if (setOnGet) {
setIntegerRanges(key, returnValue);
}
return logger.exit(returnValue);
}
/**
* This method will sort an array of integers and replace contiguous ranges with the first and
* last number of the range with a hyphen in-between.
* <p/>
* Ex. 507,508,509,513 becomes 507-509,513.
*
* @param key This is the property name.
* @param values The fully expanded integer array.
*/
public void setIntegerRanges(String key, int... values) {
StringBuilder mergedArray = new StringBuilder();
Arrays.sort(values);
for (int i = 0; i < values.length; i++) {
int start = values[i];
int end = values[i];
int index = 0;
while (start + index == values[i + index]) {
end = values[i + index++];
if (i + index > values.length) {
break;
}
}
// If the ranges are more than two integers apart, use a hyphen otherwise it looks a
// little odd.
if (end - start > 1) {
mergedArray.append(start + "-" + end + ",");
i += end - start;
} else {
mergedArray.append(start + ",");
}
}
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
}
public void setLongArray(String key, long... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (long value : values) {
mergedArray.append(Long.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setLongArray(String key, Long... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (Long value : values) {
mergedArray.append(Long.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setInetAddress(String key, InetAddress value) {
logger.entry(key, value);
properties.setProperty(key, value.getHostAddress());
logger.exit();
}
public InetAddress getInetAddress(String key, InetAddress defaultValue) {
logger.entry(key, defaultValue);
InetAddress returnValue = null;
String stringValue = properties.getProperty(key, defaultValue.getHostAddress());
try {
returnValue = InetAddress.getByName(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be an IP address, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue.getHostAddress());
returnValue = defaultValue;
}
if (setOnGet) {
setInetAddress(key, returnValue);
}
return logger.exit(returnValue);
}
public InetAddress[] getInetAddressArray(String key, InetAddress... defaultValue) {
logger.entry(key, defaultValue);
InetAddress returnValue[];
String defaultValueString[] = new String[defaultValue.length];
for(int i = 0; i < defaultValueString.length; i++) {
defaultValueString[i] = defaultValue[i].getHostAddress();
}
String returnValueString[] = getStringArray(key, defaultValueString);
returnValue = new InetAddress[returnValueString.length];
try {
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = InetAddress.getByName(returnValueString[i]);
}
} catch (Exception e) {
logger.error("The property '{}' should be an IP addresses, but '{}' was returned. Using the default values of '{}'", key, returnValueString, defaultValueString);
returnValue = defaultValue;
}
if (setOnGet) {
defaultValueString = new String[returnValue.length];
for(int i = 0; i < defaultValueString.length; i++) {
defaultValueString[i] = returnValue[i].getHostAddress();
}
setStringArray(key, defaultValueString);
}
return logger.exit(returnValue);
}
public void setDeviceOption(DeviceOption option) throws DeviceOptionException {
if (option.isArray()) {
setStringArray(option.getProperty(), option.getArrayValue());
} else {
setString(option.getProperty(), option.getValue());
}
switch (option.getType()) {
case INTEGER:
if (option.isArray()) {
if (option instanceof IntegerDeviceOption) {
setIntegerRanges(option.getProperty(), ((IntegerDeviceOption) option).getIntegerArray());
} else {
setStringArray(option.getProperty(), option.getArrayValue());
}
} else {
setString(option.getProperty(), option.getValue());
}
break;
default:
if (option.isArray()) {
setStringArray(option.getProperty(), option.getArrayValue());
} else {
setString(option.getProperty(), option.getValue());
}
break;
}
}
/**
* Returns all properties with a common root key as a HashMap.
* <p/>
* The root key will be removed from the returned key values in the returned HashMap.
*
* @param rootKey This is the root value to be searched for in properties. If you do not want
* all of the returned keys to start with a period (.), you must include the
* period in this parameter.
* @return Returns a HashMap containing all of the values found. If no values were found, the
* HashMap will be empty.
*/
public HashMap<String, String> getAllByRootKey(String rootKey) {
HashMap<String, String> returnValue = new HashMap<String, String>();
Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
if (key.startsWith(rootKey)) {
String value = properties.getProperty(key);
returnValue.put(key.substring(rootKey.length()), value);
}
}
return returnValue;
}
/**
* Returns all properties for each common root key in an array of respective a HashMaps.
* <p/>
* The root key will be removed from the returned key values in the returned HashMaps. The
* HashMap array will be in the same order as the requested root keys.
*
* @param rootKeys These are the root values to be searched for in properties. If you do not
* want all of the returned keys to start with a period (.), you must include
* the period in this parameter.
* @return Returns an array of HashMaps containing all of the respective values found. If no
* values were found, the respective HashMaps will be empty.
*/
public HashMap<String, String>[] getAllByRootKey(String... rootKeys) {
HashMap<String, String>[] returnValues = new HashMap[rootKeys.length];
for (int i = 0; i < returnValues.length; i++) {
returnValues[i] = new HashMap<>();
}
Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
for (int i = 0; i < returnValues.length; i++) {
if (key.startsWith(rootKeys[i])) {
String value = properties.getProperty(key);
returnValues[i].put(key.substring(rootKeys[i].length()), value);
}
}
}
return returnValues;
}
/**
* Returns all properties for each common root key in an the same HashMap.
* <p/>
* The root key will be removed from the returned key values in the returned HashMap. The
* HashMap will be overwrite entries in the same order as the requested root keys.
*
* @param rootKeys These are the root values to be searched for in properties. If you do not
* want all of the returned keys to start with a period (.), you must include
* the period in this parameter.
* @return Returns a HashMap containing all of the values found. If no values were found, the
* HashMap will be empty.
*/
public HashMap<String, String> mergeAllByRootKeys(String... rootKeys) {
HashMap<String, String> returnValue = new HashMap<>();
for (String rootKey : rootKeys) {
for (Map.Entry<Object, Object> name : properties.entrySet()) {
String key = (String) name.getKey();
if (key.startsWith(rootKey)) {
String putKey = key.substring(rootKey.length());
String value = (String) name.getValue();
if (logger.isDebugEnabled()) {
String oldValue = returnValue.get(putKey);
if (oldValue != null) {
logger.debug("'{}' overrides '{}' from '{}' to '{}'", rootKey, putKey, oldValue, value);
}
}
returnValue.put(putKey, value);
}
}
}
return returnValue;
}
/**
* Removes all properties with a common root key.
*
* @param rootKey This is the root value to use for removal.
*/
public void removeAllByRootKey(String rootKey) {
ArrayList<String> removes = new ArrayList<String>();
Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
if (key.startsWith(rootKey)) {
removes.add(key);
}
}
for(String remove : removes) {
properties.remove(remove);
}
}
}
|
src/main/java/opendct/config/ConfigBag.java
|
/*
* Copyright 2015 The OpenDCT Authors. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opendct.config;
import opendct.config.options.DeviceOption;
import opendct.config.options.DeviceOptionException;
import opendct.config.options.IntegerDeviceOption;
import opendct.util.Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.net.InetAddress;
import java.util.*;
public class ConfigBag {
private static final Logger logger = LogManager.getLogger(ConfigBag.class);
public final String CONFIG_NAME;
public final String CONFIG_CATEGORY;
public final String FILE_NAME;
public final String DIR_NAME;
private final Properties properties;
private final boolean setOnGet;
public ConfigBag(String configName, boolean setOnGet) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = "";
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + configName + ".properties";
DIR_NAME = Config.getConfigDirectory();
this.setOnGet = setOnGet;
properties = new Properties();
}
public ConfigBag(String configName, boolean setOnGet, Properties properties) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = "";
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + configName + ".properties";
DIR_NAME = Config.getConfigDirectory();
this.setOnGet = setOnGet;
this.properties = properties;
}
public ConfigBag(String configName, String category, boolean setOnGet) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = category;
DIR_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category;
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category +
Config.DIR_SEPARATOR + configName + ".properties";
this.setOnGet = setOnGet;
properties = new Properties();
}
public ConfigBag(String configName, String category, boolean setOnGet, Properties properties) {
CONFIG_NAME = configName;
CONFIG_CATEGORY = category;
DIR_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category;
FILE_NAME = Config.getConfigDirectory() + Config.DIR_SEPARATOR + category +
Config.DIR_SEPARATOR + configName + ".properties";
this.setOnGet = setOnGet;
this.properties = properties;
}
/**
* Loads the configuration from the pre-defined configuration directory.
* <p/>
* The filename is created based on the value of <b>CONFIG_NAME</b>.
*
* @return <i>true</i> if the configuration was loaded successfully or if the configuration is new.
*/
public synchronized boolean loadConfig() {
logger.entry();
if (Config.getConfigDirectory() == null) {
logger.fatal("The configuration directory must be defined before any properties can be loaded.");
return logger.exit(false);
} else if (!Util.createDirectory(DIR_NAME)) {
logger.fatal("Unable to create required directories.");
return logger.exit(false);
}
if (new File(FILE_NAME).exists()) {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(FILE_NAME);
} catch (FileNotFoundException e) {
logger.fatal("Unable to open the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
properties.clear();
try {
properties.load(fileInputStream);
} catch (IOException e) {
logger.fatal("Unable to read the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
} else {
logger.info("'{}' was not found. A new configuration file will be created with that name on the next save.", FILE_NAME);
}
return logger.exit(true);
}
/**
* Clears the current configuration.
*/
public synchronized void clearConfig() {
logger.entry();
logger.debug("Clearing '{}' configuration...", CONFIG_NAME);
properties.clear();
logger.exit();
}
/**
* Sorts the properties alphabetically, then saves them.
*
* @return <i>true</i> if the properties were successfully saved.
*/
public synchronized boolean saveConfig() {
logger.entry();
if (Config.getConfigDirectory() == null) {
logger.fatal("The configuration directory must be defined before any properties can be saved.");
return logger.exit(false);
} else if (!Util.createDirectory(DIR_NAME)) {
logger.fatal("Unable to create required directories.");
return logger.exit(false);
}
File file = new File(FILE_NAME);
File fileBackup = new File(FILE_NAME + ".backup");
try {
Util.copyFile(file, fileBackup, true);
} catch (IOException e) {
file.renameTo(fileBackup);
}
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(FILE_NAME);
} catch (FileNotFoundException e) {
logger.error("Unable to open the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
try {
Properties sortedProperties = new Properties() {
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
sortedProperties.putAll(properties);
sortedProperties.store(fileOutputStream, CONFIG_NAME + " Configuration File");
fileOutputStream.close();
} catch (IOException e) {
logger.error("Unable to write the configuration file '{}' => {}", FILE_NAME, e);
return logger.exit(false);
}
return logger.exit(true);
}
// This will be used to set all string properties so we can do trace logging if there is any
// configuration related weirdness.
public void setString(String key, String value) {
logger.entry(key, value);
properties.setProperty(key, value);
logger.exit();
}
// This will be used to request all string properties so we can do trace logging if there is
// any configuration related weirdness.
public String getString(String key, String defaultValue) {
logger.entry(key, defaultValue);
String returnValue = properties.getProperty(key, defaultValue);
if (setOnGet) {
setString(key, returnValue);
}
return logger.exit(returnValue);
}
public String getString(String key) {
logger.entry(key);
String returnValue = properties.getProperty(key);
return logger.exit(returnValue);
}
public void setBoolean(String key, boolean value) {
logger.entry(key, value);
properties.setProperty(key, Boolean.toString(value));
logger.exit();
}
public void setShort(String key, short value) {
logger.entry(key, value);
properties.setProperty(key, Short.toString(value));
logger.exit();
}
public void setInteger(String key, int value) {
logger.entry(key, value);
properties.setProperty(key, Integer.toString(value));
logger.exit();
}
public void setLong(String key, long value) {
logger.entry(key, value);
properties.setProperty(key, Long.toString(value));
logger.exit();
}
public void setFloat(String key, float value) {
logger.entry(key, value);
properties.setProperty(key, Float.toString(value));
logger.exit();
}
public void setDouble(String key, double value) {
logger.entry(key, value);
properties.setProperty(key, Double.toString(value));
logger.exit();
}
public boolean getBoolean(String key, boolean defaultValue) {
logger.entry(key, defaultValue);
boolean returnValue = defaultValue;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
try {
returnValue = Boolean.valueOf(stringValue.toLowerCase());
} catch (Exception e) {
logger.error("The property '{}' should be boolean, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setBoolean(key, returnValue);
}
return logger.exit(returnValue);
}
public short getShort(String key, short defaultValue) {
logger.entry(key, defaultValue);
short returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
try {
returnValue = Short.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a short, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setShort(key, returnValue);
}
return logger.exit(returnValue);
}
public int getInteger(String key, int defaultValue) {
logger.entry(key, defaultValue);
int returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Integer.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be an integer, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setInteger(key, returnValue);
}
return logger.exit(returnValue);
}
public long getLong(String key, long defaultValue) {
logger.entry(key, defaultValue);
long returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Long.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a long, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setLong(key, returnValue);
}
return logger.exit(returnValue);
}
public float getFloat(String key, float defaultValue) {
logger.entry(key, defaultValue);
float returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Float.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a float, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setFloat(key, returnValue);
}
return logger.exit(returnValue);
}
public double getDouble(String key, double defaultValue) {
logger.entry(key, defaultValue);
double returnValue = 0;
String stringValue = properties.getProperty(key, String.valueOf(defaultValue));
;
try {
returnValue = Double.valueOf(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be a float, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue);
returnValue = defaultValue;
}
if (setOnGet) {
setDouble(key, returnValue);
}
return logger.exit(returnValue);
}
public String[] getStringArray(String key, String... defaultValues) {
logger.entry();
String returnValue[];
String stringValue;
if ((stringValue = properties.getProperty(key)) != null) {
if (stringValue.equals("")) {
returnValue = new String[0];
} else {
// The parsing regex will tolerate white space between commas.
returnValue = stringValue.split("\\s*,\\s*");
}
} else {
StringBuilder mergedArray = new StringBuilder();
for (String value : defaultValues) {
mergedArray.append(value + ",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
if (setOnGet) {
properties.setProperty(key, mergedArray.toString());
}
returnValue = defaultValues;
}
return logger.exit(returnValue);
}
/**
* Gets a comma separated string array.
*
* @param key This is the property name.
* @param defaultValue This is the default value to be returned if the property does not already
* exist.
* @return This will return an empty array if the property is present, but does not contain
* anything. This will return <i>null</i> only if the property does not already exist
* and <b>defaultValue</b> was set to <i>null</i>.
*/
public String[] getStringArray(String key, String defaultValue) {
logger.entry(key, defaultValue);
String stringValue = properties.getProperty(key, defaultValue);
String returnValue[] = new String[0];
if (stringValue != null) {
if (!stringValue.equals("")) {
// The parsing regex will tolerate white space between commas.
returnValue = stringValue.split("\\s*,\\s*");
}
} else if (defaultValue == null) {
returnValue = null;
}
if (setOnGet) {
if (returnValue != null) {
setStringArray(key, returnValue);
} else {
setStringArray(key, "");
}
}
return logger.exit(returnValue);
}
public void setStringArray(String key, String... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (String value : values) {
mergedArray.append(value + ",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setIntegerArray(String key, int... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (int value : values) {
mergedArray.append(Integer.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setIntegerArray(String key, Integer... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (int value : values) {
mergedArray.append(Integer.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
/**
* This method will convert numbers with commas and hyphens into an array with all of the
* in-between numbers added.
*
* @param key This is the property name.
* @param defaultValues This is returns if this property is not yet defined.
* @return The fully expanded integer array.
*/
public int[] getIntegerRanges(String key, int... defaultValues) {
logger.entry(key, defaultValues);
int returnValue[] = defaultValues;
// Be sure to use the getStringArray() method that supports null.
String values[] = getStringArray(key, (String) null);
boolean errors = false;
if (values != null) {
ArrayList<Integer> intArray = new ArrayList<Integer>();
for (String value : values) {
// Ensure that the hyphen is not just the start of a negative number.
if (value.lastIndexOf("-") > 0) {
// The parsing regex will tolerate white space between the integers and the hyphen and allows for negative numbers.
String split[] = value.split("[0-9]*\\s*-\\s*[-0-9]*");
// You could have multiple hyphens, but why?
if (split.length > 1) {
int start;
int end;
try {
start = Integer.valueOf(split[0]);
} catch (Exception e) {
logger.error("The property '{}' should be an integer range beginning, but '{}' was returned. Using the default value of '{}'", key, split[0], defaultValues);
errors = true;
break;
}
try {
end = Integer.valueOf(split[split.length - 1]);
} catch (Exception e) {
logger.error("The property '{}' should be an integer range ending, but '{}' was returned. Using the default value of '{}'", key, split[split.length - 1], defaultValues);
errors = true;
break;
}
if (start > end) {
errors = true;
break;
}
// The range is inclusive.
for (int i = start; i <= end; i++) {
intArray.add(i);
}
} else {
logger.error("The property '{}' should be an integer range, but '{}' was returned. Using the default value of '{}'", key, value, defaultValues);
errors = true;
break;
}
} else {
try {
intArray.add(Integer.valueOf(value));
} catch (Exception e) {
logger.error("The property '{}' should be an integer, but '{}' was returned. Using the default value of '{}'", key, value, defaultValues);
errors = true;
break;
}
}
}
returnValue = new int[intArray.size()];
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = intArray.get(i);
}
}
if (errors) {
returnValue = defaultValues;
}
if (setOnGet) {
setIntegerRanges(key, returnValue);
}
return logger.exit(returnValue);
}
/**
* This method will sort an array of integers and replace contiguous ranges with the first and
* last number of the range with a hyphen in-between.
* <p/>
* Ex. 507,508,509,513 becomes 507-509,513.
*
* @param key This is the property name.
* @param values The fully expanded integer array.
*/
public void setIntegerRanges(String key, int... values) {
StringBuilder mergedArray = new StringBuilder();
Arrays.sort(values);
for (int i = 0; i < values.length; i++) {
int start = values[i];
int end = values[i];
int index = 0;
while (start + index == values[i + index]) {
end = values[i + index++];
if (i + index > values.length) {
break;
}
}
// If the ranges are more than two integers apart, use a hyphen otherwise it looks a
// little odd.
if (end - start > 1) {
mergedArray.append(start + "-" + end + ",");
i += end - start;
} else {
mergedArray.append(start + ",");
}
}
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
}
public void setLongArray(String key, long... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (long value : values) {
mergedArray.append(Long.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setLongArray(String key, Long... values) {
logger.entry(key, values);
StringBuilder mergedArray = new StringBuilder();
for (Long value : values) {
mergedArray.append(Long.toString(value));
mergedArray.append(",");
}
// Remove the extra comma at the end.
if (mergedArray.length() > 0) {
mergedArray.deleteCharAt(mergedArray.length() - 1);
}
properties.setProperty(key, mergedArray.toString());
logger.exit();
}
public void setInetAddress(String key, InetAddress value) {
logger.entry(key, value);
properties.setProperty(key, value.getHostAddress());
logger.exit();
}
public InetAddress getInetAddress(String key, InetAddress defaultValue) {
logger.entry(key, defaultValue);
InetAddress returnValue = null;
String stringValue = properties.getProperty(key, defaultValue.getHostAddress());
try {
returnValue = InetAddress.getByName(stringValue);
} catch (Exception e) {
logger.error("The property '{}' should be an IP address, but '{}' was returned. Using the default value of '{}'", key, stringValue, defaultValue.getHostAddress());
returnValue = defaultValue;
}
if (setOnGet) {
setInetAddress(key, returnValue);
}
return logger.exit(returnValue);
}
public InetAddress[] getInetAddressArray(String key, InetAddress... defaultValue) {
logger.entry(key, defaultValue);
InetAddress returnValue[];
String defaultValueString[] = new String[defaultValue.length];
for(int i = 0; i < defaultValueString.length; i++) {
defaultValueString[i] = defaultValue[i].getHostAddress();
}
String returnValueString[] = getStringArray(key, defaultValueString);
returnValue = new InetAddress[returnValueString.length];
try {
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = InetAddress.getByName(returnValueString[i]);
}
} catch (Exception e) {
logger.error("The property '{}' should be an IP addresses, but '{}' was returned. Using the default values of '{}'", key, returnValueString, defaultValueString);
returnValue = defaultValue;
}
if (setOnGet) {
defaultValueString = new String[returnValue.length];
for(int i = 0; i < defaultValueString.length; i++) {
defaultValueString[i] = returnValue[i].getHostAddress();
}
setStringArray(key, defaultValueString);
}
return logger.exit(returnValue);
}
public void setDeviceOption(DeviceOption option) throws DeviceOptionException {
if (option.isArray()) {
setStringArray(option.getProperty(), option.getArrayValue());
} else {
setString(option.getProperty(), option.getValue());
}
switch (option.getType()) {
case INTEGER:
if (option.isArray()) {
if (option instanceof IntegerDeviceOption) {
setIntegerRanges(option.getProperty(), ((IntegerDeviceOption) option).getIntegerArray());
} else {
setStringArray(option.getProperty(), option.getArrayValue());
}
} else {
setString(option.getProperty(), option.getValue());
}
break;
default:
if (option.isArray()) {
setStringArray(option.getProperty(), option.getArrayValue());
} else {
setString(option.getProperty(), option.getValue());
}
break;
}
}
/**
* Returns all properties with a common root key as a HashMap.
* <p/>
* The root key will be removed from the returned key values in the returned HashMap.
*
* @param rootKey This is the root value to be searched for in properties. If you do not want
* all of the returned keys to start with a period (.), you must include the
* period in this parameter.
* @return Returns a HashMap containing all of the values found. If no values were found, the
* HashMap will be empty.
*/
public HashMap<String, String> getAllByRootKey(String rootKey) {
HashMap<String, String> returnValue = new HashMap<String, String>();
Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
if (key.startsWith(rootKey)) {
String value = properties.getProperty(key);
returnValue.put(key.substring(rootKey.length()), value);
}
}
return returnValue;
}
/**
* Removes all properties with a common root key.
*
* @param rootKey This is the root value to use for removal.
*/
public void removeAllByRootKey(String rootKey) {
ArrayList<String> removes = new ArrayList<String>();
Enumeration names = properties.propertyNames();
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
if (key.startsWith(rootKey)) {
removes.add(key);
}
}
for(String remove : removes) {
properties.remove(remove);
}
}
}
|
Added new ways to get collections of properties.
|
src/main/java/opendct/config/ConfigBag.java
|
Added new ways to get collections of properties.
|
|
Java
|
apache-2.0
|
8d44e8751222579aa2f4472abc77d595e69ba9fc
| 0
|
lanen/gdx-ai,printedheart/gdx-ai,domokato/gdx-ai,kishorpv/gdx-ai,pizcogirl/gdx-ai,libgdx/gdx-ai,zgpxgame/gdx-ai,piotr-j/gdx-ai
|
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.ai.fma;
import com.badlogic.gdx.math.Vector;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BooleanArray;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** {@code SoftRoleSlotAssignmentStrategy} is a concrete implementation of {@link BoundedSlotAssignmentStrategy} that supports soft
* roles, i.e. roles that can be broken. Rather than a member having a list of roles it can fulfill, it has a set of values
* representing how difficult it would find it to fulfill every role. The value is known as the slot cost. To make a slot
* impossible for a member to fill, its slot cost should be infinite (you can even set a threshold to ignore all slots whose cost
* is too high; this will reduce computation time when several costs are exceeding). To make a slot ideal for a member, its slot
* cost should be zero. We can have different levels of unsuitable assignment for one member.
* <p>
* Slot costs do not necessarily have to depend only on the member and the slot roles. They can be generalized to include any
* difficulty a member might have in taking up a slot. If a formation is spread out, for example, a member may choose a slot that
* is close by over a more distant slot. Distance can be directly used as a slot cost.
* <p>
* <b>IMPORTANT NOTES:</b>
* <ul>
* <li>In order for the algorithm to work properly the slot costs can not be negative.</li>
* <li>This algorithm is often not fast enough to be used regularly. However, slot assignment happens relatively seldom (when the
* player selects a new pattern, for example, or adds a member to the formation, or a member is removed from the formation).</li>
* </ul>
*
* @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface
*
* @author davebaol */
public class SoftRoleSlotAssignmentStrategy<T extends Vector<T>> extends BoundedSlotAssignmentStrategy<T> {
protected SlotCostProvider<T> slotCostProvider;
protected float costThreshold;
private BooleanArray filledSlots;
/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and no cost threshold.
* @param slotCostProvider the slot cost provider */
public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider) {
this(slotCostProvider, Float.POSITIVE_INFINITY);
}
/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and cost threshold.
* @param slotCostProvider the slot cost provider
* @param costThreshold is a slot-cost limit, beyond which a slot is considered to be too expensive to consider occupying. */
public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider, float costThreshold) {
this.slotCostProvider = slotCostProvider;
this.costThreshold = costThreshold;
this.filledSlots = new BooleanArray();
}
@Override
public void updateSlotAssignments (Array<SlotAssignment<T>> assignments) {
// Holds a list of member and slot data for each member.
Array<MemberAndSlots<T>> memberData = new Array<MemberAndSlots<T>>();
// Compile the member data
int numberOfAssignments = assignments.size;
for (int i = 0; i < numberOfAssignments; i++) {
SlotAssignment<T> assignment = assignments.get(i);
// Create a new member datum, and fill it
MemberAndSlots<T> datum = new MemberAndSlots<T>(assignment.member);
// Add each valid slot to it
for (int j = 0; j < numberOfAssignments; j++) {
// Get the cost of the slot
float cost = slotCostProvider.getCost(assignment.member, j);
// Make sure the slot is valid
if (cost >= costThreshold) continue;
SlotAssignment<T> slot = assignments.get(j);
// Store the slot information
CostAndSlot<T> slotDatum = new CostAndSlot<T>(cost, slot.slotNumber);
datum.costAndSlots.add(slotDatum);
// Add it to the member's ease of assignment
datum.assignmentEase += 1f / (1f + cost);
}
// Add member datum
memberData.add(datum);
}
// Reset the array to keep track of which slots we have already filled.
if (numberOfAssignments > filledSlots.size) filledSlots.ensureCapacity(numberOfAssignments - filledSlots.size);
filledSlots.size = numberOfAssignments;
for (int i = 0; i < numberOfAssignments; i++)
filledSlots.set(i, false);
// Arrange members in order of ease of assignment, with the least easy first.
memberData.sort();
MEMBER_LOOP:
for (int i = 0; i < memberData.size; i++) {
MemberAndSlots<T> memberDatum = memberData.get(i);
// Choose the first slot in the list that is still empty (non-filled)
memberDatum.costAndSlots.sort();
int m = memberDatum.costAndSlots.size;
for (int j = 0; j < m; j++) {
int slotNumber = memberDatum.costAndSlots.get(j).slotNumber;
// Check if this slot is valid
if (!filledSlots.get(slotNumber)) {
// Fill this slot
SlotAssignment<T> slot = assignments.get(slotNumber);
slot.member = memberDatum.member;
slot.slotNumber = slotNumber;
// Reserve the slot
filledSlots.set(slotNumber, true);
// Go to the next member
continue MEMBER_LOOP;
}
}
// If we reach here, it's because a member has no valid assignment.
//
// TODO
// Some sensible action should be taken, such as reporting to the player.
throw new GdxRuntimeException("SoftRoleSlotAssignmentStrategy cannot find valid slot assignment for member "
+ memberDatum.member);
}
}
static class CostAndSlot<T extends Vector<T>> implements Comparable<CostAndSlot<T>> {
float cost;
int slotNumber;
public CostAndSlot (float cost, int slotNumber) {
this.cost = cost;
this.slotNumber = slotNumber;
}
@Override
public int compareTo (CostAndSlot<T> other) {
return cost < other.cost ? -1 : (cost > other.cost ? 1 : 0);
}
}
static class MemberAndSlots<T extends Vector<T>> implements Comparable<MemberAndSlots<T>> {
FormationMember<T> member;
float assignmentEase;
Array<CostAndSlot<T>> costAndSlots;
public MemberAndSlots (FormationMember<T> member) {
this.member = member;
this.assignmentEase = 0f;
this.costAndSlots = new Array<CostAndSlot<T>>();
}
@Override
public int compareTo (MemberAndSlots<T> other) {
return assignmentEase < other.assignmentEase ? -1 : (assignmentEase > other.assignmentEase ? 1 : 0);
}
}
public interface SlotCostProvider<T extends Vector<T>> {
public float getCost (FormationMember<T> member, int slotNumber);
}
}
|
gdx-ai/src/com/badlogic/gdx/ai/fma/SoftRoleSlotAssignmentStrategy.java
|
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.ai.fma;
import com.badlogic.gdx.math.Vector;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BooleanArray;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** {@code SoftRoleSlotAssignmentStrategy} is a concrete implementation of {@link BoundedSlotAssignmentStrategy} that supports soft
* roles, i.e. roles that can be broken. Rather than a member having a list of roles it can fulfill, it has a set of values
* representing how difficult it would find it to fulfill every role. The value is known as the slot cost. To make a slot
* impossible for a member to fill, its slot cost should be infinite (you can even set a threshold to ignore all slots whose cost
* is too high; this will reduce computation time when several costs are exceeding). To make a slot ideal for a member, its slot
* cost should be zero. We can have different levels of unsuitable assignment for one member.
* <p>
* Slot costs do not necessarily have to depend only on the member and the slot roles. They can be generalized to include any
* difficulty a member might have in taking up a slot. If a formation is spread out, for example, a member may choose a slot that
* is close by over a more distant slot. Distance can be directly used as a slot cost.
* <p>
* <b>IMPORTANT NOTES:</b>
* <ul>
* <li>In order for the algorithm to work properly the slot costs can not be negative.</li>
* <li>This algorithm is often not fast enough to be used regularly. However, slot assignment happens relatively seldom (when the
* player selects a new pattern, for example, or adds a member to the formation, or a member is removed from the formation).</li>
* </ul>
*
* @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface
*
* @author davebaol */
public class SoftRoleSlotAssignmentStrategy<T extends Vector<T>> extends BoundedSlotAssignmentStrategy<T> {
protected SlotCostProvider<T> slotCostProvider;
protected float costThreshold;
private BooleanArray filledSlots;
/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and no cost threshold.
* @param slotCostProvider the slot cost provider */
public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider) {
this(slotCostProvider, Float.POSITIVE_INFINITY);
}
/** Creates a {@code SoftRoleSlotAssignmentStrategy} with the given slot cost provider and cost threshold.
* @param slotCostProvider the slot cost provider
* @param costThreshold the cost threshold */
public SoftRoleSlotAssignmentStrategy (SlotCostProvider<T> slotCostProvider, float costThreshold) {
this.slotCostProvider = slotCostProvider;
this.costThreshold = costThreshold;
this.filledSlots = new BooleanArray();
}
@Override
public void updateSlotAssignments (Array<SlotAssignment<T>> assignments) {
// Holds a list of member and slot data for each member.
Array<MemberAndSlots<T>> memberData = new Array<MemberAndSlots<T>>();
// Compile the member data
int numberOfAssignments = assignments.size;
for (int i = 0; i < numberOfAssignments; i++) {
SlotAssignment<T> assignment = assignments.get(i);
// Create a new member datum, and fill it
MemberAndSlots<T> datum = new MemberAndSlots<T>(assignment.member);
// Add each valid slot to it
for (int j = 0; j < numberOfAssignments; j++) {
// Get the cost of the slot
float cost = slotCostProvider.getCost(assignment.member, j);
// Make sure the slot is valid
if (cost >= costThreshold) continue;
SlotAssignment<T> slot = assignments.get(j);
// Store the slot information
CostAndSlot<T> slotDatum = new CostAndSlot<T>(cost, slot.slotNumber);
datum.costAndSlots.add(slotDatum);
// Add it to the member's ease of assignment
datum.assignmentEase += 1f / (1f + cost);
}
// Add member datum
memberData.add(datum);
}
// Reset the array to keep track of which slots we have already filled.
if (numberOfAssignments > filledSlots.size) filledSlots.ensureCapacity(numberOfAssignments - filledSlots.size);
filledSlots.size = numberOfAssignments;
for (int i = 0; i < numberOfAssignments; i++)
filledSlots.set(i, false);
// Arrange members in order of ease of assignment, with the least easy first.
memberData.sort();
MEMBER_LOOP:
for (int i = 0; i < memberData.size; i++) {
MemberAndSlots<T> memberDatum = memberData.get(i);
// Choose the first slot in the list that is still empty (non-filled)
memberDatum.costAndSlots.sort();
int m = memberDatum.costAndSlots.size;
for (int j = 0; j < m; j++) {
int slotNumber = memberDatum.costAndSlots.get(j).slotNumber;
// Check if this slot is valid
if (!filledSlots.get(slotNumber)) {
// Fill this slot
SlotAssignment<T> slot = assignments.get(slotNumber);
slot.member = memberDatum.member;
slot.slotNumber = slotNumber;
// Reserve the slot
filledSlots.set(slotNumber, true);
// Go to the next member
continue MEMBER_LOOP;
}
}
// If we reach here, it's because a member has no valid assignment.
//
// TODO
// Some sensible action should be taken, such as reporting to the player.
throw new GdxRuntimeException("SoftRoleSlotAssignmentStrategy cannot find valid slot assignment for member "
+ memberDatum.member);
}
}
public static class CostAndSlot<T extends Vector<T>> implements Comparable<CostAndSlot<T>> {
float cost;
int slotNumber;
public CostAndSlot (float cost, int slotNumber) {
this.cost = cost;
this.slotNumber = slotNumber;
}
@Override
public int compareTo (CostAndSlot<T> other) {
return cost < other.cost ? -1 : (cost > other.cost ? 1 : 0);
}
}
public static class MemberAndSlots<T extends Vector<T>> implements Comparable<MemberAndSlots<T>> {
FormationMember<T> member;
float assignmentEase;
Array<CostAndSlot<T>> costAndSlots;
public MemberAndSlots (FormationMember<T> member) {
this.member = member;
this.assignmentEase = 0f;
this.costAndSlots = new Array<CostAndSlot<T>>();
}
@Override
public int compareTo (MemberAndSlots<T> other) {
return assignmentEase < other.assignmentEase ? -1 : (assignmentEase > other.assignmentEase ? 1 : 0);
}
}
public interface SlotCostProvider<T extends Vector<T>> {
public float getCost (FormationMember<T> member, int slotNumber);
}
}
|
Minor changes
|
gdx-ai/src/com/badlogic/gdx/ai/fma/SoftRoleSlotAssignmentStrategy.java
|
Minor changes
|
|
Java
|
apache-2.0
|
f9f17e332305aaf1a1433d6fa2cc73f1a972ff34
| 0
|
ferstl/depgraph-maven-plugin
|
package com.github.ferstl.depgraph;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
/**
* JUnit tests for {@link DependencyNodeAdapter}.
*/
public class DependencyNodeAdapterTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void defaultResolutionFromArtifact() {
DependencyNodeAdapter adapter = new DependencyNodeAdapter(createArtifact());
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void defaultResolutionFromDependencyGraphNode() {
org.apache.maven.shared.dependency.graph.DependencyNode node =
new org.apache.maven.shared.dependency.graph.internal.DefaultDependencyNode(null, createArtifact(), "", "", "");
DependencyNodeAdapter adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void defaultResolutionFromDependencyTreeNode() {
org.apache.maven.shared.dependency.tree.DependencyNode node =
new org.apache.maven.shared.dependency.tree.DependencyNode(createArtifact());
DependencyNodeAdapter adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void resolutionFromDependencyTreeNode() {
Artifact artifact = createArtifact();
Artifact relatedArtifact = createArtifact();
org.apache.maven.shared.dependency.tree.DependencyNode node =
new org.apache.maven.shared.dependency.tree.DependencyNode(artifact, org.apache.maven.shared.dependency.tree.DependencyNode.OMITTED_FOR_CONFLICT, relatedArtifact);
DependencyNodeAdapter adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.OMMITTED_FOR_CONFLICT, adapter.getResolution());
node = new org.apache.maven.shared.dependency.tree.DependencyNode(artifact, org.apache.maven.shared.dependency.tree.DependencyNode.OMITTED_FOR_DUPLICATE, relatedArtifact);
adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.OMITTED_FOR_DUPLICATE, adapter.getResolution());
node = new org.apache.maven.shared.dependency.tree.DependencyNode(artifact, org.apache.maven.shared.dependency.tree.DependencyNode.OMITTED_FOR_CYCLE);
adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.OMMITTED_FOR_CYCLE, adapter.getResolution());
}
@Test
public void defaultCompileScope() {
Artifact artifact = createArtifact();
artifact.setScope(null);
DependencyNodeAdapter adapter = new DependencyNodeAdapter(artifact);
assertEquals("compile", adapter.getArtifact().getScope());
}
@Test
public void nullArtifact() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage(not(isEmptyString()));
new DependencyNodeAdapter((Artifact) null);
}
private Artifact createArtifact() {
return new DefaultArtifact("groupId", "artifactId", "1.0.0", "compile", "jar", "", null);
}
}
|
src/test/java/com/github/ferstl/depgraph/DependencyNodeAdapterTest.java
|
package com.github.ferstl.depgraph;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
/**
* JUnit tests for {@link DependencyNodeAdapter}.
*/
public class DependencyNodeAdapterTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void defaultResolutionFromArtifact() {
DependencyNodeAdapter adapter = new DependencyNodeAdapter(createArtifact());
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void defaultResolutionFromDependencyGraphNode() {
org.apache.maven.shared.dependency.graph.DependencyNode node =
new org.apache.maven.shared.dependency.graph.internal.DefaultDependencyNode(null, createArtifact(), "", "", "");
DependencyNodeAdapter adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void defaultResolutionFromDependencyTreeNode() {
org.apache.maven.shared.dependency.tree.DependencyNode node =
new org.apache.maven.shared.dependency.tree.DependencyNode(createArtifact());
DependencyNodeAdapter adapter = new DependencyNodeAdapter(node);
assertEquals(NodeResolution.INCLUDED, adapter.getResolution());
}
@Test
public void defaultCompileScope() {
Artifact artifact = createArtifact();
artifact.setScope(null);
DependencyNodeAdapter adapter = new DependencyNodeAdapter(artifact);
assertEquals("compile", adapter.getArtifact().getScope());
}
@Test
public void nullArtifact() {
this.expectedException.expect(NullPointerException.class);
this.expectedException.expectMessage(not(isEmptyString()));
new DependencyNodeAdapter((Artifact) null);
}
private Artifact createArtifact() {
return new DefaultArtifact("groupId", "artifactId", "1.0.0", "compile", "jar", "", null);
}
}
|
More tests
|
src/test/java/com/github/ferstl/depgraph/DependencyNodeAdapterTest.java
|
More tests
|
|
Java
|
apache-2.0
|
9721462232d59f64359f288bc6d4ecbf7ed0ed04
| 0
|
jagguli/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,izonder/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,kool79/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,signed/intellij-community,akosyakov/intellij-community,samthor/intellij-community,fnouama/intellij-community,slisson/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,allotria/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,semonte/intellij-community,holmes/intellij-community,diorcety/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,diorcety/intellij-community,vladmm/intellij-community,signed/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,retomerz/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,petteyg/intellij-community,kdwink/intellij-community,ernestp/consulo,nicolargo/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,fnouama/intellij-community,izonder/intellij-community,ryano144/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,izonder/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,fitermay/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,clumsy/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,fitermay/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,apixandru/intellij-community,apixandru/intellij-community,slisson/intellij-community,allotria/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,diorcety/intellij-community,semonte/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,holmes/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,supersven/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,caot/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,semonte/intellij-community,caot/intellij-community,clumsy/intellij-community,consulo/consulo,retomerz/intellij-community,xfournet/intellij-community,izonder/intellij-community,petteyg/intellij-community,ibinti/intellij-community,semonte/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,supersven/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,amith01994/intellij-community,FHannes/intellij-community,allotria/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,orekyuu/intellij-community,ernestp/consulo,petteyg/intellij-community,xfournet/intellij-community,hurricup/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,asedunov/intellij-community,dslomov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,izonder/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,FHannes/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,consulo/consulo,lucafavatella/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,amith01994/intellij-community,slisson/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,da1z/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,robovm/robovm-studio,akosyakov/intellij-community,signed/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,signed/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,hurricup/intellij-community,diorcety/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,consulo/consulo,Lekanich/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,caot/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,samthor/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,supersven/intellij-community,asedunov/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,supersven/intellij-community,Lekanich/intellij-community,allotria/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,apixandru/intellij-community,caot/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,petteyg/intellij-community,kool79/intellij-community,supersven/intellij-community,tmpgit/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,fitermay/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,slisson/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,samthor/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,salguarnieri/intellij-community,da1z/intellij-community,vladmm/intellij-community,da1z/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,vvv1559/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,slisson/intellij-community,caot/intellij-community,kdwink/intellij-community,slisson/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,retomerz/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ryano144/intellij-community,holmes/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,xfournet/intellij-community,robovm/robovm-studio,ibinti/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,allotria/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,kdwink/intellij-community,supersven/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,consulo/consulo,ibinti/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,samthor/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,robovm/robovm-studio,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,holmes/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,holmes/intellij-community,amith01994/intellij-community,apixandru/intellij-community,asedunov/intellij-community,allotria/intellij-community,retomerz/intellij-community,fnouama/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,supersven/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,allotria/intellij-community,allotria/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,slisson/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,da1z/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,samthor/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,slisson/intellij-community,supersven/intellij-community,semonte/intellij-community,wreckJ/intellij-community,caot/intellij-community,petteyg/intellij-community,kool79/intellij-community,fnouama/intellij-community,holmes/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,adedayo/intellij-community,kool79/intellij-community,ernestp/consulo,TangHao1987/intellij-community,adedayo/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,kool79/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,dslomov/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,FHannes/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,dslomov/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,blademainer/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,semonte/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,da1z/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,jagguli/intellij-community,diorcety/intellij-community,FHannes/intellij-community,allotria/intellij-community,da1z/intellij-community,supersven/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,blademainer/intellij-community,kool79/intellij-community,petteyg/intellij-community,caot/intellij-community,signed/intellij-community,signed/intellij-community,ryano144/intellij-community,asedunov/intellij-community,jagguli/intellij-community,izonder/intellij-community,supersven/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,holmes/intellij-community,adedayo/intellij-community,semonte/intellij-community,holmes/intellij-community,diorcety/intellij-community,semonte/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ernestp/consulo,samthor/intellij-community,slisson/intellij-community,blademainer/intellij-community,kool79/intellij-community,ibinti/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,adedayo/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,Lekanich/intellij-community
|
package org.jetbrains.jps.incremental;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.io.MappingFailedException;
import com.intellij.util.io.PersistentEnumerator;
import org.jetbrains.jps.*;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.RequestFuture;
import org.jetbrains.jps.artifacts.Artifact;
import org.jetbrains.jps.incremental.java.ExternalJavacDescriptor;
import org.jetbrains.jps.incremental.java.JavaBuilder;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import org.jetbrains.jps.incremental.messages.CompilerMessage;
import org.jetbrains.jps.incremental.messages.ProgressMessage;
import org.jetbrains.jps.incremental.storage.BuildDataManager;
import org.jetbrains.jps.incremental.storage.SourceToFormMapping;
import org.jetbrains.jps.incremental.storage.SourceToOutputMapping;
import org.jetbrains.jps.incremental.storage.TimestampStorage;
import org.jetbrains.jps.server.ProjectDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Zhuravlev
* Date: 9/17/11
*/
public class IncProjectBuilder {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.IncProjectBuilder");
public static final String COMPILE_SERVER_NAME = "COMPILE SERVER";
private final ProjectDescriptor myProjectDescriptor;
private final BuilderRegistry myBuilderRegistry;
private final Map<String, String> myBuilderParams;
private final CanceledStatus myCancelStatus;
private ProjectChunks myProductionChunks;
private ProjectChunks myTestChunks;
private final List<MessageHandler> myMessageHandlers = new ArrayList<MessageHandler>();
private final MessageHandler myMessageDispatcher = new MessageHandler() {
public void processMessage(BuildMessage msg) {
for (MessageHandler h : myMessageHandlers) {
h.processMessage(msg);
}
}
};
private float myModulesProcessed = 0.0f;
private final float myTotalModulesWork;
private final int myTotalModuleLevelBuilderCount;
public IncProjectBuilder(ProjectDescriptor pd, BuilderRegistry builderRegistry, Map<String, String> builderParams, CanceledStatus cs) {
myProjectDescriptor = pd;
myBuilderRegistry = builderRegistry;
myBuilderParams = builderParams;
myCancelStatus = cs;
myProductionChunks = new ProjectChunks(pd.project, ClasspathKind.PRODUCTION_COMPILE);
myTestChunks = new ProjectChunks(pd.project, ClasspathKind.TEST_COMPILE);
myTotalModulesWork = (float)pd.rootsIndex.getTotalModuleCount() * 2; /* multiply by 2 to reflect production and test sources */
myTotalModuleLevelBuilderCount = builderRegistry.getModuleLevelBuilderCount();
}
public void addMessageHandler(MessageHandler handler) {
myMessageHandlers.add(handler);
}
public void build(CompileScope scope, final boolean isMake, final boolean isProjectRebuild) {
CompileContext context = null;
try {
try {
context = createContext(scope, isMake, isProjectRebuild);
runBuild(context);
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause instanceof PersistentEnumerator.CorruptedException || cause instanceof MappingFailedException || cause instanceof IOException) {
// force rebuild
myMessageDispatcher.processMessage(new CompilerMessage(
COMPILE_SERVER_NAME, BuildMessage.Kind.INFO,
"Internal caches are corrupted or have outdated format, forcing project rebuild: " +
e.getMessage())
);
flushContext(context);
if (isMake || isProjectRebuild) {
context = createContext(new AllProjectScope(scope.getProject(), Collections.<Artifact>emptySet(), true), false, true);
}
else {
//in case of forced compilation keep the scope, but remove all caches
context = createContext(scope, false, false);
cleanOutputRoots(context);
}
runBuild(context);
}
else {
throw e;
}
}
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause == null) {
final String msg = e.getMessage();
if (!StringUtil.isEmpty(msg)) {
myMessageDispatcher.processMessage(new ProgressMessage(msg));
}
}
else {
myMessageDispatcher.processMessage(new CompilerMessage(COMPILE_SERVER_NAME, cause));
}
}
finally {
flushContext(context);
}
}
private static void flushContext(CompileContext context) {
if (context != null) {
context.getTimestampStorage().force();
context.getDataManager().flush(false);
}
final ExternalJavacDescriptor descriptor = ExternalJavacDescriptor.KEY.get(context);
if (descriptor != null) {
try {
final RequestFuture future = descriptor.client.sendShutdownRequest();
future.waitFor(500L, TimeUnit.MILLISECONDS);
}
finally {
// ensure process is not running
descriptor.process.destroyProcess();
}
ExternalJavacDescriptor.KEY.set(context, null);
}
cleanupJavacNameTable();
}
private static boolean ourClenupFailed = false;
private static void cleanupJavacNameTable() {
try {
if (JavaBuilder.USE_EMBEDDED_JAVAC && !ourClenupFailed) {
final Field freelistField = Class.forName("com.sun.tools.javac.util.Name$Table").getDeclaredField("freelist");
freelistField.setAccessible(true);
freelistField.set(null, com.sun.tools.javac.util.List.nil());
}
}
catch (Throwable e) {
ourClenupFailed = true;
LOG.info(e);
}
}
private float updateFractionBuilderFinished(final float delta) {
myModulesProcessed += delta;
return myModulesProcessed / myTotalModulesWork;
}
private void runBuild(CompileContext context) throws ProjectBuildException {
context.setDone(0.0f);
if (context.isProjectRebuild()) {
cleanOutputRoots(context);
}
context.processMessage(new ProgressMessage("Running 'before' tasks"));
runTasks(context, myBuilderRegistry.getBeforeTasks());
context.setCompilingTests(false);
context.processMessage(new ProgressMessage("Checking production sources"));
buildChunks(context, myProductionChunks);
context.setCompilingTests(true);
context.processMessage(new ProgressMessage("Checking test sources"));
buildChunks(context, myTestChunks);
context.processMessage(new ProgressMessage("Building project"));
runProjectLevelBuilders(context);
context.processMessage(new ProgressMessage("Running 'after' tasks"));
runTasks(context, myBuilderRegistry.getAfterTasks());
context.processMessage(new ProgressMessage("Finished, saving caches..."));
}
private CompileContext createContext(CompileScope scope, boolean isMake, final boolean isProjectRebuild) throws ProjectBuildException {
final TimestampStorage tsStorage = myProjectDescriptor.timestamps.getStorage();
final FSState fsState = myProjectDescriptor.fsState;
final ModuleRootsIndex rootsIndex = myProjectDescriptor.rootsIndex;
final BuildDataManager dataManager = myProjectDescriptor.dataManager;
return new CompileContext(
scope, isMake, isProjectRebuild, myProductionChunks, myTestChunks, fsState, dataManager, tsStorage, myMessageDispatcher, rootsIndex,
myBuilderParams, myCancelStatus
);
}
private void cleanOutputRoots(CompileContext context) throws ProjectBuildException {
// whole project is affected
try {
myProjectDescriptor.timestamps.clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning timestamps storage", e);
}
try {
context.getDataManager().clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning compiler storages", e);
}
myProjectDescriptor.fsState.onRebuild();
final Collection<Module> modulesToClean = context.getProject().getModules().values();
final Set<File> rootsToDelete = new HashSet<File>();
final Set<File> allSourceRoots = new HashSet<File>();
for (Module module : modulesToClean) {
final File out = context.getProjectPaths().getModuleOutputDir(module, false);
if (out != null) {
rootsToDelete.add(out);
}
final File testOut = context.getProjectPaths().getModuleOutputDir(module, true);
if (testOut != null) {
rootsToDelete.add(testOut);
}
final List<RootDescriptor> moduleRoots = context.getModuleRoots(module);
for (RootDescriptor d : moduleRoots) {
allSourceRoots.add(d.root);
}
}
// check that output and source roots are not overlapping
final List<File> filesToDelete = new ArrayList<File>();
for (File outputRoot : rootsToDelete) {
context.checkCanceled();
boolean okToDelete = true;
if (PathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = Collections.singleton(outputRoot);
for (File srcRoot : allSourceRoots) {
if (PathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
else {
context.processMessage(new CompilerMessage(COMPILE_SERVER_NAME, BuildMessage.Kind.WARNING, "Output path " + outputRoot.getPath() + " intersects with a source root. The output cannot be cleaned."));
}
}
context.processMessage(new ProgressMessage("Cleaning output directories..."));
FileUtil.asyncDelete(filesToDelete);
}
private static void runTasks(CompileContext context, final List<BuildTask> tasks) throws ProjectBuildException {
for (BuildTask task : tasks) {
task.build(context);
}
}
private void buildChunks(CompileContext context, ProjectChunks chunks) throws ProjectBuildException {
final CompileScope scope = context.getScope();
for (ModuleChunk chunk : chunks.getChunkList()) {
if (scope.isAffected(chunk)) {
buildChunk(context, chunk);
}
else {
final float fraction = updateFractionBuilderFinished(chunk.getModules().size());
context.setDone(fraction);
}
}
}
private void buildChunk(CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
try {
context.ensureFSStateInitialized(chunk);
if (context.isMake()) {
// cleanup outputs
final Set<String> allChunkRemovedSources = new HashSet<String>();
for (Module module : chunk.getModules()) {
final Collection<String> deletedPaths = myProjectDescriptor.fsState.getDeletedPaths(module, context.isCompilingTests());
if (deletedPaths.isEmpty()) {
continue;
}
allChunkRemovedSources.addAll(deletedPaths);
final String moduleName = module.getName().toLowerCase(Locale.US);
final SourceToOutputMapping sourceToOutputStorage =
context.getDataManager().getSourceToOutputMap(moduleName, context.isCompilingTests());
// actually delete outputs associated with removed paths
for (String deletedSource : deletedPaths) {
// deleting outputs corresponding to non-existing source
final Collection<String> outputs = sourceToOutputStorage.getState(deletedSource);
if (LOG.isDebugEnabled()) {
if (outputs.size() > 0) {
final String[] buffer = new String[outputs.size()];
int i = 0;
for (final String o : outputs) {
buffer[i++] = o;
}
Arrays.sort(buffer);
LOG.info("Cleaning output files:");
for(final String o : buffer) {
LOG.info(o);
}
LOG.info("End of files");
}
}
if (outputs != null) {
for (String output : outputs) {
FileUtil.delete(new File(output));
}
sourceToOutputStorage.remove(deletedSource);
}
// check if deleted source was associated with a form
final SourceToFormMapping sourceToFormMap = context.getDataManager().getSourceToFormMap();
final String formPath = sourceToFormMap.getState(deletedSource);
if (formPath != null) {
final File formFile = new File(formPath);
if (formFile.exists()) {
context.markDirty(formFile);
}
sourceToFormMap.remove(deletedSource);
}
}
}
Paths.CHUNK_REMOVED_SOURCES_KEY.set(context, allChunkRemovedSources);
for (Module module : chunk.getModules()) {
myProjectDescriptor.fsState.clearDeletedPaths(module, context.isCompilingTests());
}
}
context.onChunkBuildStart(chunk);
runModuleLevelBuilders(context, chunk);
}
catch (ProjectBuildException e) {
throw e;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
try {
for (BuilderCategory category : BuilderCategory.values()) {
for (ModuleLevelBuilder builder : myBuilderRegistry.getBuilders(category)) {
builder.cleanupResources(context, chunk);
}
}
}
finally {
try {
context.onChunkBuildComplete(chunk);
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
Paths.CHUNK_REMOVED_SOURCES_KEY.set(context, null);
}
}
}
}
private void runModuleLevelBuilders(final CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
boolean rebuildFromScratchRequested = false;
float stageCount = myTotalModuleLevelBuilderCount;
final int modulesInChunk = chunk.getModules().size();
int buildersPassed = 0;
boolean nextPassRequired;
CHUNK_BUILD_START:
do {
nextPassRequired = false;
context.beforeCompileRound(chunk);
if (!context.isProjectRebuild()) {
syncOutputFiles(context, chunk);
}
for (BuilderCategory category : BuilderCategory.values()) {
final List<ModuleLevelBuilder> builders = myBuilderRegistry.getBuilders(category);
if (builders.isEmpty()) {
continue;
}
for (ModuleLevelBuilder builder : builders) {
final ModuleLevelBuilder.ExitCode buildResult = builder.build(context, chunk);
if (buildResult == ModuleLevelBuilder.ExitCode.ABORT) {
throw new ProjectBuildException("Builder " + builder.getDescription() + " requested build stop");
}
context.checkCanceled();
if (buildResult == ModuleLevelBuilder.ExitCode.ADDITIONAL_PASS_REQUIRED) {
if (!nextPassRequired) {
// recalculate basis
myModulesProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount += myTotalModuleLevelBuilderCount;
myModulesProcessed += (buildersPassed * modulesInChunk) / stageCount;
}
nextPassRequired = true;
}
else if (buildResult == ModuleLevelBuilder.ExitCode.CHUNK_REBUILD_REQUIRED) {
if (!rebuildFromScratchRequested && !context.isProjectRebuild()) {
// allow rebuild from scratch only once per chunk
rebuildFromScratchRequested = true;
try {
// forcibly mark all files in the chunk dirty
context.markDirty(chunk);
// reverting to the beginning
myModulesProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount = myTotalModuleLevelBuilderCount;
buildersPassed = 0;
break CHUNK_BUILD_START;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
else {
LOG.info("Builder " + builder.getDescription() + " requested second chunk rebuild");
}
}
buildersPassed++;
final float fraction = updateFractionBuilderFinished(modulesInChunk / (stageCount));
context.setDone(fraction);
}
}
}
while (nextPassRequired);
}
private void runProjectLevelBuilders(CompileContext context) throws ProjectBuildException {
for (ProjectLevelBuilder builder : myBuilderRegistry.getProjectLevelBuilders()) {
builder.build(context);
context.checkCanceled();
}
}
private static void syncOutputFiles(final CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
final BuildDataManager dataManager = context.getDataManager();
final boolean compilingTests = context.isCompilingTests();
try {
final Collection<String> allOutputs = new LinkedList<String>();
context.processFilesToRecompile(chunk, new FileProcessor() {
private final Map<Module, SourceToOutputMapping> storageMap = new HashMap<Module, SourceToOutputMapping>();
@Override
public boolean apply(Module module, File file, String sourceRoot) throws IOException {
SourceToOutputMapping srcToOut = storageMap.get(module);
if (srcToOut == null) {
srcToOut = dataManager.getSourceToOutputMap(module.getName().toLowerCase(Locale.US), compilingTests);
storageMap.put(module, srcToOut);
}
final String srcPath = FileUtil.toSystemIndependentName(file.getPath());
final Collection<String> outputs = srcToOut.getState(srcPath);
if (outputs != null) {
for (String output : outputs) {
if (LOG.isDebugEnabled()) {
allOutputs.add(output);
}
FileUtil.delete(new File(output));
}
srcToOut.remove(srcPath);
}
return true;
}
});
if (LOG.isDebugEnabled()) {
if (context.isMake() && allOutputs.size() > 0) {
LOG.info("Cleaning output files:");
final String[] buffer = new String[allOutputs.size()];
int i = 0;
for (String output : allOutputs) {
buffer[i++] = output;
}
Arrays.sort(buffer);
for (String output : buffer) {
LOG.info(output);
}
LOG.info("End of files");
}
}
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
}
|
jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
|
package org.jetbrains.jps.incremental;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.io.MappingFailedException;
import com.intellij.util.io.PersistentEnumerator;
import org.jetbrains.jps.*;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.RequestFuture;
import org.jetbrains.jps.artifacts.Artifact;
import org.jetbrains.jps.incremental.java.ExternalJavacDescriptor;
import org.jetbrains.jps.incremental.java.JavaBuilder;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import org.jetbrains.jps.incremental.messages.CompilerMessage;
import org.jetbrains.jps.incremental.messages.ProgressMessage;
import org.jetbrains.jps.incremental.storage.BuildDataManager;
import org.jetbrains.jps.incremental.storage.SourceToFormMapping;
import org.jetbrains.jps.incremental.storage.SourceToOutputMapping;
import org.jetbrains.jps.incremental.storage.TimestampStorage;
import org.jetbrains.jps.server.ProjectDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Zhuravlev
* Date: 9/17/11
*/
public class IncProjectBuilder {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.IncProjectBuilder");
public static final String COMPILE_SERVER_NAME = "COMPILE SERVER";
private final ProjectDescriptor myProjectDescriptor;
private final BuilderRegistry myBuilderRegistry;
private final Map<String, String> myBuilderParams;
private final CanceledStatus myCancelStatus;
private ProjectChunks myProductionChunks;
private ProjectChunks myTestChunks;
private final List<MessageHandler> myMessageHandlers = new ArrayList<MessageHandler>();
private final MessageHandler myMessageDispatcher = new MessageHandler() {
public void processMessage(BuildMessage msg) {
for (MessageHandler h : myMessageHandlers) {
h.processMessage(msg);
}
}
};
private float myModulesProcessed = 0.0f;
private final float myTotalModulesWork;
private final int myTotalModuleLevelBuilderCount;
public IncProjectBuilder(ProjectDescriptor pd, BuilderRegistry builderRegistry, Map<String, String> builderParams, CanceledStatus cs) {
myProjectDescriptor = pd;
myBuilderRegistry = builderRegistry;
myBuilderParams = builderParams;
myCancelStatus = cs;
myProductionChunks = new ProjectChunks(pd.project, ClasspathKind.PRODUCTION_COMPILE);
myTestChunks = new ProjectChunks(pd.project, ClasspathKind.TEST_COMPILE);
myTotalModulesWork = (float)pd.rootsIndex.getTotalModuleCount() * 2; /* multiply by 2 to reflect production and test sources */
myTotalModuleLevelBuilderCount = builderRegistry.getModuleLevelBuilderCount();
}
public void addMessageHandler(MessageHandler handler) {
myMessageHandlers.add(handler);
}
public void build(CompileScope scope, final boolean isMake, final boolean isProjectRebuild) {
CompileContext context = null;
try {
try {
context = createContext(scope, isMake, isProjectRebuild);
runBuild(context);
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause instanceof PersistentEnumerator.CorruptedException || cause instanceof MappingFailedException || cause instanceof IOException) {
// force rebuild
myMessageDispatcher.processMessage(new CompilerMessage(
COMPILE_SERVER_NAME, BuildMessage.Kind.INFO,
"Internal caches are corrupted or have outdated format, forcing project rebuild: " +
e.getMessage())
);
flushContext(context);
if (isMake || isProjectRebuild) {
context = createContext(new AllProjectScope(scope.getProject(), Collections.<Artifact>emptySet(), true), false, true);
}
else {
//in case of forced compilation keep the scope, but remove all caches
context = createContext(scope, false, false);
cleanOutputRoots(context);
}
runBuild(context);
}
else {
throw e;
}
}
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause == null) {
final String msg = e.getMessage();
if (!StringUtil.isEmpty(msg)) {
myMessageDispatcher.processMessage(new ProgressMessage(msg));
}
}
else {
myMessageDispatcher.processMessage(new CompilerMessage(COMPILE_SERVER_NAME, cause));
}
}
finally {
flushContext(context);
}
}
private static void flushContext(CompileContext context) {
if (context != null) {
context.getTimestampStorage().force();
context.getDataManager().flush(false);
}
final ExternalJavacDescriptor descriptor = ExternalJavacDescriptor.KEY.get(context);
if (descriptor != null) {
try {
final RequestFuture future = descriptor.client.sendShutdownRequest();
future.waitFor(500L, TimeUnit.MILLISECONDS);
}
finally {
// ensure process is not running
descriptor.process.destroyProcess();
}
ExternalJavacDescriptor.KEY.set(context, null);
}
cleanupJavacNameTable();
}
private static boolean ourClenupFailed = false;
private static void cleanupJavacNameTable() {
try {
if (JavaBuilder.USE_EMBEDDED_JAVAC && !ourClenupFailed) {
final Field freelistField = Class.forName("com.sun.tools.javac.util.Name$Table").getDeclaredField("freelist");
freelistField.setAccessible(true);
freelistField.set(null, com.sun.tools.javac.util.List.nil());
}
}
catch (Throwable e) {
ourClenupFailed = true;
LOG.info(e);
}
}
private float updateFractionBuilderFinished(final float delta) {
myModulesProcessed += delta;
return myModulesProcessed / myTotalModulesWork;
}
private void runBuild(CompileContext context) throws ProjectBuildException {
context.setDone(0.0f);
if (context.isProjectRebuild()) {
cleanOutputRoots(context);
}
context.processMessage(new ProgressMessage("Running 'before' tasks"));
runTasks(context, myBuilderRegistry.getBeforeTasks());
context.setCompilingTests(false);
context.processMessage(new ProgressMessage("Checking production sources"));
buildChunks(context, myProductionChunks);
context.setCompilingTests(true);
context.processMessage(new ProgressMessage("Checking test sources"));
buildChunks(context, myTestChunks);
context.processMessage(new ProgressMessage("Building project"));
runProjectLevelBuilders(context);
context.processMessage(new ProgressMessage("Running 'after' tasks"));
runTasks(context, myBuilderRegistry.getAfterTasks());
context.processMessage(new ProgressMessage("Finished, saving caches..."));
}
private CompileContext createContext(CompileScope scope, boolean isMake, final boolean isProjectRebuild) throws ProjectBuildException {
final TimestampStorage tsStorage = myProjectDescriptor.timestamps.getStorage();
final FSState fsState = myProjectDescriptor.fsState;
final ModuleRootsIndex rootsIndex = myProjectDescriptor.rootsIndex;
final BuildDataManager dataManager = myProjectDescriptor.dataManager;
return new CompileContext(
scope, isMake, isProjectRebuild, myProductionChunks, myTestChunks, fsState, dataManager, tsStorage, myMessageDispatcher, rootsIndex,
myBuilderParams, myCancelStatus
);
}
private void cleanOutputRoots(CompileContext context) throws ProjectBuildException {
// whole project is affected
try {
myProjectDescriptor.timestamps.clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning timestamps storage", e);
}
try {
context.getDataManager().clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning compiler storages", e);
}
myProjectDescriptor.fsState.onRebuild();
final Collection<Module> modulesToClean = context.getProject().getModules().values();
final Set<File> rootsToDelete = new HashSet<File>();
final Set<File> allSourceRoots = new HashSet<File>();
for (Module module : modulesToClean) {
final File out = context.getProjectPaths().getModuleOutputDir(module, false);
if (out != null) {
rootsToDelete.add(out);
}
final File testOut = context.getProjectPaths().getModuleOutputDir(module, true);
if (testOut != null) {
rootsToDelete.add(testOut);
}
final List<RootDescriptor> moduleRoots = context.getModuleRoots(module);
for (RootDescriptor d : moduleRoots) {
allSourceRoots.add(d.root);
}
}
// check that output and source roots are not overlapping
final List<File> filesToDelete = new ArrayList<File>();
for (File outputRoot : rootsToDelete) {
context.checkCanceled();
boolean okToDelete = true;
if (PathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = Collections.singleton(outputRoot);
for (File srcRoot : allSourceRoots) {
if (PathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
else {
context.processMessage(new CompilerMessage(COMPILE_SERVER_NAME, BuildMessage.Kind.WARNING, "Output path " + outputRoot.getPath() + " intersects with a source root. The output cannot be cleaned."));
}
}
context.processMessage(new ProgressMessage("Cleaning output directories..."));
FileUtil.asyncDelete(filesToDelete);
}
private static void runTasks(CompileContext context, final List<BuildTask> tasks) throws ProjectBuildException {
for (BuildTask task : tasks) {
task.build(context);
}
}
private void buildChunks(CompileContext context, ProjectChunks chunks) throws ProjectBuildException {
final CompileScope scope = context.getScope();
for (ModuleChunk chunk : chunks.getChunkList()) {
if (scope.isAffected(chunk)) {
buildChunk(context, chunk);
}
else {
final float fraction = updateFractionBuilderFinished(chunk.getModules().size());
context.setDone(fraction);
}
}
}
private void buildChunk(CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
try {
context.ensureFSStateInitialized(chunk);
if (context.isMake()) {
// cleanup outputs
final Set<String> allChunkRemovedSources = new HashSet<String>();
final SourceToFormMapping sourceToFormMap = context.getDataManager().getSourceToFormMap();
for (Module module : chunk.getModules()) {
final Collection<String> deletedPaths = myProjectDescriptor.fsState.getDeletedPaths(module, context.isCompilingTests());
allChunkRemovedSources.addAll(deletedPaths);
final String moduleName = module.getName().toLowerCase(Locale.US);
final SourceToOutputMapping sourceToOutputStorage =
context.getDataManager().getSourceToOutputMap(moduleName, context.isCompilingTests());
// actually delete outputs associated with removed paths
for (String deletedSource : deletedPaths) {
// deleting outputs corresponding to non-existing source
final Collection<String> outputs = sourceToOutputStorage.getState(deletedSource);
if (LOG.isDebugEnabled()) {
if (outputs.size() > 0) {
final String[] buffer = new String[outputs.size()];
int i = 0;
for (final String o : outputs) {
buffer[i++] = o;
}
Arrays.sort(buffer);
LOG.info("Cleaning output files:");
for(final String o : buffer) {
LOG.info(o);
}
LOG.info("End of files");
}
}
if (outputs != null) {
for (String output : outputs) {
FileUtil.delete(new File(output));
}
sourceToOutputStorage.remove(deletedSource);
}
// check if deleted source was associated with a form
final String formPath = sourceToFormMap.getState(deletedSource);
if (formPath != null) {
final File formFile = new File(formPath);
if (formFile.exists()) {
context.markDirty(formFile);
}
sourceToFormMap.remove(deletedSource);
}
}
}
Paths.CHUNK_REMOVED_SOURCES_KEY.set(context, allChunkRemovedSources);
for (Module module : chunk.getModules()) {
myProjectDescriptor.fsState.clearDeletedPaths(module, context.isCompilingTests());
}
}
context.onChunkBuildStart(chunk);
runModuleLevelBuilders(context, chunk);
}
catch (ProjectBuildException e) {
throw e;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
try {
for (BuilderCategory category : BuilderCategory.values()) {
for (ModuleLevelBuilder builder : myBuilderRegistry.getBuilders(category)) {
builder.cleanupResources(context, chunk);
}
}
}
finally {
try {
context.onChunkBuildComplete(chunk);
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
Paths.CHUNK_REMOVED_SOURCES_KEY.set(context, null);
}
}
}
}
private void runModuleLevelBuilders(final CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
boolean rebuildFromScratchRequested = false;
float stageCount = myTotalModuleLevelBuilderCount;
final int modulesInChunk = chunk.getModules().size();
int buildersPassed = 0;
boolean nextPassRequired;
CHUNK_BUILD_START:
do {
nextPassRequired = false;
context.beforeCompileRound(chunk);
if (!context.isProjectRebuild()) {
syncOutputFiles(context, chunk);
}
for (BuilderCategory category : BuilderCategory.values()) {
final List<ModuleLevelBuilder> builders = myBuilderRegistry.getBuilders(category);
if (builders.isEmpty()) {
continue;
}
for (ModuleLevelBuilder builder : builders) {
final ModuleLevelBuilder.ExitCode buildResult = builder.build(context, chunk);
if (buildResult == ModuleLevelBuilder.ExitCode.ABORT) {
throw new ProjectBuildException("Builder " + builder.getDescription() + " requested build stop");
}
context.checkCanceled();
if (buildResult == ModuleLevelBuilder.ExitCode.ADDITIONAL_PASS_REQUIRED) {
if (!nextPassRequired) {
// recalculate basis
myModulesProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount += myTotalModuleLevelBuilderCount;
myModulesProcessed += (buildersPassed * modulesInChunk) / stageCount;
}
nextPassRequired = true;
}
else if (buildResult == ModuleLevelBuilder.ExitCode.CHUNK_REBUILD_REQUIRED) {
if (!rebuildFromScratchRequested && !context.isProjectRebuild()) {
// allow rebuild from scratch only once per chunk
rebuildFromScratchRequested = true;
try {
// forcibly mark all files in the chunk dirty
context.markDirty(chunk);
// reverting to the beginning
myModulesProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount = myTotalModuleLevelBuilderCount;
buildersPassed = 0;
break CHUNK_BUILD_START;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
else {
LOG.info("Builder " + builder.getDescription() + " requested second chunk rebuild");
}
}
buildersPassed++;
final float fraction = updateFractionBuilderFinished(modulesInChunk / (stageCount));
context.setDone(fraction);
}
}
}
while (nextPassRequired);
}
private void runProjectLevelBuilders(CompileContext context) throws ProjectBuildException {
for (ProjectLevelBuilder builder : myBuilderRegistry.getProjectLevelBuilders()) {
builder.build(context);
context.checkCanceled();
}
}
private static void syncOutputFiles(final CompileContext context, ModuleChunk chunk) throws ProjectBuildException {
final BuildDataManager dataManager = context.getDataManager();
final boolean compilingTests = context.isCompilingTests();
try {
final Collection<String> allOutputs = new LinkedList<String>();
context.processFilesToRecompile(chunk, new FileProcessor() {
private final Map<Module, SourceToOutputMapping> storageMap = new HashMap<Module, SourceToOutputMapping>();
@Override
public boolean apply(Module module, File file, String sourceRoot) throws IOException {
SourceToOutputMapping srcToOut = storageMap.get(module);
if (srcToOut == null) {
srcToOut = dataManager.getSourceToOutputMap(module.getName().toLowerCase(Locale.US), compilingTests);
storageMap.put(module, srcToOut);
}
final String srcPath = FileUtil.toSystemIndependentName(file.getPath());
final Collection<String> outputs = srcToOut.getState(srcPath);
if (outputs != null) {
for (String output : outputs) {
if (LOG.isDebugEnabled()) {
allOutputs.add(output);
}
FileUtil.delete(new File(output));
}
srcToOut.remove(srcPath);
}
return true;
}
});
if (LOG.isDebugEnabled()) {
if (context.isMake() && allOutputs.size() > 0) {
LOG.info("Cleaning output files:");
final String[] buffer = new String[allOutputs.size()];
int i = 0;
for (String output : allOutputs) {
buffer[i++] = output;
}
Arrays.sort(buffer);
for (String output : buffer) {
LOG.info(output);
}
LOG.info("End of files");
}
}
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
}
|
optimization
|
jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
|
optimization
|
|
Java
|
apache-2.0
|
a5eaece61b7cb2b649e496a63a74253a226d5447
| 0
|
gbif/gbif-common-ws
|
package org.gbif.ws.security;
import org.gbif.ws.json.JacksonJsonContextResolver;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.core.MultivaluedMap;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The GBIF authentication scheme is modelled after the Amazon scheme on how to sign REST http requests
* using a private key. It uses the standard Http Authorization Header to transport the following information:
* Authorization: GBIF applicationKey:Signature
*
* <br/>
* The header starts with the authentication scheme (GBIF), followed by the plain applicationKey (the public key)
* and a unique signature for the very request which is generated using a fixed set of request attributes
* which are then encrypted by a standard HMAC-SHA1 algorithm.
*
* <br/>
* A POST request with a GBIF header would look like this:
*
* <pre>
* POST /dataset HTTP/1.1
* Host: johnsmith.s3.amazonaws.com
* Date: Mon, 26 Mar 2007 19:37:58 +0000
* x-gbif-user: trobertson
* Content-MD5: LiFThEP4Pj2TODQXa/oFPg==
* Authorization: GBIF gbif.portal:frJIUN8DYpKDtOLCwo//yllqDzg=
* </pre>
*
* When signing an http request in addition to the Authentication header some additional custom headers are added
* which are used to sign and digest the message.
* <br/>
* x-gbif-user is added to transport a proxied user in which the application is acting.
* <br/>
* Content-MD5 is added if a body entity exists.
* See Concent-MD5 header specs: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
*/
@Singleton
public class GbifAuthService {
private static final Logger LOG = LoggerFactory.getLogger(GbifAuthService.class);
private static final String ALGORITHM = "HmacSHA1";
private static final String CHAR_ENCODING = "UTF8";
public static final String HEADER_AUTHORIZATION = "Authorization";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_CONTENT_MD5 = "Content-MD5";
public static final String GBIF_SCHEME = "GBIF";
public static final String HEADER_GBIF_USER = "x-gbif-user";
public static final String HEADER_ORIGINAL_REQUEST_URL = "x-url";
private static final char NEWLINE = '\n';
private static final Pattern COLON_PATTERN = Pattern.compile(":");
private final ImmutableMap<String, String> keyStore;
private final String appKey;
private final ObjectMapper mapper = new JacksonJsonContextResolver().getContext(null);
private GbifAuthService(Map<String, String> appKeys, String appKey) {
keyStore = ImmutableMap.copyOf(appKeys);
this.appKey = appKey;
LOG.info("Initialised appkey store with {} keys", keyStore.size());
}
/**
* Creates a new GBIF authentication service for applications that need to validate requests
* for various application keys. Used by the GBIF webservice apps that require authentication.
*/
public static GbifAuthService multiKeyAuthService(Map<String, String> appKeys) {
return new GbifAuthService(appKeys, null);
}
/**
* Creates a new GBIF authentication service for clients that want to sign requests always using a single
* application key. Used by the GBIF portal and other trusted applications that need to proxy a user.
*/
public static GbifAuthService singleKeyAuthService(String appKey, String secret) {
LOG.info("Initialising auth service with key {}", appKey);
return new GbifAuthService(ImmutableMap.of(appKey, secret), appKey);
}
/**
* Extracts the information to be encrypted from a request and concatenates them into a single String.
* When the server receives an authenticated request, it compares the computed request signature
* with the signature provided in the request in StringToSign.
* For that reason this string may only contain information also available in the exact same form to the server.
*
* @return unique string for a request
*
* @see <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html">AWS Docs</a>
*/
private String buildStringToSign(ContainerRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getMethod());
sb.append(NEWLINE);
// custom header set by varnish overrides real URI
// see http://dev.gbif.org/issues/browse/GBIFCOM-137
if (request.getRequestHeaders().containsKey(HEADER_ORIGINAL_REQUEST_URL)) {
sb.append(request.getRequestHeaders().getFirst(HEADER_ORIGINAL_REQUEST_URL));
} else {
sb.append(getCanonicalizedPath(request.getRequestUri()));
}
appendHeader(sb, request.getRequestHeaders(), HEADER_CONTENT_TYPE, false);
appendHeader(sb, request.getRequestHeaders(), HEADER_CONTENT_MD5, true);
appendHeader(sb, request.getRequestHeaders(), HEADER_GBIF_USER, true);
return sb.toString();
}
/**
* Build the string to be signed for a client request by extracting header information from the request.
* For PUT/POST requests that contain a body content it is required that the Content-MD5 header
* is already present on the request instance!
*/
private String buildStringToSign(ClientRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getMethod());
sb.append(NEWLINE);
sb.append(getCanonicalizedPath(request.getURI()));
appendHeader(sb, request.getHeaders(), HEADER_CONTENT_TYPE, false);
appendHeader(sb, request.getHeaders(), HEADER_CONTENT_MD5, true);
appendHeader(sb, request.getHeaders(), HEADER_GBIF_USER, true);
return sb.toString();
}
private void appendHeader(StringBuilder sb, MultivaluedMap<String, ?> request, String header, boolean caseSensitive) {
if (request.containsKey(header)) {
sb.append(NEWLINE);
if (caseSensitive) {
sb.append(request.getFirst(header));
} else {
sb.append(request.getFirst(header).toString().toLowerCase());
}
}
}
/**
* @return an absolute uri of the resource path alone, excluding host, scheme and query parameters
*/
private String getCanonicalizedPath(URI uri) {
return uri.normalize().getPath();
}
private String buildAuthHeader(String applicationKey, String signature) {
return GBIF_SCHEME + " " + applicationKey + ":" + signature;
}
/**
* Generates a Base64 encoded HMAC-SHA1 signature of the passed in string with the given secret key.
* See Message Authentication Code specs http://tools.ietf.org/html/rfc2104
* @param stringToSign the string to be signed
* @param secretKey the secret key to use in the
*/
private String buildSignature(String stringToSign, String secretKey) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
SecretKeySpec secret = new SecretKeySpec(secretKey.getBytes(Charset.forName("UTF8")), ALGORITHM);
mac.init(secret);
byte[] digest = mac.doFinal(stringToSign.getBytes());
return new String(Base64.encode(digest), "ASCII");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Cant find " + ALGORITHM + " message digester", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported character encoding " + CHAR_ENCODING, e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid secret key " + secretKey, e);
}
}
/**
* Signs a request by adding a Content-MD5 and Authorization header.
* For PUT/POST requests that contain a body entity the Content-MD5 header is created using the same
* JSON mapper for serialization as the clients use.
*
* Other format than JSON are not supported currently !!!
*/
public void signRequest(String username, ClientRequest request) {
Preconditions.checkNotNull(appKey, "To sign request a single application key is required");
// first add custom GBIF headers so we can use them to build the string to sign
// the proxied username
request.getHeaders().putSingle(HEADER_GBIF_USER, username);
// the canonical path header
request.getHeaders().putSingle(HEADER_ORIGINAL_REQUEST_URL, getCanonicalizedPath(request.getURI()));
// adds content md5
if (request.getEntity() != null) {
request.getHeaders().putSingle(HEADER_CONTENT_MD5, buildContentMD5(request.getEntity()));
}
// build the unique string to sign
final String stringToSign = buildStringToSign(request);
// find private key for this app
final String secretKey = getPrivateKey(appKey);
if (secretKey == null) {
LOG.warn("Skip signing request with unknown application key: {}", appKey);
return;
}
// sign
String signature = buildSignature(stringToSign, secretKey);
// build authorization header string
String header = buildAuthHeader(appKey, signature);
// add authorization header
LOG.debug("Adding authentication header to request {} for proxied user {} : {}", request.getURI(), username, header);
request.getHeaders().putSingle(HEADER_AUTHORIZATION, header);
}
/**
* Generates the Base64 encoded 128 bit MD5 digest of the entire content string suitable for the
* Content-MD5 header value.
* See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
*/
private String buildContentMD5(Object entity) {
try {
byte[] content = mapper.writeValueAsBytes(entity);
return new String(Base64.encode(DigestUtils.md5(content)), "ASCII");
} catch (IOException e) {
LOG.error("Failed to serialize http entity [{}]", entity);
throw new RuntimeException(e);
}
}
public boolean isValidRequest(ContainerRequest request) {
// parse auth header
final String authHeader = request.getHeaderValue(HEADER_AUTHORIZATION);
if (Strings.isNullOrEmpty(authHeader) || !authHeader.startsWith(GBIF_SCHEME + " ")) {
LOG.info(HEADER_AUTHORIZATION + " header is no GBIF scheme");
return false;
}
String[] values = COLON_PATTERN.split(authHeader.substring(5), 2);
if (values.length < 2) {
LOG.warn("Invalid syntax for application key and signature: {}", authHeader);
return false;
}
final String appKey = values[0];
final String signatureFound = values[1];
if (appKey == null || signatureFound == null) {
LOG.warn("Authentication header missing applicationKey or signature: {}", authHeader);
return false;
}
String secretKey = getPrivateKey(appKey);
if (secretKey == null) {
LOG.warn("Unknown application key: {}", appKey);
return false;
}
//
String stringToSign = buildStringToSign(request);
// sign
String signature = buildSignature(stringToSign, secretKey);
// compare signatures
if (signatureFound.equals(signature)) {
LOG.debug("Trusted application with matching signatures");
return true;
}
LOG.info("Invalid signature: {}", authHeader);
LOG.debug("StringToSign: {}", stringToSign);
return false;
}
private String getPrivateKey(String appKey) {
return keyStore.get(appKey);
}
}
|
src/main/java/org/gbif/ws/security/GbifAuthService.java
|
package org.gbif.ws.security;
import org.gbif.ws.json.JacksonJsonContextResolver;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.ws.rs.core.MultivaluedMap;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The GBIF authentication scheme is modelled after the Amazon scheme on how to sign REST http requests
* using a private key. It uses the standard Http Authorization Header to transport the following information:
* Authorization: GBIF applicationKey:Signature
*
* <br/>
* The header starts with the authentication scheme (GBIF), followed by the plain applicationKey (the public key)
* and a unique signature for the very request which is generated using a fixed set of request attributes
* which are then encrypted by a standard HMAC-SHA1 algorithm.
*
* <br/>
* A POST request with a GBIF header would look like this:
*
* <pre>
* POST /dataset HTTP/1.1
* Host: johnsmith.s3.amazonaws.com
* Date: Mon, 26 Mar 2007 19:37:58 +0000
* x-gbif-user: trobertson
* Content-MD5: LiFThEP4Pj2TODQXa/oFPg==
* Authorization: GBIF gbif.portal:frJIUN8DYpKDtOLCwo//yllqDzg=
* </pre>
*
* When signing an http request in addition to the Authentication header some additional custom headers are added
* which are used to sign and digest the message.
* <br/>
* x-gbif-user is added to transport a proxied user in which the application is acting.
* <br/>
* Content-MD5 is added if a body entity exists.
* See Concent-MD5 header specs: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
*/
@Singleton
public class GbifAuthService {
private static final Logger LOG = LoggerFactory.getLogger(GbifAuthService.class);
private static final String ALGORITHM = "HmacSHA1";
private static final String CHAR_ENCODING = "UTF8";
public static final String HEADER_AUTHORIZATION = "Authorization";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_CONTENT_MD5 = "Content-MD5";
public static final String GBIF_SCHEME = "GBIF";
public static final String HEADER_GBIF_USER = "x-gbif-user";
public static final String HEADER_ORIGINAL_REQUEST_URL = "x-url";
private static final char NEWLINE = '\n';
private static final Pattern COLON_PATTERN = Pattern.compile(":");
private final ImmutableMap<String, String> keyStore;
private final String appKey;
private final ObjectMapper mapper = new JacksonJsonContextResolver().getContext(null);
private GbifAuthService(Map<String, String> appKeys, String appKey) {
keyStore = ImmutableMap.copyOf(appKeys);
this.appKey = appKey;
LOG.info("Initialised appkey store with {} keys", keyStore.size());
}
/**
* Creates a new GBIF authentication service for applications that need to validate requests
* for various application keys. Used by the GBIF webservice apps that require authentication.
*/
public static GbifAuthService multiKeyAuthService(Map<String, String> appKeys) {
return new GbifAuthService(appKeys, null);
}
/**
* Creates a new GBIF authentication service for clients that want to sign requests always using a single
* application key. Used by the GBIF portal and other trusted applications that need to proxy a user.
*/
public static GbifAuthService singleKeyAuthService(String appKey, String secret) {
LOG.info("Initialising auth service with key {}", appKey);
return new GbifAuthService(ImmutableMap.of(appKey, secret), appKey);
}
/**
* Extracts the information to be encrypted from a request and concatenates them into a single String.
* When the server receives an authenticated request, it compares the computed request signature
* with the signature provided in the request in StringToSign.
* For that reason this string may only contain information also available in the exact same form to the server.
*
* @return unique string for a request
*
* @see <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html">AWS Docs</a>
*/
private String buildStringToSign(ContainerRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getMethod());
sb.append(NEWLINE);
// custom header set by varnish overrides real URI
// see http://dev.gbif.org/issues/browse/GBIFCOM-137
if (request.getRequestHeaders().containsKey(HEADER_ORIGINAL_REQUEST_URL)) {
sb.append(request.getRequestHeaders().getFirst(HEADER_ORIGINAL_REQUEST_URL));
} else {
sb.append(getCanonicalizedPath(request.getRequestUri()));
}
appendHeader(sb, request.getRequestHeaders(), HEADER_CONTENT_TYPE, false);
appendHeader(sb, request.getRequestHeaders(), HEADER_CONTENT_MD5, true);
appendHeader(sb, request.getRequestHeaders(), HEADER_GBIF_USER, true);
return sb.toString();
}
/**
* Build the string to be signed for a client request by extracting header information from the request.
* For PUT/POST requests that contain a body content it is required that the Content-MD5 header
* is already present on the request instance!
*/
private String buildStringToSign(ClientRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getMethod());
sb.append(NEWLINE);
sb.append(getCanonicalizedPath(request.getURI()));
appendHeader(sb, request.getHeaders(), HEADER_CONTENT_TYPE, false);
appendHeader(sb, request.getHeaders(), HEADER_CONTENT_MD5, true);
appendHeader(sb, request.getHeaders(), HEADER_GBIF_USER, true);
return sb.toString();
}
private void appendHeader(StringBuilder sb, MultivaluedMap<String, ?> request, String header, boolean caseSensitive) {
if (request.containsKey(header)) {
sb.append(NEWLINE);
if (caseSensitive) {
sb.append(request.getFirst(header));
} else {
sb.append(request.getFirst(header).toString().toLowerCase());
}
}
}
/**
* @return an absolute uri of the resource path alone, excluding host, scheme and query parameters
*/
private String getCanonicalizedPath(URI uri) {
return uri.normalize().getPath();
}
private String buildAuthHeader(String applicationKey, String signature) {
return GBIF_SCHEME + " " + applicationKey + ":" + signature;
}
/**
* Generates a Base64 encoded HMAC-SHA1 signature of the passed in string with the given secret key.
* See Message Authentication Code specs http://tools.ietf.org/html/rfc2104
* @param stringToSign the string to be signed
* @param secretKey the secret key to use in the
*/
private String buildSignature(String stringToSign, String secretKey) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
SecretKeySpec secret = new SecretKeySpec(secretKey.getBytes(Charset.forName("UTF8")), ALGORITHM);
mac.init(secret);
byte[] digest = mac.doFinal(stringToSign.getBytes());
return new String(Base64.encode(digest), "ASCII");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Cant find " + ALGORITHM + " message digester", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported character encoding " + CHAR_ENCODING, e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Invalid secret key " + secretKey, e);
}
}
/**
* Signs a request by adding a Content-MD5 and Authorization header.
* For PUT/POST requests that contain a body entity the Content-MD5 header is created using the same
* JSON mapper for serialization as the clients use.
*
* Other format than JSON are not supported currently !!!
*/
public void signRequest(String username, ClientRequest request) {
Preconditions.checkNotNull(appKey, "To sign request a single application key is required");
// first add custom GBIF headers so we can use them to build the string to sign
// the proxied username
request.getHeaders().putSingle(HEADER_GBIF_USER, username);
// the canonical path header
request.getHeaders().putSingle(HEADER_ORIGINAL_REQUEST_URL, getCanonicalizedPath(request.getURI()));
// adds content md5
if (request.getEntity() != null) {
request.getHeaders().putSingle(HEADER_CONTENT_MD5, buildContentMD5(request.getEntity()));
}
// build the unique string to sign
final String stringToSign = buildStringToSign(request);
System.out.println(stringToSign);
// find private key for this app
final String secretKey = getPrivateKey(appKey);
if (secretKey == null) {
LOG.warn("Skip signing request with unknown application key: {}", appKey);
return;
}
// sign
String signature = buildSignature(stringToSign, secretKey);
// build authorization header string
String header = buildAuthHeader(appKey, signature);
// add authorization header
LOG.debug("Adding authentication header to request {} for proxied user {} : {}", request.getURI(), username, header);
request.getHeaders().putSingle(HEADER_AUTHORIZATION, header);
}
/**
* Generates the Base64 encoded 128 bit MD5 digest of the entire content string suitable for the
* Content-MD5 header value.
* See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.15
*/
private String buildContentMD5(Object entity) {
try {
byte[] content = mapper.writeValueAsBytes(entity);
return new String(Base64.encode(DigestUtils.md5(content)), "ASCII");
} catch (IOException e) {
LOG.error("Failed to serialize http entity [{}]", entity);
throw new RuntimeException(e);
}
}
public boolean isValidRequest(ContainerRequest request) {
// parse auth header
final String authHeader = request.getHeaderValue(HEADER_AUTHORIZATION);
if (Strings.isNullOrEmpty(authHeader) || !authHeader.startsWith(GBIF_SCHEME + " ")) {
LOG.info(HEADER_AUTHORIZATION + " header is no GBIF scheme");
return false;
}
String[] values = COLON_PATTERN.split(authHeader.substring(5), 2);
if (values.length < 2) {
LOG.warn("Invalid syntax for application key and signature: {}", authHeader);
return false;
}
final String appKey = values[0];
final String signatureFound = values[1];
if (appKey == null || signatureFound == null) {
LOG.warn("Authentication header missing applicationKey or signature: {}", authHeader);
return false;
}
String secretKey = getPrivateKey(appKey);
if (secretKey == null) {
LOG.warn("Unknown application key: {}", appKey);
return false;
}
//
String stringToSign = buildStringToSign(request);
// sign
String signature = buildSignature(stringToSign, secretKey);
// compare signatures
if (signatureFound.equals(signature)) {
LOG.debug("Trusted application with matching signatures");
return true;
}
LOG.info("Invalid signature: {}", authHeader);
LOG.debug("StringToSign: {}", stringToSign);
return false;
}
private String getPrivateKey(String appKey) {
return keyStore.get(appKey);
}
}
|
removes System.out
|
src/main/java/org/gbif/ws/security/GbifAuthService.java
|
removes System.out
|
|
Java
|
apache-2.0
|
325da823dc0e527c002bf78f719a83c56f25df79
| 0
|
aparo/elasticsearch,aparo/elasticsearch,aparo/elasticsearch,aparo/elasticsearch,aparo/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,fubuki/elasticsearch,aparo/elasticsearch
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.action.shard;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import static org.elasticsearch.cluster.routing.ImmutableShardRouting.readShardRoutingEntry;
/**
*
*/
public class ShardStateAction extends AbstractComponent {
private final TransportService transportService;
private final ClusterService clusterService;
private final AllocationService allocationService;
private final ThreadPool threadPool;
private final BlockingQueue<ShardRoutingEntry> startedShardsQueue = ConcurrentCollections.newBlockingQueue();
private final BlockingQueue<ShardRoutingEntry> failedShardQueue = ConcurrentCollections.newBlockingQueue();
@Inject
public ShardStateAction(Settings settings, ClusterService clusterService, TransportService transportService,
AllocationService allocationService, ThreadPool threadPool) {
super(settings);
this.clusterService = clusterService;
this.transportService = transportService;
this.allocationService = allocationService;
this.threadPool = threadPool;
transportService.registerHandler(ShardStartedTransportHandler.ACTION, new ShardStartedTransportHandler());
transportService.registerHandler(ShardFailedTransportHandler.ACTION, new ShardFailedTransportHandler());
}
public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String reason) throws ElasticsearchException {
DiscoveryNode masterNode = clusterService.state().nodes().masterNode();
if (masterNode == null) {
logger.warn("can't send shard failed for {}. no master known.", shardRouting);
return;
}
shardFailed(shardRouting, indexUUID, reason, masterNode);
}
public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String reason, final DiscoveryNode masterNode) throws ElasticsearchException {
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason);
logger.warn("{} sending failed shard for {}", shardRouting.shardId(), shardRoutingEntry);
if (clusterService.localNode().equals(masterNode)) {
innerShardFailed(shardRoutingEntry);
} else {
transportService.sendRequest(masterNode,
ShardFailedTransportHandler.ACTION, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send failed shard to {}", exp, masterNode);
}
});
}
}
public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String reason) throws ElasticsearchException {
DiscoveryNode masterNode = clusterService.state().nodes().masterNode();
if (masterNode == null) {
logger.warn("can't send shard started for {}. no master known.", shardRouting);
return;
}
shardStarted(shardRouting, indexUUID, reason, masterNode);
}
public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String reason, final DiscoveryNode masterNode) throws ElasticsearchException {
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason);
logger.debug("sending shard started for {}", shardRoutingEntry);
if (clusterService.localNode().equals(masterNode)) {
innerShardStarted(shardRoutingEntry);
} else {
transportService.sendRequest(masterNode,
ShardStartedTransportHandler.ACTION, new ShardRoutingEntry(shardRouting, indexUUID, reason), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send shard started to [{}]", exp, masterNode);
}
});
}
}
private void innerShardFailed(final ShardRoutingEntry shardRoutingEntry) {
logger.warn("{} received shard failed for {}", shardRoutingEntry.shardRouting.shardId(), shardRoutingEntry);
failedShardQueue.add(shardRoutingEntry);
clusterService.submitStateUpdateTask("shard-failed (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.HIGH, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (shardRoutingEntry.processed) {
return currentState;
}
List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<>();
failedShardQueue.drainTo(shardRoutingEntries);
// nothing to process (a previous event has processed it already)
if (shardRoutingEntries.isEmpty()) {
return currentState;
}
MetaData metaData = currentState.getMetaData();
List<ShardRouting> shardRoutingsToBeApplied = new ArrayList<>(shardRoutingEntries.size());
for (int i = 0; i < shardRoutingEntries.size(); i++) {
ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i);
shardRoutingEntry.processed = true;
ShardRouting shardRouting = shardRoutingEntry.shardRouting;
IndexMetaData indexMetaData = metaData.index(shardRouting.index());
// if there is no metadata or the current index is not of the right uuid, the index has been deleted while it was being allocated
// which is fine, we should just ignore this
if (indexMetaData == null) {
continue;
}
if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) {
logger.debug("{} ignoring shard failed, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry);
continue;
}
logger.debug("{} will apply shard failed {}", shardRouting.shardId(), shardRoutingEntry);
shardRoutingsToBeApplied.add(shardRouting);
}
RoutingAllocation.Result routingResult = allocationService.applyFailedShards(currentState, shardRoutingsToBeApplied);
if (!routingResult.changed()) {
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
}
private void innerShardStarted(final ShardRoutingEntry shardRoutingEntry) {
logger.debug("received shard started for {}", shardRoutingEntry);
// buffer shard started requests, and the state update tasks will simply drain it
// this is to optimize the number of "started" events we generate, and batch them
// possibly, we can do time based batching as well, but usually, we would want to
// process started events as fast as possible, to make shards available
startedShardsQueue.add(shardRoutingEntry);
clusterService.submitStateUpdateTask("shard-started (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.URGENT,
new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (shardRoutingEntry.processed) {
return currentState;
}
List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<>();
startedShardsQueue.drainTo(shardRoutingEntries);
// nothing to process (a previous event has processed it already)
if (shardRoutingEntries.isEmpty()) {
return currentState;
}
RoutingTable routingTable = currentState.routingTable();
MetaData metaData = currentState.getMetaData();
List<ShardRouting> shardRoutingToBeApplied = new ArrayList<>(shardRoutingEntries.size());
for (int i = 0; i < shardRoutingEntries.size(); i++) {
ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i);
shardRoutingEntry.processed = true;
ShardRouting shardRouting = shardRoutingEntry.shardRouting;
try {
IndexMetaData indexMetaData = metaData.index(shardRouting.index());
IndexRoutingTable indexRoutingTable = routingTable.index(shardRouting.index());
// if there is no metadata, no routing table or the current index is not of the right uuid, the index has been deleted while it was being allocated
// which is fine, we should just ignore this
if (indexMetaData == null) {
continue;
}
if (indexRoutingTable == null) {
continue;
}
if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) {
logger.debug("{} ignoring shard started, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry);
continue;
}
// find the one that maps to us, if its already started, no need to do anything...
// the shard might already be started since the nodes that is starting the shards might get cluster events
// with the shard still initializing, and it will try and start it again (until the verification comes)
IndexShardRoutingTable indexShardRoutingTable = indexRoutingTable.shard(shardRouting.id());
boolean applyShardEvent = true;
for (ShardRouting entry : indexShardRoutingTable) {
if (shardRouting.currentNodeId().equals(entry.currentNodeId())) {
// we found the same shard that exists on the same node id
if (!entry.initializing()) {
// shard is in initialized state, skipping event (probable already started)
logger.debug("{} ignoring shard started event for {}, current state: {}", shardRouting.shardId(), shardRoutingEntry, entry.state());
applyShardEvent = false;
}
}
}
if (applyShardEvent) {
shardRoutingToBeApplied.add(shardRouting);
logger.debug("{} will apply shard started {}", shardRouting.shardId(), shardRoutingEntry);
}
} catch (Throwable t) {
logger.error("{} unexpected failure while processing shard started [{}]", t, shardRouting.shardId(), shardRouting);
}
}
if (shardRoutingToBeApplied.isEmpty()) {
return currentState;
}
RoutingAllocation.Result routingResult = allocationService.applyStartedShards(currentState, shardRoutingToBeApplied, true);
if (!routingResult.changed()) {
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
}
private class ShardFailedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> {
static final String ACTION = "cluster/shardFailure";
@Override
public ShardRoutingEntry newInstance() {
return new ShardRoutingEntry();
}
@Override
public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
innerShardFailed(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
class ShardStartedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> {
static final String ACTION = "cluster/shardStarted";
@Override
public ShardRoutingEntry newInstance() {
return new ShardRoutingEntry();
}
@Override
public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
innerShardStarted(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
static class ShardRoutingEntry extends TransportRequest {
private ShardRouting shardRouting;
private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
private String reason;
volatile boolean processed; // state field, no need to serialize
private ShardRoutingEntry() {
}
private ShardRoutingEntry(ShardRouting shardRouting, String indexUUID, String reason) {
this.shardRouting = shardRouting;
this.reason = reason;
this.indexUUID = indexUUID;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardRouting = readShardRoutingEntry(in);
reason = in.readString();
indexUUID = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardRouting.writeTo(out);
out.writeString(reason);
out.writeString(indexUUID);
}
@Override
public String toString() {
return "" + shardRouting + ", indexUUID [" + indexUUID + "], reason [" + reason + "]";
}
}
}
|
src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.action.shard;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import static org.elasticsearch.cluster.routing.ImmutableShardRouting.readShardRoutingEntry;
/**
*
*/
public class ShardStateAction extends AbstractComponent {
private final TransportService transportService;
private final ClusterService clusterService;
private final AllocationService allocationService;
private final ThreadPool threadPool;
private final BlockingQueue<ShardRoutingEntry> startedShardsQueue = ConcurrentCollections.newBlockingQueue();
private final BlockingQueue<ShardRoutingEntry> failedShardQueue = ConcurrentCollections.newBlockingQueue();
@Inject
public ShardStateAction(Settings settings, ClusterService clusterService, TransportService transportService,
AllocationService allocationService, ThreadPool threadPool) {
super(settings);
this.clusterService = clusterService;
this.transportService = transportService;
this.allocationService = allocationService;
this.threadPool = threadPool;
transportService.registerHandler(ShardStartedTransportHandler.ACTION, new ShardStartedTransportHandler());
transportService.registerHandler(ShardFailedTransportHandler.ACTION, new ShardFailedTransportHandler());
}
public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String reason) throws ElasticsearchException {
DiscoveryNode masterNode = clusterService.state().nodes().masterNode();
if (masterNode == null) {
logger.debug("can't send shard failed for {}. no master known.", shardRouting);
}
shardFailed(shardRouting, indexUUID, reason, masterNode);
}
public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String reason, final DiscoveryNode masterNode) throws ElasticsearchException {
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason);
logger.warn("{} sending failed shard for {}", shardRouting.shardId(), shardRoutingEntry);
if (clusterService.localNode().equals(masterNode)) {
innerShardFailed(shardRoutingEntry);
} else {
transportService.sendRequest(clusterService.state().nodes().masterNode(),
ShardFailedTransportHandler.ACTION, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send failed shard to {}", exp, masterNode);
}
});
}
}
public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String reason) throws ElasticsearchException {
DiscoveryNode masterNode = clusterService.state().nodes().masterNode();
if (masterNode == null) {
logger.debug("can't send shard started for {}. no master known.", shardRouting);
}
shardStarted(shardRouting, indexUUID, reason, masterNode);
}
public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String reason, final DiscoveryNode masterNode) throws ElasticsearchException {
ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason);
logger.debug("sending shard started for {}", shardRoutingEntry);
if (clusterService.localNode().equals(masterNode)) {
innerShardStarted(shardRoutingEntry);
} else {
transportService.sendRequest(masterNode,
ShardStartedTransportHandler.ACTION, new ShardRoutingEntry(shardRouting, indexUUID, reason), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) {
@Override
public void handleException(TransportException exp) {
logger.warn("failed to send shard started to [{}]", exp, masterNode);
}
});
}
}
private void innerShardFailed(final ShardRoutingEntry shardRoutingEntry) {
logger.warn("{} received shard failed for {}", shardRoutingEntry.shardRouting.shardId(), shardRoutingEntry);
failedShardQueue.add(shardRoutingEntry);
clusterService.submitStateUpdateTask("shard-failed (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.HIGH, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (shardRoutingEntry.processed) {
return currentState;
}
List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<>();
failedShardQueue.drainTo(shardRoutingEntries);
// nothing to process (a previous event has processed it already)
if (shardRoutingEntries.isEmpty()) {
return currentState;
}
MetaData metaData = currentState.getMetaData();
List<ShardRouting> shardRoutingsToBeApplied = new ArrayList<>(shardRoutingEntries.size());
for (int i = 0; i < shardRoutingEntries.size(); i++) {
ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i);
shardRoutingEntry.processed = true;
ShardRouting shardRouting = shardRoutingEntry.shardRouting;
IndexMetaData indexMetaData = metaData.index(shardRouting.index());
// if there is no metadata or the current index is not of the right uuid, the index has been deleted while it was being allocated
// which is fine, we should just ignore this
if (indexMetaData == null) {
continue;
}
if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) {
logger.debug("{} ignoring shard failed, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry);
continue;
}
logger.debug("{} will apply shard failed {}", shardRouting.shardId(), shardRoutingEntry);
shardRoutingsToBeApplied.add(shardRouting);
}
RoutingAllocation.Result routingResult = allocationService.applyFailedShards(currentState, shardRoutingsToBeApplied);
if (!routingResult.changed()) {
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
}
private void innerShardStarted(final ShardRoutingEntry shardRoutingEntry) {
logger.debug("received shard started for {}", shardRoutingEntry);
// buffer shard started requests, and the state update tasks will simply drain it
// this is to optimize the number of "started" events we generate, and batch them
// possibly, we can do time based batching as well, but usually, we would want to
// process started events as fast as possible, to make shards available
startedShardsQueue.add(shardRoutingEntry);
clusterService.submitStateUpdateTask("shard-started (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.URGENT,
new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
if (shardRoutingEntry.processed) {
return currentState;
}
List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<>();
startedShardsQueue.drainTo(shardRoutingEntries);
// nothing to process (a previous event has processed it already)
if (shardRoutingEntries.isEmpty()) {
return currentState;
}
RoutingTable routingTable = currentState.routingTable();
MetaData metaData = currentState.getMetaData();
List<ShardRouting> shardRoutingToBeApplied = new ArrayList<>(shardRoutingEntries.size());
for (int i = 0; i < shardRoutingEntries.size(); i++) {
ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i);
shardRoutingEntry.processed = true;
ShardRouting shardRouting = shardRoutingEntry.shardRouting;
try {
IndexMetaData indexMetaData = metaData.index(shardRouting.index());
IndexRoutingTable indexRoutingTable = routingTable.index(shardRouting.index());
// if there is no metadata, no routing table or the current index is not of the right uuid, the index has been deleted while it was being allocated
// which is fine, we should just ignore this
if (indexMetaData == null) {
continue;
}
if (indexRoutingTable == null) {
continue;
}
if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) {
logger.debug("{} ignoring shard started, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry);
continue;
}
// find the one that maps to us, if its already started, no need to do anything...
// the shard might already be started since the nodes that is starting the shards might get cluster events
// with the shard still initializing, and it will try and start it again (until the verification comes)
IndexShardRoutingTable indexShardRoutingTable = indexRoutingTable.shard(shardRouting.id());
boolean applyShardEvent = true;
for (ShardRouting entry : indexShardRoutingTable) {
if (shardRouting.currentNodeId().equals(entry.currentNodeId())) {
// we found the same shard that exists on the same node id
if (!entry.initializing()) {
// shard is in initialized state, skipping event (probable already started)
logger.debug("{} ignoring shard started event for {}, current state: {}", shardRouting.shardId(), shardRoutingEntry, entry.state());
applyShardEvent = false;
}
}
}
if (applyShardEvent) {
shardRoutingToBeApplied.add(shardRouting);
logger.debug("{} will apply shard started {}", shardRouting.shardId(), shardRoutingEntry);
}
} catch (Throwable t) {
logger.error("{} unexpected failure while processing shard started [{}]", t, shardRouting.shardId(), shardRouting);
}
}
if (shardRoutingToBeApplied.isEmpty()) {
return currentState;
}
RoutingAllocation.Result routingResult = allocationService.applyStartedShards(currentState, shardRoutingToBeApplied, true);
if (!routingResult.changed()) {
return currentState;
}
return ClusterState.builder(currentState).routingResult(routingResult).build();
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
});
}
private class ShardFailedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> {
static final String ACTION = "cluster/shardFailure";
@Override
public ShardRoutingEntry newInstance() {
return new ShardRoutingEntry();
}
@Override
public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
innerShardFailed(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
class ShardStartedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> {
static final String ACTION = "cluster/shardStarted";
@Override
public ShardRoutingEntry newInstance() {
return new ShardRoutingEntry();
}
@Override
public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception {
innerShardStarted(request);
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
static class ShardRoutingEntry extends TransportRequest {
private ShardRouting shardRouting;
private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
private String reason;
volatile boolean processed; // state field, no need to serialize
private ShardRoutingEntry() {
}
private ShardRoutingEntry(ShardRouting shardRouting, String indexUUID, String reason) {
this.shardRouting = shardRouting;
this.reason = reason;
this.indexUUID = indexUUID;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardRouting = readShardRoutingEntry(in);
reason = in.readString();
indexUUID = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardRouting.writeTo(out);
out.writeString(reason);
out.writeString(indexUUID);
}
@Override
public String toString() {
return "" + shardRouting + ", indexUUID [" + indexUUID + "], reason [" + reason + "]";
}
}
}
|
Core: Added missing return statements.
Closes #6841
|
src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
|
Core: Added missing return statements.
|
|
Java
|
apache-2.0
|
0953a7a63e827d0071be89d475ba16e15922ccbc
| 0
|
august782/pitest,august782/pitest,august782/pitest
|
package org.pitest.coverage.execute;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.pitest.coverage.ClassStatistics;
import org.pitest.coverage.CoverageResult;
import org.pitest.functional.SideEffect1;
import org.pitest.testapi.Description;
import org.pitest.util.Id;
import org.pitest.util.ReceiveStrategy;
import org.pitest.util.SafeDataInputStream;
import sun.pitest.CodeCoverageStore;
final class Receive implements ReceiveStrategy {
private final Map<Integer, String> classIdToName = new ConcurrentHashMap<Integer, String>();
private final SideEffect1<CoverageResult> handler;
Receive(final SideEffect1<CoverageResult> handler) {
this.handler = handler;
}
public void apply(final byte control, final SafeDataInputStream is) {
switch (control) {
case Id.CLAZZ:
final int id = is.readInt();
final String name = is.readString();
this.classIdToName.put(id, name);
break;
case Id.OUTCOME:
handleTestEnd(is);
break;
case Id.DONE:
// nothing to do ?
}
}
private void handleTestEnd(final SafeDataInputStream is) {
final Description d = is.read(Description.class);
final long numberOfResults = is.readLong();
final Map<Integer, ClassStatistics> hits = new HashMap<Integer, ClassStatistics>();
for (int i = 0; i != numberOfResults; i++) {
readLineHit(is, hits);
}
CoverageResult cr = createCoverageResult(is, d, hits);
if (cr.isGreenTest()) {
this.handler.apply(cr);
}
//this.handler.apply(createCoverageResult(is, d, hits));
}
private void readLineHit(final SafeDataInputStream is,
final Map<Integer, ClassStatistics> hits) {
final long encoded = is.readLong();
final int classId = CodeCoverageStore.decodeClassId(encoded);
final int lineNumber = CodeCoverageStore.decodeLineId(encoded);
final ClassStatistics stats = getStatisticsForClass(hits, classId);
stats.registerLineVisit(lineNumber);
}
private CoverageResult createCoverageResult(final SafeDataInputStream is,
final Description d, final Map<Integer, ClassStatistics> hits) {
final boolean isGreen = is.readBoolean();
final int executionTime = is.readInt();
final CoverageResult cr = new CoverageResult(d, executionTime, isGreen,
hits.values());
return cr;
}
private ClassStatistics getStatisticsForClass(
final Map<Integer, ClassStatistics> hits, final int classId) {
ClassStatistics stats = hits.get(classId);
if (stats == null) {
stats = new ClassStatistics(this.classIdToName.get(classId));
hits.put(classId, stats);
}
return stats;
}
}
|
pitest/src/main/java/org/pitest/coverage/execute/Receive.java
|
package org.pitest.coverage.execute;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.pitest.coverage.ClassStatistics;
import org.pitest.coverage.CoverageResult;
import org.pitest.functional.SideEffect1;
import org.pitest.testapi.Description;
import org.pitest.util.Id;
import org.pitest.util.ReceiveStrategy;
import org.pitest.util.SafeDataInputStream;
import sun.pitest.CodeCoverageStore;
final class Receive implements ReceiveStrategy {
private final Map<Integer, String> classIdToName = new ConcurrentHashMap<Integer, String>();
private final SideEffect1<CoverageResult> handler;
Receive(final SideEffect1<CoverageResult> handler) {
this.handler = handler;
}
public void apply(final byte control, final SafeDataInputStream is) {
switch (control) {
case Id.CLAZZ:
final int id = is.readInt();
final String name = is.readString();
this.classIdToName.put(id, name);
break;
case Id.OUTCOME:
handleTestEnd(is);
break;
case Id.DONE:
// nothing to do ?
}
}
private void handleTestEnd(final SafeDataInputStream is) {
final Description d = is.read(Description.class);
final long numberOfResults = is.readLong();
final Map<Integer, ClassStatistics> hits = new HashMap<Integer, ClassStatistics>();
for (int i = 0; i != numberOfResults; i++) {
readLineHit(is, hits);
}
//CoverageResult cr = createCoverageResult(is, d, hits);
//if (cr.isGreenTest()) {
// this.handler.apply(cr);
//}
this.handler.apply(createCoverageResult(is, d, hits));
}
private void readLineHit(final SafeDataInputStream is,
final Map<Integer, ClassStatistics> hits) {
final long encoded = is.readLong();
final int classId = CodeCoverageStore.decodeClassId(encoded);
final int lineNumber = CodeCoverageStore.decodeLineId(encoded);
final ClassStatistics stats = getStatisticsForClass(hits, classId);
stats.registerLineVisit(lineNumber);
}
private CoverageResult createCoverageResult(final SafeDataInputStream is,
final Description d, final Map<Integer, ClassStatistics> hits) {
final boolean isGreen = is.readBoolean();
final int executionTime = is.readInt();
final CoverageResult cr = new CoverageResult(d, executionTime, isGreen,
hits.values());
return cr;
}
private ClassStatistics getStatisticsForClass(
final Map<Integer, ClassStatistics> hits, final int classId) {
ClassStatistics stats = hits.get(classId);
if (stats == null) {
stats = new ClassStatistics(this.classIdToName.get(classId));
hits.put(classId, stats);
}
return stats;
}
}
|
Actually ignore the test if it is not green
|
pitest/src/main/java/org/pitest/coverage/execute/Receive.java
|
Actually ignore the test if it is not green
|
|
Java
|
apache-2.0
|
a53fe9fb0f0ccfbfb940cce670e0a17bda80c09c
| 0
|
scalyr/Scalyr-Java-Client
|
/*
* Scalyr client library
* Copyright 2012 Scalyr, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scalyr.api.knobs;
import com.scalyr.api.Converter;
import com.scalyr.api.ScalyrDeadlineException;
import com.scalyr.api.TuningConstants;
import com.scalyr.api.internal.Logging;
import com.scalyr.api.internal.ScalyrUtil;
import com.scalyr.api.json.JSONObject;
import com.scalyr.api.logs.Severity;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Encapsulates a specific entry in a JSON-format configuration file.
* <p>
* It is generally best to use a type-specific subclass of Knob, such as
* Knob.Integer or Knob.String, rather than casting the result of
* Knob.get() yourself. This is because Java casting does not know how to
* convert between numeric types (e.g. Double -> Integer), and so simple casting
* is liable to throw ClassCastException.
*/
public class Knob {
/**
* Files in which we look for the value. We use the first file that defines our key.
*
* If useDefaultFiles is true, then this list should be overwritten with defaultFiles before
* use.
*/
private ConfigurationFile[] files;
/**
* If true, then our files list needs to be replaced with defaultFiles. We do this lazily on first access,
* so that Knobs can be constructed before setDefaultFiles is invoked.
*/
private boolean useDefaultFiles;
/**
* The key we look for in each file. If null, then we always use our default value.
*/
private final java.lang.String key;
/**
* Value used if no file defines the key.
*/
private final Object defaultValue;
/**
* False until we first retrieve a value from the configuration file. Once this is true, it will never
* be false.
*/
private volatile boolean hasValue;
/**
* True if we are sure that our value is up to date with respect to the underlying configuration files.
* Always false if hasValue is false.
*/
private volatile boolean valueUpToDate;
/**
* The most recently observed value. Undefined if hasValue is false.
*/
private volatile Object value;
/**
* The number of times we've had to fetch our value from the configuration file. Used to decide when to
* create a file listener and proactively track the value.
*/
private int uncachedFetchCount;
/**
* Callback used to listen for changes in the underlying file, or null if we are not currently
* listening. We listen if updateListeners is nonempty, or if this knob has been fetched enough
* times that it's worth caching.
*/
private Consumer<ConfigurationFile> fileListener;
/**
* All callbacks which have been registered to be notified when our value changes.
*/
private Set<Consumer<Knob>> updateListeners = new HashSet<>();
/**
* List of files to be used if no files were explicitly specified. Null until initialized by
* a call to setDefaultFiles.
*/
private static AtomicReference<ConfigurationFile[]> defaultFiles = new AtomicReference<ConfigurationFile[]>(null);
/**
* Specify a default list of configuration files. This will be used for any Knob in which no file list was specified.
* Existing Knobs are not affected by changes to the default file list.
*/
public static void setDefaultFiles(ConfigurationFile[] files) {
defaultFiles.set(files);
}
/**
* @param key The key to look for (a fieldname of the top-level JSON object in the file), or null to always use defaultValue.
* @param defaultValue Value to return from {@link #get()} if the file does not exist or does not
* contain the key.
* @param files The files in which we look for the value. We use the first file that
* defines the specified key. If no files are specified, we use defaultFiles
*/
public Knob(java.lang.String key, Object defaultValue, ConfigurationFile ... files) {
if (files.length > 0) {
this.files = files;
} else {
useDefaultFiles = true;
}
this.key = key;
this.defaultValue = defaultValue;
}
/**
* If our files list has not yet been initialized, initialize it with the default.
*/
private synchronized void prepareFilesList() {
if (useDefaultFiles) {
files = defaultFiles.get();
if (files == null)
throw new RuntimeException("Must call setDefaultFiles before using a Knob with no ConfigurationFiles");
useDefaultFiles = false;
}
}
/**
* Return a value from the first configuration file which contains the specified key.
* <p>
* Ignore any files which do not exist. If none of the files contain the key, or the key is null, return defaultValue.
* If any file has not yet been retrieved from the server, we block until it can be retrieved.
*
* @param valueKey A key into the top-level object in that file, or null to force the default value.
* @param defaultValue Value to return if the file does not exist or does not contain the key.
* @param files The files in which we search for the value.
*/
public static Object get(java.lang.String valueKey, Object defaultValue, ConfigurationFile ... files) {
return new Knob(valueKey, defaultValue, files).get();
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to an Integer.
*/
public static java.lang.Integer getInteger(java.lang.String valueKey, java.lang.Integer defaultValue, ConfigurationFile ... files) {
return Converter.toInteger(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to an Long.
*/
public static java.lang.Long getLong(java.lang.String valueKey, java.lang.Long defaultValue, ConfigurationFile ... files) {
return Converter.toLong(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a Double.
*/
public static java.lang.Double getDouble(java.lang.String valueKey, java.lang.Double defaultValue, ConfigurationFile ... files) {
return Converter.toDouble(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a Boolean.
*/
public static java.lang.Boolean getBoolean(java.lang.String valueKey, java.lang.Boolean defaultValue, ConfigurationFile ... files) {
return Converter.toBoolean(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a String.
*/
public static java.lang.String getString(java.lang.String valueKey, java.lang.String defaultValue, ConfigurationFile ... files) {
return Converter.toString(get(valueKey, defaultValue, files));
}
/**
* Return the value at the specified key in our file.
*
* If the file does not exist or does not contain the key (or the key is null), return our default value.
* If the file has not yet been retrieved from the server, we block until it can be retrieved.
*/
public Object get() {
return getWithTimeout(null);
}
/**
* Like get(), but if the file has not yet been retrieved from the server, and the specified time
* interval elapses before the file is retrieved from the server, throw a ScalyrDeadlineException.
*
* @throws ScalyrDeadlineException
*/
public Object getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return getWithTimeout(timeoutInMs, false);
}
/**
* Like get(), but if the file has not yet been retrieved from the server, and the specified time
* interval elapses before the file is retrieved from the server, throw a ScalyrDeadlineException.
*
* @param timeoutInMs Maximum amount of time to wait for the initial file retrieval. Null means
* to wait as long as needed.
* @param bypassCache If true, then we always examine the configuration file(s), rather than relying on
* our cached value for the knob.
*
* @throws ScalyrDeadlineException
*/
public Object getWithTimeout(java.lang.Long timeoutInMs, boolean bypassCache) throws ScalyrDeadlineException {
if (!bypassCache && valueUpToDate)
return value;
Object newValue = defaultValue;
boolean ensuredFileListener = false;
if (key != null) {
synchronized (this) {
uncachedFetchCount++;
if (uncachedFetchCount >= TuningConstants.KNOB_CACHE_THRESHOLD) {
// Ensure that we have a fileListener, so that we can update our value if the configuration
// file(s) change. We don't do this unless the knob is fetched repeatedly, because the fileListener
// will prevent this Knob object from ever being garbage collected.
ensureFileListener();
ensuredFileListener = true;
}
}
long entryTime = (timeoutInMs != null) ? ScalyrUtil.currentTimeMillis() : 0;
prepareFilesList();
for (ConfigurationFile file : files) {
JSONObject parsedFile;
try {
if (timeoutInMs != null) {
long elapsed = Math.max(ScalyrUtil.currentTimeMillis() - entryTime, 0);
parsedFile = file.getAsJsonWithTimeout(timeoutInMs - elapsed, timeoutInMs);
} else {
parsedFile = file.getAsJson();
}
} catch (BadConfigurationFileException ex) {
parsedFile = null;
Logging.log(Severity.info, Logging.tagKnobFileInvalid,
"Knob: ignoring file [" + file + "]: it does not contain valid JSON");
}
if (parsedFile != null && parsedFile.containsKey(key)) {
newValue = parsedFile.get(key);
break;
}
}
}
synchronized (this) {
Object oldValue = value;
boolean hadValue = hasValue;
value = newValue;
hasValue = true;
if (ensuredFileListener)
valueUpToDate = true;
if (!hadValue || !ScalyrUtil.equals(value, oldValue)) {
List<Consumer<Knob>> listenerSnapshot = new ArrayList<>(updateListeners);
for (Consumer<Knob> updateListener : listenerSnapshot) {
updateListener.accept(this);
}
}
return newValue;
}
}
/**
* Register a callback to be invoked whenever our value changes.
*/
public synchronized Knob addUpdateListener(Consumer<Knob> updateListener) {
if (updateListeners.size() == 0) {
ensureFileListener();
}
updateListeners.add(updateListener);
return this;
}
/**
* If we don't yet have a fileListener, then add one.
*/
private synchronized void ensureFileListener() {
if (fileListener == null) {
fileListener = updatedFile -> {
if (allFilesHaveValues())
getWithTimeout(null, true);
};
prepareFilesList();
for (ConfigurationFile file : files)
file.addUpdateListener(fileListener);
}
}
protected synchronized boolean allFilesHaveValues() {
prepareFilesList();
for (ConfigurationFile file : files)
if (!file.hasState())
return false;
return true;
}
/**
* De-register a callback. If the callback was not registered, we do nothing.
*/
public synchronized Knob removeUpdateListener(Consumer<Knob> updateListener) {
updateListeners.remove(updateListener);
return this;
}
/**
* No-op developer convenience/hygiene method: when defining a new Knob that
* we ought to cleanup at some point, add this method to the Knob declaration:
*
* ```
* final Knob.Boolean useOldImplementation = new Knob.Boolean("useOldImplementation", false).expireHint("12/15/2017");
* ```
*
* @param dateStr after which we may want to pull this knob. Not currently parsed.
* @return self for chaining
*/
public Knob expireHint(java.lang.String dateStr) {
return this;
}
/**
* Subclass of Knob which is specialized for Integer values, with or without SI.
*/
public static class Integer extends Knob {
public Integer(java.lang.String valueKey, java.lang.Integer defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Integer get() {
return convertWithSI(super.get());
}
@Override public java.lang.Integer getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return convertWithSI(super.getWithTimeout(timeoutInMs));
}
@Override public Integer expireHint(java.lang.String dateStr) {
return this;
}
private java.lang.Integer convertWithSI(Object obj) {
try {
return Converter.toInteger(obj);
} catch (RuntimeException ex) {
return Converter.parseNumberWithSI(obj).intValue();
}
}
}
/**
* Subclass of Knob which is specialized for Long values, with or without SI.
*/
public static class Long extends Knob {
public Long(java.lang.String valueKey, java.lang.Long defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Long get() {
return convertWithSI(super.get());
}
@Override public java.lang.Long getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return convertWithSI(super.getWithTimeout(timeoutInMs));
}
@Override public Long expireHint(java.lang.String dateStr) {
return this;
}
private java.lang.Long convertWithSI(Object obj) {
try {
return Converter.toLong(obj);
} catch (RuntimeException ex) {
return Converter.parseNumberWithSI(obj);
}
}
}
/**
* Subclass of Knob which is specialized for Double values.
*/
public static class Double extends Knob {
public Double(java.lang.String valueKey, java.lang.Double defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Double get() {
return Converter.toDouble(super.get());
}
@Override public java.lang.Double getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toDouble(super.getWithTimeout(timeoutInMs));
}
@Override public Double expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob which is specialized for Boolean values.
*/
public static class Boolean extends Knob {
public Boolean(java.lang.String valueKey, java.lang.Boolean defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Boolean get() {
return Converter.toBoolean(super.get());
}
@Override public java.lang.Boolean getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toBoolean(super.getWithTimeout(timeoutInMs));
}
@Override public Boolean expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob which is specialized for String values.
*/
public static class String extends Knob {
public String(java.lang.String valueKey, java.lang.String defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.String get() {
return Converter.toString(super.get());
}
@Override public java.lang.String getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toString(super.getWithTimeout(timeoutInMs));
}
@Override public String expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob for durations, to make writing them nicer (eg. "2 minutes" or "1 day").
*/
public static class Duration extends Knob {
public Duration(java.lang.String valueKey, java.lang.Long defaultValue, TimeUnit defaultTimeUnit, ConfigurationFile ... files) {
//we'll always store default value in Nanoseconds
super(valueKey, TimeUnit.NANOSECONDS.convert(defaultValue, defaultTimeUnit), files);
}
/*
* OVERRIDING OLD METHODS
*/
//Since with get() we can't specify a unit for time, we'll return a java.time.Duration
@Override public java.time.Duration get() {
return this.getWithTimeout(null, false);
}
@Override public java.time.Duration getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return this.getWithTimeout(timeoutInMs, false);
}
@Override public java.time.Duration getWithTimeout(java.lang.Long timeoutInMs, boolean bypassCache) throws ScalyrDeadlineException {
Object value = super.getWithTimeout(timeoutInMs, bypassCache);
if (value instanceof java.lang.String) { //We got entry from config file
java.lang.String[] splitInput = ((java.lang.String) value).trim().split(" +");
try {
if (splitInput.length != 2) {
throw new RuntimeException();
}
return java.time.Duration.of(java.lang.Long.parseLong(splitInput[0]), convertTimeType(timeUnitMap.get(splitInput[1])));
} catch (NumberFormatException e) { //Error in magnitude format
throw new RuntimeException("Formatting error in your config file, in the magnitude of your time: \"" + splitInput[0] + "\"");
} catch (NullPointerException e) { //Error in unit format
throw new RuntimeException("Formatting error in your config file, in the units of your time: \"" + splitInput[1] + "\"");
} catch (RuntimeException e) { //Some other formatting error entirely
throw new RuntimeException("Formatting error in your config file: \"" + value + "\"");
}
} else { //Using default value
return java.time.Duration.of((long) value, ChronoUnit.NANOS);
}
}
@Override public Duration expireHint(java.lang.String dateStr) {
return this;
}
/*
* NEW METHODS
*/
public java.lang.Long seconds() {
return getTimeInFormat(TimeUnit.SECONDS);
}
public java.lang.Long millis() {
return getTimeInFormat(TimeUnit.MILLISECONDS);
}
public java.lang.Long micros() {
return getTimeInFormat(TimeUnit.MICROSECONDS);
}
public java.lang.Long nanos() {
return getTimeInFormat(TimeUnit.NANOSECONDS);
}
public java.lang.Long minutes() {
return getTimeInFormat(TimeUnit.MINUTES);
}
public java.lang.Long hours() {
return getTimeInFormat(TimeUnit.HOURS);
}
public java.lang.Long days() {
return getTimeInFormat(TimeUnit.DAYS);
}
/*
* HELPER STUFF
*/
private java.lang.Long getTimeInFormat(TimeUnit format) {
Object value = super.getWithTimeout(null, false);
if (value instanceof java.lang.String) { //We got entry from config file
java.lang.String[] splitInput = ((java.lang.String) value).trim().split(" +");
try {
if (splitInput.length != 2) {
throw new RuntimeException();
}
return format.convert(java.lang.Long.parseLong(splitInput[0]), timeUnitMap.get(splitInput[1]));
} catch (NumberFormatException e) { //Error in magnitude format
throw new RuntimeException("Formatting error in your config file, in the magnitude of your time: \"" + splitInput[0] + "\"");
} catch (NullPointerException e) { //Error in unit format
throw new RuntimeException("Formatting error in your config file, in the units of your time: \"" + splitInput[1] + "\"");
} catch (RuntimeException e) { //Some other formatting error entirely
throw new RuntimeException("Formatting error in your config file: \"" + value + "\"");
}
} else { //Using default value
return format.convert((long) value, TimeUnit.NANOSECONDS);
}
}
private static ChronoUnit convertTimeType(TimeUnit tu) {
if (tu == null) {
return null;
}
switch (tu) {
case DAYS:
return ChronoUnit.DAYS;
case HOURS:
return ChronoUnit.HOURS;
case MINUTES:
return ChronoUnit.MINUTES;
case SECONDS:
return ChronoUnit.SECONDS;
case MICROSECONDS:
return ChronoUnit.MICROS;
case MILLISECONDS:
return ChronoUnit.MILLIS;
case NANOSECONDS:
return ChronoUnit.NANOS;
default:
return null;
}
}
private static final Map<java.lang.String, TimeUnit> timeUnitMap = new HashMap<java.lang.String, TimeUnit>(){{
put("s" , TimeUnit.SECONDS ) ;
put("sec" , TimeUnit.SECONDS ) ;
put("secs" , TimeUnit.SECONDS ) ;
put("second" , TimeUnit.SECONDS ) ;
put("seconds" , TimeUnit.SECONDS ) ;
put("ms" , TimeUnit.MILLISECONDS ) ;
put("millis" , TimeUnit.MILLISECONDS ) ;
put("milliseconds" , TimeUnit.MILLISECONDS ) ;
put("micros" , TimeUnit.MICROSECONDS ) ;
put("microseconds" , TimeUnit.MICROSECONDS ) ;
put("\u03BC" , TimeUnit.MICROSECONDS ) ; // µ, or very similar-looking
put("\u03BCs" , TimeUnit.MICROSECONDS ) ;
put("\u00B5" , TimeUnit.MICROSECONDS ) ; // µ, or very similar-looking
put("\u00B5s" , TimeUnit.MICROSECONDS ) ;
put("ns" , TimeUnit.NANOSECONDS ) ;
put("nanos" , TimeUnit.NANOSECONDS ) ;
put("nanoseconds" , TimeUnit.NANOSECONDS ) ;
put("m" , TimeUnit.MINUTES ) ;
put("min" , TimeUnit.MINUTES ) ;
put("mins" , TimeUnit.MINUTES ) ;
put("minute" , TimeUnit.MINUTES ) ;
put("minutes" , TimeUnit.MINUTES ) ;
put("h" , TimeUnit.HOURS ) ;
put("hour" , TimeUnit.HOURS ) ;
put("hours" , TimeUnit.HOURS ) ;
put("d" , TimeUnit.DAYS ) ;
put("day" , TimeUnit.DAYS ) ;
put("days" , TimeUnit.DAYS ) ;
}};
}
}
|
src/main/com/scalyr/api/knobs/Knob.java
|
/*
* Scalyr client library
* Copyright 2012 Scalyr, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scalyr.api.knobs;
import com.scalyr.api.Converter;
import com.scalyr.api.ScalyrDeadlineException;
import com.scalyr.api.TuningConstants;
import com.scalyr.api.internal.Logging;
import com.scalyr.api.internal.ScalyrUtil;
import com.scalyr.api.json.JSONObject;
import com.scalyr.api.logs.Severity;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Encapsulates a specific entry in a JSON-format configuration file.
* <p>
* It is generally best to use a type-specific subclass of Knob, such as
* Knob.Integer or Knob.String, rather than casting the result of
* Knob.get() yourself. This is because Java casting does not know how to
* convert between numeric types (e.g. Double -> Integer), and so simple casting
* is liable to throw ClassCastException.
*/
public class Knob {
/**
* Files in which we look for the value. We use the first file that defines our key.
*
* If useDefaultFiles is true, then this list should be overwritten with defaultFiles before
* use.
*/
private ConfigurationFile[] files;
/**
* If true, then our files list needs to be replaced with defaultFiles. We do this lazily on first access,
* so that Knobs can be constructed before setDefaultFiles is invoked.
*/
private boolean useDefaultFiles;
/**
* The key we look for in each file. If null, then we always use our default value.
*/
private final java.lang.String key;
/**
* Value used if no file defines the key.
*/
private final Object defaultValue;
/**
* False until we first retrieve a value from the configuration file. Once this is true, it will never
* be false.
*/
private volatile boolean hasValue;
/**
* True if we are sure that our value is up to date with respect to the underlying configuration files.
* Always false if hasValue is false.
*/
private volatile boolean valueUpToDate;
/**
* The most recently observed value. Undefined if hasValue is false.
*/
private volatile Object value;
/**
* The number of times we've had to fetch our value from the configuration file. Used to decide when to
* create a file listener and proactively track the value.
*/
private int uncachedFetchCount;
/**
* Callback used to listen for changes in the underlying file, or null if we are not currently
* listening. We listen if updateListeners is nonempty, or if this knob has been fetched enough
* times that it's worth caching.
*/
private Consumer<ConfigurationFile> fileListener;
/**
* All callbacks which have been registered to be notified when our value changes.
*/
private Set<Consumer<Knob>> updateListeners = new HashSet<>();
/**
* List of files to be used if no files were explicitly specified. Null until initialized by
* a call to setDefaultFiles.
*/
private static AtomicReference<ConfigurationFile[]> defaultFiles = new AtomicReference<ConfigurationFile[]>(null);
/**
* Specify a default list of configuration files. This will be used for any Knob in which no file list was specified.
* Existing Knobs are not affected by changes to the default file list.
*/
public static void setDefaultFiles(ConfigurationFile[] files) {
defaultFiles.set(files);
}
/**
* @param key The key to look for (a fieldname of the top-level JSON object in the file), or null to always use defaultValue.
* @param defaultValue Value to return from {@link #get()} if the file does not exist or does not
* contain the key.
* @param files The files in which we look for the value. We use the first file that
* defines the specified key. If no files are specified, we use defaultFiles
*/
public Knob(java.lang.String key, Object defaultValue, ConfigurationFile ... files) {
if (files.length > 0) {
this.files = files;
} else {
useDefaultFiles = true;
}
this.key = key;
this.defaultValue = defaultValue;
}
/**
* If our files list has not yet been initialized, initialize it with the default.
*/
private synchronized void prepareFilesList() {
if (useDefaultFiles) {
files = defaultFiles.get();
if (files == null)
throw new RuntimeException("Must call setDefaultFiles before using a Knob with no ConfigurationFiles");
useDefaultFiles = false;
}
}
/**
* Return a value from the first configuration file which contains the specified key.
* <p>
* Ignore any files which do not exist. If none of the files contain the key, or the key is null, return defaultValue.
* If any file has not yet been retrieved from the server, we block until it can be retrieved.
*
* @param valueKey A key into the top-level object in that file, or null to force the default value.
* @param defaultValue Value to return if the file does not exist or does not contain the key.
* @param files The files in which we search for the value.
*/
public static Object get(java.lang.String valueKey, Object defaultValue, ConfigurationFile ... files) {
return new Knob(valueKey, defaultValue, files).get();
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to an Integer.
*/
public static java.lang.Integer getInteger(java.lang.String valueKey, java.lang.Integer defaultValue, ConfigurationFile ... files) {
return Converter.toInteger(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to an Long.
*/
public static java.lang.Long getLong(java.lang.String valueKey, java.lang.Long defaultValue, ConfigurationFile ... files) {
return Converter.toLong(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a Double.
*/
public static java.lang.Double getDouble(java.lang.String valueKey, java.lang.Double defaultValue, ConfigurationFile ... files) {
return Converter.toDouble(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a Boolean.
*/
public static java.lang.Boolean getBoolean(java.lang.String valueKey, java.lang.Boolean defaultValue, ConfigurationFile ... files) {
return Converter.toBoolean(get(valueKey, defaultValue, files));
}
/**
* Like {@link #get(java.lang.String, Object, ConfigurationFile[])}, but converts the value to a String.
*/
public static java.lang.String getString(java.lang.String valueKey, java.lang.String defaultValue, ConfigurationFile ... files) {
return Converter.toString(get(valueKey, defaultValue, files));
}
/**
* Return the value at the specified key in our file.
*
* If the file does not exist or does not contain the key (or the key is null), return our default value.
* If the file has not yet been retrieved from the server, we block until it can be retrieved.
*/
public Object get() {
return getWithTimeout(null);
}
/**
* Like get(), but if the file has not yet been retrieved from the server, and the specified time
* interval elapses before the file is retrieved from the server, throw a ScalyrDeadlineException.
*
* @throws ScalyrDeadlineException
*/
public Object getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return getWithTimeout(timeoutInMs, false);
}
/**
* Like get(), but if the file has not yet been retrieved from the server, and the specified time
* interval elapses before the file is retrieved from the server, throw a ScalyrDeadlineException.
*
* @param timeoutInMs Maximum amount of time to wait for the initial file retrieval. Null means
* to wait as long as needed.
* @param bypassCache If true, then we always examine the configuration file(s), rather than relying on
* our cached value for the knob.
*
* @throws ScalyrDeadlineException
*/
public Object getWithTimeout(java.lang.Long timeoutInMs, boolean bypassCache) throws ScalyrDeadlineException {
if (!bypassCache && valueUpToDate)
return value;
Object newValue = defaultValue;
boolean ensuredFileListener = false;
if (key != null) {
synchronized (this) {
uncachedFetchCount++;
if (uncachedFetchCount >= TuningConstants.KNOB_CACHE_THRESHOLD) {
// Ensure that we have a fileListener, so that we can update our value if the configuration
// file(s) change. We don't do this unless the knob is fetched repeatedly, because the fileListener
// will prevent this Knob object from ever being garbage collected.
ensureFileListener();
ensuredFileListener = true;
}
}
long entryTime = (timeoutInMs != null) ? ScalyrUtil.currentTimeMillis() : 0;
prepareFilesList();
for (ConfigurationFile file : files) {
JSONObject parsedFile;
try {
if (timeoutInMs != null) {
long elapsed = Math.max(ScalyrUtil.currentTimeMillis() - entryTime, 0);
parsedFile = file.getAsJsonWithTimeout(timeoutInMs - elapsed, timeoutInMs);
} else {
parsedFile = file.getAsJson();
}
} catch (BadConfigurationFileException ex) {
parsedFile = null;
Logging.log(Severity.info, Logging.tagKnobFileInvalid,
"Knob: ignoring file [" + file + "]: it does not contain valid JSON");
}
if (parsedFile != null && parsedFile.containsKey(key)) {
newValue = parsedFile.get(key);
break;
}
}
}
synchronized (this) {
Object oldValue = value;
boolean hadValue = hasValue;
value = newValue;
hasValue = true;
if (ensuredFileListener)
valueUpToDate = true;
if (!hadValue || !ScalyrUtil.equals(value, oldValue)) {
List<Consumer<Knob>> listenerSnapshot = new ArrayList<>(updateListeners);
for (Consumer<Knob> updateListener : listenerSnapshot) {
updateListener.accept(this);
}
}
return newValue;
}
}
/**
* Register a callback to be invoked whenever our value changes.
*/
public synchronized Knob addUpdateListener(Consumer<Knob> updateListener) {
if (updateListeners.size() == 0) {
ensureFileListener();
}
updateListeners.add(updateListener);
return this;
}
/**
* If we don't yet have a fileListener, then add one.
*/
private synchronized void ensureFileListener() {
if (fileListener == null) {
fileListener = updatedFile -> {
if (allFilesHaveValues())
getWithTimeout(null, true);
};
prepareFilesList();
for (ConfigurationFile file : files)
file.addUpdateListener(fileListener);
}
}
protected synchronized boolean allFilesHaveValues() {
prepareFilesList();
for (ConfigurationFile file : files)
if (!file.hasState())
return false;
return true;
}
/**
* De-register a callback. If the callback was not registered, we do nothing.
*/
public synchronized Knob removeUpdateListener(Consumer<Knob> updateListener) {
updateListeners.remove(updateListener);
return this;
}
/**
* No-op developer convenience/hygiene method: when defining a new Knob that
* we ought to cleanup at some point, add this method to the Knob declaration:
*
* ```
* final Knob.Boolean useOldImplementation = new Knob.Boolean("useOldImplementation", false).expireHint("12/15/2017");
* ```
*
* @param dateStr after which we may want to pull this knob. Not currently parsed.
* @return self for chaining
*/
public Knob expireHint(java.lang.String dateStr) {
return this;
}
/**
* Subclass of Knob which is specialized for Integer values, with or without SI.
*/
public static class Integer extends Knob {
public Integer(java.lang.String valueKey, java.lang.Integer defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Integer get() {
return convertWithSI(super.get());
}
@Override public java.lang.Integer getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return convertWithSI(super.getWithTimeout(timeoutInMs));
}
@Override public Integer expireHint(java.lang.String dateStr) {
return this;
}
private java.lang.Integer convertWithSI(Object obj) {
try {
return Converter.toInteger(obj);
} catch (RuntimeException ex) {
return Converter.parseNumberWithSI(obj).intValue();
}
}
}
/**
* Subclass of Knob which is specialized for Long values, with or without SI.
*/
public static class Long extends Knob {
public Long(java.lang.String valueKey, java.lang.Long defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Long get() {
return convertWithSI(super.get());
}
@Override public java.lang.Long getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return convertWithSI(super.getWithTimeout(timeoutInMs));
}
@Override public Long expireHint(java.lang.String dateStr) {
return this;
}
private java.lang.Long convertWithSI(Object obj) {
try {
return Converter.toLong(obj);
} catch (RuntimeException ex) {
return Converter.parseNumberWithSI(obj);
}
}
}
/**
* Subclass of Knob which is specialized for Double values.
*/
public static class Double extends Knob {
public Double(java.lang.String valueKey, java.lang.Double defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Double get() {
return Converter.toDouble(super.get());
}
@Override public java.lang.Double getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toDouble(super.getWithTimeout(timeoutInMs));
}
@Override public Double expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob which is specialized for Boolean values.
*/
public static class Boolean extends Knob {
public Boolean(java.lang.String valueKey, java.lang.Boolean defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.Boolean get() {
return Converter.toBoolean(super.get());
}
@Override public java.lang.Boolean getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toBoolean(super.getWithTimeout(timeoutInMs));
}
@Override public Boolean expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob which is specialized for String values.
*/
public static class String extends Knob {
public String(java.lang.String valueKey, java.lang.String defaultValue, ConfigurationFile ... files) {
super(valueKey, defaultValue, files);
}
@Override public java.lang.String get() {
return Converter.toString(super.get());
}
@Override public java.lang.String getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return Converter.toString(super.getWithTimeout(timeoutInMs));
}
@Override public String expireHint(java.lang.String dateStr) {
return this;
}
}
/**
* Subclass of Knob for durations, to make writing them nicer (eg. "2 minutes" or "1 day").
*/
public static class Duration extends Knob {
public Duration(java.lang.String valueKey, java.lang.Long defaultValue, TimeUnit defaultTimeUnit, ConfigurationFile ... files) {
//we'll always store default value in Nanoseconds
super(valueKey, TimeUnit.NANOSECONDS.convert(defaultValue, defaultTimeUnit), files);
}
/*
* OVERRIDING OLD METHODS
*/
//Since with get() we can't specify a unit for time, we'll return a java.time.Duration
@Override public java.time.Duration get() {
return this.getWithTimeout(null, false);
}
@Override public java.time.Duration getWithTimeout(java.lang.Long timeoutInMs) throws ScalyrDeadlineException {
return this.getWithTimeout(timeoutInMs, false);
}
@Override public java.time.Duration getWithTimeout(java.lang.Long timeoutInMs, boolean bypassCache) throws ScalyrDeadlineException {
Object value = super.getWithTimeout(timeoutInMs, bypassCache);
if (value instanceof java.lang.String) { //We got entry from config file
java.lang.String[] splitInput = ((java.lang.String) value).trim().split(" +");
try {
if (splitInput.length != 2) {
throw new RuntimeException();
}
return java.time.Duration.of(java.lang.Long.parseLong(splitInput[0]), convertTimeType(timeUnitMap.get(splitInput[1])));
} catch (NumberFormatException e) { //Error in magnitude format
throw new RuntimeException("Formatting error in your config file, in the magnitude of your time: \"" + splitInput[0] + "\"");
} catch (NullPointerException e) { //Error in unit format
throw new RuntimeException("Formatting error in your config file, in the units of your time: \"" + splitInput[1] + "\"");
} catch (RuntimeException e) { //Some other formatting error entirely
throw new RuntimeException("Formatting error in your config file: \"" + splitInput[0] + "\"");
}
} else { //Using default value
return java.time.Duration.of((long) value, ChronoUnit.NANOS);
}
}
@Override public Duration expireHint(java.lang.String dateStr) {
return this;
}
/*
* NEW METHODS
*/
public java.lang.Long seconds() {
return getTimeInFormat(TimeUnit.SECONDS);
}
public java.lang.Long millis() {
return getTimeInFormat(TimeUnit.MILLISECONDS);
}
public java.lang.Long micros() {
return getTimeInFormat(TimeUnit.MICROSECONDS);
}
public java.lang.Long nanos() {
return getTimeInFormat(TimeUnit.NANOSECONDS);
}
public java.lang.Long minutes() {
return getTimeInFormat(TimeUnit.MINUTES);
}
public java.lang.Long hours() {
return getTimeInFormat(TimeUnit.HOURS);
}
public java.lang.Long days() {
return getTimeInFormat(TimeUnit.DAYS);
}
/*
* HELPER STUFF
*/
private java.lang.Long getTimeInFormat(TimeUnit format) {
Object value = super.getWithTimeout(null, false);
if (value instanceof java.lang.String) { //We got entry from config file
java.lang.String[] splitInput = ((java.lang.String) value).trim().split(" +");
try {
if (splitInput.length != 2) {
throw new RuntimeException();
}
return format.convert(java.lang.Long.parseLong(splitInput[0]), timeUnitMap.get(splitInput[1]));
} catch (NumberFormatException e) { //Error in magnitude format
throw new RuntimeException("Formatting error in your config file, in the magnitude of your time: \"" + splitInput[0] + "\"");
} catch (NullPointerException e) { //Error in unit format
throw new RuntimeException("Formatting error in your config file, in the units of your time: \"" + splitInput[1] + "\"");
} catch (RuntimeException e) { //Some other formatting error entirely
throw new RuntimeException("Formatting error in your config file: \"" + splitInput[0] + "\"");
}
} else { //Using default value
return format.convert((long) value, TimeUnit.NANOSECONDS);
}
}
private static ChronoUnit convertTimeType(TimeUnit tu) {
if (tu == null) {
return null;
}
switch (tu) {
case DAYS:
return ChronoUnit.DAYS;
case HOURS:
return ChronoUnit.HOURS;
case MINUTES:
return ChronoUnit.MINUTES;
case SECONDS:
return ChronoUnit.SECONDS;
case MICROSECONDS:
return ChronoUnit.MICROS;
case MILLISECONDS:
return ChronoUnit.MILLIS;
case NANOSECONDS:
return ChronoUnit.NANOS;
default:
return null;
}
}
private static final Map<java.lang.String, TimeUnit> timeUnitMap = new HashMap<java.lang.String, TimeUnit>(){{
put("s" , TimeUnit.SECONDS ) ;
put("sec" , TimeUnit.SECONDS ) ;
put("secs" , TimeUnit.SECONDS ) ;
put("second" , TimeUnit.SECONDS ) ;
put("seconds" , TimeUnit.SECONDS ) ;
put("ms" , TimeUnit.MILLISECONDS ) ;
put("millis" , TimeUnit.MILLISECONDS ) ;
put("milliseconds" , TimeUnit.MILLISECONDS ) ;
put("micros" , TimeUnit.MICROSECONDS ) ;
put("microseconds" , TimeUnit.MICROSECONDS ) ;
put("\u03BC" , TimeUnit.MICROSECONDS ) ; // µ, or very similar-looking
put("\u03BCs" , TimeUnit.MICROSECONDS ) ;
put("\u00B5" , TimeUnit.MICROSECONDS ) ; // µ, or very similar-looking
put("\u00B5s" , TimeUnit.MICROSECONDS ) ;
put("ns" , TimeUnit.NANOSECONDS ) ;
put("nanos" , TimeUnit.NANOSECONDS ) ;
put("nanoseconds" , TimeUnit.NANOSECONDS ) ;
put("m" , TimeUnit.MINUTES ) ;
put("min" , TimeUnit.MINUTES ) ;
put("mins" , TimeUnit.MINUTES ) ;
put("minute" , TimeUnit.MINUTES ) ;
put("minutes" , TimeUnit.MINUTES ) ;
put("h" , TimeUnit.HOURS ) ;
put("hour" , TimeUnit.HOURS ) ;
put("hours" , TimeUnit.HOURS ) ;
put("d" , TimeUnit.DAYS ) ;
put("day" , TimeUnit.DAYS ) ;
put("days" , TimeUnit.DAYS ) ;
}};
}
}
|
changed error message a bit
|
src/main/com/scalyr/api/knobs/Knob.java
|
changed error message a bit
|
|
Java
|
apache-2.0
|
a341ed4f9a5895a3c2962bf3cb5ffb6ef48a8c42
| 0
|
adaptivecomputing/plugins-commons
|
package com.adaptc.mws.plugins;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* A service for easily creating new events and notification conditions. This service offloads the burden of
* generating fields such as "origin" and "code" to the plugin framework and provides enumerations to help write
* clean code without the use of magic strings. Note that while the service is called the event service, it also
* contains methods for dealing with notification conditions which are commonly related to events.
* <p/>
* For more information on how to use this service, see the MWS User Guide
* section on Plugin Event Service.
* @author bsaville
*/
public interface IPluginEventService {
/**
* The plugin component code for all plugins that do not explicitly define the value in the
* project or the plugin. This is used in generating the event code when creating events.
*/
public static final int UNKNOWN_PLUGIN_COMPONENT = 0xFF;
/**
* Determines the severity of the event.
*/
public enum Severity {
/**
* Represents an informational event
*/
INFO(0x0),
/**
* Represents an warning event
*/
WARN(0x1),
/**
* Represents an error event
*/
ERROR(0x2),
/**
* Represents a fatal event
*/
FATAL(0x3);
private int code;
public int getCode() {
return code;
}
private Severity(int code) {
this.code = code;
}
}
/**
* Determines who would be concerned with this event or notification condition.
*/
public enum EscalationLevel {
/**
* For typical users
*/
USER(0x0),
/**
* For power users and users
*/
POWER_USER(0x1),
/**
* For administrators, power users, and users
*/
ADMIN(0x2),
/**
* For internal events only, may <b>NOT</b> be used for notification conditions.
*/
INTERNAL(0x3);
private int code;
public int getCode() {
return code;
}
private EscalationLevel(int code) {
this.code = code;
}
}
/**
* Represents an object associated with an event.
*/
public class AssociatedObject {
/**
* The type of the associated object such as "Node", "VM", "Policy", etc.
*/
String type;
/**
* The id of the associated object.
*/
String id;
public AssociatedObject() {
// Default constructor
}
/**
* Map constructor used to allow map passing for lists of associated objects and making sure casting works
* as expected.
* @param map A map containing "type" and "id"
*/
public AssociatedObject(Map<String, String> map) {
if (map==null)
return;
this.type = map.get("type");
this.id = map.get("id");
}
}
/**
* Creates an event with the specified properties and using the current date as the event date.
* @param severity The severity of the event
* @param escalationLevel The escalation level of the event
* @param eventCode The unique (for each plugin with a correct plugin component code) code of the event
* @param eventType The event type, such as "Node Modify" or "VM Migrate", may be null
* @param originSuffix The suffix to append to the automatically generated origin, may be null ({@link IPluginEvent#getOriginSuffix()})
* @param message The fully resolved message describing the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Severity severity, EscalationLevel escalationLevel, int eventCode, String eventType,
String originSuffix, String message, List<String> arguments, List<AssociatedObject> objects)
throws Exception;
/**
* Same as {@link #createEvent(Severity, EscalationLevel, int, String, String, String, List, List)} but with
* a specified event date.
* @param eventDate The date that the event occurred
* @param severity The severity of the event
* @param escalationLevel The escalation level of the event
* @param eventCode The unique (for each plugin with a correct plugin component code) code of the event
* @param eventType The event type, such as "Node Modify" or "VM Migrate", may be null
* @param originSuffix The suffix to append to the automatically generated origin, may be null ({@link IPluginEvent#getOriginSuffix()})
* @param message The fully resolved message describing the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Date eventDate, Severity severity, EscalationLevel escalationLevel, int eventCode,
String eventType, String originSuffix, String message, List<String> arguments,
List<AssociatedObject> objects)
throws Exception;
/**
* Creates an event using a {@link IPluginEvent} value with the instance specific information of arguments and
* associated objects. The arguments will be used in combination with the message code to fully resolve
* the message when creating the actual event. The current date will be used as the event date.
* @param pluginEvent The non-null {@link IPluginEvent} value specifying the attributes of the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(IPluginEvent pluginEvent, List<String> arguments, List<AssociatedObject> objects)
throws Exception;
/**
* Same as {@link #createEvent(IPluginEvent, List, List)} but with a specified event date.
* @param eventDate The date that the event occurred
* @param pluginEvent The non-null {@link IPluginEvent} value specifying the attributes of the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Date eventDate, IPluginEvent pluginEvent, List<String> arguments,
List<AssociatedObject> objects)
throws Exception;
/**
* Creates or updates a notification condition with the specified properties and using the current date as the
* observed date and no expiration duration.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
*/
public void updateNotificationCondition(EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details)
throws Exception;
/**
* Creates or updates a notification condition with the specified properties and using the current date as the
* observed date.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
* @param expirationDuration The duration before the notification is marked as expired if not observed again
*/
public void updateNotificationCondition(EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details,
Long expirationDuration)
throws Exception;
/**
* Same as {@link #updateNotificationCondition(EscalationLevel, String, AssociatedObject, Map)} but with a
* specified observed date.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
*/
public void updateNotificationCondition(Date observedDate, EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details)
throws Exception;
/**
* Same as {@link #updateNotificationCondition(EscalationLevel, String, AssociatedObject, Map, Long)} but
* with a specified observed date.
* @param observedDate The date that the notification condition was observed
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
* @param expirationDuration The duration before the notification is marked as expired if not observed again
*/
public void updateNotificationCondition(Date observedDate, EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details,
Long expirationDuration)
throws Exception;
}
|
commons/src/main/java/com/adaptc/mws/plugins/IPluginEventService.java
|
package com.adaptc.mws.plugins;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* A service for easily creating new events and notification conditions. This service offloads the burden of
* generating fields such as "origin" and "code" to the plugin framework and provides enumerations to help write
* clean code without the use of magic strings. Note that while the service is called the event service, it also
* contains methods for dealing with notification conditions which are commonly related to events.
* <p/>
* For more information on how to use this service, see the MWS User Guide
* section on Plugin Event Service.
* @author bsaville
*/
public interface IPluginEventService {
/**
* The plugin component code for all plugins that do not explicitly define the value in the
* project or the plugin. This is used in generating the event code when creating events.
*/
public static final int UNKNOWN_PLUGIN_COMPONENT = 0xFF;
/**
* Determines the severity of the event.
*/
public enum Severity {
/**
* Represents an informational event
*/
INFO(0x0),
/**
* Represents an warning event
*/
WARN(0x1),
/**
* Represents an error event
*/
ERROR(0x2),
/**
* Represents a fatal event
*/
FATAL(0x3);
private int code;
public int getCode() {
return code;
}
private Severity(int code) {
this.code = code;
}
}
/**
* Determines who would be concerned with this event or notification condition.
*/
public enum EscalationLevel {
/**
* For typical users
*/
USER(0x0),
/**
* For power users and users
*/
POWER_USER(0x1),
/**
* For administrators, power users, and users
*/
ADMIN(0x2),
/**
* For internal events only, may <b>NOT</b> be used for notification conditions.
*/
INTERNAL(0x3);
private int code;
public int getCode() {
return code;
}
private EscalationLevel(int code) {
this.code = code;
}
}
/**
* Represents an object associated with an event.
*/
public class AssociatedObject {
/**
* The type of the associated object such as "Node", "VM", "Policy", etc.
*/
String type;
/**
* The id of the associated object.
*/
String id;
public AssociatedObject() {
// Default constructor
}
/**
* Map constructor used to allow map passing for lists of associated objects and making sure casting works
* as expected.
* @param map A map containing "type" and "id"
*/
public AssociatedObject(Map<String, String> map) {
if (map==null)
return;
this.type = map.get("type");
this.id = map.get("id");
}
}
/**
* Creates an event with the specified properties and using the current date as the event date.
* @param severity The severity of the event
* @param escalationLevel The escalation level of the event
* @param eventCode The unique (for each plugin with a correct plugin component code) code of the event
* @param eventType The event type, such as "Node Modify" or "VM Migrate", may be null
* @param originSuffix The suffix to append to the automatically generated origin, may be null ({@link IPluginEvent#getOriginSuffix()})
* @param message The fully resolved message describing the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Severity severity, EscalationLevel escalationLevel, int eventCode, String eventType,
String originSuffix, String message, List<String> arguments, List<AssociatedObject> objects)
throws Exception;
/**
* Same as {@link #createEvent(Severity, EscalationLevel, int, String, String, String, List, List)} but with
* a specified event date.
* @param eventDate The date that the event occurred
* @param severity The severity of the event
* @param escalationLevel The escalation level of the event
* @param eventCode The unique (for each plugin with a correct plugin component code) code of the event
* @param eventType The event type, such as "Node Modify" or "VM Migrate", may be null
* @param originSuffix The suffix to append to the automatically generated origin, may be null ({@link IPluginEvent#getOriginSuffix()})
* @param message The fully resolved message describing the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Date eventDate, Severity severity, EscalationLevel escalationLevel, int eventCode,
String eventType, String originSuffix, String message, List<String> arguments,
List<AssociatedObject> objects)
throws Exception;
/**
* Creates an event using a {@link IPluginEvent} value with the instance specific information of arguments and
* associated objects. The arguments will be used in combination with the message code to fully resolve
* the message when creating the actual event. The current date will be used as the event date.
* @param pluginEvent The non-null {@link IPluginEvent} value specifying the attributes of the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(IPluginEvent pluginEvent, List<String> arguments, List<AssociatedObject> objects)
throws Exception;
/**
* Same as {@link #createEvent(IPluginEvent, List, List)} but with a specified event date.
* @param eventDate The date that the event occurred
* @param pluginEvent The non-null {@link IPluginEvent} value specifying the attributes of the event
* @param arguments The arguments of the event message, may be null or empty
* @param objects A list of objects associated with the event, may be null or empty
*/
public void createEvent(Date eventDate, IPluginEvent pluginEvent, List<String> arguments,
List<AssociatedObject> objects)
throws Exception;
/**
* Creates or updates a notification condition with the specified properties and using the current date as the
* observed date and no expiration duration.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
*/
public void updateNotificationCondition(EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details)
throws Exception;
/**
* Creates or updates a notification condition with the specified properties and using the current date as the
* observed date.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
* @param expirationDuration The duration before the notification is marked as expired if not observed again
*/
public void updateNotificationCondition(EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details,
Long expirationDuration)
throws Exception;
/**
* Same as {@link #updateNotificationCondition(EscalationLevel, String, AssociatedObject, Map)} but with a
* specified observed date.
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
*/
public void updateNotificationCondition(Date observedDate, EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details)
throws Exception;
/**
* Same as {@link #updateNotificationCondition(EscalationLevel, String, AssociatedObject, Map, Long)} but
* with a specified observed date.
* @param observedDate The date that the notification condition was observed
* @param escalationLevel The escalation level of the notification, may not be INTERNAL
* @param message The full resolved message describing the notification
* @param associatedObject The object associated with the notification, such as Node "node1", may be null
* @param details Arbitrary details associated with the notification, may be null or empty
* @param expirationDuration The duration before the notification is marked as expired if not observed again
*/
public void createNotificationCondition(Date observedDate, EscalationLevel escalationLevel, String message,
AssociatedObject associatedObject, Map<String, String> details,
Long expirationDuration)
throws Exception;
}
|
Missed a method
|
commons/src/main/java/com/adaptc/mws/plugins/IPluginEventService.java
|
Missed a method
|
|
Java
|
apache-2.0
|
b8d8e0e1f78bd36524d65c101ac411c65df180ce
| 0
|
fortyrunner/hawtio,andytaylor/hawtio,skarsaune/hawtio,mposolda/hawtio,jfbreault/hawtio,mposolda/hawtio,hawtio/hawtio,tadayosi/hawtio,hawtio/hawtio,telefunken/hawtio,samkeeleyong/hawtio,padmaragl/hawtio,jfbreault/hawtio,voipme2/hawtio,samkeeleyong/hawtio,voipme2/hawtio,rajdavies/hawtio,tadayosi/hawtio,rajdavies/hawtio,hawtio/hawtio,stalet/hawtio,grgrzybek/hawtio,stalet/hawtio,fortyrunner/hawtio,grgrzybek/hawtio,padmaragl/hawtio,voipme2/hawtio,andytaylor/hawtio,andytaylor/hawtio,stalet/hawtio,tadayosi/hawtio,padmaragl/hawtio,uguy/hawtio,telefunken/hawtio,rajdavies/hawtio,grgrzybek/hawtio,Fatze/hawtio,mposolda/hawtio,skarsaune/hawtio,tadayosi/hawtio,uguy/hawtio,voipme2/hawtio,uguy/hawtio,andytaylor/hawtio,jfbreault/hawtio,fortyrunner/hawtio,andytaylor/hawtio,telefunken/hawtio,uguy/hawtio,skarsaune/hawtio,mposolda/hawtio,samkeeleyong/hawtio,skarsaune/hawtio,fortyrunner/hawtio,stalet/hawtio,mposolda/hawtio,padmaragl/hawtio,hawtio/hawtio,uguy/hawtio,skarsaune/hawtio,padmaragl/hawtio,rajdavies/hawtio,samkeeleyong/hawtio,telefunken/hawtio,Fatze/hawtio,Fatze/hawtio,Fatze/hawtio,samkeeleyong/hawtio,stalet/hawtio,jfbreault/hawtio,tadayosi/hawtio,Fatze/hawtio,jfbreault/hawtio,grgrzybek/hawtio,grgrzybek/hawtio,voipme2/hawtio,hawtio/hawtio,rajdavies/hawtio,telefunken/hawtio
|
package io.hawt.maven;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.artifact.MavenMetadataSource;
public abstract class BaseMojo extends AbstractMojo {
private long daemonThreadJoinTimeout = 15000L;
@Component
MavenProject project;
@Component
ArtifactResolver artifactResolver;
@Component
ArtifactFactory artifactFactory;
@Component
MavenProjectBuilder projectBuilder;
@Component
ArtifactMetadataSource metadataSource;
@Parameter(property = "localRepository", readonly = true, required = true)
ArtifactRepository localRepository;
@Parameter(property = "project.remoteArtifactRepositories")
List<?> remoteRepositories;
@Parameter(readonly = true, property = "plugin.artifacts")
List<Artifact> pluginDependencies;
@Parameter(readonly = true, property = "project.dependencyArtifacts")
Set<Artifact> projectDependencies;
@Parameter(property = "hawtio.logClasspath", defaultValue = "false")
boolean logClasspath;
@Parameter(property = "hawtio.logDependencies", defaultValue = "false")
boolean logDependencies;
@Parameter(property = "hawtio.offline", defaultValue = "false")
boolean offline;
String extraPluginDependencyArtifactId;
String extendedPluginDependencyArtifactId;
protected void doBeforeExecute() {
if (offline) {
getLog().info("hawtio is running in offline mode");
System.setProperty("hawtio.offline", "true");
}
}
protected void doAfterExecute() {
System.clearProperty("hawtio.offline");
}
/**
* Set up a classloader for the execution of the main class.
*
* @return the classloader
* @throws org.apache.maven.plugin.MojoExecutionException
*/
protected ClassLoader getClassLoader(Set<Artifact> artifacts) throws Exception {
Set<URL> classpathURLs = new LinkedHashSet<URL>();
addCustomClasspaths(classpathURLs, true);
// add ourselves to top of classpath
URL mainClasses = new File(project.getBuild().getOutputDirectory()).toURI().toURL();
getLog().debug("Adding to classpath : " + mainClasses);
classpathURLs.add(mainClasses);
for (Artifact artifact : artifacts) {
File file = artifact.getFile();
if (file != null) {
classpathURLs.add(file.toURI().toURL());
}
}
addCustomClasspaths(classpathURLs, false);
if (logClasspath) {
getLog().info("Classpath (" + classpathURLs.size() + " entries):");
for (URL url : classpathURLs) {
getLog().info(" " + url.getFile().toString());
}
}
return new URLClassLoader(classpathURLs.toArray(new URL[classpathURLs.size()]));
}
/**
* To add any custom urls to the classpath
*
* @param classpathURLs the resolved classpaths
*/
protected void addCustomClasspaths(Set<URL> classpathURLs, boolean first) throws Exception {
// noop
}
protected Set<Artifact> resolveArtifacts() throws Exception {
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
// project classpath must be first
this.addRelevantProjectDependencies(artifacts);
// and extra plugin classpath
this.addExtraPluginDependencies(artifacts);
// and plugin classpath last
this.addRelevantPluginDependencies(artifacts);
Iterator<Artifact> it = artifacts.iterator();
while (it.hasNext()) {
Artifact artifact = it.next();
if (filterUnwantedArtifacts(artifact)) {
getLog().info("Removing unwanted artifact: " + artifact);
it.remove();
}
}
return artifacts;
}
protected void resolvedArtifacts(Set<Artifact> artifacts) throws Exception {
if (logDependencies) {
List<Artifact> sorted = new ArrayList<Artifact>(artifacts);
Collections.sort(sorted);
getLog().info("Artifact (" + sorted.size() + " entries):");
for (Artifact artifact : sorted) {
getLog().info(" " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getType() + ":" + artifact.getVersion() + ":" + artifact.getScope());
}
}
}
/**
* Filter unwanted artifacts
*
* @param artifact the artifact
* @return <tt>true</tt> to skip this artifact, <tt>false</tt> to keep it
*/
protected boolean filterUnwantedArtifacts(Artifact artifact) {
// filter out maven and plexus stuff (plexus used by maven plugins)
if (artifact.getGroupId().startsWith("org.apache.maven")) {
return true;
} else if (artifact.getGroupId().startsWith("org.codehaus.plexus")) {
return true;
}
return false;
}
/**
* Add any relevant project dependencies to the classpath. Takes
* includeProjectDependencies into consideration.
*/
@SuppressWarnings("unchecked")
protected void addRelevantProjectDependencies(Set<Artifact> artifacts) throws Exception {
getLog().debug("Project Dependencies will be included.");
Set<Artifact> dependencies = project.getArtifacts();
getLog().debug("There are " + dependencies.size() + " dependencies in the project");
// system scope dependencies are not returned by maven 2.0. See MEXEC-17
dependencies.addAll(getAllNonTestOrProvidedScopedDependencies());
Iterator<Artifact> iter = dependencies.iterator();
while (iter.hasNext()) {
Artifact classPathElement = iter.next();
getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath");
artifacts.add(classPathElement);
}
}
/**
* Add any relevant project dependencies to the classpath. Indirectly takes
* includePluginDependencies and ExecutableDependency into consideration.
*/
protected void addExtraPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException {
if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) {
return;
}
Set<Artifact> deps = new HashSet<Artifact>(this.pluginDependencies);
for (Artifact artifact : deps) {
// must
if (artifact.getArtifactId().equals(extraPluginDependencyArtifactId)
|| artifact.getArtifactId().equals(extendedPluginDependencyArtifactId)) {
getLog().debug("Adding extra plugin dependency artifact: " + artifact.getArtifactId() + " to classpath");
artifacts.add(artifact);
// add the transient dependencies of this artifact
Set<Artifact> resolvedDeps = resolveExecutableDependencies(artifact);
for (Artifact dep : resolvedDeps) {
getLog().debug("Adding extra plugin dependency artifact: " + dep.getArtifactId() + " to classpath");
artifacts.add(dep);
}
}
}
}
/**
* Add any relevant project dependencies to the classpath.
*/
protected void addRelevantPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException {
if (pluginDependencies == null) {
return;
}
Iterator<Artifact> iter = this.pluginDependencies.iterator();
while (iter.hasNext()) {
Artifact classPathElement = iter.next();
getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath");
artifacts.add(classPathElement);
}
}
protected Collection<Artifact> getAllNonTestOrProvidedScopedDependencies() throws Exception {
List<Artifact> answer = new ArrayList<Artifact>();
for (Artifact artifact : getAllDependencies()) {
// do not add test or provided artifacts
if (!artifact.getScope().equals(Artifact.SCOPE_TEST) && !artifact.getScope().equals(Artifact.SCOPE_PROVIDED)) {
answer.add(artifact);
}
}
return answer;
}
// generic method to retrieve all the transitive dependencies
protected Collection<Artifact> getAllDependencies() throws Exception {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (Iterator<?> dependencies = project.getDependencies().iterator(); dependencies.hasNext();) {
Dependency dependency = (Dependency)dependencies.next();
String groupId = dependency.getGroupId();
String artifactId = dependency.getArtifactId();
VersionRange versionRange;
try {
versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new MojoExecutionException("unable to parse version", e);
}
String type = dependency.getType();
if (type == null) {
type = "jar";
}
String classifier = dependency.getClassifier();
boolean optional = dependency.isOptional();
String scope = dependency.getScope();
if (scope == null) {
scope = Artifact.SCOPE_COMPILE;
}
Artifact art = this.artifactFactory.createDependencyArtifact(groupId, artifactId, versionRange,
type, classifier, scope, null, optional);
if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
art.setFile(new File(dependency.getSystemPath()));
}
List<String> exclusions = new ArrayList<String>();
for (Iterator<?> j = dependency.getExclusions().iterator(); j.hasNext();) {
Exclusion e = (Exclusion)j.next();
exclusions.add(e.getGroupId() + ":" + e.getArtifactId());
}
ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
art.setDependencyFilter(newFilter);
artifacts.add(art);
}
return artifacts;
}
/**
* Get the artifact which refers to the POM of the executable artifact.
*
* @param executableArtifact this artifact refers to the actual assembly.
* @return an artifact which refers to the POM of the executable artifact.
*/
protected Artifact getExecutablePomArtifact(Artifact executableArtifact) {
return this.artifactFactory.createBuildArtifact(executableArtifact.getGroupId(), executableArtifact
.getArtifactId(), executableArtifact.getVersion(), "pom");
}
@SuppressWarnings("unchecked")
protected Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact) throws MojoExecutionException {
Set<Artifact> executableDependencies;
try {
MavenProject executableProject = this.projectBuilder.buildFromRepository(executablePomArtifact,
this.remoteRepositories,
this.localRepository);
// get all of the dependencies for the executable project
List<Artifact> dependencies = executableProject.getDependencies();
// make Artifacts of all the dependencies
Set<Artifact> dependencyArtifacts
= MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies,
null, null, null);
// not forgetting the Artifact of the project itself
dependencyArtifacts.add(executableProject.getArtifact());
// resolve all dependencies transitively to obtain a comprehensive
// list of assemblies
ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts,
executablePomArtifact,
Collections.emptyMap(),
this.localRepository,
this.remoteRepositories,
metadataSource, null,
Collections.emptyList());
executableDependencies = result.getArtifacts();
} catch (Exception ex) {
throw new MojoExecutionException("Encountered problems resolving dependencies of the executable "
+ "in preparation for its execution.", ex);
}
return executableDependencies;
}
protected void joinNonDaemonThreads(ThreadGroup threadGroup) {
boolean foundNonDaemon;
do {
foundNonDaemon = false;
Collection<Thread> threads = getActiveThreads(threadGroup);
for (Thread thread : threads) {
if (thread.isDaemon()) {
continue;
}
foundNonDaemon = true; // try again; maybe more threads were
// created while we were busy
joinThread(thread, 0);
}
} while (foundNonDaemon);
}
protected void joinThread(Thread thread, long timeoutMsecs) {
try {
getLog().info("Joining on thread " + thread);
thread.join(timeoutMsecs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // good practice if don't throw
getLog().warn("interrupted while joining against thread " + thread, e); // not
// expected!
}
// generally abnormal
if (thread.isAlive()) {
getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least "
+ timeoutMsecs + "msecs");
}
}
protected Collection<Thread> getActiveThreads(ThreadGroup threadGroup) {
Thread[] threads = new Thread[threadGroup.activeCount()];
int numThreads = threadGroup.enumerate(threads);
Collection<Thread> result = new ArrayList<Thread>(numThreads);
for (int i = 0; i < threads.length && threads[i] != null; i++) {
result.add(threads[i]);
}
// note: result should be modifiable
return result;
}
@SuppressWarnings("deprecation")
protected void terminateThreads(ThreadGroup threadGroup) {
long startTime = System.currentTimeMillis();
Set<Thread> uncooperativeThreads = new HashSet<Thread>(); // these were not responsive
// to interruption
for (Collection<Thread> threads = getActiveThreads(threadGroup); !threads.isEmpty(); threads = getActiveThreads(threadGroup), threads
.removeAll(uncooperativeThreads)) {
// Interrupt all threads we know about as of this instant (harmless
// if spuriously went dead (! isAlive())
// or if something else interrupted it ( isInterrupted() ).
for (Thread thread : threads) {
getLog().debug("interrupting thread " + thread);
thread.interrupt();
}
// Now join with a timeout and call stop() (assuming flags are set
// right)
for (Thread thread : threads) {
if (!thread.isAlive()) {
continue; // and, presumably it won't show up in
// getActiveThreads() next iteration
}
if (daemonThreadJoinTimeout <= 0) {
joinThread(thread, 0); // waits until not alive; no timeout
continue;
}
long timeout = daemonThreadJoinTimeout - (System.currentTimeMillis() - startTime);
if (timeout > 0) {
joinThread(thread, timeout);
}
if (!thread.isAlive()) {
continue;
}
uncooperativeThreads.add(thread); // ensure we don't process
getLog().warn("thread " + thread + " will linger despite being asked to die via interruption");
}
}
if (!uncooperativeThreads.isEmpty()) {
getLog().warn("NOTE: "
+ uncooperativeThreads.size()
+ " thread(s) did not finish despite being asked to "
+ " via interruption. This is not a problem with exec:java, it is a problem with the running code."
+ " Although not serious, it should be remedied.");
} else {
int activeCount = threadGroup.activeCount();
if (activeCount != 0) {
Thread[] threadsArray = new Thread[1];
threadGroup.enumerate(threadsArray);
getLog().debug("strange; " + activeCount + " thread(s) still active in the group "
+ threadGroup + " such as " + threadsArray[0]);
}
}
}
}
|
hawtio-maven-plugin/src/main/java/io/hawt/maven/BaseMojo.java
|
package io.hawt.maven;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.artifact.MavenMetadataSource;
public abstract class BaseMojo extends AbstractMojo {
private long daemonThreadJoinTimeout = 15000L;
@Component
MavenProject project;
@Component
ArtifactResolver artifactResolver;
@Component
ArtifactFactory artifactFactory;
@Component
MavenProjectBuilder projectBuilder;
@Component
ArtifactMetadataSource metadataSource;
@Parameter(property = "localRepository", readonly = true, required = true)
ArtifactRepository localRepository;
@Parameter(property = "project.remoteArtifactRepositories")
List<?> remoteRepositories;
@Parameter(readonly = true, property = "plugin.artifacts")
List<Artifact> pluginDependencies;
@Parameter(readonly = true, property = "project.dependencyArtifacts")
Set<Artifact> projectDependencies;
@Parameter(property = "hawtio.logClasspath", defaultValue = "false")
boolean logClasspath;
@Parameter(property = "hawtio.logDependencies", defaultValue = "false")
boolean logDependencies;
@Parameter(property = "hawtio.offline", defaultValue = "false")
boolean offline;
String extraPluginDependencyArtifactId;
String extendedPluginDependencyArtifactId;
protected void doBeforeExecute() {
if (offline) {
getLog().info("hawtio is running in offline mode");
System.setProperty("hawtio.offline", "true");
}
}
protected void doAfterExecute() {
System.clearProperty("hawtio.offline");
}
/**
* Set up a classloader for the execution of the main class.
*
* @return the classloader
* @throws org.apache.maven.plugin.MojoExecutionException
*/
protected ClassLoader getClassLoader(Set<Artifact> artifacts) throws Exception {
Set<URL> classpathURLs = new LinkedHashSet<URL>();
addCustomClasspaths(classpathURLs, true);
// add ourselves to top of classpath
URL mainClasses = new File(project.getBuild().getOutputDirectory()).toURI().toURL();
getLog().debug("Adding to classpath : " + mainClasses);
classpathURLs.add(mainClasses);
for (Artifact artifact : artifacts) {
classpathURLs.add(artifact.getFile().toURI().toURL());
}
addCustomClasspaths(classpathURLs, false);
if (logClasspath) {
getLog().info("Classpath (" + classpathURLs.size() + " entries):");
for (URL url : classpathURLs) {
getLog().info(" " + url.getFile().toString());
}
}
return new URLClassLoader(classpathURLs.toArray(new URL[classpathURLs.size()]));
}
/**
* To add any custom urls to the classpath
*
* @param classpathURLs the resolved classpaths
*/
protected void addCustomClasspaths(Set<URL> classpathURLs, boolean first) throws Exception {
// noop
}
protected Set<Artifact> resolveArtifacts() throws Exception {
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
// project classpath must be first
this.addRelevantProjectDependencies(artifacts);
// and extra plugin classpath
this.addExtraPluginDependencies(artifacts);
// and plugin classpath last
this.addRelevantPluginDependencies(artifacts);
Iterator<Artifact> it = artifacts.iterator();
while (it.hasNext()) {
Artifact artifact = it.next();
if (filterUnwantedArtifacts(artifact)) {
getLog().info("Removing unwanted artifact: " + artifact);
it.remove();
}
}
return artifacts;
}
protected void resolvedArtifacts(Set<Artifact> artifacts) throws Exception {
if (logDependencies) {
List<Artifact> sorted = new ArrayList<Artifact>(artifacts);
Collections.sort(sorted);
getLog().info("Artifact (" + sorted.size() + " entries):");
for (Artifact artifact : sorted) {
getLog().info(" " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getType() + ":" + artifact.getVersion() + ":" + artifact.getScope());
}
}
}
/**
* Filter unwanted artifacts
*
* @param artifact the artifact
* @return <tt>true</tt> to skip this artifact, <tt>false</tt> to keep it
*/
protected boolean filterUnwantedArtifacts(Artifact artifact) {
// filter out maven and plexus stuff (plexus used by maven plugins)
if (artifact.getGroupId().startsWith("org.apache.maven")) {
return true;
} else if (artifact.getGroupId().startsWith("org.codehaus.plexus")) {
return true;
}
return false;
}
/**
* Add any relevant project dependencies to the classpath. Takes
* includeProjectDependencies into consideration.
*/
@SuppressWarnings("unchecked")
protected void addRelevantProjectDependencies(Set<Artifact> artifacts) throws Exception {
getLog().debug("Project Dependencies will be included.");
Set<Artifact> dependencies = project.getArtifacts();
getLog().debug("There are " + dependencies.size() + " dependencies in the project");
// system scope dependencies are not returned by maven 2.0. See MEXEC-17
dependencies.addAll(getAllNonTestOrProvidedScopedDependencies());
Iterator<Artifact> iter = dependencies.iterator();
while (iter.hasNext()) {
Artifact classPathElement = iter.next();
getLog().debug("Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath");
artifacts.add(classPathElement);
}
}
/**
* Add any relevant project dependencies to the classpath. Indirectly takes
* includePluginDependencies and ExecutableDependency into consideration.
*/
protected void addExtraPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException {
if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) {
return;
}
Set<Artifact> deps = new HashSet<Artifact>(this.pluginDependencies);
for (Artifact artifact : deps) {
// must
if (artifact.getArtifactId().equals(extraPluginDependencyArtifactId)
|| artifact.getArtifactId().equals(extendedPluginDependencyArtifactId)) {
getLog().debug("Adding extra plugin dependency artifact: " + artifact.getArtifactId() + " to classpath");
artifacts.add(artifact);
// add the transient dependencies of this artifact
Set<Artifact> resolvedDeps = resolveExecutableDependencies(artifact);
for (Artifact dep : resolvedDeps) {
getLog().debug("Adding extra plugin dependency artifact: " + dep.getArtifactId() + " to classpath");
artifacts.add(dep);
}
}
}
}
/**
* Add any relevant project dependencies to the classpath.
*/
protected void addRelevantPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException {
if (pluginDependencies == null) {
return;
}
Iterator<Artifact> iter = this.pluginDependencies.iterator();
while (iter.hasNext()) {
Artifact classPathElement = iter.next();
getLog().debug("Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath");
artifacts.add(classPathElement);
}
}
protected Collection<Artifact> getAllNonTestOrProvidedScopedDependencies() throws Exception {
List<Artifact> answer = new ArrayList<Artifact>();
for (Artifact artifact : getAllDependencies()) {
// do not add test or provided artifacts
if (!artifact.getScope().equals(Artifact.SCOPE_TEST) && !artifact.getScope().equals(Artifact.SCOPE_PROVIDED)) {
answer.add(artifact);
}
}
return answer;
}
// generic method to retrieve all the transitive dependencies
protected Collection<Artifact> getAllDependencies() throws Exception {
List<Artifact> artifacts = new ArrayList<Artifact>();
for (Iterator<?> dependencies = project.getDependencies().iterator(); dependencies.hasNext();) {
Dependency dependency = (Dependency)dependencies.next();
String groupId = dependency.getGroupId();
String artifactId = dependency.getArtifactId();
VersionRange versionRange;
try {
versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
} catch (InvalidVersionSpecificationException e) {
throw new MojoExecutionException("unable to parse version", e);
}
String type = dependency.getType();
if (type == null) {
type = "jar";
}
String classifier = dependency.getClassifier();
boolean optional = dependency.isOptional();
String scope = dependency.getScope();
if (scope == null) {
scope = Artifact.SCOPE_COMPILE;
}
Artifact art = this.artifactFactory.createDependencyArtifact(groupId, artifactId, versionRange,
type, classifier, scope, null, optional);
if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
art.setFile(new File(dependency.getSystemPath()));
}
List<String> exclusions = new ArrayList<String>();
for (Iterator<?> j = dependency.getExclusions().iterator(); j.hasNext();) {
Exclusion e = (Exclusion)j.next();
exclusions.add(e.getGroupId() + ":" + e.getArtifactId());
}
ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
art.setDependencyFilter(newFilter);
artifacts.add(art);
}
return artifacts;
}
/**
* Get the artifact which refers to the POM of the executable artifact.
*
* @param executableArtifact this artifact refers to the actual assembly.
* @return an artifact which refers to the POM of the executable artifact.
*/
protected Artifact getExecutablePomArtifact(Artifact executableArtifact) {
return this.artifactFactory.createBuildArtifact(executableArtifact.getGroupId(), executableArtifact
.getArtifactId(), executableArtifact.getVersion(), "pom");
}
@SuppressWarnings("unchecked")
protected Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact) throws MojoExecutionException {
Set<Artifact> executableDependencies;
try {
MavenProject executableProject = this.projectBuilder.buildFromRepository(executablePomArtifact,
this.remoteRepositories,
this.localRepository);
// get all of the dependencies for the executable project
List<Artifact> dependencies = executableProject.getDependencies();
// make Artifacts of all the dependencies
Set<Artifact> dependencyArtifacts
= MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies,
null, null, null);
// not forgetting the Artifact of the project itself
dependencyArtifacts.add(executableProject.getArtifact());
// resolve all dependencies transitively to obtain a comprehensive
// list of assemblies
ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts,
executablePomArtifact,
Collections.emptyMap(),
this.localRepository,
this.remoteRepositories,
metadataSource, null,
Collections.emptyList());
executableDependencies = result.getArtifacts();
} catch (Exception ex) {
throw new MojoExecutionException("Encountered problems resolving dependencies of the executable "
+ "in preparation for its execution.", ex);
}
return executableDependencies;
}
protected void joinNonDaemonThreads(ThreadGroup threadGroup) {
boolean foundNonDaemon;
do {
foundNonDaemon = false;
Collection<Thread> threads = getActiveThreads(threadGroup);
for (Thread thread : threads) {
if (thread.isDaemon()) {
continue;
}
foundNonDaemon = true; // try again; maybe more threads were
// created while we were busy
joinThread(thread, 0);
}
} while (foundNonDaemon);
}
protected void joinThread(Thread thread, long timeoutMsecs) {
try {
getLog().info("Joining on thread " + thread);
thread.join(timeoutMsecs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // good practice if don't throw
getLog().warn("interrupted while joining against thread " + thread, e); // not
// expected!
}
// generally abnormal
if (thread.isAlive()) {
getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least "
+ timeoutMsecs + "msecs");
}
}
protected Collection<Thread> getActiveThreads(ThreadGroup threadGroup) {
Thread[] threads = new Thread[threadGroup.activeCount()];
int numThreads = threadGroup.enumerate(threads);
Collection<Thread> result = new ArrayList<Thread>(numThreads);
for (int i = 0; i < threads.length && threads[i] != null; i++) {
result.add(threads[i]);
}
// note: result should be modifiable
return result;
}
@SuppressWarnings("deprecation")
protected void terminateThreads(ThreadGroup threadGroup) {
long startTime = System.currentTimeMillis();
Set<Thread> uncooperativeThreads = new HashSet<Thread>(); // these were not responsive
// to interruption
for (Collection<Thread> threads = getActiveThreads(threadGroup); !threads.isEmpty(); threads = getActiveThreads(threadGroup), threads
.removeAll(uncooperativeThreads)) {
// Interrupt all threads we know about as of this instant (harmless
// if spuriously went dead (! isAlive())
// or if something else interrupted it ( isInterrupted() ).
for (Thread thread : threads) {
getLog().debug("interrupting thread " + thread);
thread.interrupt();
}
// Now join with a timeout and call stop() (assuming flags are set
// right)
for (Thread thread : threads) {
if (!thread.isAlive()) {
continue; // and, presumably it won't show up in
// getActiveThreads() next iteration
}
if (daemonThreadJoinTimeout <= 0) {
joinThread(thread, 0); // waits until not alive; no timeout
continue;
}
long timeout = daemonThreadJoinTimeout - (System.currentTimeMillis() - startTime);
if (timeout > 0) {
joinThread(thread, timeout);
}
if (!thread.isAlive()) {
continue;
}
uncooperativeThreads.add(thread); // ensure we don't process
getLog().warn("thread " + thread + " will linger despite being asked to die via interruption");
}
}
if (!uncooperativeThreads.isEmpty()) {
getLog().warn("NOTE: "
+ uncooperativeThreads.size()
+ " thread(s) did not finish despite being asked to "
+ " via interruption. This is not a problem with exec:java, it is a problem with the running code."
+ " Although not serious, it should be remedied.");
} else {
int activeCount = threadGroup.activeCount();
if (activeCount != 0) {
Thread[] threadsArray = new Thread[1];
threadGroup.enumerate(threadsArray);
getLog().debug("strange; " + activeCount + " thread(s) still active in the group "
+ threadGroup + " such as " + threadsArray[0]);
}
}
}
}
|
avoid possible NPE
|
hawtio-maven-plugin/src/main/java/io/hawt/maven/BaseMojo.java
|
avoid possible NPE
|
|
Java
|
apache-2.0
|
b3adf192a1483adebb71d23ad8d16fb5f872cb30
| 0
|
cuba-platform/cuba,cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,dimone-kun/cuba
|
/*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.web;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Events;
import com.haulmont.cuba.core.global.GlobalConfig;
import com.haulmont.cuba.core.global.MessageTools;
import com.haulmont.cuba.gui.components.Frame;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.executors.IllegalConcurrentAccessException;
import com.haulmont.cuba.gui.settings.SettingsClient;
import com.haulmont.cuba.gui.theme.ThemeConstants;
import com.haulmont.cuba.gui.theme.ThemeConstantsRepository;
import com.haulmont.cuba.security.app.UserSessionService;
import com.haulmont.cuba.security.global.LoginException;
import com.haulmont.cuba.security.global.NoUserSessionException;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.auth.WebAuthConfig;
import com.haulmont.cuba.web.controllers.ControllerUtils;
import com.haulmont.cuba.web.exception.ExceptionHandlers;
import com.haulmont.cuba.web.log.AppLog;
import com.haulmont.cuba.web.security.events.SessionHeartbeatEvent;
import com.haulmont.cuba.web.settings.WebSettingsClient;
import com.haulmont.cuba.web.sys.AppCookies;
import com.haulmont.cuba.web.sys.BackgroundTaskManager;
import com.haulmont.cuba.web.sys.LinkHandler;
import com.vaadin.server.AbstractClientConnector;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import java.util.*;
import java.util.concurrent.Future;
/**
* Central class of the web application. An instance of this class is created for each client's session and is bound
* to {@link VaadinSession}.
* <br>
* Use {@link #getInstance()} static method to obtain the reference to the current App instance.
*/
public abstract class App {
public static final String NAME = "cuba_App";
public static final String USER_SESSION_ATTR = "userSessionId";
public static final String APP_THEME_COOKIE_PREFIX = "APP_THEME_NAME_";
public static final String COOKIE_LOCALE = "LAST_LOCALE";
private static final Logger log = LoggerFactory.getLogger(App.class);
static {
AbstractClientConnector.setIncorrectConcurrentAccessHandler(() -> {
throw new IllegalConcurrentAccessException();
});
}
protected AppLog appLog;
protected Connection connection;
protected ExceptionHandlers exceptionHandlers;
@Inject
protected GlobalConfig globalConfig;
@Inject
protected WebConfig webConfig;
@Inject
protected WebAuthConfig webAuthConfig;
@Inject
protected WindowConfig windowConfig;
@Inject
protected ThemeConstantsRepository themeConstantsRepository;
@Inject
protected UserSessionService userSessionService;
@Inject
protected MessageTools messageTools;
@Inject
protected SettingsClient settingsClient;
@Inject
protected Events events;
protected AppCookies cookies;
protected LinkHandler linkHandler;
protected BackgroundTaskManager backgroundTaskManager = new BackgroundTaskManager();
protected String webResourceTimestamp = "DEBUG";
protected ThemeConstants themeConstants;
public App() {
log.trace("Creating application {}", this);
}
protected ThemeConstants loadTheme() {
String appWindowTheme = webConfig.getAppWindowTheme();
String userAppTheme = cookies.getCookieValue(APP_THEME_COOKIE_PREFIX + globalConfig.getWebContextName());
if (userAppTheme != null) {
if (!Objects.equals(userAppTheme, appWindowTheme)) {
// check theme support
Set<String> supportedThemes = themeConstantsRepository.getAvailableThemes();
if (supportedThemes.contains(userAppTheme)) {
appWindowTheme = userAppTheme;
}
}
}
ThemeConstants theme = themeConstantsRepository.getConstants(appWindowTheme);
if (theme == null) {
throw new IllegalStateException("Unable to use theme constants '" + appWindowTheme + "'");
}
return theme;
}
protected void applyTheme(String appWindowTheme) {
ThemeConstants theme = themeConstantsRepository.getConstants(appWindowTheme);
if (theme == null) {
log.warn("Unable to use theme constants '{}'", appWindowTheme);
} else {
this.themeConstants = theme;
setUserAppTheme(appWindowTheme);
}
}
/**
* Initializes exception handlers immediately after login and logout.
* Can be overridden in descendants to manipulate exception handlers programmatically.
*
* @param isConnected true after login, false after logout
*/
protected void initExceptionHandlers(boolean isConnected) {
if (isConnected) {
exceptionHandlers.createByConfiguration();
} else {
exceptionHandlers.removeAll();
}
}
/**
* @return currently displayed top-level window
*/
public Window.TopLevelWindow getTopLevelWindow() {
return getAppUI().getTopLevelWindow();
}
/**
* @return current UI
*/
public AppUI getAppUI() {
return AppUI.getCurrent();
}
public ThemeConstants getThemeConstants() {
return themeConstants;
}
public List<AppUI> getAppUIs() {
List<AppUI> list = new ArrayList<>();
for (UI ui : VaadinSession.getCurrent().getUIs()) {
if (ui instanceof AppUI)
list.add((AppUI) ui);
else
log.warn("Invalid UI in the session: {}", ui);
}
return list;
}
public abstract void loginOnStart() throws LoginException;
protected Connection createConnection() {
return AppBeans.getPrototype(Connection.NAME);
}
/**
* Called when <em>the first</em> UI of the session is initialized.
*/
protected void init(Locale requestLocale) {
VaadinSession vSession = VaadinSession.getCurrent();
vSession.setAttribute(App.class, this);
vSession.setLocale(messageTools.getDefaultLocale());
// set root error handler for all session
vSession.setErrorHandler(event -> {
try {
getExceptionHandlers().handle(event);
getAppLog().log(event);
} catch (Throwable e) {
//noinspection ThrowableResultOfMethodCallIgnored
log.error("Error handling exception\nOriginal exception:\n{}\nException in handlers:\n{}",
ExceptionUtils.getStackTrace(event.getThrowable()), ExceptionUtils.getStackTrace(e)
);
}
});
appLog = new AppLog();
connection = createConnection();
exceptionHandlers = new ExceptionHandlers(this);
cookies = new AppCookies();
themeConstants = loadTheme();
VaadinServlet vaadinServlet = VaadinServlet.getCurrent();
ServletContext sc = vaadinServlet.getServletContext();
String resourcesTimestamp = sc.getInitParameter("webResourcesTs");
if (StringUtils.isNotEmpty(resourcesTimestamp)) {
this.webResourceTimestamp = resourcesTimestamp;
}
log.debug("Initializing application");
// get default locale from config
Locale targetLocale = resolveLocale(requestLocale);
setLocale(targetLocale);
}
protected Locale resolveLocale(@Nullable Locale requestLocale) {
Map<String, Locale> locales = globalConfig.getAvailableLocales();
if (globalConfig.getLocaleSelectVisible()) {
String lastLocale = getCookieValue(COOKIE_LOCALE);
if (lastLocale != null) {
for (Locale locale : locales.values()) {
if (locale.toLanguageTag().equals(lastLocale)) {
return locale;
}
}
}
}
if (requestLocale != null) {
Locale requestTrimmedLocale = messageTools.trimLocale(requestLocale);
if (locales.containsValue(requestTrimmedLocale)) {
return requestTrimmedLocale;
}
// if not found and application locale contains country, try to match by language only
if (!StringUtils.isEmpty(requestLocale.getCountry())) {
Locale appLocale = Locale.forLanguageTag(requestLocale.getLanguage());
for (Locale locale : locales.values()) {
if (Locale.forLanguageTag(locale.getLanguage()).equals(appLocale)) {
return locale;
}
}
}
}
// return default locale
return messageTools.getDefaultLocale();
}
/**
* Called on each browser tab initialization.
*/
public void createTopLevelWindow(AppUI ui) {
WebWindowManager wm = AppBeans.getPrototype(WebWindowManager.NAME);
wm.setUi(ui);
String topLevelWindowId = routeTopLevelWindowId();
wm.createTopLevelWindow(windowConfig.getWindowInfo(topLevelWindowId));
}
protected abstract String routeTopLevelWindowId();
public void createTopLevelWindow() {
createTopLevelWindow(AppUI.getCurrent());
}
/**
* Initialize new TopLevelWindow and replace current
*
* @param topLevelWindowId target top level window id
*/
public void navigateTo(String topLevelWindowId) {
WebWindowManager wm = AppBeans.getPrototype(WebWindowManager.NAME);
wm.setUi(AppUI.getCurrent());
wm.createTopLevelWindow(windowConfig.getWindowInfo(topLevelWindowId));
}
/**
* Called from heartbeat request. <br>
* Used for ping middleware session and show session messages
*/
public void onHeartbeat() {
Connection connection = getConnection();
boolean sessionIsAlive = false;
if (connection.isAuthenticated()) {
// Ping middleware session if connected and show messages
log.debug("Ping middleware session");
try {
String message = userSessionService.getMessages();
sessionIsAlive = true;
if (message != null) {
message = message.replace("\n", "<br/>");
getWindowManager().showNotification(message, Frame.NotificationType.ERROR_HTML);
}
} catch (NoUserSessionException ignored) {
// ignore no user session exception
} catch (Exception e) {
log.warn("Exception while session ping", e);
}
}
if (sessionIsAlive) {
events.publish(new SessionHeartbeatEvent(this));
}
}
/**
* @return Current App instance. Can be invoked anywhere in application code.
* @throws IllegalStateException if no application instance is bound to the current {@link VaadinSession}
*/
public static App getInstance() {
VaadinSession vSession = VaadinSession.getCurrent();
if (vSession == null) {
throw new IllegalStateException("No VaadinSession found");
}
if (!vSession.hasLock()) {
throw new IllegalStateException("VaadinSession is not owned by the current thread");
}
App app = vSession.getAttribute(App.class);
if (app == null) {
throw new IllegalStateException("No App is bound to the current VaadinSession");
}
return app;
}
/**
* @return true if an {@link App} instance is currently bound and can be safely obtained by {@link #getInstance()}
*/
public static boolean isBound() {
VaadinSession vSession = VaadinSession.getCurrent();
return vSession != null
&& vSession.hasLock()
&& vSession.getAttribute(App.class) != null;
}
/**
* @return Current connection object
*/
public Connection getConnection() {
return connection;
}
/**
* @return WindowManager instance or null if the current UI has no MainWindow
*/
public WebWindowManager getWindowManager() {
if (getAppUI() == null) {
return null;
}
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
return topLevelWindow != null ? (WebWindowManager) topLevelWindow.getWindowManager() : null;
}
public AppLog getAppLog() {
return appLog;
}
public ExceptionHandlers getExceptionHandlers() {
return exceptionHandlers;
}
public String getCookieValue(String name) {
return cookies.getCookieValue(name);
}
public int getCookieMaxAge(String name) {
return cookies.getCookieMaxAge(name);
}
public void addCookie(String name, String value, int maxAge) {
cookies.addCookie(name, value, maxAge);
}
public void addCookie(String name, String value) {
cookies.addCookie(name, value);
}
public void removeCookie(String name) {
cookies.removeCookie(name);
}
public Locale getLocale() {
return VaadinSession.getCurrent().getLocale();
}
public void setLocale(Locale locale) {
UserSession session = getConnection().getSession();
if (session != null) {
session.setLocale(locale);
}
AppUI currentUi = AppUI.getCurrent();
// it can be null if we handle request in a custom RequestHandler
if (currentUi != null) {
currentUi.setLocale(locale);
currentUi.updateClientSystemMessages(locale);
}
VaadinSession.getCurrent().setLocale(locale);
for (AppUI ui : getAppUIs()) {
if (ui != currentUi) {
ui.accessSynchronously(() -> {
ui.setLocale(locale);
ui.updateClientSystemMessages(locale);
});
}
}
}
public void setUserAppTheme(String themeName) {
addCookie(APP_THEME_COOKIE_PREFIX + globalConfig.getWebContextName(), themeName);
}
public String getWebResourceTimestamp() {
return webResourceTimestamp;
}
public void addBackgroundTask(Future task) {
backgroundTaskManager.addTask(task);
}
public void removeBackgroundTask(Future task) {
backgroundTaskManager.removeTask(task);
}
public void cleanupBackgroundTasks() {
backgroundTaskManager.cleanupTasks();
}
public void closeAllWindows() {
log.debug("Closing all windows");
try {
for (AppUI ui : getAppUIs()) {
ui.accessSynchronously(() -> {
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
if (topLevelWindow != null) {
WebWindowManager webWindowManager = (WebWindowManager) topLevelWindow.getWindowManager();
webWindowManager.disableSavingScreenHistory = true;
webWindowManager.closeAll();
}
// also remove all native Vaadin windows, that is not under CUBA control
for (com.vaadin.ui.Window win : new ArrayList<>(ui.getWindows())) {
ui.removeWindow(win);
}
});
}
} catch (Throwable e) {
log.error("Error closing all windows", e);
}
}
protected void clearSettingsCache() {
((WebSettingsClient) settingsClient).clearCache();
}
/**
* Try to perform logout. If there are unsaved changes in opened windows then logout will not be performed and
* unsaved changes dialog will appear.
*/
public void logout() {
logout(null);
}
/**
* Try to perform logout. If there are unsaved changes in opened windows then logout will not be performed and
* unsaved changes dialog will appear.
*
* @param runWhenLoggedOut runnable that will be invoked if user decides to logout
*/
public void logout(@Nullable Runnable runWhenLoggedOut) {
try {
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
if (topLevelWindow != null) {
topLevelWindow.saveSettings();
WebWindowManager wm = (WebWindowManager) topLevelWindow.getWindowManager();
wm.checkModificationsAndCloseAll(() -> {
Connection connection = getConnection();
connection.logout();
if (runWhenLoggedOut != null) {
runWhenLoggedOut.run();
}
});
} else {
Connection connection = getConnection();
connection.logout();
if (runWhenLoggedOut != null) {
runWhenLoggedOut.run();
}
}
} catch (Exception e) {
log.error("Error on logout", e);
String url = ControllerUtils.getLocationWithoutParams() + "?restartApp";
AppUI.getCurrent().getPage().open(url, "_self");
}
}
}
|
modules/web/src/com/haulmont/cuba/web/App.java
|
/*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.web;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Events;
import com.haulmont.cuba.core.global.GlobalConfig;
import com.haulmont.cuba.core.global.MessageTools;
import com.haulmont.cuba.gui.components.Frame;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.executors.IllegalConcurrentAccessException;
import com.haulmont.cuba.gui.settings.SettingsClient;
import com.haulmont.cuba.gui.theme.ThemeConstants;
import com.haulmont.cuba.gui.theme.ThemeConstantsRepository;
import com.haulmont.cuba.security.app.UserSessionService;
import com.haulmont.cuba.security.global.LoginException;
import com.haulmont.cuba.security.global.NoUserSessionException;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.auth.WebAuthConfig;
import com.haulmont.cuba.web.controllers.ControllerUtils;
import com.haulmont.cuba.web.exception.ExceptionHandlers;
import com.haulmont.cuba.web.log.AppLog;
import com.haulmont.cuba.web.security.events.SessionHeartbeatEvent;
import com.haulmont.cuba.web.settings.WebSettingsClient;
import com.haulmont.cuba.web.sys.AppCookies;
import com.haulmont.cuba.web.sys.BackgroundTaskManager;
import com.haulmont.cuba.web.sys.LinkHandler;
import com.vaadin.server.AbstractClientConnector;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import java.util.*;
import java.util.concurrent.Future;
/**
* Central class of the web application. An instance of this class is created for each client's session and is bound
* to {@link VaadinSession}.
* <br>
* Use {@link #getInstance()} static method to obtain the reference to the current App instance.
*/
public abstract class App {
public static final String NAME = "cuba_App";
public static final String USER_SESSION_ATTR = "userSessionId";
public static final String APP_THEME_COOKIE_PREFIX = "APP_THEME_NAME_";
public static final String COOKIE_LOCALE = "LAST_LOCALE";
private static final Logger log = LoggerFactory.getLogger(App.class);
static {
AbstractClientConnector.setIncorrectConcurrentAccessHandler(() -> {
throw new IllegalConcurrentAccessException();
});
}
protected AppLog appLog;
protected Connection connection;
protected ExceptionHandlers exceptionHandlers;
@Inject
protected GlobalConfig globalConfig;
@Inject
protected WebConfig webConfig;
@Inject
protected WebAuthConfig webAuthConfig;
@Inject
protected WindowConfig windowConfig;
@Inject
protected ThemeConstantsRepository themeConstantsRepository;
@Inject
protected UserSessionService userSessionService;
@Inject
protected MessageTools messageTools;
@Inject
protected SettingsClient settingsClient;
@Inject
protected Events events;
protected AppCookies cookies;
protected LinkHandler linkHandler;
protected BackgroundTaskManager backgroundTaskManager = new BackgroundTaskManager();
protected String webResourceTimestamp = "DEBUG";
protected ThemeConstants themeConstants;
public App() {
log.trace("Creating application {}", this);
}
protected ThemeConstants loadTheme() {
String appWindowTheme = webConfig.getAppWindowTheme();
String userAppTheme = cookies.getCookieValue(APP_THEME_COOKIE_PREFIX + globalConfig.getWebContextName());
if (userAppTheme != null) {
if (!Objects.equals(userAppTheme, appWindowTheme)) {
// check theme support
Set<String> supportedThemes = themeConstantsRepository.getAvailableThemes();
if (supportedThemes.contains(userAppTheme)) {
appWindowTheme = userAppTheme;
}
}
}
ThemeConstants theme = themeConstantsRepository.getConstants(appWindowTheme);
if (theme == null) {
throw new IllegalStateException("Unable to use theme constants '" + appWindowTheme + "'");
}
return theme;
}
protected void applyTheme(String appWindowTheme) {
ThemeConstants theme = themeConstantsRepository.getConstants(appWindowTheme);
if (theme == null) {
log.warn("Unable to use theme constants '{}'", appWindowTheme);
} else {
this.themeConstants = theme;
setUserAppTheme(appWindowTheme);
}
}
/**
* Initializes exception handlers immediately after login and logout.
* Can be overridden in descendants to manipulate exception handlers programmatically.
*
* @param isConnected true after login, false after logout
*/
protected void initExceptionHandlers(boolean isConnected) {
if (isConnected) {
exceptionHandlers.createByConfiguration();
} else {
exceptionHandlers.removeAll();
}
}
/**
* @return currently displayed top-level window
*/
public Window.TopLevelWindow getTopLevelWindow() {
return getAppUI().getTopLevelWindow();
}
/**
* @return current UI
*/
public AppUI getAppUI() {
return AppUI.getCurrent();
}
public ThemeConstants getThemeConstants() {
return themeConstants;
}
public List<AppUI> getAppUIs() {
List<AppUI> list = new ArrayList<>();
for (UI ui : VaadinSession.getCurrent().getUIs()) {
if (ui instanceof AppUI)
list.add((AppUI) ui);
else
log.warn("Invalid UI in the session: {}", ui);
}
return list;
}
public abstract void loginOnStart() throws LoginException;
protected Connection createConnection() {
return AppBeans.getPrototype(Connection.NAME);
}
/**
* Called when <em>the first</em> UI of the session is initialized.
*/
protected void init(Locale requestLocale) {
VaadinSession vSession = VaadinSession.getCurrent();
vSession.setAttribute(App.class, this);
vSession.setLocale(messageTools.getDefaultLocale());
// set root error handler for all session
vSession.setErrorHandler(event -> {
try {
getExceptionHandlers().handle(event);
getAppLog().log(event);
} catch (Throwable e) {
//noinspection ThrowableResultOfMethodCallIgnored
log.error("Error handling exception\nOriginal exception:\n{}\nException in handlers:\n{}",
ExceptionUtils.getStackTrace(event.getThrowable()), ExceptionUtils.getStackTrace(e)
);
}
});
appLog = new AppLog();
connection = createConnection();
exceptionHandlers = new ExceptionHandlers(this);
cookies = new AppCookies();
themeConstants = loadTheme();
VaadinServlet vaadinServlet = VaadinServlet.getCurrent();
ServletContext sc = vaadinServlet.getServletContext();
String resourcesTimestamp = sc.getInitParameter("webResourcesTs");
if (StringUtils.isNotEmpty(resourcesTimestamp)) {
this.webResourceTimestamp = resourcesTimestamp;
}
log.debug("Initializing application");
// get default locale from config
Locale targetLocale = resolveLocale(requestLocale);
setLocale(targetLocale);
}
protected Locale resolveLocale(@Nullable Locale requestLocale) {
Map<String, Locale> locales = globalConfig.getAvailableLocales();
if (globalConfig.getLocaleSelectVisible()) {
String lastLocale = getCookieValue(COOKIE_LOCALE);
if (lastLocale != null) {
for (Locale locale : locales.values()) {
if (locale.toLanguageTag().equals(lastLocale)) {
return locale;
}
}
}
}
if (requestLocale != null) {
Locale requestTrimmedLocale = messageTools.trimLocale(requestLocale);
if (locales.containsValue(requestTrimmedLocale)) {
return requestTrimmedLocale;
}
// if not found and application locale contains country, try to match by language only
if (!StringUtils.isEmpty(requestLocale.getCountry())) {
Locale appLocale = Locale.forLanguageTag(requestLocale.getLanguage());
for (Locale locale : locales.values()) {
if (Locale.forLanguageTag(locale.getLanguage()).equals(appLocale)) {
return locale;
}
}
}
}
// return default locale
return messageTools.getDefaultLocale();
}
/**
* Called on each browser tab initialization.
*/
public void createTopLevelWindow(AppUI ui) {
WebWindowManager wm = AppBeans.getPrototype(WebWindowManager.NAME);
wm.setUi(ui);
String topLevelWindowId = routeTopLevelWindowId();
wm.createTopLevelWindow(windowConfig.getWindowInfo(topLevelWindowId));
}
protected abstract String routeTopLevelWindowId();
public void createTopLevelWindow() {
createTopLevelWindow(AppUI.getCurrent());
}
/**
* Initialize new TopLevelWindow and replace current
*
* @param topLevelWindowId target top level window id
*/
public void navigateTo(String topLevelWindowId) {
WebWindowManager wm = AppBeans.getPrototype(WebWindowManager.NAME);
wm.setUi(AppUI.getCurrent());
wm.createTopLevelWindow(windowConfig.getWindowInfo(topLevelWindowId));
}
/**
* Called from heartbeat request. <br>
* Used for ping middleware session and show session messages
*/
public void onHeartbeat() {
Connection connection = getConnection();
boolean sessionIsAlive = false;
if (connection.isAuthenticated()) {
// Ping middleware session if connected and show messages
log.debug("Ping middleware session");
try {
String message = userSessionService.getMessages();
sessionIsAlive = true;
if (message != null) {
message = message.replace("\n", "<br/>");
getWindowManager().showNotification(message, Frame.NotificationType.ERROR_HTML);
}
} catch (NoUserSessionException ignored) {
// ignore no user session exception
} catch (Exception e) {
log.warn("Exception while session ping", e);
}
}
if (sessionIsAlive) {
events.publish(new SessionHeartbeatEvent(this));
}
}
/**
* @return Current App instance. Can be invoked anywhere in application code.
* @throws IllegalStateException if no application instance is bound to the current {@link VaadinSession}
*/
public static App getInstance() {
VaadinSession vSession = VaadinSession.getCurrent();
if (vSession == null) {
throw new IllegalStateException("No VaadinSession found");
}
App app = vSession.getAttribute(App.class);
if (app == null) {
throw new IllegalStateException("No App is bound to the current VaadinSession");
}
return app;
}
/**
* @return true if an {@link App} instance is currently bound and can be safely obtained by {@link #getInstance()}
*/
public static boolean isBound() {
VaadinSession vSession = VaadinSession.getCurrent();
return vSession != null
&& vSession.hasLock()
&& vSession.getAttribute(App.class) != null;
}
/**
* @return Current connection object
*/
public Connection getConnection() {
return connection;
}
/**
* @return WindowManager instance or null if the current UI has no MainWindow
*/
public WebWindowManager getWindowManager() {
if (getAppUI() == null) {
return null;
}
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
return topLevelWindow != null ? (WebWindowManager) topLevelWindow.getWindowManager() : null;
}
public AppLog getAppLog() {
return appLog;
}
public ExceptionHandlers getExceptionHandlers() {
return exceptionHandlers;
}
public String getCookieValue(String name) {
return cookies.getCookieValue(name);
}
public int getCookieMaxAge(String name) {
return cookies.getCookieMaxAge(name);
}
public void addCookie(String name, String value, int maxAge) {
cookies.addCookie(name, value, maxAge);
}
public void addCookie(String name, String value) {
cookies.addCookie(name, value);
}
public void removeCookie(String name) {
cookies.removeCookie(name);
}
public Locale getLocale() {
return VaadinSession.getCurrent().getLocale();
}
public void setLocale(Locale locale) {
UserSession session = getConnection().getSession();
if (session != null) {
session.setLocale(locale);
}
AppUI currentUi = AppUI.getCurrent();
// it can be null if we handle request in a custom RequestHandler
if (currentUi != null) {
currentUi.setLocale(locale);
currentUi.updateClientSystemMessages(locale);
}
VaadinSession.getCurrent().setLocale(locale);
for (AppUI ui : getAppUIs()) {
if (ui != currentUi) {
ui.accessSynchronously(() -> {
ui.setLocale(locale);
ui.updateClientSystemMessages(locale);
});
}
}
}
public void setUserAppTheme(String themeName) {
addCookie(APP_THEME_COOKIE_PREFIX + globalConfig.getWebContextName(), themeName);
}
public String getWebResourceTimestamp() {
return webResourceTimestamp;
}
public void addBackgroundTask(Future task) {
backgroundTaskManager.addTask(task);
}
public void removeBackgroundTask(Future task) {
backgroundTaskManager.removeTask(task);
}
public void cleanupBackgroundTasks() {
backgroundTaskManager.cleanupTasks();
}
public void closeAllWindows() {
log.debug("Closing all windows");
try {
for (AppUI ui : getAppUIs()) {
ui.accessSynchronously(() -> {
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
if (topLevelWindow != null) {
WebWindowManager webWindowManager = (WebWindowManager) topLevelWindow.getWindowManager();
webWindowManager.disableSavingScreenHistory = true;
webWindowManager.closeAll();
}
// also remove all native Vaadin windows, that is not under CUBA control
for (com.vaadin.ui.Window win : new ArrayList<>(ui.getWindows())) {
ui.removeWindow(win);
}
});
}
} catch (Throwable e) {
log.error("Error closing all windows", e);
}
}
protected void clearSettingsCache() {
((WebSettingsClient) settingsClient).clearCache();
}
/**
* Try to perform logout. If there are unsaved changes in opened windows then logout will not be performed and
* unsaved changes dialog will appear.
*/
public void logout() {
logout(null);
}
/**
* Try to perform logout. If there are unsaved changes in opened windows then logout will not be performed and
* unsaved changes dialog will appear.
*
* @param runWhenLoggedOut runnable that will be invoked if user decides to logout
*/
public void logout(@Nullable Runnable runWhenLoggedOut) {
try {
Window.TopLevelWindow topLevelWindow = getTopLevelWindow();
if (topLevelWindow != null) {
topLevelWindow.saveSettings();
WebWindowManager wm = (WebWindowManager) topLevelWindow.getWindowManager();
wm.checkModificationsAndCloseAll(() -> {
Connection connection = getConnection();
connection.logout();
if (runWhenLoggedOut != null) {
runWhenLoggedOut.run();
}
});
} else {
Connection connection = getConnection();
connection.logout();
if (runWhenLoggedOut != null) {
runWhenLoggedOut.run();
}
}
} catch (Exception e) {
log.error("Error on logout", e);
String url = ControllerUtils.getLocationWithoutParams() + "?restartApp";
AppUI.getCurrent().getPage().open(url, "_self");
}
}
}
|
PL-10316 WebUserSessionSource does not check if VaadinSession is locked by the current thread
|
modules/web/src/com/haulmont/cuba/web/App.java
|
PL-10316 WebUserSessionSource does not check if VaadinSession is locked by the current thread
|
|
Java
|
bsd-3-clause
|
408fcced8e1071c4171a0da1e00858d9d0a6a0eb
| 0
|
paul-hammant/BDD_framework_proof_of_concept
|
package newjb.core;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* One scenario done three different ways.
* The scenario being a failing scenario wrapped in three pairs of before/after steps.
*/
public class IntegrationTest {
// Simple class to test
public static class Calculator {
private int value;
public Calculator(int startingValue) {
value = startingValue;
}
public void add(int num) {
value = value + num;
}
public Integer currentValue() {
return value;
}
public void divide(int num) {
value = value / num;
}
}
public static class CalculatorSteps {
private Calculator calculator;
@Given("a current value of (.*)")
public void givenAValueOf(String x) {
calculator = new Calculator(Integer.parseInt(x));
}
@When("(.*) is added")
public void numberIsAdded(String num) {
calculator.add(Integer.parseInt(num));
}
@When("(.*) is divided")
public void numberIsDivided(String num) {
calculator.divide(Integer.parseInt(num));
}
@Then("the result is (.*)")
public void thenEventsJustSo(String shouldBe) {
assertThat(calculator.currentValue(), is(equalTo(Integer.parseInt(shouldBe))));
}
}
@Test
public void calculatorShouldBeAbleToAddTwoNumbers() {
test("Sc( Given a current value of 1✓ When 1 is added✓ Then the result is 2✓ ✓)",
"Given a current value of 1",
"When 1 is added",
"Then the result is 2");
test("Sc( Given a current value of 2✓ When 2 is added✓ Then the result is 4✓ ✓)",
"Given a current value of 2",
"When 2 is added",
"Then the result is 4");
test("Sc( Given a current value of 1✓ When -1 is added✓ Then the result is 0✓ ✓)",
"Given a current value of 1",
"When -1 is added",
"Then the result is 0");
}
private void test(String expectation, String... steps) {
LittleEventLanguage monitor = new LittleEventLanguage();
Scenario scenario = new ScenarioFactory(CalculatorSteps.class)
.withSteps(steps)
.createScenario();
DefaultStepFactory stepFactory = new DefaultStepFactory();
Method[] meths = CalculatorSteps.class.getDeclaredMethods();
CalculatorSteps calcSteps = new CalculatorSteps();
for (Method method : meths) {
stepFactory.add(method, calcSteps);
}
boolean passed = scenario.perform(stepFactory, monitor);
assertThat("scenario did not pass: " + monitor.eventString(),
passed, is(equalTo(true)));
assertThat(monitor.eventString(), is(equalTo(expectation)));
}
@Test
public void calculatorShouldBeAbleToFivideTwoNumbers() {
test("Sc( Given a current value of 1✓ When 1 is divided✓ Then the result is 1✓ ✓)",
"Given a current value of 1",
"When 1 is divided",
"Then the result is 1");
test("Sc( Given a current value of 4✓ When 2 is divided✓ Then the result is 2✓ ✓)",
"Given a current value of 4",
"When 2 is divided",
"Then the result is 2");
try {
test("Sc( Given a current value of 11✓ When 0 is divided(/ by zero) Then the result is infinity- ✗)",
"Given a current value of 11",
"When 0 is divided",
"Then the result is infinity");
fail("should have barfed");
} catch (AssertionError e) {
assertThat(e.getMessage().trim(), is(equalTo("scenario did not pass: Sc( Given a current value of 11✓ When 0 is divided(/ by zero) Then the result is infinity- ✗)\n" +
"Expected: is <true>\n" +
" got: <false>")));
}
}
}
|
src/test/java/newjb/core/IntegrationTest.java
|
package newjb.core;
import org.junit.Test;
import java.lang.reflect.Method;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* One scenario done three different ways.
* The scenario being a failing scenario wrapped in three pairs of before/after steps.
*/
public class IntegrationTest {
// Simple class to test
public static class Calculator {
private int value;
public Calculator(int startingValue) {
value = startingValue;
}
public void add(int num) {
value = value + num;
}
public Integer currentValue() {
return value;
}
}
public static class CalculatorSteps {
private Calculator calculator;
@Given("a current value of (.*)")
public void givenAValueOf(String x) {
calculator = new Calculator(Integer.parseInt(x));
}
@When("(.*) is added")
public void numberIsAdded(String num) {
calculator.add(Integer.parseInt(num));
}
@Then("the result is (.*)")
public void thenEventsJustSo(String shouldBe) {
assertThat(calculator.currentValue(), is(equalTo(Integer.parseInt(shouldBe))));
}
}
@Test
public void calculatorShouldBeAbleToAddTwoNumbers() {
addTest("Sc( Given a current value of 1✓ When 1 is added✓ Then the result is 2✓ ✓)",
"Given a current value of 1",
"When 1 is added",
"Then the result is 2");
addTest("Sc( Given a current value of 2✓ When 2 is added✓ Then the result is 4✓ ✓)",
"Given a current value of 2",
"When 2 is added",
"Then the result is 4");
addTest("Sc( Given a current value of 1✓ When -1 is added✓ Then the result is 0✓ ✓)",
"Given a current value of 1",
"When -1 is added",
"Then the result is 0");
}
private void addTest(String expectation, String... steps) {
LittleEventLanguage monitor = new LittleEventLanguage();
Scenario scenario = new ScenarioFactory(CalculatorSteps.class)
.withSteps(steps)
.createScenario();
DefaultStepFactory stepFactory = new DefaultStepFactory();
Method[] meths = CalculatorSteps.class.getDeclaredMethods();
CalculatorSteps calcSteps = new CalculatorSteps();
for (Method method : meths) {
stepFactory.add(method, calcSteps);
}
boolean passed = scenario.perform(stepFactory, monitor);
assertThat("scenario did not pass: " + monitor.eventString(),
passed, is(equalTo(true)));
assertThat(monitor.eventString(), is(equalTo(expectation)));
}
}
|
another example, this time with an expected failure
|
src/test/java/newjb/core/IntegrationTest.java
|
another example, this time with an expected failure
|
|
Java
|
bsd-3-clause
|
a16a2479c361e1ab09dd3edc14c6832e5e3e391a
| 0
|
WillerZ/snique-client-android
|
package com.nomzit.snique;
import static com.nomzit.snique.Utilities.extractBytesFromHexInString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CacheManager;
import android.webkit.WebView;
public class SniqueActivity extends Activity {
private WebView wv;
private static final byte keyRaw[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc,
(byte) 0xdd, (byte) 0xee, (byte) 0xff };
private SniqueMessageDecoder decoder;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle(R.string.app_name);
try
{
decoder = new SniqueMessageDecoder(keyRaw);
}
catch (WillNeverWorkException e)
{
Log.e("SniqueActivity", "Could not create decoder",e);
System.exit(4);
}
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
SniqueWebViewClient wvc = new SniqueWebViewClient(this);
wv.setWebViewClient(wvc);
String url = "http://blog.nomzit.com/snique/";
// Get HTML and decode outside of UI thread to avoid blocking UI.
new NetworkTask().execute(url);
}
protected void pageLoading(SniqueWebViewClient wvc, Bitmap favicon) {
try {
Method getActionBarMethod = this.getClass().getMethod("getActionBar", (Class<?>) null);
Object actionBar = getActionBarMethod.invoke(this, (Object) null);
Method setIconMethod = actionBar.getClass().getMethod("setIcon", Drawable.class);
setIconMethod.invoke(actionBar, new BitmapDrawable(favicon));
} catch (SecurityException e) {
Log.e("SniqueActivity", "Security exception getting getActionBar() method", e);
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
Log.e("SniqueActivity", "Illegal argument exception calling getActionBar() method", e);
} catch (IllegalAccessException e) {
Log.e("SniqueActivity", "Illegal access exception calling getActionBar() method", e);
} catch (InvocationTargetException e) {
Log.e("SniqueActivity", "Invocation target exception calling getActionBar() method", e);
}
}
private void displayData(SniqueMessage message)
{
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.when = System.currentTimeMillis();
notification.defaults = Notification.DEFAULT_ALL;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.statusbar;
notification.setLatestEventInfo(getApplicationContext(), "snique", message.getMessage(), null);
notificationManager.notify(message.getId(), notification);
}
public void resetTitle() {
this.setTitle(R.string.app_name);
}
public SniqueMessage decodeData(String html) throws InvalidKeyException, NoMessageException, WillNeverWorkException
{
Log.d("SniqueActivity", "decodeData");
Pattern findsrc = Pattern.compile("src\\s*=\\s*['\"]([^']*)['\"]");
Matcher srcMatcher = findsrc.matcher(html);
boolean hassrc = srcMatcher.find();
if (!hassrc) {
Log.d("SniqueActivity", "No src tags");
return null;
}
List<String> urls = new ArrayList<String>();
do
{
String srcUrl = srcMatcher.group(1);
urls.add(srcUrl);
}
while (srcMatcher.find());
List<String> etags = new ArrayList<String>();
for (String imgUrl : urls)
{
Log.d("SniqueActivity", imgUrl);
// CacheManager seems to work well enough to be used for retrieving image data successfully.
CacheManager.CacheResult imgCr = CacheManager.getCacheFile(imgUrl, null);
String ETag = null;
if (imgCr != null)
{
ETag = imgCr.getETag();
}
else
{
// However, if we get here we couldn't find the image in the cache.
// At least we only need to get the headers, not the entire image.
Log.d("SniqueActivity", "Image " + imgUrl + " not in cache, downloading headers");
try
{
HttpURLConnection con = (HttpURLConnection) new URL(imgUrl).openConnection();
con.connect();
ETag = con.getHeaderField("ETag");
}
catch (MalformedURLException e)
{
Log.e("SniqueActivity", "MalformedURLException", e);
}
catch (IOException e)
{
Log.e("SniqueActivity", "IOException", e);
}
}
if (ETag == null)
continue;
Log.d("SniqueActivity", ETag);
if ((ETag.charAt(0) == 'W') || (ETag.charAt(0) == 'w'))
ETag = ETag.substring(2, ETag.length() - 1);
else
ETag = ETag.substring(1, ETag.length() - 1);
etags.add(ETag);
}
urls = null;
Log.d("SniqueActivity", "etags are" + etags);
byte message[][] = new byte[etags.size()][];
int messageIndex = 0;
for (String etag:etags)
{
byte newFragment[] = extractBytesFromHexInString(etag);
if (newFragment.length > 0)
message[messageIndex++] = newFragment;
}
return decoder.decodeMessage(new CodedMessage(message));
}
protected class NetworkTask extends AsyncTask<String, Void, SniqueMessage>
{
@Override
protected SniqueMessage doInBackground(String... params)
{
// Retrieve HTML source from URL being loaded
String url = params[0];
String html = null;
String mimeType = "text/html";
String charSet = "US-ASCII";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
Header acceptEncoding = new BasicHeader("Accept-Encoding","gzip;q=1.0, identity;q=0.5, deflate;q=0.1, *;q=0");
request.setHeader(acceptEncoding);
HttpResponse response = client.execute(request);
Header headers[] = response.getHeaders("content-type");
for (Header contentType: headers)
{
String value = contentType.getValue();
Pattern findMime = Pattern.compile("\\s*([^;\\s]*)");
Matcher mimeMatcher = findMime.matcher(value);
boolean hasMime = mimeMatcher.find();
if (hasMime)
{
mimeType = mimeMatcher.group(1);
}
else
{
Log.i("SniqueActivity", "No MIME type in response for url "+ url);
}
Pattern findCharset = Pattern.compile(";\\s*charset\\s*=\\s*([^;\\s]*)");
Matcher charsetMatcher = findCharset.matcher(value);
boolean hasCharset = charsetMatcher.find();
if (hasCharset)
{
charSet = charsetMatcher.group(1);
}
else
{
Log.i("SniqueActivity", "No character set in response for url "+ url);
}
}
boolean hasGzip = false;
boolean hasDeflate = false;
headers = response.getHeaders("content-encoding");
for (Header contentEncoding: headers)
{
String value = contentEncoding.getValue();
Pattern findGzip = Pattern.compile("\\s*(gzip)",Pattern.CASE_INSENSITIVE);
Matcher gzipMatcher = findGzip.matcher(value);
hasGzip = gzipMatcher.find();
Log.i("SniqueActivity", "gzip content-encoding? "+ hasGzip);
Pattern findDeflate = Pattern.compile("\\s*(deflate)",Pattern.CASE_INSENSITIVE);
Matcher deflateMatcher = findDeflate.matcher(value);
hasDeflate = deflateMatcher.find();
Log.i("SniqueActivity", "deflate content-encoding? "+ hasDeflate);
if (!(hasGzip || hasDeflate))
Log.e("SniqueActivity", "Cannot process content-encoding: "+ value);
}
InputStream in = response.getEntity().getContent();
if (hasGzip)
in = new GZIPInputStream(in);
else if (hasDeflate)
in = new InflaterInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(in,Charset.forName(charSet)));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (html == null)
{
return null;
}
// Display page in WebView
wv.loadDataWithBaseURL(url, html, mimeType, charSet, null);
// Check for data to decode
SniqueMessage data = null;
try
{
data = decodeData(html);
}
catch (InvalidKeyException e)
{
Log.e("SniqueActivity - Network Task", "Invalid Key", e);
}
catch (NoMessageException e)
{
Log.d("SniqueActivity - Network Task", "No Message");
}
catch (WillNeverWorkException e)
{
Log.e("SniqueActivity - Network Task", "Decoding will never work", e);
}
return data;
}
@Override
protected void onPostExecute(SniqueMessage message) {
if (message != null) {
// We have a decoded message, return to UI thread
displayData(message);
} else {
// No message detected, so reset the title of the activity
resetTitle();
}
}
}
}
|
src/com/nomzit/snique/SniqueActivity.java
|
package com.nomzit.snique;
import static com.nomzit.snique.Utilities.extractBytesFromHexInString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.CacheManager;
import android.webkit.WebView;
public class SniqueActivity extends Activity {
private WebView wv;
private static final byte keyRaw[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc,
(byte) 0xdd, (byte) 0xee, (byte) 0xff };
private SniqueMessageDecoder decoder;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle(R.string.app_name);
try
{
decoder = new SniqueMessageDecoder(keyRaw);
}
catch (WillNeverWorkException e)
{
Log.e("SniqueActivity", "Could not create decoder",e);
System.exit(4);
}
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
SniqueWebViewClient wvc = new SniqueWebViewClient(this);
wv.setWebViewClient(wvc);
String url = "http://blog.nomzit.com/snique/";
// Get HTML and decode outside of UI thread to avoid blocking UI.
new NetworkTask().execute(url);
}
protected void pageLoading(SniqueWebViewClient wvc, Bitmap favicon) {
try {
Method getActionBarMethod = this.getClass().getMethod("getActionBar", (Class<?>) null);
Object actionBar = getActionBarMethod.invoke(this, (Object) null);
Method setIconMethod = actionBar.getClass().getMethod("setIcon", Drawable.class);
setIconMethod.invoke(actionBar, new BitmapDrawable(favicon));
} catch (SecurityException e) {
Log.e("SniqueActivity", "Security exception getting getActionBar() method", e);
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
Log.e("SniqueActivity", "Illegal argument exception calling getActionBar() method", e);
} catch (IllegalAccessException e) {
Log.e("SniqueActivity", "Illegal access exception calling getActionBar() method", e);
} catch (InvocationTargetException e) {
Log.e("SniqueActivity", "Invocation target exception calling getActionBar() method", e);
}
}
private void displayData(SniqueMessage message)
{
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.when = System.currentTimeMillis();
notification.defaults = Notification.DEFAULT_ALL;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.statusbar;
notification.setLatestEventInfo(getApplicationContext(), "snique", message.getMessage(), null);
notificationManager.notify(message.getId(), notification);
}
public void resetTitle() {
this.setTitle(R.string.app_name);
}
public SniqueMessage decodeData(String html) throws InvalidKeyException, NoMessageException, WillNeverWorkException
{
Log.d("SniqueActivity", "decodeData");
Pattern findsrc = Pattern.compile("src\\s*=\\s*['\"]([^']*)['\"]");
Matcher srcMatcher = findsrc.matcher(html);
boolean hassrc = srcMatcher.find();
if (!hassrc) {
Log.d("SniqueActivity", "No src tags");
return null;
}
List<String> urls = new ArrayList<String>();
do
{
String srcUrl = srcMatcher.group(1);
urls.add(srcUrl);
}
while (srcMatcher.find());
List<String> etags = new ArrayList<String>();
for (String imgUrl : urls)
{
Log.d("SniqueActivity", imgUrl);
// CacheManager seems to work well enough to be used for retrieving image data successfully.
CacheManager.CacheResult imgCr = CacheManager.getCacheFile(imgUrl, null);
String ETag = null;
if (imgCr != null)
{
ETag = imgCr.getETag();
}
else
{
// However, if we get here we couldn't find the image in the cache.
// At least we only need to get the headers, not the entire image.
Log.d("SniqueActivity", "Image " + imgUrl + " not in cache, downloading headers");
try
{
HttpURLConnection con = (HttpURLConnection) new URL(imgUrl).openConnection();
con.connect();
ETag = con.getHeaderField("ETag");
}
catch (MalformedURLException e)
{
Log.e("SniqueActivity", "MalformedURLException", e);
}
catch (IOException e)
{
Log.e("SniqueActivity", "IOException", e);
}
}
if (ETag == null)
continue;
Log.d("SniqueActivity", ETag);
if ((ETag.charAt(0) == 'W') || (ETag.charAt(0) == 'w'))
ETag = ETag.substring(2, ETag.length() - 1);
else
ETag = ETag.substring(1, ETag.length() - 1);
etags.add(ETag);
}
urls = null;
Log.d("SniqueActivity", "etags are" + etags);
byte message[][] = new byte[etags.size()][];
int messageIndex = 0;
for (String etag:etags)
{
byte newFragment[] = extractBytesFromHexInString(etag);
if (newFragment.length > 0)
message[messageIndex++] = newFragment;
}
return decoder.decodeMessage(new CodedMessage(message));
}
protected class NetworkTask extends AsyncTask<String, Void, SniqueMessage>
{
@Override
protected SniqueMessage doInBackground(String... params)
{
// Retrieve HTML source from URL being loaded
String url = params[0];
String html = null;
String mimeType = "text/html";
String charSet = "US-ASCII";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header headers[] = response.getHeaders("content-type");
for (Header contentType: headers)
{
String value = contentType.getValue();
Pattern findMime = Pattern.compile("\\s*([^;\\s]*)");
Matcher mimeMatcher = findMime.matcher(value);
boolean hasMime = mimeMatcher.find();
if (hasMime)
{
mimeType = mimeMatcher.group(1);
}
else
{
Log.i("SniqueActivity", "No MIME type in response for url "+ url);
}
Pattern findCharset = Pattern.compile(";\\s*charset\\s*=\\s*([^;\\s]*)");
Matcher charsetMatcher = findCharset.matcher(value);
boolean hasCharset = charsetMatcher.find();
if (hasCharset)
{
charSet = charsetMatcher.group(1);
}
else
{
Log.i("SniqueActivity", "No character set in response for url "+ url);
}
}
boolean hasGzip = false;
boolean hasCompress = false;
boolean hasDeflate = false;
headers = response.getHeaders("content-encoding");
for (Header contentEncoding: headers)
{
String value = contentEncoding.getValue();
Log.i("SniqueActivity", "content-encoding: "+ value);
Pattern findGzip = Pattern.compile("\\s*(gzip)",Pattern.CASE_INSENSITIVE);
Matcher gzipMatcher = findGzip.matcher(value);
hasGzip = gzipMatcher.find();
Log.i("SniqueActivity", "gzip content-encoding? "+ hasGzip);
Pattern findCompress = Pattern.compile("\\s*(compress)",Pattern.CASE_INSENSITIVE);
Matcher compressMatcher = findCompress.matcher(value);
hasCompress = compressMatcher.find();
Log.i("SniqueActivity", "compress content-encoding? "+ hasCompress);
Pattern findDeflate = Pattern.compile("\\s*(deflate)",Pattern.CASE_INSENSITIVE);
Matcher deflateMatcher = findDeflate.matcher(value);
hasDeflate = deflateMatcher.find();
Log.i("SniqueActivity", "deflate content-encoding? "+ hasDeflate);
}
InputStream in = response.getEntity().getContent();
if (hasGzip)
in = new GZIPInputStream(in);
else if (hasDeflate)
in = new InflaterInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(in,Charset.forName(charSet)));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (html == null)
{
return null;
}
// Display page in WebView
wv.loadDataWithBaseURL(url, html, mimeType, charSet, null);
// Check for data to decode
SniqueMessage data = null;
try
{
data = decodeData(html);
}
catch (InvalidKeyException e)
{
Log.e("SniqueActivity - Network Task", "Invalid Key", e);
}
catch (NoMessageException e)
{
Log.d("SniqueActivity - Network Task", "No Message");
}
catch (WillNeverWorkException e)
{
Log.e("SniqueActivity - Network Task", "Decoding will never work", e);
}
return data;
}
@Override
protected void onPostExecute(SniqueMessage message) {
if (message != null) {
// We have a decoded message, return to UI thread
displayData(message);
} else {
// No message detected, so reset the title of the activity
resetTitle();
}
}
}
}
|
Improvements to http encoding logic
Remove 'compress' detection as we can't decode it.
Set Accept-Encoding on the requests to indicate we prefer gzip over
identity, identity over deflate, and can't process anything else.
|
src/com/nomzit/snique/SniqueActivity.java
|
Improvements to http encoding logic
|
|
Java
|
bsd-3-clause
|
4d916863730db464754cc5ee0bf95f4dd66bbae0
| 0
|
applidium/Shutterbug
|
package com.applidium.shutterbugdemo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.applidium.shutterbug.FetchableImageView;
import com.applidium.shutterbug.cache.ImageCache;
public class ShutterbugActivity extends Activity {
private ListView mListView;
private DemoAdapter mAdapter;
private ProgressDialog mProgressDialog;
private List<String> mUrls = new ArrayList<String>();
private List<String> mTitles = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shutterbug);
mListView = (ListView) findViewById(R.id.list);
mAdapter = new DemoAdapter();
mListView.setAdapter(mAdapter);
Button b = (Button) findViewById(R.id.clear_cache_button);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ImageCache.getSharedImageCache(ShutterbugActivity.this).clear();
mAdapter.notifyDataSetChanged();
}
});
loadGalleryContents();
}
private class DemoAdapter extends BaseAdapter {
public int getCount() {
return mUrls.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.shutterbug_demo_row, null);
}
TextView text = (TextView) view.findViewById(R.id.text);
text.setText("#" + position + ": " + mTitles.get(position));
FetchableImageView image = (FetchableImageView) view.findViewById(R.id.image);
image.setImage(mUrls.get(position));
return view;
}
}
private void loadGalleryContents() {
mProgressDialog = ProgressDialog.show(this, "", getString(R.string.loading));
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://imgur.com/gallery/top/all.json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", "");
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
JSONObject result = new JSONObject(new java.util.Scanner(in).useDelimiter("\\A").next());
if (result.has("data")) {
JSONArray data = result.getJSONArray("data");
mUrls.clear();
mTitles.clear();
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
mUrls.add("http://api.imgur.com/" + dataObject.getString("hash") + "s" + dataObject.getString("ext"));
mTitles.add(dataObject.getString("title"));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
mProgressDialog.dismiss();
}
}.execute();
}
}
|
ShutterbugDemo/src/com/applidium/shutterbugdemo/ShutterbugActivity.java
|
package com.applidium.shutterbugdemo;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.applidium.shutterbug.FetchableImageView;
import com.applidium.shutterbug.cache.ImageCache;
public class ShutterbugActivity extends Activity {
private ListView mListView;
private DemoAdapter mAdapter;
private ProgressDialog mProgressDialog;
private List<String> mUrls = new ArrayList<String>();
private List<String> mTitles = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shutterbug);
mListView = (ListView) findViewById(R.id.list);
mAdapter = new DemoAdapter();
mListView.setAdapter(mAdapter);
Button b = (Button) findViewById(R.id.clear_cache_button);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ImageCache.getSharedImageCache(ShutterbugActivity.this).clear();
mAdapter.notifyDataSetChanged();
}
});
loadGalleryContents();
}
private class DemoAdapter extends BaseAdapter {
public int getCount() {
return mUrls.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.shutterbug_demo_row, null);
}
TextView text = (TextView) view.findViewById(R.id.text);
text.setText("#" + position + ": " + mTitles.get(position));
FetchableImageView image = (FetchableImageView) view.findViewById(R.id.image);
image.setImage(mUrls.get(position));
return view;
}
}
private void loadGalleryContents() {
mProgressDialog = ProgressDialog.show(this, "", getString(R.string.loading));
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://imgur.com/gallery/top/all.json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
JSONObject result = new JSONObject(new java.util.Scanner(in).useDelimiter("\\A").next());
if (result.has("data")) {
JSONArray data = result.getJSONArray("data");
mUrls.clear();
mTitles.clear();
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
mUrls.add("http://api.imgur.com/" + dataObject.getString("hash") + "s" + dataObject.getString("ext"));
mTitles.add(dataObject.getString("title"));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
mProgressDialog.dismiss();
}
}.execute();
}
}
|
Removed User-Agent from imgur request
|
ShutterbugDemo/src/com/applidium/shutterbugdemo/ShutterbugActivity.java
|
Removed User-Agent from imgur request
|
|
Java
|
bsd-3-clause
|
597904c1f00dc21248ec7781fd34257471424ce9
| 0
|
iamedu/dari,iamedu/dari,iamedu/dari,iamedu/dari
|
package com.psddev.dari.maven;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import com.psddev.dari.util.ObjectUtils;
/**
* @goal analyze-all
* @requiresDependencyResolution compile
*/
public class AnalyzeAllMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
ClassLoader loader = ObjectUtils.getCurrentClassLoader();
Method addUrlMethod = null;
Log log = getLog();
if (loader instanceof URLClassLoader) {
try {
addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addUrlMethod.setAccessible(true);
} catch (NoSuchMethodException error) {
throw new MojoExecutionException(
"Can't find URLClassLoader#addURL method to change the current class loader!",
error);
}
}
for (Object artifact : project.getArtifacts()) {
try {
addUrlMethod.invoke(loader, ((Artifact) artifact).getFile().toURI().toURL());
} catch (Exception error) {
throw new MojoExecutionException(
String.format("Can't include [%s] in the classpath!", artifact),
error);
}
}
try {
addUrlMethod.invoke(loader, new File(project.getBuild().getOutputDirectory()).toURI().toURL());
} catch (Exception error) {
throw new MojoExecutionException(
"Can't include project build output directory in the classpath!",
error);
}
PrintStream oldErr = System.err;
System.setErr(new PrintStream(new NullOutputStream()));
try {
AnalyzeAllThread thread = new AnalyzeAllThread(log);
thread.start();
try {
thread.join();
} catch (InterruptedException error) {
// Interrupted most likely by user so move on.
}
if (thread.getLogger().hasErrors()) {
throw new MojoFailureException("");
}
} finally {
System.setErr(oldErr);
}
}
}
|
maven/src/main/java/com/psddev/dari/maven/AnalyzeAllMojo.java
|
package com.psddev.dari.maven;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import com.psddev.dari.util.ObjectUtils;
/**
* @goal analyze-all
* @requiresDependencyResolution compile
*/
public class AnalyzeAllMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
ClassLoader loader = ObjectUtils.getCurrentClassLoader();
Method addUrlMethod = null;
Log log = getLog();
if (loader instanceof URLClassLoader) {
try {
addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addUrlMethod.setAccessible(true);
} catch (NoSuchMethodException error) {
throw new MojoExecutionException(
"Can't find URLClassLoader#addURL method to change the current class loader!",
error);
}
}
for (Object artifact : project.getArtifacts()) {
try {
addUrlMethod.invoke(loader, ((Artifact) artifact).getFile().toURI().toURL());
} catch (Exception error) {
throw new MojoExecutionException(
String.format("Can't include [%s] in the classpath!", artifact),
error);
}
}
try {
addUrlMethod.invoke(loader, new File(project.getBuild().getOutputDirectory()).toURI().toURL());
} catch (Exception error) {
throw new MojoExecutionException(
"Can't include project build output directory in the classpath!",
error);
}
PrintStream oldErr = System.err;
System.setErr(new PrintStream(new NullOutputStream()));
try {
AnalyzeAllThread thread = new AnalyzeAllThread(log);
thread.start();
try {
thread.join();
} catch (InterruptedException error) {
}
if (thread.getLogger().hasErrors()) {
throw new MojoFailureException("");
}
} finally {
System.setErr(oldErr);
}
}
}
|
Fixes checkstyle violation.
|
maven/src/main/java/com/psddev/dari/maven/AnalyzeAllMojo.java
|
Fixes checkstyle violation.
|
|
Java
|
mit
|
84afeb10f29a7173bb02e172151dd4c3637b6135
| 0
|
intuit/karate,intuit/karate,intuit/karate,intuit/karate
|
/*
* The MIT License
*
* Copyright 2020 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.http;
import com.intuit.karate.FileUtils;
import com.intuit.karate.Logger;
import com.intuit.karate.core.Config;
import com.intuit.karate.core.Variable;
import com.intuit.karate.graal.JsValue;
import java.util.List;
import java.util.Map;
/**
*
* @author pthomas3
*/
public class HttpLogger {
private int requestCount;
private final Logger logger;
public HttpLogger(Logger logger) {
this.logger = logger;
}
private static void logHeaders(int num, String prefix, StringBuilder sb,
HttpLogModifier modifier, Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) {
return;
}
sb.append('\n');
headers.forEach((k, v) -> {
for (String value : v) {
sb.append(num).append(prefix).append(k).append(": ");
if (modifier == null) {
sb.append(value);
} else {
sb.append(modifier.header(k, value));
}
sb.append('\n');
}
});
}
private static void logBody(Config config, HttpLogModifier logModifier,
StringBuilder sb, String uri, byte[] body, boolean request) {
if (body == null) {
return;
}
String text;
if (config != null && needsPrettyLogging(config, request)) {
Object converted = JsValue.fromBytes(body, false, null);
Variable v = new Variable(converted);
text = v.getAsPrettyString();
} else {
text = FileUtils.toString(body);
}
if (logModifier != null) {
text = request ? logModifier.request(uri, text) : logModifier.response(uri, text);
}
sb.append(text);
}
private static boolean needsPrettyLogging(Config config, boolean request) {
return logPrettyRequest(config, request) || logPrettyResponse(config, request);
}
private static boolean logPrettyResponse(Config config, boolean request) {
return !request && config.isLogPrettyResponse();
}
private static boolean logPrettyRequest(Config config, boolean request) {
return request && config.isLogPrettyRequest();
}
private static HttpLogModifier logModifier(Config config, String uri) {
HttpLogModifier logModifier = config.getLogModifier();
return logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;
}
public static String getStatusFailureMessage(int expected, Config config, HttpRequest request, Response response) {
String url = request.getUrl();
HttpLogModifier logModifier = logModifier(config, url);
String maskedUrl = logModifier == null ? url : logModifier.uri(url);
String rawResponse = response.getBodyAsString();
if (rawResponse != null && logModifier != null) {
rawResponse = logModifier.response(url, rawResponse);
}
long responseTime = request.getEndTimeMillis() - request.getStartTimeMillis();
return "status code was: " + response.getStatus() + ", expected: " + expected
+ ", response time in milliseconds: " + responseTime + ", url: " + maskedUrl
+ ", response: \n" + rawResponse;
}
public void logRequest(Config config, HttpRequest request) {
requestCount++;
String uri = request.getUrl();
HttpLogModifier requestModifier = logModifier(config, uri);
String maskedUri = requestModifier == null ? uri : requestModifier.uri(uri);
StringBuilder sb = new StringBuilder();
sb.append("request:\n").append(requestCount).append(" > ")
.append(request.getMethod()).append(' ').append(maskedUri);
logHeaders(requestCount, " > ", sb, requestModifier, request.getHeaders());
ResourceType rt = ResourceType.fromContentType(request.getContentType());
if (rt == null || rt.isBinary()) {
// don't log body
} else {
byte[] body = rt == ResourceType.MULTIPART ? request.getBodyForDisplay().getBytes() : request.getBody();
logBody(config, requestModifier, sb, uri, body, true);
}
sb.append('\n');
logger.debug("{}", sb);
}
public void logResponse(Config config, HttpRequest request, Response response) {
long startTime = request.getStartTimeMillis();
long elapsedTime = request.getEndTimeMillis() - startTime;
StringBuilder sb = new StringBuilder();
String uri = request.getUrl();
HttpLogModifier responseModifier = logModifier(config, uri);
sb.append("response time in milliseconds: ").append(elapsedTime).append('\n');
sb.append(requestCount).append(" < ").append(response.getStatus());
logHeaders(requestCount, " < ", sb, responseModifier, response.getHeaders());
ResourceType rt = response.getResourceType();
if (rt == null || rt.isBinary()) {
// don't log body
} else {
logBody(config, responseModifier, sb, uri, response.getBody(), false);
}
logger.debug("{}", sb);
}
}
|
karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java
|
/*
* The MIT License
*
* Copyright 2020 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.http;
import com.intuit.karate.Logger;
import com.intuit.karate.graal.JsValue;
import com.intuit.karate.core.Config;
import com.intuit.karate.core.Variable;
import java.util.List;
import java.util.Map;
/**
*
* @author pthomas3
*/
public class HttpLogger {
private int requestCount;
private final Logger logger;
public HttpLogger(Logger logger) {
this.logger = logger;
}
private static void logHeaders(int num, String prefix, StringBuilder sb,
HttpLogModifier modifier, Map<String, List<String>> headers) {
if (headers == null || headers.isEmpty()) {
return;
}
sb.append('\n');
headers.forEach((k, v) -> {
for (String value : v) {
sb.append(num).append(prefix).append(k).append(": ");
if (modifier == null) {
sb.append(value);
} else {
sb.append(modifier.header(k, value));
}
sb.append('\n');
}
});
}
private static void logBody(Config config, HttpLogModifier logModifier,
StringBuilder sb, String uri, Object body, boolean request) {
if (body == null) {
return;
}
Variable v = new Variable(body);
String text;
if (config != null && needsPrettyLogging(config, request)) {
text = v.getAsPrettyString();
} else {
text = v.getAsString();
}
if (logModifier != null) {
text = request ? logModifier.request(uri, text) : logModifier.response(uri, text);
}
sb.append(text);
}
private static boolean needsPrettyLogging(Config config, boolean request) {
return logPrettyRequest(config, request) || logPrettyResponse(config, request);
}
private static boolean logPrettyResponse(Config config, boolean request) {
return !request && config.isLogPrettyResponse();
}
private static boolean logPrettyRequest(Config config, boolean request) {
return request && config.isLogPrettyRequest();
}
private static HttpLogModifier logModifier(Config config, String uri) {
HttpLogModifier logModifier = config.getLogModifier();
return logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;
}
public static String getStatusFailureMessage(int expected, Config config, HttpRequest request, Response response) {
String url = request.getUrl();
HttpLogModifier logModifier = logModifier(config, url);
String maskedUrl = logModifier == null ? url : logModifier.uri(url);
String rawResponse = response.getBodyAsString();
if (rawResponse != null && logModifier != null) {
rawResponse = logModifier.response(url, rawResponse);
}
long responseTime = request.getEndTimeMillis() - request.getStartTimeMillis();
return "status code was: " + response.getStatus() + ", expected: " + expected
+ ", response time in milliseconds: " + responseTime + ", url: " + maskedUrl
+ ", response: \n" + rawResponse;
}
public void logRequest(Config config, HttpRequest request) {
requestCount++;
String uri = request.getUrl();
HttpLogModifier requestModifier = logModifier(config, uri);
String maskedUri = requestModifier == null ? uri : requestModifier.uri(uri);
StringBuilder sb = new StringBuilder();
sb.append("request:\n").append(requestCount).append(" > ")
.append(request.getMethod()).append(' ').append(maskedUri);
logHeaders(requestCount, " > ", sb, requestModifier, request.getHeaders());
ResourceType rt = ResourceType.fromContentType(request.getContentType());
if (rt == null || rt.isBinary()) {
// don't log body
} else {
Object converted = rt == ResourceType.URLENCODED ? null : request.getBodyForDisplay();
if (converted == null) {
try {
converted = JsValue.fromBytes(request.getBody(), true, rt);
} catch (Throwable t) {
converted = request.getBodyAsString();
}
}
logBody(config, requestModifier, sb, uri, converted, true);
}
sb.append('\n');
logger.debug("{}", sb);
}
public void logResponse(Config config, HttpRequest request, Response response) {
long startTime = request.getStartTimeMillis();
long elapsedTime = request.getEndTimeMillis() - startTime;
StringBuilder sb = new StringBuilder();
String uri = request.getUrl();
HttpLogModifier responseModifier = logModifier(config, uri);
sb.append("response time in milliseconds: ").append(elapsedTime).append('\n');
sb.append(requestCount).append(" < ").append(response.getStatus());
logHeaders(requestCount, " < ", sb, responseModifier, response.getHeaders());
ResourceType rt = response.getResourceType();
if (rt == null || rt.isBinary()) {
// don't log body
} else {
Object converted;
try {
converted = JsValue.fromBytes(response.getBody(), true, rt);
} catch (Throwable t) {
converted = response.getBodyAsString();
}
logBody(config, responseModifier, sb, uri, converted, false);
}
logger.debug("{}", sb);
}
}
|
request and response logged to report will be as-is
unless pretty has been switched on
should have done this sooner
|
karate-core/src/main/java/com/intuit/karate/http/HttpLogger.java
|
request and response logged to report will be as-is unless pretty has been switched on should have done this sooner
|
|
Java
|
mit
|
63b6421199c232e549c923a5c9470149ad10ec33
| 0
|
enebo/oj,enebo/oj,enebo/oj,enebo/oj
|
package oj;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.TimeZone;
import jnr.posix.util.Platform;
import oj.options.DumpType;
import oj.options.NanDump;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyComplex;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyNil;
import org.jruby.RubyNumeric;
import org.jruby.RubyRange;
import org.jruby.RubyRational;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.RubyStruct;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.ext.stringio.StringIO;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.util.ByteList;
import org.jruby.util.Sprintf;
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;
import static oj.options.DumpType.ArrayNew;
import static oj.options.DumpType.ArrayType;
import static oj.options.DumpType.ObjectNew;
import static oj.options.DumpType.ObjectType;
import static oj.Options.*;
import static oj.NumInfo.OJ_INFINITY;
/**
* Created by enebo on 9/9/15.
*/
public class Dump {
static int MAX_DEPTH = 1000;
private static final byte[] BIG_O_KEY = {'"', '^', 'O', '"', ':'};
private static final byte[] C_KEY = {'"', '^', 'c', '"', ':'};
private static final byte[] O_KEY = {'"', '^', 'o', '"', ':'};
private static final byte[] I_KEY = {'"', '^', 'i', '"', ':'};
private static final byte[] PARTIAL_I_KEY = {'"', '^', 'i'};
private static final byte[] T_KEY = {'"', '^', 't', '"', ':'};
private static final byte[] U_KEY = {'"', '^', 'u', '"', ':', '['};
private static final byte[] SELF_KEY = {'"', 's', 'e', 'l', 'f', '"', ':'};
private static final byte[] NULL_VALUE = {'n', 'u', 'l', 'l'};
private static final byte[] TRUE_VALUE = {'t', 'r', 'u', 'e'};
private static final byte[] FALSE_VALUE = {'f', 'a', 'l', 's', 'e'};
public static final byte[] INFINITY_VALUE = {'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'};
private static final byte[] NINFINITY_VALUE = {'-', 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'};
private static final byte[] NAN_VALUE = {'N', 'a', 'N'};
public static final byte[] INF_VALUE = {'3', '.', '0', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
public static final byte[] NINF_VALUE = {'-', '3', '.', '0', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
public static final byte[] NAN_NUMERIC_VALUE = {'3', '.', '3', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
private static final byte[] ZERO_POINT_ZERO = {'0', '.', '0'};
static String hex_chars = "0123456789abcdef";
// JSON standard except newlines are no escaped
static int newline_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,1,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
// JSON standard
static int hibit_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
// High bit set characters are always encoded as unicode. Worse case is 3
// bytes per character in the output. That makes this conservative.
static int ascii_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
// XSS safe mode
static int xss_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,6,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,6,1,6,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
static int newline_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += newline_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int hibit_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += hibit_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int ascii_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += ascii_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int xss_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += xss_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static void fill_indent(Out out, int cnt) {
if (out.indent > 0) {
cnt *= out.indent;
out.append('\n');
for (; 0 < cnt; cnt--) {
out.append(' ');
}
}
}
static void dump_ulong(long num, Out out) {
byte[] buf = new byte[32]; // FIXME: Can be instance variable
int b = buf.length - 1;
if (0 < num) {
for (; 0 < num; num /= 10, b--) {
buf[b] = (byte) ((num % 10) + '0');
}
b++;
} else {
buf[b] = '0';
}
for (; b < buf.length; b++) {
out.append(buf[b]);
}
}
static void dump_hex(int c, Out out) {
int d = (c >> 4) & 0x0F;
out.append(hex_chars.charAt(d));
d = c & 0x0F;
out.append(hex_chars.charAt(d));
}
static void dump_raw(byte[] str, Out out) {
out.append(str);
}
static void dump_raw(ByteList str, Out out) {
out.append(str);
}
static int dump_unicode(ThreadContext context, ByteList str, int str_i, int end, Out out) {
int code;
int b = str.get(str_i);
int i, cnt;
if (0xC0 == (0xE0 & b)) {
cnt = 1;
code = b & 0x0000001F;
} else if (0xE0 == (0xF0 & b)) {
cnt = 2;
code = b & 0x0000000F;
} else if (0xF0 == (0xF8 & b)) {
cnt = 3;
code = b & 0x00000007;
} else if (0xF8 == (0xFC & b)) {
cnt = 4;
code = b & 0x00000003;
} else if (0xFC == (0xFE & b)) {
cnt = 5;
code = b & 0x00000001;
} else {
throw context.runtime.newEncodingError("Invalid Unicode\n");
}
str_i++;
for (; 0 < cnt; cnt--, str_i++) {
b = str.get(str_i);
if (end <= str_i || 0x80 != (0xC0 & b)) {
throw context.runtime.newEncodingError("Invalid Unicode\n");
}
code = (code << 6) | (b & 0x0000003F);
}
if (0x0000FFFF < code) {
int c1;
code -= 0x00010000;
c1 = ((code >> 10) & 0x000003FF) + 0x0000D800;
code = (code & 0x000003FF) + 0x0000DC00;
out.append('\\');
out.append('u');
for (i = 3; 0 <= i; i--) {
out.append(hex_chars.charAt((int)(c1 >> (i * 4)) & 0x0F));
}
}
out.append('\\');
out.append('u');
for (i = 3; 0 <= i; i--) {
out.append(hex_chars.charAt((int)(code >> (i * 4)) & 0x0F));
}
return str_i - 1;
}
// returns 0 if not using circular references, -1 if not further writing is
// needed (duplicate), and a positive value if the object was added to the cache.
static long check_circular(IRubyObject obj, Out out) {
Integer id = 0;
if (ObjectMode == out.opts.mode && Yes == out.opts.circular) {
id = out.circ_cache.get(obj);
if (id == null) {
out.circ_cnt++;
id = out.circ_cnt;
out.circ_cache.put(obj, id);
} else {
out.append('"');
out.append('^');
out.append('r');
dump_ulong(id.longValue(), out);
out.append('"');
return -1;
}
}
return id.longValue();
}
static void dump_nil(Out out) {
out.append(NULL_VALUE);
}
static void dump_true(Out out) {
out.append(TRUE_VALUE);
}
static void dump_false(Out out) {
out.append(FALSE_VALUE);
}
static void dump_fixnum(RubyFixnum obj, Out out) {
byte buf[] = new byte[32];
int b = buf.length - 1;
long num = obj.getLongValue();
boolean neg = false;
if (num < 0) {
num = -num;
neg = true;
}
if (num == 0) {
buf[b] = '0';
} else {
for (; 0 < num; num /= 10, b--) {
buf[b] = (byte) ((num % 10) + '0');
}
if (neg) {
buf[b] = '-';
} else {
b++;
}
}
int size = buf.length - b;
out.append(buf, b, size);
}
static void dump_bignum(ThreadContext context, RubyBignum obj, Out out) {
// Note: This uses boxed call to to_s because 9.1 -> 9.2 changed return type on non-boxed version
// from IRubyObject -> RubyString.
out.append(obj.to_s(new IRubyObject[] { context.runtime.newFixnum(10) }).convertToString().getByteList());
}
static void dump_float(ThreadContext context, RubyFloat obj, Out out) {
double d = obj.getDoubleValue();
if (d == 0.0) {
out.append(ZERO_POINT_ZERO);
} else if (d == OJ_INFINITY) {
dumpInfNanForFloat(out, obj, INF_VALUE, INFINITY_VALUE);
} else if (d == -OJ_INFINITY) {
dumpInfNanForFloat(out, obj, NINF_VALUE, NINFINITY_VALUE);
} else if (Double.isNaN(d)) {
dumpNanNanForFloat(out, obj);
/*} else if (d == (double)(long)d) { // FIXME: Precision overflow?
cnt = snprintf(buf, sizeof(buf), "%.1f", d);*/
} else if (0 == out.opts.float_prec) {
IRubyObject rstr = Helpers.invoke(context, obj, "to_s");
if (!(rstr instanceof RubyString)) {
throw context.runtime.newArgumentError("Expected a String");
}
out.append(((RubyString) rstr).getByteList().bytes());
} else {
ByteList buf = new ByteList();
Sprintf.sprintf(buf, out.opts.float_fmt, obj);
out.append(buf);
}
}
private static final void dumpNanNanForFloat(Out out, IRubyObject value) {
if (out.opts.mode == ObjectMode) {
out.append(NAN_NUMERIC_VALUE);
} else {
NanDump nd = out.opts.dump_opts.nan_dump;
if (nd == NanDump.AutoNan) {
switch (out.opts.mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
case NullMode: nd = NanDump.NullNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: out.append(NAN_VALUE); break;
case NullNan: out.append(NULL_VALUE); break;
case HugeNan:
default: out.append(NAN_NUMERIC_VALUE); break;
}
}
}
private static final void dumpInfNanForFloat(Out out, IRubyObject value, byte[] inf_value, byte[] infinity_value) {
if (out.opts.mode == ObjectMode) {
out.append(inf_value);
} else {
NanDump nd = out.opts.dump_opts.nan_dump;
if (nd == NanDump.AutoNan) {
switch (out.opts.mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
case NullMode: nd = NanDump.NullNan; break;
case CustomMode: nd = NanDump.NullNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: out.append(infinity_value); break;
case NullNan: out.append(NULL_VALUE); break;
case HugeNan:
default: out.append(inf_value); break;
}
}
}
// FIXME: This is going to mess up blindly grabbing bytes if it mismatches UTF-8 (I believe all strings
// will be UTF-8 or clean ascii 7-bit).
static void dump_cstr(ThreadContext context, String str, boolean is_sym, boolean escape1, Out out) {
dump_cstr(context, new ByteList(str.getBytes(), UTF8Encoding.INSTANCE), is_sym, escape1, out);
}
static void dump_cstr(ThreadContext context, ByteList str, boolean is_sym, boolean escape1, Out out) {
int size;
int[] cmap;
int str_i = 0;
switch (out.opts.escape_mode) {
case NLEsc:
cmap = newline_friendly_chars;
size = newline_friendly_size(str);
break;
case ASCIIEsc:
cmap = ascii_friendly_chars;
size = ascii_friendly_size(str);
break;
case XSSEsc:
cmap = xss_friendly_chars;
size = xss_friendly_size(str);
break;
case JSONEsc:
default:
cmap = hibit_friendly_chars;
size = hibit_friendly_size(str);
}
int cnt = str.length();
out.append('"');
if (escape1) {
out.append('\\');
out.append('u');
out.append('0');
out.append('0');
dump_hex(str.get(str_i), out);
cnt--;
size--;
str_i++;
is_sym = false; // just to make sure
}
if (cnt == size) {
if (is_sym) out.append(':');
out.append(str.unsafeBytes(), str.begin() + str_i, cnt);
out.append('"');
} else {
if (is_sym) {
out.append(':');
}
for (; str_i < cnt; str_i++) {
switch (cmap[(int)str.get(str_i) & 0xff]) {
case 1:
out.append(str.get(str_i));
break;
case 2:
out.append('\\');
switch ((byte) str.get(str_i)) {
case '\\': out.append('\\'); break;
case '\b': out.append('b'); break;
case '\t': out.append('t'); break;
case '\n': out.append('n'); break;
case '\f': out.append('f'); break;
case '\r': out.append('r'); break;
default: out.append(str.get(str_i)); break;
}
break;
case 3: // Unicode
str_i = dump_unicode(context, str, str_i, cnt, out);
break;
case 6: // control characters
out.append('\\');
out.append('u');
out.append('0');
out.append('0');
dump_hex(str.get(str_i), out);
break;
default:
break; // ignore, should never happen if the table is correct
}
}
out.append('"');
}
}
static void dump_str_comp(ThreadContext context, RubyString obj, Out out) {
dump_cstr(context, obj.getByteList(), false, false, out);
}
static void dump_str_obj(ThreadContext context, RubyString string, Out out) {
ByteList str = string.getByteList();
boolean escape = isEscapeString(str);
if (string.isAsciiOnly() && !escape) { // Fast path. JRuby already knows if it is a clean ASCII string.
out.append('"');
out.append(str.unsafeBytes(), str.begin(), str.realSize());
out.append('"');
} else {
dump_cstr(context, str, false, escape, out);
}
}
static boolean isEscapeString(ByteList str) {
if (str.realSize() >=2 ) {
int s = str.get(0);
if (s == ':') return true;
if (s == '^'){
s = str.get(1);
return s == 'r' || s == 'i';
}
}
return false;
}
static void dump_sym_comp(ThreadContext context, RubySymbol obj, Out out) {
dump_cstr(context, ((RubyString) obj.to_s()).getByteList(), false, false, out);
}
static void dump_sym_obj(ThreadContext context, RubySymbol obj, Out out) {
dump_cstr(context, ((RubyString) obj.to_s()).getByteList(), true, false, out);
}
static void dump_class_comp(ThreadContext context, RubyModule clas, Out out) {
dump_cstr(context, new ByteList(clas.getName().getBytes()), false, false, out);
}
static void dump_class_obj(ThreadContext context, RubyModule clas, Out out) {
out.append('{');
out.append(C_KEY);
dump_cstr(context, new ByteList(clas.getName().getBytes()), false, false, out);
out.append('}');
}
static void dump_array(ThreadContext context, RubyArray array, int depth, Out out) {
int d2 = depth + 1;
long id = check_circular(array, out);
if (id < 0) return; // duplicate found (written out in check_circular)
out.append('[');
if (id > 0) {
fill_indent(out, d2);
out.append(PARTIAL_I_KEY);
dump_ulong(id, out);
out.append('"');
}
if (array.isEmpty()) {
out.append(']');
} else {
if (id > 0) out.append(',');
int cnt = array.getLength() - 1;
for (int i = 0; i <= cnt; i++) {
indent(out, d2, out.opts.dump_opts.array_nl);
dump_val(context, array.eltInternal(i), d2, out, null);
if (i < cnt) out.append(',');
}
indent(out, depth, out.opts.dump_opts.array_nl);
out.append(']');
}
}
static void indent(Out out, int depth, ByteList nl) {
if (out.opts.dump_opts.use) {
if (nl != ByteList.EMPTY_BYTELIST) out.append(nl);
if (out.opts.dump_opts.indent_str != ByteList.EMPTY_BYTELIST) {
for (int j = depth; 0 < j; j--) {
out.append(out.opts.dump_opts.indent_str);
}
}
} else {
fill_indent(out, depth);
}
}
static void hash_cb_strict(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
if (out.omit_nil && value.isNil()) return;
int depth = out.depth;
if (!(key instanceof RubyString)) {
throw context.runtime.newTypeError("In :strict mode all Hash keys must be Strings, not " + key.getMetaClass().getName());
}
if (out.opts.dump_opts.use) {
if (out.opts.dump_opts.hash_nl != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.hash_nl);
}
if (out.opts.dump_opts.indent_str != ByteList.EMPTY_BYTELIST) {
int i;
for (i = depth; 0 < i; i--) {
out.append(out.opts.dump_opts.indent_str);
}
}
dump_str_comp(context, (RubyString) key, out);
if (out.opts.dump_opts.before_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.before_sep);
}
out.append(':');
if (out.opts.dump_opts.after_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.after_sep);
}
} else {
fill_indent(out, depth);
dump_str_comp(context, (RubyString) key, out);
out.append(':');
}
dump_val(context, value, depth, out, null);
out.depth = depth;
out.append(',');
}
static void hash_cb_compat(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
int depth = out.depth;
indent(out, depth, out.opts.dump_opts.hash_nl);
if (key instanceof RubyString) {
dump_str_comp(context, (RubyString) key, out);
} else if (key instanceof RubySymbol) {
dump_sym_comp(context, (RubySymbol) key, out);
} else {
/*rb_raise(rb_eTypeError, "In :compat mode all Hash keys must be Strings or Symbols, not %s.\n", rb_class2name(rb_obj_class(key)));*/
dump_cstr(context, stringToByteList(context, key, "to_s"), false, false, out);
}
if (out.opts.dump_opts.use) {
if (out.opts.dump_opts.before_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.before_sep);
}
out.append(':');
if (out.opts.dump_opts.after_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.after_sep);
}
} else {
out.append(':');
}
dump_val(context, value, depth, out, null);
out.depth = depth;
out.append(',');
}
static void hash_cb_object(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
if (out.opts.ignore != null && dump_ignore(out, value)) return;
if (out.omit_nil && value.isNil()) return;
int depth = out.depth;
fill_indent(out, depth);
if (key instanceof RubyString) {
dump_str_obj(context, (RubyString) key, out);
out.append(':');
dump_val(context, value, depth, out, null);
} else if (key instanceof RubySymbol) {
dump_sym_obj(context, (RubySymbol) key, out);
out.append(':');
dump_val(context, value, depth, out, null);
} else {
int d2 = depth + 1;
int i;
boolean started = false;
int b;
out.append('"');
out.append('^');
out.append('#');
out.hash_cnt++;
for (i = 28; 0 <= i; i -= 4) {
b = (int)((out.hash_cnt >> i) & 0x0000000F);
if ('\0' != b) {
started = true;
}
if (started) {
out.append(hex_chars.charAt(b));
}
}
out.append('"');
out.append(':');
out.append('[');
fill_indent(out, d2);
dump_val(context, key, d2, out, null);
out.append(',');
fill_indent(out, d2);
dump_val(context, value, d2, out, null);
fill_indent(out, depth);
out.append(']');
}
out.depth = depth;
out.append(',');
}
static void dump_hash(final ThreadContext context, IRubyObject obj, RubyClass clas, int depth, int mode, Out out) {
int cnt;
if (null != clas && !(obj instanceof RubyHash) && ObjectMode == mode) {
dump_obj_attrs(context, obj, clas, 0, depth, out);
return;
}
RubyHash hash = (RubyHash) obj;
cnt = hash.size();
if (0 == cnt) {
out.append('{');
out.append('}');
} else {
long id = check_circular(obj, out);
if (0 > id) {
return;
}
out.append('{');
if (0 < id) {
fill_indent(out, depth + 1);
out.append('"');
out.append('^');
out.append('i');
out.append('"');
out.append(':');
dump_ulong(id, out);
out.append(',');
}
out.depth = depth + 1;
if (ObjectMode == mode) {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_object(context, key, value, out);
}
},
out);
} else if (CompatMode == mode) {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_compat(context, key, value, out);
}
},
out);
} else {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_strict(context, key, value, out);
}
},
out);
}
if (',' == out.get(-1)) {
out.pop(); // backup to overwrite last comma
}
indent(out, depth, out.opts.dump_opts.hash_nl);
out.append('}');
}
}
// In JRuby rb_time_timespec equivalent is not public.
// FIXME: Move into EmbeddedAPI when I make it
private static long[] extractTimespec(ThreadContext context, IRubyObject value) {
long[] timespec = new long[2];
if (value instanceof RubyFloat) {
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(value) : RubyNumeric.num2long(value);
double fraction = ((RubyFloat) value).getDoubleValue() % 1.0;
timespec[1] = (long)(fraction * 1e9 + 0.5);
} else if (value instanceof RubyNumeric) {
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(value) : RubyNumeric.num2long(value);
timespec[1] = 0;
} else {
RubyTime time;
if (value instanceof RubyTime) {
time = ((RubyTime) value);
} else {
time = (RubyTime) TypeConverter.convertToType(value, context.runtime.getTime(), "to_time", true);
}
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.to_i()) : RubyNumeric.num2long(time.to_i());
timespec[1] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.nsec()) : RubyNumeric.num2long(time.nsec());
}
return timespec;
}
static void dump_time(ThreadContext context, IRubyObject obj, Out out, boolean withZone) {
long[] timespec = extractTimespec(context, obj);
long sec = timespec[0];
long nsec = timespec[1];
byte[] buf = new byte[64];
int b = buf.length - 1;
boolean neg = false;
int dot;
long one = 1000000000;
// JRuby returns negative nsec....not sure if this is correct or whether sec should subtract 1 too?
if (nsec < 0) {
nsec = one + nsec;
sec--;
}
if (withZone) {
long tzsecs = obj.callMethod(context, "utc_offset").convertToInteger().getLongValue();
boolean zneg = (0 > tzsecs);
if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
tzsecs = 86400;
}
if (zneg) {
tzsecs = -tzsecs;
}
if (0 == tzsecs) {
buf[b] = '0';
b--;
} else {
for (; 0 < tzsecs; b--, tzsecs /= 10) {
buf[b] = (byte) ('0' + (tzsecs % 10));
}
if (zneg) {
buf[b] = '-';
b--;
}
}
buf[b] = 'e';
b--;
}
if (0 > sec) {
neg = true;
sec = -sec;
if (0 < nsec) {
nsec = 1000000000 - nsec;
sec--;
}
}
dot = b - 9;
if (0 < out.opts.sec_prec) {
if (9 > out.opts.sec_prec) {
for (int i = 9 - out.opts.sec_prec; 0 < i; i--) {
dot++;
nsec = (nsec + 5) / 10;
one /= 10;
}
}
if (one <= nsec) {
nsec -= one;
sec++;
}
for (; dot < b; b--, nsec /= 10) {
buf[b] = (byte) ('0' + (nsec % 10));
}
buf[b] = '.';
b--;
}
if (0 == sec) {
buf[b] = '0';
b--;
} else {
for (; 0 < sec; b--, sec /= 10) {
buf[b] = (byte) ('0' + (sec % 10));
}
}
if (neg) {
buf[b] = '-';
b--;
}
b++;
int size = buf.length - b;
out.append(buf, b, size);
}
static void dump_ruby_time(ThreadContext context, IRubyObject obj, Out out) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
static void dump_xml_time(ThreadContext context, IRubyObject obj, Out out) {
long[] timespec = extractTimespec(context, obj);
long sec = timespec[0];
long nsec = timespec[1];
StringBuilder buf = new StringBuilder();
Formatter formatter = new Formatter(buf);
long one = 1000000000;
long tzsecs = obj.callMethod(context, "utc_offset").convertToInteger().getLongValue();
int tzhour, tzmin;
char tzsign = '+';
if (9 > out.opts.sec_prec) {
int i;
for (i = 9 - out.opts.sec_prec; 0 < i; i--) {
nsec = (nsec + 5) / 10;
one /= 10;
}
if (one <= nsec) {
nsec -= one;
sec++;
}
}
// 2012-01-05T23:58:07.123456000+09:00
//tm = localtime(&sec);
sec += tzsecs;
Date date = new Date(sec*1000); // milliseconds since epoch
Calendar tm = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
tm.setTime(date);
if (0 > tzsecs) {
tzsign = '-';
tzhour = (int)(tzsecs / -3600);
tzmin = (int)(tzsecs / -60) - (tzhour * 60);
} else {
tzhour = (int)(tzsecs / 3600);
tzmin = (int)(tzsecs / 60) - (tzhour * 60);
}
if (0 == nsec || 0 == out.opts.sec_prec) {
if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
formatter.format("%04d-%02d-%02dT%02d:%02d:%02dZ",
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND));
dump_cstr(context, buf.toString(), false, false, out);
} else {
formatter.format("%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND),
tzsign, tzhour, tzmin);
dump_cstr(context, buf.toString(), false, false, out);
}
} else if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
String format = "%04d-%02d-%02dT%02d:%02d:%02d.%09dZ";
if (9 > out.opts.sec_prec) {
format = "%04d-%02d-%02dT%02d:%02d:%02d.%0" + (char) ('0' + out.opts.sec_prec);
}
formatter.format(format,
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND), nsec);
dump_cstr(context, buf.toString(), false, false, out);
} else {
String format = "%04d-%02d-%02dT%02d:%02d:%02d.%09d%c%02d:%02d";
if (9 > out.opts.sec_prec) {
format = "%04d-%02d-%02dT%02d:%02d:%02d.%0" + (char) ('0' + out.opts.sec_prec) + "d%c%02d:%02d";
}
formatter.format(format,
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND), nsec,
tzsign, tzhour, tzmin);
dump_cstr(context, buf.toString(), false, false, out);
}
}
static void dump_data_strict(ThreadContext context, IRubyObject obj, Out out) {
if (obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else {
raise_strict(obj);
}
}
static void dump_data_null(ThreadContext context, IRubyObject obj, Out out) {
if (obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else {
dump_nil(out);
}
}
static void dump_data_comp(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(obj.getRuntime().getCurrentContext(), "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(obj, context.runtime.getHash());
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (Yes == out.opts.bigdec_as_num && obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(obj.getRuntime().getCurrentContext(), "as_json");
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
if (obj instanceof RubyTime) {
switch (out.opts.time_format) {
case RubyTime: dump_ruby_time(context, obj, out); break;
case XmlTime: dump_xml_time(context, obj, out); break;
case UnixZTime: dump_time(context, obj, out, true); break;
case UnixTime:
default: dump_time(context, obj, out, false); break;
}
} else if (obj instanceof RubyBigDecimal) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
}
}
static void dump_data_obj(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj instanceof org.jruby.RubyTime) {
out.append('{');
out.append(T_KEY);
switch (out.opts.time_format) {
case RubyTime: // Does not output fractional seconds
case XmlTime:
dump_xml_time(context, obj, out);
break;
case UnixZTime:
dump_time(context, obj, out, true);
break;
case UnixTime:
default:
dump_time(context, obj, out, false);
break;
}
out.append('}');
} else if (obj instanceof RubyBigDecimal) {
ByteList str = stringToByteList(context, obj, "to_s");
if (out.opts.bigdec_as_num != No) {
dump_raw(str, out);
} else if (INFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, true), out);
} else if (NINFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, false), out);
} else {
dump_cstr(context, str, false, false, out);
}
} else {
dump_nil(out);
}
}
private static byte[] nan_str(IRubyObject value, NanDump nd, char mode, boolean positive) {
if (nd == NanDump.AutoNan) {
switch (mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: return positive ? INFINITY_VALUE : NINFINITY_VALUE;
case NullNan: return NULL_VALUE;
case HugeNan:
return INF_VALUE;
}
return null; // C source does this but this I believe will crash in both impls...let's see....
}
// FIXME: both C and Java can crash potentially I added check here but
// I should see if C oj crashes for these cases.
static ByteList stringToByteList(ThreadContext context, IRubyObject obj, String method) {
IRubyObject stringResult = obj.callMethod(context, method);
if (!(stringResult instanceof RubyString)) {
throw context.runtime.newTypeError("Expected a String");
}
return ((RubyString) stringResult).getByteList();
}
static void dump_obj_comp(ThreadContext context, IRubyObject obj, int depth, Out out, IRubyObject[] argv) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(context, "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(h.getMetaClass().getName() + ".to_hash() did not return a Hash");
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(context, "as_json", argv);
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
if (obj instanceof RubyBigDecimal) {
ByteList rstr = stringToByteList(context, obj, "to_s");
if (Yes == out.opts.bigdec_as_num) {
dump_raw(rstr, out);
} else {
dump_cstr(context, rstr, false, false, out);
}
//FIXME: what if datetime does not exist?
} else {
RubyClass dateTime = context.runtime.getClass("DateTime");
RubyClass date = context.runtime.getClass("Date");
if (dateTime != null && dateTime.isInstance(obj) || date != null && date.isInstance(obj) || obj instanceof RubyRational) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_obj_attrs(context, obj, null, 0, depth, out);
}
}
}
}
static void dump_obj_obj(ThreadContext context, IRubyObject obj, int depth, Out out) {
long id = check_circular(obj, out);
if (0 <= id) {
if (obj instanceof RubyBigDecimal) {
ByteList str = stringToByteList(context, obj, "to_s");
if (INFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, true), out);
} else if (NINFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, false), out);
} else {
dump_raw(str, out);
}
} else {
dump_obj_attrs(context, obj, obj.getMetaClass(), id, depth, out);
}
}
}
static void dump_obj_attrs(ThreadContext context, IRubyObject obj, RubyClass clas, long id, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (null != clas) {
ByteList class_name = ((RubyString) clas.name()).getByteList();
fill_indent(out, d2);
out.append(O_KEY);
dump_cstr(context, class_name, false, false, out);
}
if (0 < id) {
out.append(',');
fill_indent(out, d2);
out.append(I_KEY);
dump_ulong(id, out);
}
if (obj instanceof RubyString) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_cstr(context, ((RubyString) obj).getByteList(), false, false, out);
} else if (obj instanceof RubyArray) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_array(context, (RubyArray) obj, depth + 1, out);
} else if (obj instanceof RubyHash) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_hash(context, obj, null, depth + 1, out.opts.mode, out);
}
List<Variable<Object>> variables = obj.getVariableList();
if (clas != null && !variables.isEmpty()) {
out.append(',');
}
boolean first = true;
for (Variable<Object> variable: variables) {
String name = variable.getName();
// FIXME: We may crash if non ruby object is internal????
IRubyObject value = (IRubyObject) variable.getValue();
if (out.opts.ignore != null && dump_ignore(out, value)) continue;
if (out.omit_nil && value.isNil()) continue;
if (first) {
first = false;
} else {
out.append(',');
}
fill_indent(out, d2);
if (name.charAt(0) == '@') {
dump_cstr(context, name.substring(1), false, false, out);
} else {
dump_cstr(context, "~" + name, false, false, out);
}
out.append(':');
dump_val(context, value, d2, out, null);
}
out.depth = depth;
fill_indent(out, depth);
out.append('}');
}
static void dump_struct_comp(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(context, "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(obj.getMetaClass().getName() + ".to_hash() did not return a Hash.");
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(context, "as_json");
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
}
static void dump_struct_obj(ThreadContext context, RubyStruct obj, int depth, Out out) {
String class_name = obj.getMetaClass().getName();
int d2 = depth + 1;
int d3 = d2 + 1;
out.append('{');
fill_indent(out, d2);
out.append(U_KEY);
if (class_name.charAt(0) == '#') {
RubyArray ma = obj.members();
int cnt = ma.size();
out.append('[');
for (int i = 0; i < cnt; i++) {
RubySymbol name = (RubySymbol) ma.eltOk(i); // struct forces all members to be symbols
if (0 < i) {
out.append(',');
}
out.append('"');
out.append(name.asString().getByteList());
out.append('"');
}
out.append(']');
} else {
fill_indent(out, d3);
out.append('"');
out.append(class_name);
out.append('"');
}
out.append(',');
boolean first = true;
for (Object n: obj.members()) {
IRubyObject name = (IRubyObject) n;
if (first) {
first = false;
} else {
out.append(',');
}
fill_indent(out, d3);
dump_val(context, obj.aref(name), d3, out, null);
}
out.append(']');
out.append('}');
}
static void dump_range_obj(ThreadContext context, RubyRange obj, int depth, Out out) {
String class_name = obj.getMetaClass().getName();
int d2 = depth + 1;
int d3 = d2 + 1;
out.append('{');
fill_indent(out, d2);
out.append(U_KEY);
fill_indent(out, d3);
out.append('"');
out.append(class_name);
out.append('"');
out.append(',');
dump_val(context, obj.begin(context), d3, out, null);
out.append(',');
dump_val(context, obj.end(context), d3, out, null);
out.append(',');
dump_val(context, obj.exclude_end_p(), d3, out, null);
out.append(']');
out.append('}');
}
static void dump_odd(ThreadContext context, IRubyObject obj, Odd odd, RubyClass clas, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (clas != null) {
ByteList class_name = ((RubyString) clas.name()).getByteList();
fill_indent(out, d2);
out.append(BIG_O_KEY);
dump_cstr(context, class_name, false, false, out);
out.append(',');
}
if (odd.raw) {
RubyString str = (RubyString) obj.callMethod(context, odd.attrs[0]).checkStringType();
out.append('"');
out.append(odd.attrs[0]);
out.append('"');
out.append(':');
out.append(str.getByteList());
} else {
for (int index = 0; index < odd.attrs.length; index++) {
String name = odd.attrs[index];
IRubyObject value = oddValue(context, obj, name, odd, index);
fill_indent(out, d2);
dump_cstr(context, name, false, false, out);
out.append(':');
dump_val(context, value, d2, out, null);
out.append(',');
}
out.pop(); // remove last ','
}
out.append('}');
}
private static IRubyObject oddValue(ThreadContext context, IRubyObject obj, String name, Odd odd, int index) {
if (odd.attrFuncs[index] != null) return odd.attrFuncs[index].execute(context, obj);
if (name.indexOf('.') == -1) return obj.callMethod(context, name);
IRubyObject value = obj;
for (String segment : name.split("\\.")) {
value = value.callMethod(context, segment);
}
return value;
}
static void raise_strict(IRubyObject obj) {
throw obj.getRuntime().newTypeError("Failed to dump " + obj.getMetaClass().getName() + " Object to JSON in strict mode.");
}
static void dump_val(ThreadContext context, IRubyObject obj, int depth, Out out, IRubyObject[] argv) {
if (MAX_DEPTH < depth) {
throw new RaiseException(context.runtime, context.runtime.getNoMemoryError(), "Too deeply nested.", true);
}
if (obj instanceof RubyNil) {
dump_nil(out);
} else if (obj instanceof RubyBoolean) {
if (obj == context.runtime.getTrue()) {
dump_true(out);
} else {
dump_false(out);
}
} else if (obj instanceof RubyFixnum) {
dump_fixnum((RubyFixnum) obj, out);
} else if (obj instanceof RubyFloat) {
dump_float(context, (RubyFloat) obj, out);
} else if (obj instanceof RubyModule) { // Also will be RubyClass
switch (out.opts.mode) {
case StrictMode: raise_strict(obj); break;
case NullMode: dump_nil(out); break;
case CompatMode: dump_class_comp(context, (RubyModule) obj, out); break;
case ObjectMode:
default: dump_class_obj(context, (RubyModule) obj, out); break;
}
} else if (obj instanceof RubySymbol) {
switch (out.opts.mode) {
case StrictMode:
raise_strict(obj);
break;
case NullMode:
dump_nil(out);
break;
case CompatMode:
dump_sym_comp(context, (RubySymbol) obj, out);
break;
case ObjectMode:
default:
dump_sym_obj(context, (RubySymbol) obj, out);
break;
}
} else if (obj instanceof RubyStruct || obj instanceof RubyRange) { // In MRI T_STRUCT is also Range
switch (out.opts.mode) {
case StrictMode:
raise_strict(obj);
break;
case NullMode:
dump_nil(out);
break;
case CompatMode:
dump_struct_comp(context, obj, depth, out);
break;
case ObjectMode:
default:
if (obj instanceof RubyRange) {
dump_range_obj(context, (RubyRange) obj, depth, out);
} else {
dump_struct_obj(context, (RubyStruct) obj, depth, out);
}
break;
}
} else {
// Most developers have enough sense not to subclass primitive types but
// since these classes could potentially be subclassed a check for odd
// classes is performed.
{
RubyClass clas = obj.getMetaClass();
Odd odd;
if (ObjectMode == out.opts.mode && null != (odd = out.oj.getOdd(clas))) {
dump_odd(context, obj, odd, clas, depth + 1, out);
return;
}
if (obj instanceof RubyBignum) {
dump_bignum(context, (RubyBignum) obj, out);
} else if (obj.getMetaClass() == context.runtime.getString()) {
switch (out.opts.mode) {
case StrictMode:
case NullMode:
case CompatMode:
dump_str_comp(context, (RubyString) obj, out);
break;
case ObjectMode:
default:
dump_str_obj(context, (RubyString) obj, out);
break;
}
} else if (obj.getMetaClass() == context.runtime.getArray()) {
dump_array(context, (RubyArray) obj, depth, out);
} else if (obj.getMetaClass() == context.runtime.getHash()) {
dump_hash(context, obj, clas, depth, out.opts.mode, out);
} else if (obj instanceof RubyComplex || obj instanceof RubyRegexp) {
switch (out.opts.mode) {
case StrictMode: raise_strict(obj); break;
case NullMode: dump_nil(out); break;
case CompatMode:
case ObjectMode:
default: dump_obj_comp(context, obj, depth, out, argv); break;
}
} else if (obj instanceof RubyTime || obj instanceof RubyBigDecimal) { // FIXME: not sure it is only these two types.
switch (out.opts.mode) {
case StrictMode: dump_data_strict(context, obj, out); break;
case NullMode: dump_data_null(context, obj, out); break;
case CompatMode: dump_data_comp(context, obj, depth, out); break;
case ObjectMode:
default: dump_data_obj(context, obj, depth, out); break;
}
} else {
switch (out.opts.mode) {
case StrictMode: dump_data_strict(context, obj, out); break;
case NullMode: dump_data_null(context, obj, out); break;
case CompatMode: dump_obj_comp(context, obj, depth, out, argv); break;
case ObjectMode:
default: dump_obj_obj(context, obj, depth, out); break;
}
// What type causes this? throw context.runtime.newNotImplementedError("\"Failed to dump '" + obj.getMetaClass().getName() + "'.");
}
}
}
}
static void obj_to_json(ThreadContext context, IRubyObject obj, Options copts, Out out) {
obj_to_json_using_params(context, obj, copts, out, IRubyObject.NULL_ARRAY);
}
static void obj_to_json_using_params(ThreadContext context, IRubyObject obj, Options copts, Out out, IRubyObject[] argv) {
out.circ_cnt = 0;
out.opts = copts;
out.hash_cnt = 0;
out.omit_nil = copts.dump_opts.omit_nil;
if (Yes == copts.circular) {
out.new_circ_cache();
}
out.indent = copts.indent;
dump_val(context, obj, 0, out, argv);
if (0 < out.indent) {
switch (out.peek(0)) {
case ']':
case '}':
out.append('\n');
default:
break;
}
}
if (Yes == copts.circular) {
out.delete_circ_cache();
}
}
void oj_write_obj_to_file(ThreadContext context, OjLibrary oj, IRubyObject obj, String path, Options copts) {
Out out = new Out(oj);
FileOutputStream f = null;
out.omit_nil = copts.dump_opts.omit_nil;
obj_to_json(context, obj, copts, out);
try {
f = new FileOutputStream(path);
out.write(f);
} catch (FileNotFoundException e) {
throw context.runtime.newIOErrorFromException(e);
} catch (IOException e) {
throw context.runtime.newIOErrorFromException(e);
} finally {
if (f != null) {
try { f.close(); } catch (IOException e) {}
}
}
}
static void oj_write_obj_to_stream(ThreadContext context, OjLibrary oj, IRubyObject obj, IRubyObject stream, Options copts) {
Out out = new Out(oj);
out.omit_nil = copts.dump_opts.omit_nil;
obj_to_json(context, obj, copts, out);
// Note: Removed Windows path as it called native write on fileno and JRuby does work the same way.
if (obj instanceof StringIO) {
((StringIO) obj).write(context, context.runtime.newString(out.buf));
} else if (stream.respondsTo("write")) {
stream.callMethod(context, "write", context.runtime.newString(out.buf));
} else {
throw context.runtime.newArgumentError("to_stream() expected an IO Object.");
}
}
// dump leaf functions
static void dump_leaf_str(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
dump_cstr(context, leaf.str, false, false, out);
break;
case RUBY_VAL: {
// FIXME: I think this will always be a string or raise here.
RubyString value = (RubyString) TypeConverter.checkStringType(context.runtime, leaf.value);
value = StringSupport.checkEmbeddedNulls(context.runtime, value);
dump_cstr(context, value.getByteList(), false, false, out);
break;
}
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_fixnum(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
out.append(leaf.str);
break;
case RUBY_VAL:
if (leaf.value instanceof RubyBignum) {
dump_bignum(context, (RubyBignum) leaf.value, out);
} else {
dump_fixnum((RubyFixnum) leaf.value, out);
}
break;
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_float(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
out.append(leaf.str);
break;
case RUBY_VAL:
dump_float(context, (RubyFloat) leaf.value, out);
break;
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_array(ThreadContext context, Leaf leaf, int depth, Out out) {
int d2 = depth + 1;
out.append('[');
if (leaf.hasElements()) {
boolean first = true;
for (Leaf element: leaf.elements) {
if (!first) out.append(',');
fill_indent(out, d2);
dump_leaf(context, element, d2, out);
first = false;
}
fill_indent(out, depth);
}
out.append(']');
}
static void dump_leaf_hash(ThreadContext context, Leaf leaf, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (leaf.hasElements()) {
boolean first = true;
for (Leaf element: leaf.elements) {
if (!first) out.append(',');
fill_indent(out, d2);
dump_cstr(context, element.key, false, false, out);
out.append(':');
dump_leaf(context, element, d2, out);
first = false;
}
fill_indent(out, depth);
}
out.append('}');
}
static void dump_leaf(ThreadContext context, Leaf leaf, int depth, Out out) {
switch (leaf.rtype) {
case T_NIL:
dump_nil(out);
break;
case T_TRUE:
dump_true(out);
break;
case T_FALSE:
dump_false(out);
break;
case T_STRING:
dump_leaf_str(context, leaf, out);
break;
case T_FIXNUM:
dump_leaf_fixnum(context, leaf, out);
break;
case T_FLOAT:
dump_leaf_float(context, leaf, out);
break;
case T_ARRAY:
dump_leaf_array(context, leaf, depth, out);
break;
case T_HASH:
dump_leaf_hash(context, leaf, depth, out);
break;
default:
throw context.runtime.newTypeError("Unexpected type " + leaf.rtype);
}
}
public static Out leaf_to_json(ThreadContext context, OjLibrary oj, Leaf leaf, Options copts) {
Out out = new Out(oj);
out.circ_cnt = 0;
out.opts = copts;
out.hash_cnt = 0;
out.indent = copts.indent;
dump_leaf(context, leaf, 0, out);
return out;
}
public static void leaf_to_file(ThreadContext context, OjLibrary oj, Leaf leaf, String path, Options copts) {
Out out = leaf_to_json(context, oj, leaf, copts);
FileOutputStream f = null;
try {
f = new FileOutputStream(path);
out.write(f);
} catch (IOException e) {
throw context.runtime.newIOErrorFromException(e);
} finally {
if (f != null) {
try { f.close(); } catch (IOException e) {}
}
}
}
// string writer functions
static void key_check(ThreadContext context, StrWriter sw, ByteList key) {
DumpType type = sw.peekTypes();
if (null == key && (ObjectNew == type || ObjectType == type)) {
throw context.runtime.newStandardError("Can not push onto an Object without a key.");
}
}
static void push_type(StrWriter sw, DumpType type) {
sw.types.push(type);
}
static void maybe_comma(StrWriter sw) {
DumpType type = sw.peekTypes();
if (type == ObjectNew) {
sw.types.set(sw.types.size() - 1, ObjectType);
} else if (type == ArrayNew) {
sw.types.set(sw.types.size() - 1, ArrayType);
} else if (type == ObjectType || type == ArrayType) {
// Always have a few characters available in the out.buf.
sw.out.append(',');
}
}
static void push_key(ThreadContext context, StrWriter sw, ByteList key) {
DumpType type = sw.peekTypes();
if (sw.keyWritten) {
throw context.runtime.newStandardError("Can not push more than one key before pushing a non-key.");
}
if (ObjectNew != type && ObjectType != type) {
throw context.runtime.newStandardError("Can only push a key onto an Object.");
}
maybe_comma(sw);
if (!sw.types.empty()) {
fill_indent(sw.out, sw.types.size());
}
dump_cstr(context, key, false, false, sw.out);
sw.out.append(':');
sw.keyWritten = true;
}
static void push_object(ThreadContext context, StrWriter sw, ByteList key) {
dump_key(context, sw, key);
sw.out.append('{');
push_type(sw, ObjectNew);
}
static void push_array(ThreadContext context, StrWriter sw, ByteList key) {
dump_key(context, sw, key);
sw.out.append('[');
push_type(sw, ArrayNew);
}
static void push_value(ThreadContext context, StrWriter sw, IRubyObject val, ByteList key) {
dump_key(context, sw, key);
dump_val(context, val, sw.types.size(), sw.out, null);
}
static void push_json(ThreadContext context, StrWriter sw, ByteList json, ByteList key) {
dump_key(context, sw, key);
dump_raw(json, sw.out);
}
private static void dump_key(ThreadContext context, StrWriter sw, ByteList key) {
if (sw.keyWritten) {
sw.keyWritten = false;
} else {
key_check(context, sw, key);
maybe_comma(sw);
if (!sw.types.empty()) {
fill_indent(sw.out, sw.types.size());
}
if (null != key) {
dump_cstr(context, key, false, false, sw.out);
sw.out.append(':');
}
}
}
static void pop(ThreadContext context, StrWriter sw) {
if (sw.keyWritten) {
sw.keyWritten = false;
throw context.runtime.newStandardError("Can not pop after writing a key but no value.");
}
if (sw.types.empty()) {
throw context.runtime.newStandardError("Can not pop with no open array or object.");
}
DumpType type = sw.types.pop();
fill_indent(sw.out, sw.types.size());
if (type == ObjectNew || type == ObjectType) {
sw.out.append('}');
} else if (type == ArrayNew || type == ArrayType) {
sw.out.append(']');
}
if (sw.types.empty() && 0 <= sw.out.indent) {
sw.out.append('\n');
}
}
static void pop_all(ThreadContext context, StrWriter sw) {
while (!sw.types.empty()) {
pop(context, sw);
}
}
// Unlike C version we assume check has been made that there is an ignore list
// and we are in the correct mode.
static boolean dump_ignore(Out out, IRubyObject value) {
RubyModule clas = value.getMetaClass();
for (RubyModule module: out.opts.ignore) {
if (module == clas) return true;
}
return false;
}
}
|
ext/java/oj/Dump.java
|
package oj;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.TimeZone;
import jnr.posix.util.Platform;
import oj.options.DumpType;
import oj.options.NanDump;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyComplex;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyNil;
import org.jruby.RubyNumeric;
import org.jruby.RubyRange;
import org.jruby.RubyRational;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.RubyStruct;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.ext.stringio.StringIO;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.util.ByteList;
import org.jruby.util.Sprintf;
import org.jruby.util.StringSupport;
import org.jruby.util.TypeConverter;
import static oj.options.DumpType.ArrayNew;
import static oj.options.DumpType.ArrayType;
import static oj.options.DumpType.ObjectNew;
import static oj.options.DumpType.ObjectType;
import static oj.Options.*;
import static oj.NumInfo.OJ_INFINITY;
/**
* Created by enebo on 9/9/15.
*/
public class Dump {
static int MAX_DEPTH = 1000;
private static final byte[] BIG_O_KEY = {'"', '^', 'O', '"', ':'};
private static final byte[] C_KEY = {'"', '^', 'c', '"', ':'};
private static final byte[] O_KEY = {'"', '^', 'o', '"', ':'};
private static final byte[] I_KEY = {'"', '^', 'i', '"', ':'};
private static final byte[] PARTIAL_I_KEY = {'"', '^', 'i'};
private static final byte[] T_KEY = {'"', '^', 't', '"', ':'};
private static final byte[] U_KEY = {'"', '^', 'u', '"', ':', '['};
private static final byte[] SELF_KEY = {'"', 's', 'e', 'l', 'f', '"', ':'};
private static final byte[] NULL_VALUE = {'n', 'u', 'l', 'l'};
private static final byte[] TRUE_VALUE = {'t', 'r', 'u', 'e'};
private static final byte[] FALSE_VALUE = {'f', 'a', 'l', 's', 'e'};
public static final byte[] INFINITY_VALUE = {'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'};
private static final byte[] NINFINITY_VALUE = {'-', 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'};
private static final byte[] NAN_VALUE = {'N', 'a', 'N'};
public static final byte[] INF_VALUE = {'3', '.', '0', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
public static final byte[] NINF_VALUE = {'-', '3', '.', '0', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
public static final byte[] NAN_NUMERIC_VALUE = {'3', '.', '3', 'e', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3', '2', '3', '8', '4', '6'};
private static final byte[] ZERO_POINT_ZERO = {'0', '.', '0'};
static String hex_chars = "0123456789abcdef";
// JSON standard except newlines are no escaped
static int newline_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,1,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
// JSON standard
static int hibit_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
// High bit set characters are always encoded as unicode. Worse case is 3
// bytes per character in the output. That makes this conservative.
static int ascii_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
// XSS safe mode
static int xss_friendly_chars[] = {
6,6,6,6,6,6,6,6,2,2,2,6,2,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1,1,2,1,1,1,6,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,6,1,6,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
static int newline_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += newline_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int hibit_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += hibit_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int ascii_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += ascii_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static int xss_friendly_size(ByteList str) {
int len = str.length();
int size = 0;
for (int i = 0; 0 < len; i++, len--) {
size += xss_friendly_chars[str.get(i) & 0xff];
}
return size - len * (int)'0';
}
static void fill_indent(Out out, int cnt) {
if (out.indent > 0) {
cnt *= out.indent;
out.append('\n');
for (; 0 < cnt; cnt--) {
out.append(' ');
}
}
}
static void dump_ulong(long num, Out out) {
byte[] buf = new byte[32]; // FIXME: Can be instance variable
int b = buf.length - 1;
if (0 < num) {
for (; 0 < num; num /= 10, b--) {
buf[b] = (byte) ((num % 10) + '0');
}
b++;
} else {
buf[b] = '0';
}
for (; b < buf.length; b++) {
out.append(buf[b]);
}
}
static void dump_hex(int c, Out out) {
int d = (c >> 4) & 0x0F;
out.append(hex_chars.charAt(d));
d = c & 0x0F;
out.append(hex_chars.charAt(d));
}
static void dump_raw(byte[] str, Out out) {
out.append(str);
}
static void dump_raw(ByteList str, Out out) {
out.append(str);
}
static int dump_unicode(ThreadContext context, ByteList str, int str_i, int end, Out out) {
int code;
int b = str.get(str_i);
int i, cnt;
if (0xC0 == (0xE0 & b)) {
cnt = 1;
code = b & 0x0000001F;
} else if (0xE0 == (0xF0 & b)) {
cnt = 2;
code = b & 0x0000000F;
} else if (0xF0 == (0xF8 & b)) {
cnt = 3;
code = b & 0x00000007;
} else if (0xF8 == (0xFC & b)) {
cnt = 4;
code = b & 0x00000003;
} else if (0xFC == (0xFE & b)) {
cnt = 5;
code = b & 0x00000001;
} else {
throw context.runtime.newEncodingError("Invalid Unicode\n");
}
str_i++;
for (; 0 < cnt; cnt--, str_i++) {
b = str.get(str_i);
if (end <= str_i || 0x80 != (0xC0 & b)) {
throw context.runtime.newEncodingError("Invalid Unicode\n");
}
code = (code << 6) | (b & 0x0000003F);
}
if (0x0000FFFF < code) {
int c1;
code -= 0x00010000;
c1 = ((code >> 10) & 0x000003FF) + 0x0000D800;
code = (code & 0x000003FF) + 0x0000DC00;
out.append('\\');
out.append('u');
for (i = 3; 0 <= i; i--) {
out.append(hex_chars.charAt((int)(c1 >> (i * 4)) & 0x0F));
}
}
out.append('\\');
out.append('u');
for (i = 3; 0 <= i; i--) {
out.append(hex_chars.charAt((int)(code >> (i * 4)) & 0x0F));
}
return str_i - 1;
}
// returns 0 if not using circular references, -1 if not further writing is
// needed (duplicate), and a positive value if the object was added to the cache.
static long check_circular(IRubyObject obj, Out out) {
Integer id = 0;
if (ObjectMode == out.opts.mode && Yes == out.opts.circular) {
id = out.circ_cache.get(obj);
if (id == null) {
out.circ_cnt++;
id = out.circ_cnt;
out.circ_cache.put(obj, id);
} else {
out.append('"');
out.append('^');
out.append('r');
dump_ulong(id.longValue(), out);
out.append('"');
return -1;
}
}
return id.longValue();
}
static void dump_nil(Out out) {
out.append(NULL_VALUE);
}
static void dump_true(Out out) {
out.append(TRUE_VALUE);
}
static void dump_false(Out out) {
out.append(FALSE_VALUE);
}
static void dump_fixnum(RubyFixnum obj, Out out) {
byte buf[] = new byte[32];
int b = buf.length - 1;
long num = obj.getLongValue();
boolean neg = false;
if (num < 0) {
num = -num;
neg = true;
}
if (num == 0) {
buf[b] = '0';
} else {
for (; 0 < num; num /= 10, b--) {
buf[b] = (byte) ((num % 10) + '0');
}
if (neg) {
buf[b] = '-';
} else {
b++;
}
}
int size = buf.length - b;
out.append(buf, b, size);
}
static void dump_bignum(ThreadContext context, RubyBignum obj, Out out) {
// Note: This uses boxed call to to_s because 9.1 -> 9.2 changed return type on non-boxed version
// from IRubyObject -> RubyString.
out.append(obj.to_s(new IRubyObject[] { context.runtime.newFixnum(10) }).convertToString().getByteList());
}
static void dump_float(ThreadContext context, RubyFloat obj, Out out) {
double d = obj.getDoubleValue();
if (d == 0.0) {
out.append(ZERO_POINT_ZERO);
} else if (d == OJ_INFINITY) {
dumpInfNanForFloat(out, obj, INF_VALUE, INFINITY_VALUE);
} else if (d == -OJ_INFINITY) {
dumpInfNanForFloat(out, obj, NINF_VALUE, NINFINITY_VALUE);
} else if (Double.isNaN(d)) {
dumpNanNanForFloat(out, obj);
/*} else if (d == (double)(long)d) { // FIXME: Precision overflow?
cnt = snprintf(buf, sizeof(buf), "%.1f", d);*/
} else if (0 == out.opts.float_prec) {
IRubyObject rstr = Helpers.invoke(context, obj, "to_s");
if (!(rstr instanceof RubyString)) {
throw context.runtime.newArgumentError("Expected a String");
}
out.append(((RubyString) rstr).getByteList().bytes());
} else {
ByteList buf = new ByteList();
Sprintf.sprintf(buf, out.opts.float_fmt, obj);
out.append(buf);
}
}
private static final void dumpNanNanForFloat(Out out, IRubyObject value) {
if (out.opts.mode == ObjectMode) {
out.append(NAN_NUMERIC_VALUE);
} else {
NanDump nd = out.opts.dump_opts.nan_dump;
if (nd == NanDump.AutoNan) {
switch (out.opts.mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
case NullMode: nd = NanDump.NullNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: out.append(NAN_VALUE); break;
case NullNan: out.append(NULL_VALUE); break;
case HugeNan:
default: out.append(NAN_NUMERIC_VALUE); break;
}
}
}
private static final void dumpInfNanForFloat(Out out, IRubyObject value, byte[] inf_value, byte[] infinity_value) {
if (out.opts.mode == ObjectMode) {
out.append(inf_value);
} else {
NanDump nd = out.opts.dump_opts.nan_dump;
if (nd == NanDump.AutoNan) {
switch (out.opts.mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
case NullMode: nd = NanDump.NullNan; break;
case CustomMode: nd = NanDump.NullNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: out.append(infinity_value); break;
case NullNan: out.append(NULL_VALUE); break;
case HugeNan:
default: out.append(inf_value); break;
}
}
}
// FIXME: This is going to mess up blindly grabbing bytes if it mismatches UTF-8 (I believe all strings
// will be UTF-8 or clean ascii 7-bit).
static void dump_cstr(ThreadContext context, String str, boolean is_sym, boolean escape1, Out out) {
dump_cstr(context, new ByteList(str.getBytes(), UTF8Encoding.INSTANCE), is_sym, escape1, out);
}
static void dump_cstr(ThreadContext context, ByteList str, boolean is_sym, boolean escape1, Out out) {
int size;
int[] cmap;
int str_i = 0;
switch (out.opts.escape_mode) {
case NLEsc:
cmap = newline_friendly_chars;
size = newline_friendly_size(str);
break;
case ASCIIEsc:
cmap = ascii_friendly_chars;
size = ascii_friendly_size(str);
break;
case XSSEsc:
cmap = xss_friendly_chars;
size = xss_friendly_size(str);
break;
case JSONEsc:
default:
cmap = hibit_friendly_chars;
size = hibit_friendly_size(str);
}
int cnt = str.length();
out.append('"');
if (escape1) {
out.append('\\');
out.append('u');
out.append('0');
out.append('0');
dump_hex(str.get(str_i), out);
cnt--;
size--;
str_i++;
is_sym = false; // just to make sure
}
if (cnt == size) {
if (is_sym) out.append(':');
out.append(str.unsafeBytes(), str.begin() + str_i, cnt);
out.append('"');
} else {
if (is_sym) {
out.append(':');
}
for (; str_i < cnt; str_i++) {
switch (cmap[(int)str.get(str_i) & 0xff]) {
case 1:
out.append(str.get(str_i));
break;
case 2:
out.append('\\');
switch ((byte) str.get(str_i)) {
case '\\': out.append('\\'); break;
case '\b': out.append('b'); break;
case '\t': out.append('t'); break;
case '\n': out.append('n'); break;
case '\f': out.append('f'); break;
case '\r': out.append('r'); break;
default: out.append(str.get(str_i)); break;
}
break;
case 3: // Unicode
str_i = dump_unicode(context, str, str_i, cnt, out);
break;
case 6: // control characters
out.append('\\');
out.append('u');
out.append('0');
out.append('0');
dump_hex(str.get(str_i), out);
break;
default:
break; // ignore, should never happen if the table is correct
}
}
out.append('"');
}
}
static void dump_str_comp(ThreadContext context, RubyString obj, Out out) {
dump_cstr(context, obj.getByteList(), false, false, out);
}
static void dump_str_obj(ThreadContext context, RubyString string, Out out) {
ByteList str = string.getByteList();
boolean escape = isEscapeString(str);
if (string.isAsciiOnly() && !escape) { // Fast path. JRuby already knows if it is a clean ASCII string.
out.append('"');
out.append(str.unsafeBytes(), str.begin(), str.realSize());
out.append('"');
} else {
dump_cstr(context, str, false, escape, out);
}
}
static boolean isEscapeString(ByteList str) {
if (str.realSize() >=2 ) {
int s = str.get(0);
if (s == ':') return true;
if (s == '^'){
s = str.get(1);
return s == 'r' || s == 'i';
}
}
return false;
}
static void dump_sym_comp(ThreadContext context, RubySymbol obj, Out out) {
dump_cstr(context, ((RubyString) obj.to_s()).getByteList(), false, false, out);
}
static void dump_sym_obj(ThreadContext context, RubySymbol obj, Out out) {
dump_cstr(context, ((RubyString) obj.to_s()).getByteList(), true, false, out);
}
static void dump_class_comp(ThreadContext context, RubyModule clas, Out out) {
dump_cstr(context, new ByteList(clas.getName().getBytes()), false, false, out);
}
static void dump_class_obj(ThreadContext context, RubyModule clas, Out out) {
out.append('{');
out.append(C_KEY);
dump_cstr(context, new ByteList(clas.getName().getBytes()), false, false, out);
out.append('}');
}
static void dump_array(ThreadContext context, RubyArray array, int depth, Out out) {
int d2 = depth + 1;
long id = check_circular(array, out);
if (id < 0) return; // duplicate found (written out in check_circular)
out.append('[');
if (id > 0) {
fill_indent(out, d2);
out.append(PARTIAL_I_KEY);
dump_ulong(id, out);
out.append('"');
}
if (array.isEmpty()) {
out.append(']');
} else {
if (id > 0) out.append(',');
int cnt = array.getLength() - 1;
for (int i = 0; i <= cnt; i++) {
indent(out, d2, out.opts.dump_opts.array_nl);
dump_val(context, array.eltInternal(i), d2, out, null);
if (i < cnt) out.append(',');
}
indent(out, depth, out.opts.dump_opts.array_nl);
out.append(']');
}
}
static void indent(Out out, int depth, ByteList nl) {
if (out.opts.dump_opts.use) {
if (nl != ByteList.EMPTY_BYTELIST) out.append(nl);
if (out.opts.dump_opts.indent_str != ByteList.EMPTY_BYTELIST) {
for (int j = depth; 0 < j; j--) {
out.append(out.opts.dump_opts.indent_str);
}
}
} else {
fill_indent(out, depth);
}
}
static void hash_cb_strict(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
int depth = out.depth;
if (!(key instanceof RubyString)) {
throw context.runtime.newTypeError("In :strict mode all Hash keys must be Strings, not " + key.getMetaClass().getName());
}
if (out.opts.dump_opts.use) {
if (out.opts.dump_opts.hash_nl != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.hash_nl);
}
if (out.opts.dump_opts.indent_str != ByteList.EMPTY_BYTELIST) {
int i;
for (i = depth; 0 < i; i--) {
out.append(out.opts.dump_opts.indent_str);
}
}
dump_str_comp(context, (RubyString) key, out);
if (out.opts.dump_opts.before_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.before_sep);
}
out.append(':');
if (out.opts.dump_opts.after_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.after_sep);
}
} else {
fill_indent(out, depth);
dump_str_comp(context, (RubyString) key, out);
out.append(':');
}
dump_val(context, value, depth, out, null);
out.depth = depth;
out.append(',');
}
static void hash_cb_compat(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
int depth = out.depth;
indent(out, depth, out.opts.dump_opts.hash_nl);
if (key instanceof RubyString) {
dump_str_comp(context, (RubyString) key, out);
} else if (key instanceof RubySymbol) {
dump_sym_comp(context, (RubySymbol) key, out);
} else {
/*rb_raise(rb_eTypeError, "In :compat mode all Hash keys must be Strings or Symbols, not %s.\n", rb_class2name(rb_obj_class(key)));*/
dump_cstr(context, stringToByteList(context, key, "to_s"), false, false, out);
}
if (out.opts.dump_opts.use) {
if (out.opts.dump_opts.before_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.before_sep);
}
out.append(':');
if (out.opts.dump_opts.after_sep != ByteList.EMPTY_BYTELIST) {
out.append(out.opts.dump_opts.after_sep);
}
} else {
out.append(':');
}
dump_val(context, value, depth, out, null);
out.depth = depth;
out.append(',');
}
static void hash_cb_object(ThreadContext context, IRubyObject key, IRubyObject value, Out out) {
if (out.opts.ignore != null && dump_ignore(out, value)) return;
if (out.omit_nil && value.isNil()) return;
int depth = out.depth;
fill_indent(out, depth);
if (key instanceof RubyString) {
dump_str_obj(context, (RubyString) key, out);
out.append(':');
dump_val(context, value, depth, out, null);
} else if (key instanceof RubySymbol) {
dump_sym_obj(context, (RubySymbol) key, out);
out.append(':');
dump_val(context, value, depth, out, null);
} else {
int d2 = depth + 1;
int i;
boolean started = false;
int b;
out.append('"');
out.append('^');
out.append('#');
out.hash_cnt++;
for (i = 28; 0 <= i; i -= 4) {
b = (int)((out.hash_cnt >> i) & 0x0000000F);
if ('\0' != b) {
started = true;
}
if (started) {
out.append(hex_chars.charAt(b));
}
}
out.append('"');
out.append(':');
out.append('[');
fill_indent(out, d2);
dump_val(context, key, d2, out, null);
out.append(',');
fill_indent(out, d2);
dump_val(context, value, d2, out, null);
fill_indent(out, depth);
out.append(']');
}
out.depth = depth;
out.append(',');
}
static void dump_hash(final ThreadContext context, IRubyObject obj, RubyClass clas, int depth, int mode, Out out) {
int cnt;
if (null != clas && !(obj instanceof RubyHash) && ObjectMode == mode) {
dump_obj_attrs(context, obj, clas, 0, depth, out);
return;
}
RubyHash hash = (RubyHash) obj;
cnt = hash.size();
if (0 == cnt) {
out.append('{');
out.append('}');
} else {
long id = check_circular(obj, out);
if (0 > id) {
return;
}
out.append('{');
if (0 < id) {
fill_indent(out, depth + 1);
out.append('"');
out.append('^');
out.append('i');
out.append('"');
out.append(':');
dump_ulong(id, out);
out.append(',');
}
out.depth = depth + 1;
if (ObjectMode == mode) {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_object(context, key, value, out);
}
},
out);
} else if (CompatMode == mode) {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_compat(context, key, value, out);
}
},
out);
} else {
hash.visitAll(context,
new RubyHash.VisitorWithState<Out>() {
@Override
public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Out out) {
hash_cb_strict(context, key, value, out);
}
},
out);
}
if (',' == out.get(-1)) {
out.pop(); // backup to overwrite last comma
}
indent(out, depth, out.opts.dump_opts.hash_nl);
out.append('}');
}
}
// In JRuby rb_time_timespec equivalent is not public.
// FIXME: Move into EmbeddedAPI when I make it
private static long[] extractTimespec(ThreadContext context, IRubyObject value) {
long[] timespec = new long[2];
if (value instanceof RubyFloat) {
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(value) : RubyNumeric.num2long(value);
double fraction = ((RubyFloat) value).getDoubleValue() % 1.0;
timespec[1] = (long)(fraction * 1e9 + 0.5);
} else if (value instanceof RubyNumeric) {
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(value) : RubyNumeric.num2long(value);
timespec[1] = 0;
} else {
RubyTime time;
if (value instanceof RubyTime) {
time = ((RubyTime) value);
} else {
time = (RubyTime) TypeConverter.convertToType(value, context.runtime.getTime(), "to_time", true);
}
timespec[0] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.to_i()) : RubyNumeric.num2long(time.to_i());
timespec[1] = Platform.IS_32_BIT ? RubyNumeric.num2int(time.nsec()) : RubyNumeric.num2long(time.nsec());
}
return timespec;
}
static void dump_time(ThreadContext context, IRubyObject obj, Out out, boolean withZone) {
long[] timespec = extractTimespec(context, obj);
long sec = timespec[0];
long nsec = timespec[1];
byte[] buf = new byte[64];
int b = buf.length - 1;
boolean neg = false;
int dot;
long one = 1000000000;
// JRuby returns negative nsec....not sure if this is correct or whether sec should subtract 1 too?
if (nsec < 0) {
nsec = one + nsec;
sec--;
}
if (withZone) {
long tzsecs = obj.callMethod(context, "utc_offset").convertToInteger().getLongValue();
boolean zneg = (0 > tzsecs);
if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
tzsecs = 86400;
}
if (zneg) {
tzsecs = -tzsecs;
}
if (0 == tzsecs) {
buf[b] = '0';
b--;
} else {
for (; 0 < tzsecs; b--, tzsecs /= 10) {
buf[b] = (byte) ('0' + (tzsecs % 10));
}
if (zneg) {
buf[b] = '-';
b--;
}
}
buf[b] = 'e';
b--;
}
if (0 > sec) {
neg = true;
sec = -sec;
if (0 < nsec) {
nsec = 1000000000 - nsec;
sec--;
}
}
dot = b - 9;
if (0 < out.opts.sec_prec) {
if (9 > out.opts.sec_prec) {
for (int i = 9 - out.opts.sec_prec; 0 < i; i--) {
dot++;
nsec = (nsec + 5) / 10;
one /= 10;
}
}
if (one <= nsec) {
nsec -= one;
sec++;
}
for (; dot < b; b--, nsec /= 10) {
buf[b] = (byte) ('0' + (nsec % 10));
}
buf[b] = '.';
b--;
}
if (0 == sec) {
buf[b] = '0';
b--;
} else {
for (; 0 < sec; b--, sec /= 10) {
buf[b] = (byte) ('0' + (sec % 10));
}
}
if (neg) {
buf[b] = '-';
b--;
}
b++;
int size = buf.length - b;
out.append(buf, b, size);
}
static void dump_ruby_time(ThreadContext context, IRubyObject obj, Out out) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
static void dump_xml_time(ThreadContext context, IRubyObject obj, Out out) {
long[] timespec = extractTimespec(context, obj);
long sec = timespec[0];
long nsec = timespec[1];
StringBuilder buf = new StringBuilder();
Formatter formatter = new Formatter(buf);
long one = 1000000000;
long tzsecs = obj.callMethod(context, "utc_offset").convertToInteger().getLongValue();
int tzhour, tzmin;
char tzsign = '+';
if (9 > out.opts.sec_prec) {
int i;
for (i = 9 - out.opts.sec_prec; 0 < i; i--) {
nsec = (nsec + 5) / 10;
one /= 10;
}
if (one <= nsec) {
nsec -= one;
sec++;
}
}
// 2012-01-05T23:58:07.123456000+09:00
//tm = localtime(&sec);
sec += tzsecs;
Date date = new Date(sec*1000); // milliseconds since epoch
Calendar tm = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
tm.setTime(date);
if (0 > tzsecs) {
tzsign = '-';
tzhour = (int)(tzsecs / -3600);
tzmin = (int)(tzsecs / -60) - (tzhour * 60);
} else {
tzhour = (int)(tzsecs / 3600);
tzmin = (int)(tzsecs / 60) - (tzhour * 60);
}
if (0 == nsec || 0 == out.opts.sec_prec) {
if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
formatter.format("%04d-%02d-%02dT%02d:%02d:%02dZ",
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND));
dump_cstr(context, buf.toString(), false, false, out);
} else {
formatter.format("%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND),
tzsign, tzhour, tzmin);
dump_cstr(context, buf.toString(), false, false, out);
}
} else if (0 == tzsecs && obj.callMethod(context, "utc?").isTrue()) {
String format = "%04d-%02d-%02dT%02d:%02d:%02d.%09dZ";
if (9 > out.opts.sec_prec) {
format = "%04d-%02d-%02dT%02d:%02d:%02d.%0" + (char) ('0' + out.opts.sec_prec);
}
formatter.format(format,
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND), nsec);
dump_cstr(context, buf.toString(), false, false, out);
} else {
String format = "%04d-%02d-%02dT%02d:%02d:%02d.%09d%c%02d:%02d";
if (9 > out.opts.sec_prec) {
format = "%04d-%02d-%02dT%02d:%02d:%02d.%0" + (char) ('0' + out.opts.sec_prec) + "d%c%02d:%02d";
}
formatter.format(format,
tm.get(Calendar.YEAR), tm.get(Calendar.MONTH) + 1, tm.get(Calendar.DAY_OF_MONTH),
tm.get(Calendar.HOUR_OF_DAY), tm.get(Calendar.MINUTE), tm.get(Calendar.SECOND), nsec,
tzsign, tzhour, tzmin);
dump_cstr(context, buf.toString(), false, false, out);
}
}
static void dump_data_strict(ThreadContext context, IRubyObject obj, Out out) {
if (obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else {
raise_strict(obj);
}
}
static void dump_data_null(ThreadContext context, IRubyObject obj, Out out) {
if (obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else {
dump_nil(out);
}
}
static void dump_data_comp(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(obj.getRuntime().getCurrentContext(), "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(obj, context.runtime.getHash());
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (Yes == out.opts.bigdec_as_num && obj instanceof RubyBigDecimal) {
dump_raw(stringToByteList(context, obj, "to_s"), out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(obj.getRuntime().getCurrentContext(), "as_json");
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
if (obj instanceof RubyTime) {
switch (out.opts.time_format) {
case RubyTime: dump_ruby_time(context, obj, out); break;
case XmlTime: dump_xml_time(context, obj, out); break;
case UnixZTime: dump_time(context, obj, out, true); break;
case UnixTime:
default: dump_time(context, obj, out, false); break;
}
} else if (obj instanceof RubyBigDecimal) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
}
}
static void dump_data_obj(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj instanceof org.jruby.RubyTime) {
out.append('{');
out.append(T_KEY);
switch (out.opts.time_format) {
case RubyTime: // Does not output fractional seconds
case XmlTime:
dump_xml_time(context, obj, out);
break;
case UnixZTime:
dump_time(context, obj, out, true);
break;
case UnixTime:
default:
dump_time(context, obj, out, false);
break;
}
out.append('}');
} else if (obj instanceof RubyBigDecimal) {
ByteList str = stringToByteList(context, obj, "to_s");
if (out.opts.bigdec_as_num != No) {
dump_raw(str, out);
} else if (INFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, true), out);
} else if (NINFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, false), out);
} else {
dump_cstr(context, str, false, false, out);
}
} else {
dump_nil(out);
}
}
private static byte[] nan_str(IRubyObject value, NanDump nd, char mode, boolean positive) {
if (nd == NanDump.AutoNan) {
switch (mode) {
case CompatMode: nd = NanDump.WordNan; break;
case StrictMode: nd = NanDump.RaiseNan; break;
}
}
switch(nd) {
case RaiseNan: raise_strict(value); break;
case WordNan: return positive ? INFINITY_VALUE : NINFINITY_VALUE;
case NullNan: return NULL_VALUE;
case HugeNan:
return INF_VALUE;
}
return null; // C source does this but this I believe will crash in both impls...let's see....
}
// FIXME: both C and Java can crash potentially I added check here but
// I should see if C oj crashes for these cases.
static ByteList stringToByteList(ThreadContext context, IRubyObject obj, String method) {
IRubyObject stringResult = obj.callMethod(context, method);
if (!(stringResult instanceof RubyString)) {
throw context.runtime.newTypeError("Expected a String");
}
return ((RubyString) stringResult).getByteList();
}
static void dump_obj_comp(ThreadContext context, IRubyObject obj, int depth, Out out, IRubyObject[] argv) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(context, "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(h.getMetaClass().getName() + ".to_hash() did not return a Hash");
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(context, "as_json", argv);
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
if (obj instanceof RubyBigDecimal) {
ByteList rstr = stringToByteList(context, obj, "to_s");
if (Yes == out.opts.bigdec_as_num) {
dump_raw(rstr, out);
} else {
dump_cstr(context, rstr, false, false, out);
}
//FIXME: what if datetime does not exist?
} else {
RubyClass dateTime = context.runtime.getClass("DateTime");
RubyClass date = context.runtime.getClass("Date");
if (dateTime != null && dateTime.isInstance(obj) || date != null && date.isInstance(obj) || obj instanceof RubyRational) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_obj_attrs(context, obj, null, 0, depth, out);
}
}
}
}
static void dump_obj_obj(ThreadContext context, IRubyObject obj, int depth, Out out) {
long id = check_circular(obj, out);
if (0 <= id) {
if (obj instanceof RubyBigDecimal) {
ByteList str = stringToByteList(context, obj, "to_s");
if (INFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, true), out);
} else if (NINFINITY_VALUE.equals(str)) {
dump_raw(nan_str(obj, out.opts.dump_opts.nan_dump, out.opts.mode, false), out);
} else {
dump_raw(str, out);
}
} else {
dump_obj_attrs(context, obj, obj.getMetaClass(), id, depth, out);
}
}
}
static void dump_obj_attrs(ThreadContext context, IRubyObject obj, RubyClass clas, long id, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (null != clas) {
ByteList class_name = ((RubyString) clas.name()).getByteList();
fill_indent(out, d2);
out.append(O_KEY);
dump_cstr(context, class_name, false, false, out);
}
if (0 < id) {
out.append(',');
fill_indent(out, d2);
out.append(I_KEY);
dump_ulong(id, out);
}
if (obj instanceof RubyString) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_cstr(context, ((RubyString) obj).getByteList(), false, false, out);
} else if (obj instanceof RubyArray) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_array(context, (RubyArray) obj, depth + 1, out);
} else if (obj instanceof RubyHash) {
out.append(',');
fill_indent(out, d2);
out.append(SELF_KEY);
dump_hash(context, obj, null, depth + 1, out.opts.mode, out);
}
List<Variable<Object>> variables = obj.getVariableList();
if (clas != null && !variables.isEmpty()) {
out.append(',');
}
boolean first = true;
for (Variable<Object> variable: variables) {
String name = variable.getName();
// FIXME: We may crash if non ruby object is internal????
IRubyObject value = (IRubyObject) variable.getValue();
if (out.opts.ignore != null && dump_ignore(out, value)) continue;
if (out.omit_nil && value.isNil()) continue;
if (first) {
first = false;
} else {
out.append(',');
}
fill_indent(out, d2);
if (name.charAt(0) == '@') {
dump_cstr(context, name.substring(1), false, false, out);
} else {
dump_cstr(context, "~" + name, false, false, out);
}
out.append(':');
dump_val(context, value, d2, out, null);
}
out.depth = depth;
fill_indent(out, depth);
out.append('}');
}
static void dump_struct_comp(ThreadContext context, IRubyObject obj, int depth, Out out) {
if (obj.respondsTo("to_hash")) {
IRubyObject h = obj.callMethod(context, "to_hash");
if (!(h instanceof RubyHash)) {
throw context.runtime.newTypeError(obj.getMetaClass().getName() + ".to_hash() did not return a Hash.");
}
dump_hash(context, h, null, depth, out.opts.mode, out);
} else if (obj.respondsTo("as_json")) {
IRubyObject aj = obj.callMethod(context, "as_json");
// Catch the obvious brain damaged recursive dumping.
if (aj == obj) {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
} else {
dump_val(context, aj, depth, out, null);
}
} else if (Yes == out.opts.to_json && obj.respondsTo("to_json")) {
out.append(stringToByteList(context, obj, "to_json"));
} else {
dump_cstr(context, stringToByteList(context, obj, "to_s"), false, false, out);
}
}
static void dump_struct_obj(ThreadContext context, RubyStruct obj, int depth, Out out) {
String class_name = obj.getMetaClass().getName();
int d2 = depth + 1;
int d3 = d2 + 1;
out.append('{');
fill_indent(out, d2);
out.append(U_KEY);
if (class_name.charAt(0) == '#') {
RubyArray ma = obj.members();
int cnt = ma.size();
out.append('[');
for (int i = 0; i < cnt; i++) {
RubySymbol name = (RubySymbol) ma.eltOk(i); // struct forces all members to be symbols
if (0 < i) {
out.append(',');
}
out.append('"');
out.append(name.asString().getByteList());
out.append('"');
}
out.append(']');
} else {
fill_indent(out, d3);
out.append('"');
out.append(class_name);
out.append('"');
}
out.append(',');
boolean first = true;
for (Object n: obj.members()) {
IRubyObject name = (IRubyObject) n;
if (first) {
first = false;
} else {
out.append(',');
}
fill_indent(out, d3);
dump_val(context, obj.aref(name), d3, out, null);
}
out.append(']');
out.append('}');
}
static void dump_range_obj(ThreadContext context, RubyRange obj, int depth, Out out) {
String class_name = obj.getMetaClass().getName();
int d2 = depth + 1;
int d3 = d2 + 1;
out.append('{');
fill_indent(out, d2);
out.append(U_KEY);
fill_indent(out, d3);
out.append('"');
out.append(class_name);
out.append('"');
out.append(',');
dump_val(context, obj.begin(context), d3, out, null);
out.append(',');
dump_val(context, obj.end(context), d3, out, null);
out.append(',');
dump_val(context, obj.exclude_end_p(), d3, out, null);
out.append(']');
out.append('}');
}
static void dump_odd(ThreadContext context, IRubyObject obj, Odd odd, RubyClass clas, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (clas != null) {
ByteList class_name = ((RubyString) clas.name()).getByteList();
fill_indent(out, d2);
out.append(BIG_O_KEY);
dump_cstr(context, class_name, false, false, out);
out.append(',');
}
if (odd.raw) {
RubyString str = (RubyString) obj.callMethod(context, odd.attrs[0]).checkStringType();
out.append('"');
out.append(odd.attrs[0]);
out.append('"');
out.append(':');
out.append(str.getByteList());
} else {
for (int index = 0; index < odd.attrs.length; index++) {
String name = odd.attrs[index];
IRubyObject value = oddValue(context, obj, name, odd, index);
fill_indent(out, d2);
dump_cstr(context, name, false, false, out);
out.append(':');
dump_val(context, value, d2, out, null);
out.append(',');
}
out.pop(); // remove last ','
}
out.append('}');
}
private static IRubyObject oddValue(ThreadContext context, IRubyObject obj, String name, Odd odd, int index) {
if (odd.attrFuncs[index] != null) return odd.attrFuncs[index].execute(context, obj);
if (name.indexOf('.') == -1) return obj.callMethod(context, name);
IRubyObject value = obj;
for (String segment : name.split("\\.")) {
value = value.callMethod(context, segment);
}
return value;
}
static void raise_strict(IRubyObject obj) {
throw obj.getRuntime().newTypeError("Failed to dump " + obj.getMetaClass().getName() + " Object to JSON in strict mode.");
}
static void dump_val(ThreadContext context, IRubyObject obj, int depth, Out out, IRubyObject[] argv) {
if (MAX_DEPTH < depth) {
throw new RaiseException(context.runtime, context.runtime.getNoMemoryError(), "Too deeply nested.", true);
}
if (obj instanceof RubyNil) {
dump_nil(out);
} else if (obj instanceof RubyBoolean) {
if (obj == context.runtime.getTrue()) {
dump_true(out);
} else {
dump_false(out);
}
} else if (obj instanceof RubyFixnum) {
dump_fixnum((RubyFixnum) obj, out);
} else if (obj instanceof RubyFloat) {
dump_float(context, (RubyFloat) obj, out);
} else if (obj instanceof RubyModule) { // Also will be RubyClass
switch (out.opts.mode) {
case StrictMode: raise_strict(obj); break;
case NullMode: dump_nil(out); break;
case CompatMode: dump_class_comp(context, (RubyModule) obj, out); break;
case ObjectMode:
default: dump_class_obj(context, (RubyModule) obj, out); break;
}
} else if (obj instanceof RubySymbol) {
switch (out.opts.mode) {
case StrictMode:
raise_strict(obj);
break;
case NullMode:
dump_nil(out);
break;
case CompatMode:
dump_sym_comp(context, (RubySymbol) obj, out);
break;
case ObjectMode:
default:
dump_sym_obj(context, (RubySymbol) obj, out);
break;
}
} else if (obj instanceof RubyStruct || obj instanceof RubyRange) { // In MRI T_STRUCT is also Range
switch (out.opts.mode) {
case StrictMode:
raise_strict(obj);
break;
case NullMode:
dump_nil(out);
break;
case CompatMode:
dump_struct_comp(context, obj, depth, out);
break;
case ObjectMode:
default:
if (obj instanceof RubyRange) {
dump_range_obj(context, (RubyRange) obj, depth, out);
} else {
dump_struct_obj(context, (RubyStruct) obj, depth, out);
}
break;
}
} else {
// Most developers have enough sense not to subclass primitive types but
// since these classes could potentially be subclassed a check for odd
// classes is performed.
{
RubyClass clas = obj.getMetaClass();
Odd odd;
if (ObjectMode == out.opts.mode && null != (odd = out.oj.getOdd(clas))) {
dump_odd(context, obj, odd, clas, depth + 1, out);
return;
}
if (obj instanceof RubyBignum) {
dump_bignum(context, (RubyBignum) obj, out);
} else if (obj.getMetaClass() == context.runtime.getString()) {
switch (out.opts.mode) {
case StrictMode:
case NullMode:
case CompatMode:
dump_str_comp(context, (RubyString) obj, out);
break;
case ObjectMode:
default:
dump_str_obj(context, (RubyString) obj, out);
break;
}
} else if (obj.getMetaClass() == context.runtime.getArray()) {
dump_array(context, (RubyArray) obj, depth, out);
} else if (obj.getMetaClass() == context.runtime.getHash()) {
dump_hash(context, obj, clas, depth, out.opts.mode, out);
} else if (obj instanceof RubyComplex || obj instanceof RubyRegexp) {
switch (out.opts.mode) {
case StrictMode: raise_strict(obj); break;
case NullMode: dump_nil(out); break;
case CompatMode:
case ObjectMode:
default: dump_obj_comp(context, obj, depth, out, argv); break;
}
} else if (obj instanceof RubyTime || obj instanceof RubyBigDecimal) { // FIXME: not sure it is only these two types.
switch (out.opts.mode) {
case StrictMode: dump_data_strict(context, obj, out); break;
case NullMode: dump_data_null(context, obj, out); break;
case CompatMode: dump_data_comp(context, obj, depth, out); break;
case ObjectMode:
default: dump_data_obj(context, obj, depth, out); break;
}
} else {
switch (out.opts.mode) {
case StrictMode: dump_data_strict(context, obj, out); break;
case NullMode: dump_data_null(context, obj, out); break;
case CompatMode: dump_obj_comp(context, obj, depth, out, argv); break;
case ObjectMode:
default: dump_obj_obj(context, obj, depth, out); break;
}
// What type causes this? throw context.runtime.newNotImplementedError("\"Failed to dump '" + obj.getMetaClass().getName() + "'.");
}
}
}
}
static void obj_to_json(ThreadContext context, IRubyObject obj, Options copts, Out out) {
obj_to_json_using_params(context, obj, copts, out, IRubyObject.NULL_ARRAY);
}
static void obj_to_json_using_params(ThreadContext context, IRubyObject obj, Options copts, Out out, IRubyObject[] argv) {
out.circ_cnt = 0;
out.opts = copts;
out.hash_cnt = 0;
if (Yes == copts.circular) {
out.new_circ_cache();
}
out.indent = copts.indent;
dump_val(context, obj, 0, out, argv);
if (0 < out.indent) {
switch (out.peek(0)) {
case ']':
case '}':
out.append('\n');
default:
break;
}
}
if (Yes == copts.circular) {
out.delete_circ_cache();
}
}
void oj_write_obj_to_file(ThreadContext context, OjLibrary oj, IRubyObject obj, String path, Options copts) {
Out out = new Out(oj);
FileOutputStream f = null;
out.omit_nil = copts.dump_opts.omit_nil;
obj_to_json(context, obj, copts, out);
try {
f = new FileOutputStream(path);
out.write(f);
} catch (FileNotFoundException e) {
throw context.runtime.newIOErrorFromException(e);
} catch (IOException e) {
throw context.runtime.newIOErrorFromException(e);
} finally {
if (f != null) {
try { f.close(); } catch (IOException e) {}
}
}
}
static void oj_write_obj_to_stream(ThreadContext context, OjLibrary oj, IRubyObject obj, IRubyObject stream, Options copts) {
Out out = new Out(oj);
out.omit_nil = copts.dump_opts.omit_nil;
obj_to_json(context, obj, copts, out);
// Note: Removed Windows path as it called native write on fileno and JRuby does work the same way.
if (obj instanceof StringIO) {
((StringIO) obj).write(context, context.runtime.newString(out.buf));
} else if (stream.respondsTo("write")) {
stream.callMethod(context, "write", context.runtime.newString(out.buf));
} else {
throw context.runtime.newArgumentError("to_stream() expected an IO Object.");
}
}
// dump leaf functions
static void dump_leaf_str(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
dump_cstr(context, leaf.str, false, false, out);
break;
case RUBY_VAL: {
// FIXME: I think this will always be a string or raise here.
RubyString value = (RubyString) TypeConverter.checkStringType(context.runtime, leaf.value);
value = StringSupport.checkEmbeddedNulls(context.runtime, value);
dump_cstr(context, value.getByteList(), false, false, out);
break;
}
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_fixnum(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
out.append(leaf.str);
break;
case RUBY_VAL:
if (leaf.value instanceof RubyBignum) {
dump_bignum(context, (RubyBignum) leaf.value, out);
} else {
dump_fixnum((RubyFixnum) leaf.value, out);
}
break;
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_float(ThreadContext context, Leaf leaf, Out out) {
switch (leaf.value_type) {
case STR_VAL:
out.append(leaf.str);
break;
case RUBY_VAL:
dump_float(context, (RubyFloat) leaf.value, out);
break;
case COL_VAL:
default:
throw context.runtime.newTypeError("Unexpected value type " + leaf.value_type + ".");
}
}
static void dump_leaf_array(ThreadContext context, Leaf leaf, int depth, Out out) {
int d2 = depth + 1;
out.append('[');
if (leaf.hasElements()) {
boolean first = true;
for (Leaf element: leaf.elements) {
if (!first) out.append(',');
fill_indent(out, d2);
dump_leaf(context, element, d2, out);
first = false;
}
fill_indent(out, depth);
}
out.append(']');
}
static void dump_leaf_hash(ThreadContext context, Leaf leaf, int depth, Out out) {
int d2 = depth + 1;
out.append('{');
if (leaf.hasElements()) {
boolean first = true;
for (Leaf element: leaf.elements) {
if (!first) out.append(',');
fill_indent(out, d2);
dump_cstr(context, element.key, false, false, out);
out.append(':');
dump_leaf(context, element, d2, out);
first = false;
}
fill_indent(out, depth);
}
out.append('}');
}
static void dump_leaf(ThreadContext context, Leaf leaf, int depth, Out out) {
switch (leaf.rtype) {
case T_NIL:
dump_nil(out);
break;
case T_TRUE:
dump_true(out);
break;
case T_FALSE:
dump_false(out);
break;
case T_STRING:
dump_leaf_str(context, leaf, out);
break;
case T_FIXNUM:
dump_leaf_fixnum(context, leaf, out);
break;
case T_FLOAT:
dump_leaf_float(context, leaf, out);
break;
case T_ARRAY:
dump_leaf_array(context, leaf, depth, out);
break;
case T_HASH:
dump_leaf_hash(context, leaf, depth, out);
break;
default:
throw context.runtime.newTypeError("Unexpected type " + leaf.rtype);
}
}
public static Out leaf_to_json(ThreadContext context, OjLibrary oj, Leaf leaf, Options copts) {
Out out = new Out(oj);
out.circ_cnt = 0;
out.opts = copts;
out.hash_cnt = 0;
out.indent = copts.indent;
dump_leaf(context, leaf, 0, out);
return out;
}
public static void leaf_to_file(ThreadContext context, OjLibrary oj, Leaf leaf, String path, Options copts) {
Out out = leaf_to_json(context, oj, leaf, copts);
FileOutputStream f = null;
try {
f = new FileOutputStream(path);
out.write(f);
} catch (IOException e) {
throw context.runtime.newIOErrorFromException(e);
} finally {
if (f != null) {
try { f.close(); } catch (IOException e) {}
}
}
}
// string writer functions
static void key_check(ThreadContext context, StrWriter sw, ByteList key) {
DumpType type = sw.peekTypes();
if (null == key && (ObjectNew == type || ObjectType == type)) {
throw context.runtime.newStandardError("Can not push onto an Object without a key.");
}
}
static void push_type(StrWriter sw, DumpType type) {
sw.types.push(type);
}
static void maybe_comma(StrWriter sw) {
DumpType type = sw.peekTypes();
if (type == ObjectNew) {
sw.types.set(sw.types.size() - 1, ObjectType);
} else if (type == ArrayNew) {
sw.types.set(sw.types.size() - 1, ArrayType);
} else if (type == ObjectType || type == ArrayType) {
// Always have a few characters available in the out.buf.
sw.out.append(',');
}
}
static void push_key(ThreadContext context, StrWriter sw, ByteList key) {
DumpType type = sw.peekTypes();
if (sw.keyWritten) {
throw context.runtime.newStandardError("Can not push more than one key before pushing a non-key.");
}
if (ObjectNew != type && ObjectType != type) {
throw context.runtime.newStandardError("Can only push a key onto an Object.");
}
maybe_comma(sw);
if (!sw.types.empty()) {
fill_indent(sw.out, sw.types.size());
}
dump_cstr(context, key, false, false, sw.out);
sw.out.append(':');
sw.keyWritten = true;
}
static void push_object(ThreadContext context, StrWriter sw, ByteList key) {
dump_key(context, sw, key);
sw.out.append('{');
push_type(sw, ObjectNew);
}
static void push_array(ThreadContext context, StrWriter sw, ByteList key) {
dump_key(context, sw, key);
sw.out.append('[');
push_type(sw, ArrayNew);
}
static void push_value(ThreadContext context, StrWriter sw, IRubyObject val, ByteList key) {
dump_key(context, sw, key);
dump_val(context, val, sw.types.size(), sw.out, null);
}
static void push_json(ThreadContext context, StrWriter sw, ByteList json, ByteList key) {
dump_key(context, sw, key);
dump_raw(json, sw.out);
}
private static void dump_key(ThreadContext context, StrWriter sw, ByteList key) {
if (sw.keyWritten) {
sw.keyWritten = false;
} else {
key_check(context, sw, key);
maybe_comma(sw);
if (!sw.types.empty()) {
fill_indent(sw.out, sw.types.size());
}
if (null != key) {
dump_cstr(context, key, false, false, sw.out);
sw.out.append(':');
}
}
}
static void pop(ThreadContext context, StrWriter sw) {
if (sw.keyWritten) {
sw.keyWritten = false;
throw context.runtime.newStandardError("Can not pop after writing a key but no value.");
}
if (sw.types.empty()) {
throw context.runtime.newStandardError("Can not pop with no open array or object.");
}
DumpType type = sw.types.pop();
fill_indent(sw.out, sw.types.size());
if (type == ObjectNew || type == ObjectType) {
sw.out.append('}');
} else if (type == ArrayNew || type == ArrayType) {
sw.out.append(']');
}
if (sw.types.empty() && 0 <= sw.out.indent) {
sw.out.append('\n');
}
}
static void pop_all(ThreadContext context, StrWriter sw) {
while (!sw.types.empty()) {
pop(context, sw);
}
}
// Unlike C version we assume check has been made that there is an ignore list
// and we are in the correct mode.
static boolean dump_ignore(Out out, IRubyObject value) {
RubyModule clas = value.getMetaClass();
for (RubyModule module: out.opts.ignore) {
if (module == clas) return true;
}
return false;
}
}
|
Fix omit_nil for strict dumping.
|
ext/java/oj/Dump.java
|
Fix omit_nil for strict dumping.
|
|
Java
|
mit
|
584f83250cc5f188ff8b3b4b832bfa9a215c02ae
| 0
|
OpenAMEE/amee.platform.api
|
package com.amee.platform.resource.datacategory;
import com.amee.base.resource.MediaTypeNotSupportedException;
import com.amee.domain.data.DataCategory;
import com.amee.domain.data.DataItem;
import com.amee.domain.data.ItemDefinition;
import com.amee.domain.data.ItemValue;
import com.amee.domain.tag.Tag;
import com.amee.service.data.DataService;
import com.amee.service.locale.LocaleService;
import com.amee.service.metadata.MetadataService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;
@Service
@Scope("prototype")
public class DataCategoryEcospoldRenderer implements DataCategoryRenderer {
private final Namespace XSI_NS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
private final Namespace NS = Namespace.getNamespace("http://www.EcoInvent.org/EcoSpold01");
private final String SCHEMA_LOCATION = "http://www.EcoInvent.org/EcoSpold01 EcoSpold01Dataset.xsd";
private DataCategory dataCategory;
private Element rootElem;
private Element datasetElem;
private Element flowDataElem;
@Autowired
private DataService dataService;
@Autowired
private MetadataService metadataService;
@Autowired
private LocaleService localeService;
public void start() {
rootElem = new Element("ecoSpold", NS);
rootElem.addNamespaceDeclaration(XSI_NS);
rootElem.setAttribute("schemaLocation", SCHEMA_LOCATION, XSI_NS);
}
public void ok() {
// Not implemented for ecospold.
}
public void newDataCategory(DataCategory dataCategory) {
this.dataCategory = dataCategory;
// Only display ecoinvent data in ecospold format.
if (dataCategory.getEcoinventMetaInformation().isEmpty()) {
throw new MediaTypeNotSupportedException();
}
}
public void addBasic() {
try {
SAXBuilder builder = new SAXBuilder();
// Add the dataset element
Document doc = builder.build(new StringReader(dataCategory.getEcoinventDatasetAttributes()));
if (rootElem != null) {
rootElem.addContent(doc.getRootElement().detach());
datasetElem = rootElem.getChild("dataset", NS);
}
// Add the metainformation element
doc = builder.build(new StringReader(dataCategory.getEcoinventMetaInformation()));
if (datasetElem != null) {
datasetElem.addContent(doc.getRootElement().detach());
}
} catch (JDOMException e) {
throw new RuntimeException("Caught JDOMException: " + e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException("Caught IOException: " + e.getMessage(), e);
}
// Add the flowData (data items)
flowDataElem = new Element("flowData", NS);
if (datasetElem != null) {
datasetElem.addContent(flowDataElem);
}
// Pre-cache metadata and locales for the Data Items.
metadataService.loadMetadatasForItemValueDefinitions(dataCategory.getItemDefinition().getItemValueDefinitions());
localeService.loadLocaleNamesForItemValueDefinitions(dataCategory.getItemDefinition().getItemValueDefinitions());
// For each data item, add each item value definition name and data item value
for (DataItem dataItem : dataService.getDataItems(dataCategory)) {
Element exchangeElem = new Element("exchange", NS);
for (ItemValue itemValue : dataItem.getItemValues()) {
// Convert group to category and subGroup to subCategory
String name = itemValue.getName();
if (name.equals("group")) {
name = "category";
} else if (name.equals("subGroup")) {
name = "subCategory";
}
// The outputGroup and inputGroup values are displayed as child elements not attributes
// Only display the element if it is non-empty.
if (name.equals("outputGroup") || name.equals("inputGroup")) {
if (!itemValue.getValue().isEmpty()) {
exchangeElem.addContent(new Element(name, NS).setText(itemValue.getValue()));
}
} else {
exchangeElem.setAttribute(name, itemValue.getValue());
}
}
flowDataElem.addContent(exchangeElem);
}
// Clear caches.
metadataService.clearMetadatas();
localeService.clearLocaleNames();
}
public void addPath() {
// Not implemented for ecospold.
}
public void addParent() {
// Not implemented for ecospold.
}
public void addAudit() {
// Not implemented for ecospold.
}
public void addAuthority() {
// Not implemented for ecospold.
}
public void addWikiDoc() {
// Not implemented for ecospold.
}
public void addProvenance() {
// Not implemented for ecospold.
}
public void addItemDefinition(ItemDefinition id) {
// Not implemented for ecospold.
}
public void startTags() {
// Not implemented for ecospold.
}
public void newTag(Tag tag) {
// Not implemented for ecospold.
}
public String getMediaType() {
return "application/x.ecospold+xml";
}
public Document getObject() {
return new Document(rootElem);
}
}
|
src/main/java/com/amee/platform/resource/datacategory/DataCategoryEcospoldRenderer.java
|
package com.amee.platform.resource.datacategory;
import com.amee.base.resource.MediaTypeNotSupportedException;
import com.amee.domain.data.DataCategory;
import com.amee.domain.data.DataItem;
import com.amee.domain.data.ItemDefinition;
import com.amee.domain.data.ItemValue;
import com.amee.domain.tag.Tag;
import com.amee.service.data.DataService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;
@Service
@Scope("prototype")
public class DataCategoryEcospoldRenderer implements DataCategoryRenderer {
private final Namespace XSI_NS = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
private final Namespace NS = Namespace.getNamespace("http://www.EcoInvent.org/EcoSpold01");
private final String SCHEMA_LOCATION = "http://www.EcoInvent.org/EcoSpold01 EcoSpold01Dataset.xsd";
private DataCategory dataCategory;
private Element rootElem;
private Element datasetElem;
private Element flowDataElem;
@Autowired
private DataService dataService;
public void start() {
rootElem = new Element("ecoSpold", NS);
rootElem.addNamespaceDeclaration(XSI_NS);
rootElem.setAttribute("schemaLocation", SCHEMA_LOCATION, XSI_NS);
}
public void ok() {
// Not implemented for ecospold.
}
public void newDataCategory(DataCategory dataCategory) {
this.dataCategory = dataCategory;
// Only display ecoinvent data in ecospold format.
if (dataCategory.getEcoinventMetaInformation().isEmpty()) {
throw new MediaTypeNotSupportedException();
}
}
public void addBasic() {
try {
SAXBuilder builder = new SAXBuilder();
// Add the dataset element
Document doc = builder.build(new StringReader(dataCategory.getEcoinventDatasetAttributes()));
if (rootElem != null) {
rootElem.addContent(doc.getRootElement().detach());
datasetElem = rootElem.getChild("dataset", NS);
}
// Add the metainformation element
doc = builder.build(new StringReader(dataCategory.getEcoinventMetaInformation()));
if (datasetElem != null) {
datasetElem.addContent(doc.getRootElement().detach());
}
} catch (JDOMException e) {
throw new RuntimeException("Caught JDOMException: " + e.getMessage(), e);
} catch (IOException e) {
throw new RuntimeException("Caught IOException: " + e.getMessage(), e);
}
// Add the flowData (data items)
flowDataElem = new Element("flowData", NS);
if (datasetElem != null) {
datasetElem.addContent(flowDataElem);
}
// For each data item, add each item value definition name and data item value
for (DataItem dataItem : dataService.getDataItems(dataCategory)) {
Element exchangeElem = new Element("exchange", NS);
for (ItemValue itemValue : dataItem.getItemValues()) {
// Convert group to category and subGroup to subCategory
String name = itemValue.getName();
if (name.equals("group")) {
name = "category";
} else if (name.equals("subGroup")) {
name = "subCategory";
}
// The outputGroup and inputGroup values are displayed as child elements not attributes
// Only display the element if it is non-empty.
if (name.equals("outputGroup") || name.equals("inputGroup")) {
if (!itemValue.getValue().isEmpty()) {
exchangeElem.addContent(new Element(name, NS).setText(itemValue.getValue()));
}
} else {
exchangeElem.setAttribute(name, itemValue.getValue());
}
}
flowDataElem.addContent(exchangeElem);
}
}
public void addPath() {
// Not implemented for ecospold.
}
public void addParent() {
// Not implemented for ecospold.
}
public void addAudit() {
// Not implemented for ecospold.
}
public void addAuthority() {
// Not implemented for ecospold.
}
public void addWikiDoc() {
// Not implemented for ecospold.
}
public void addProvenance() {
// Not implemented for ecospold.
}
public void addItemDefinition(ItemDefinition id) {
// Not implemented for ecospold.
}
public void startTags() {
// Not implemented for ecospold.
}
public void newTag(Tag tag) {
// Not implemented for ecospold.
}
public String getMediaType() {
return "application/x.ecospold+xml";
}
public Document getObject() {
return new Document(rootElem);
}
}
|
Add pre-loading of caches to ecospold renderer. PL-6378.
|
src/main/java/com/amee/platform/resource/datacategory/DataCategoryEcospoldRenderer.java
|
Add pre-loading of caches to ecospold renderer. PL-6378.
|
|
Java
|
mit
|
a5d674ba21268bd3107dd3b07379ec8da0892531
| 0
|
greghaskins/spectrum
|
package com.greghaskins.spectrum.internal.configuration;
import com.greghaskins.spectrum.Configure;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
/**
* Represents the state of tagging for Spectrum - what it presently means.
*/
public class TaggingFilterCriteria {
private Set<String> included = new HashSet<>();
private Set<String> excluded = new HashSet<>();
private static final String TAGS_SEPARATOR = ",";
public TaggingFilterCriteria() {
include(fromSystemProperty(Configure.INCLUDE_TAGS_PROPERTY));
exclude(fromSystemProperty(Configure.EXCLUDE_TAGS_PROPERTY));
}
public void include(String... tags) {
include(Arrays.stream(tags));
}
private void include(Stream<String> tags) {
this.included.clear();
tags.forEach(this.included::add);
}
public void exclude(String... tags) {
exclude(Arrays.stream(tags));
}
private void exclude(Stream<String> tags) {
this.excluded.clear();
tags.forEach(this.excluded::add);
}
@Override
public TaggingFilterCriteria clone() {
TaggingFilterCriteria copy = new TaggingFilterCriteria();
copy.include(this.included.stream());
copy.exclude(this.excluded.stream());
return copy;
}
boolean isAllowedToRun(Collection<String> tags) {
return !isExcluded(tags) && compliesWithRequired(tags);
}
private boolean isExcluded(Collection<String> tags) {
return tags.stream().anyMatch(this.excluded::contains);
}
private boolean compliesWithRequired(Collection<String> tags) {
return this.included.isEmpty()
|| tags.stream().anyMatch(this.included::contains);
}
private String[] fromSystemProperty(final String property) {
return Optional.ofNullable(System.getProperty(property))
.map(string -> string.split(TaggingFilterCriteria.TAGS_SEPARATOR))
.filter(TaggingFilterCriteria::notArrayWithEmptyValue)
.orElse(new String[0]);
}
private static boolean notArrayWithEmptyValue(final String[] array) {
return !(array.length == 1 && array[0].isEmpty());
}
}
|
src/main/java/com/greghaskins/spectrum/internal/configuration/TaggingFilterCriteria.java
|
package com.greghaskins.spectrum.internal.configuration;
import com.greghaskins.spectrum.Configure;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
/**
* Represents the state of tagging for Spectrum - what it presently means.
*/
public class TaggingFilterCriteria {
private Set<String> included = new HashSet<>();
private Set<String> excluded = new HashSet<>();
private static final String TAGS_SEPARATOR = ",";
public TaggingFilterCriteria() {
include(fromSystemProperty(Configure.INCLUDE_TAGS_PROPERTY));
exclude(fromSystemProperty(Configure.EXCLUDE_TAGS_PROPERTY));
}
public void include(String... tags) {
include(Arrays.stream(tags));
}
private void include(Stream<String> tags) {
this.included.clear();
tags.forEach(this.included::add);
}
public void exclude(String... tags) {
exclude(Arrays.stream(tags));
}
private void exclude(Stream<String> tags) {
this.excluded.clear();
tags.forEach(this.excluded::add);
}
@Override
public TaggingFilterCriteria clone() {
TaggingFilterCriteria copy = new TaggingFilterCriteria();
copy.include(this.included.stream());
copy.exclude(this.excluded.stream());
return copy;
}
public boolean isAllowedToRun(Collection<String> tags) {
return !isExcluded(tags) && compliesWithRequired(tags);
}
private boolean isExcluded(Collection<String> tags) {
return tags.stream()
.filter(this.excluded::contains)
.findFirst()
.isPresent();
}
private boolean compliesWithRequired(Collection<String> tags) {
return this.included.isEmpty()
|| tags.stream()
.filter(this.included::contains)
.findFirst()
.isPresent();
}
private String[] fromSystemProperty(final String property) {
return Optional.ofNullable(System.getProperty(property))
.map(string -> string.split(TaggingFilterCriteria.TAGS_SEPARATOR))
.filter(TaggingFilterCriteria::notArrayWithEmptyValue)
.orElse(new String[0]);
}
private static boolean notArrayWithEmptyValue(final String[] array) {
return !(array.length == 1 && array[0].isEmpty());
}
}
|
Minor cleanup in TaggingFIlterCriteria
|
src/main/java/com/greghaskins/spectrum/internal/configuration/TaggingFilterCriteria.java
|
Minor cleanup in TaggingFIlterCriteria
|
|
Java
|
mit
|
fadda548ec913bedf8eb961f3afbfa55e79fe396
| 0
|
Jasonette/JASONETTE-Android
|
package com.jasonette.seed.Action;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.jasonette.seed.Helper.JasonHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Route;
import okio.BufferedSink;
public class JasonOauthAction {
public void auth(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if(options.has("version") && options.getString("version").equals("1")) {
//
//OAuth 1
//
JSONObject request_options = options.getJSONObject("request");
JSONObject authorize_options = options.getJSONObject("authorize");
String client_id = request_options.getString("client_id");
String client_secret = request_options.getString("client_secret");
if(!request_options.has("scheme") || request_options.getString("scheme").length() == 0
|| !request_options.has("host") || request_options.getString("host").length() == 0
|| !request_options.has("path") || request_options.getString("path").length() == 0
|| !authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
JSONObject request_options_data = request_options.getJSONObject("data");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(request_options.getString("scheme"))
.encodedAuthority(request_options.getString("host"))
.encodedPath(request_options.getString("path"));
final String requestUri = uriBuilder.build().toString();
final Uri.Builder authorizeUriBuilder = new Uri.Builder();
authorizeUriBuilder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
String callback_uri = request_options_data.getString("oauth_callback");
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() {
return requestUri;
}
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return authorizeUriBuilder
.appendQueryParameter("oauth_token", requestToken.getToken())
.build().toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(callback_uri)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String client_id = params[0];
OAuth1RequestToken request_token = oauthService.getRequestToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id + "_request_token_secret", request_token.getTokenSecret()).apply();
String auth_url = oauthService.getAuthorizationUrl(request_token);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(auth_url));
context.startActivity(intent);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(client_id);
}
} else {
//
//OAuth 2
//
JSONObject authorize_options = options.getJSONObject("authorize");
JSONObject authorize_options_data = new JSONObject();
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
}
if(authorize_options_data.has("grant_type") && authorize_options_data.getString("grant_type").equals("password")) {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
|| !authorize_options_data.has("username") || authorize_options_data.getString("username").length() == 0
|| !authorize_options_data.has("password") || authorize_options_data.getString("password").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
String username = authorize_options_data.getString("username");
String password = authorize_options_data.getString("password");
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return uri.toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
if(authorize_options_data.has("state") && authorize_options_data.getString("state").length() > 0) {
serviceBuilder.state(authorize_options_data.getString("state"));
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
Map<String, String> additionalParams = new HashMap<>();
Iterator paramKeys = authorize_options_data.keys();
while(paramKeys.hasNext()) {
String key = (String)paramKeys.next();
if(key != "redirect_uri" || key != "response_type" || key != "scope" || key != "state") {
String value = authorize_options_data.getString(key);
additionalParams.put(key, value);
}
}
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String username = params[0];
String password = params[1];
String client_id = params[2];
String access_token = oauthService.getAccessTokenPasswordGrant(username, password).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} catch(JSONException e) {
handleError(e, action, event, context);
}
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(username, password, client_id);
}
} else {
//
//Assuming code auth
//
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
if(authorize_options.length() == 0) {
JasonHelper.next("error", action, data, event, context);
} else {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
String redirect_uri = "";
//Secret can be missing in implicit authentication
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(authorize_options_data.has("redirect_uri")) {
redirect_uri = authorize_options_data.getString("redirect_uri");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return uri.toString();
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
if(authorize_options_data.has("state") && authorize_options_data.getString("state").length() > 0) {
serviceBuilder.state(authorize_options_data.getString("state"));
}
serviceBuilder.callback(redirect_uri);
OAuth20Service oauthService = serviceBuilder.build(oauthApi);
Map<String, String> additionalParams = new HashMap<>();
Iterator paramKeys = authorize_options_data.keys();
while(paramKeys.hasNext()) {
String key = (String)paramKeys.next();
if(key != "redirect_uri" || key != "response_type" || key != "scope" || key != "state") {
String value = authorize_options_data.getString(key);
additionalParams.put(key, value);
}
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(oauthService.getAuthorizationUrl(additionalParams)));
context.startActivity(intent);
}
}
} else {
JSONObject error = new JSONObject();
error.put("data", "Authorize data missing");
JasonHelper.next("error", action, error, event, context);
}
}
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void access_token(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getJSONObject("access").getString("client_id");
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
if(access_token != null) {
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject error = new JSONObject();
error.put("data", "access token not found");
JasonHelper.next("error", action, error, event, context);
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void oauth_callback(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if (options.has("version") && options.getString("version").equals("1")) {
//OAuth 1
if(action.has("uri")) {
Uri uri = Uri.parse(action.getString("uri"));
String oauth_token = uri.getQueryParameter("oauth_token");
String oauth_verifier = uri.getQueryParameter("oauth_verifier");
JSONObject access_options = options.getJSONObject("access");
if(
oauth_token.length() > 0 && oauth_verifier.length() > 0
&& access_options.has("scheme") && access_options.getString("scheme").length() > 0
&& access_options.has("host") && access_options.getString("host").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("client_id") && access_options.getString("client_id").length() > 0
&& access_options.has("client_secret") && access_options.getString("client_secret").length() > 0
) {
String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(access_options.getString("scheme"))
.encodedAuthority(access_options.getString("host"))
.encodedPath(access_options.getString("path"));
final String accessUri = uriBuilder.build().toString();
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() {
return accessUri.toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String string_oauth_token = params[0];
String oauth_verifier = params[1];
String client_id = params[2];
String oauth_token_secret = preferences.getString(client_id + "_request_token_secret", null);
OAuth1RequestToken oauthToken = new OAuth1RequestToken(string_oauth_token, oauth_token_secret);
OAuth1AccessToken access_token = oauthService.getAccessToken(oauthToken, oauth_verifier);
preferences.edit().putString(client_id, access_token.getToken()).apply();
preferences.edit().putString(client_id + "_access_token_secret", access_token.getTokenSecret()).apply();
JSONObject result = new JSONObject();
result.put("token", access_token.getToken());
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(oauth_token, oauth_verifier, client_id);
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
// OAuth 2
Uri uri = Uri.parse(action.getString("uri"));
String access_token = uri.getQueryParameter("access_token"); // get access token from url here
JSONObject authorize_options = options.getJSONObject("authorize");
if (access_token != null && access_token.length() > 0) {
String client_id = authorize_options.getString("client_id");
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject access_options = options.getJSONObject("access");
final String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
String redirect_uri = "";
if(access_options.has("redirect_uri")) {
redirect_uri = access_options.getString("redirect_uri");
}
final String code = uri.getQueryParameter("code");
if (access_options.length() == 0
|| !access_options.has("scheme") || access_options.getString("scheme").length() == 0
|| !access_options.has("host") || access_options.getString("host").length() == 0
|| !access_options.has("path") || access_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
final Uri.Builder builder = new Uri.Builder();
builder.scheme(access_options.getString("scheme"))
.authority(access_options.getString("host"))
.appendEncodedPath(access_options.getString("path"));
if(redirect_uri != "") {
builder.appendQueryParameter("redirect_uri", redirect_uri);
}
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return builder.build().toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
serviceBuilder.apiSecret(client_secret);
if(redirect_uri != "") {
serviceBuilder.callback(redirect_uri);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
String access_token = oauthService.getAccessToken(code).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
} catch(JSONException e) {
handleError(e, action, event, context);
}
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
}
}
}
catch(JSONException e) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
public void reset(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
if(options.has("version") && options.getString("version").equals("1")) {
//TODO
} else {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().remove(client_id).apply();
JasonHelper.next("success", action, data, event, context);
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void request(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
String client_secret = "";
if(options.has("client_secret") && options.getString("client_secret").length() > 0) {
client_secret = options.getString("client_secret");
}
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
String path = options.getString("path");
String scheme = options.getString("scheme");
String host = options.getString("host");
String method;
if(options.has("method")) {
method = options.getString("method");
} else {
method = "GET";
}
if(access_token != null && access_token.length() > 0) {
JSONObject params = new JSONObject();
if(options.has("data")) {
params = options.getJSONObject("data");
}
JSONObject headers = new JSONObject();
if(options.has("headers")) {
headers = options.getJSONObject("headers");
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.encodedAuthority(host);
uriBuilder.path(path);
Uri uri = uriBuilder.build();
String url = uri.toString();
final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);
Iterator paramKeys = params.keys();
while(paramKeys.hasNext()) {
String key = (String)paramKeys.next();
String value = params.getString(key);
request.addParameter(key, value);
}
Iterator headerKeys = headers.keys();
while(headerKeys.hasNext()) {
String key = (String)headerKeys.next();
String value = headers.getString(key);
request.addHeader(key, value);
}
if(options.has("version") && options.getString("version").equals("1")) {
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() { return null; }
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth10aService oauthService = serviceBuilder.build(oauthApi);
String access_token_secret = sharedPreferences.getString(client_id + "_access_token_secret", null);
oauthService.signRequest(new OAuth1AccessToken(access_token, access_token_secret), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
} else {
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
oauthService.signRequest(new OAuth2AccessToken(access_token), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
} else {
JasonHelper.next("error", action, data, event, context);
}
//change exception
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
private void handleError(Exception e, JSONObject action, JSONObject event, Context context) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
|
app/src/main/java/com/jasonette/seed/Action/JasonOauthAction.java
|
package com.jasonette.seed.Action;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.jasonette.seed.Helper.JasonHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
public class JasonOauthAction {
public void auth(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if(options.has("version") && options.getString("version").equals("1")) {
//
//OAuth 1
//
JSONObject request_options = options.getJSONObject("request");
JSONObject authorize_options = options.getJSONObject("authorize");
String client_id = request_options.getString("client_id");
String client_secret = request_options.getString("client_secret");
if(!request_options.has("scheme") || request_options.getString("scheme").length() == 0
|| !request_options.has("host") || request_options.getString("host").length() == 0
|| !request_options.has("path") || request_options.getString("path").length() == 0
|| !authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
JSONObject request_options_data = request_options.getJSONObject("data");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(request_options.getString("scheme"))
.encodedAuthority(request_options.getString("host"))
.encodedPath(request_options.getString("path"));
final String requestUri = uriBuilder.build().toString();
final Uri.Builder authorizeUriBuilder = new Uri.Builder();
authorizeUriBuilder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
String callback_uri = request_options_data.getString("oauth_callback");
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() {
return requestUri;
}
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return authorizeUriBuilder
.appendQueryParameter("oauth_token", requestToken.getToken())
.build().toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(callback_uri)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String client_id = params[0];
OAuth1RequestToken request_token = oauthService.getRequestToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id + "_request_token_secret", request_token.getTokenSecret()).apply();
String auth_url = oauthService.getAuthorizationUrl(request_token);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(auth_url));
context.startActivity(intent);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(client_id);
}
} else {
//
//OAuth 2
//
JSONObject authorize_options = options.getJSONObject("authorize");
JSONObject authorize_options_data = new JSONObject();
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
}
if(authorize_options_data.has("grant_type") && authorize_options_data.getString("grant_type").equals("password")) {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
|| !authorize_options_data.has("username") || authorize_options_data.getString("username").length() == 0
|| !authorize_options_data.has("password") || authorize_options_data.getString("password").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
String username = authorize_options_data.getString("username");
String password = authorize_options_data.getString("password");
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return uri.toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
String username = params[0];
String password = params[1];
String client_id = params[2];
String access_token = oauthService.getAccessTokenPasswordGrant(username, password).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} catch(JSONException e) {
handleError(e, action, event, context);
}
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(username, password, client_id);
}
} else {
if(authorize_options.has("data")) {
authorize_options_data = authorize_options.getJSONObject("data");
} else {
JSONObject error = new JSONObject();
error.put("data", "Authorize data missing");
JasonHelper.next("error", action, error, event, context);
}
//
//Assuming code auth
//
if(authorize_options.length() == 0) {
JasonHelper.next("error", action, data, event, context);
} else {
String client_id = authorize_options.getString("client_id");
String client_secret = "";
String redirect_uri = "";
//Secret can be missing in implicit authentication
if(authorize_options.has("client_secret")) {
client_secret = authorize_options.getString("client_secret");
}
if(authorize_options_data.has("redirect_uri")) {
redirect_uri = authorize_options_data.getString("redirect_uri");
}
if(!authorize_options.has("scheme") || authorize_options.getString("scheme").length() == 0
|| !authorize_options.has("host") || authorize_options.getString("host").length() == 0
|| !authorize_options.has("path") || authorize_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
Uri.Builder builder = new Uri.Builder();
builder.scheme(authorize_options.getString("scheme"))
.encodedAuthority(authorize_options.getString("host"))
.encodedPath(authorize_options.getString("path"));
final Uri uri = builder.build();
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return uri.toString();
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
if(authorize_options_data.has("scope") && authorize_options_data.getString("scope").length() > 0) {
serviceBuilder.scope(authorize_options_data.getString("scope"));
}
serviceBuilder.callback(redirect_uri);
OAuth20Service oauthService = serviceBuilder.build(oauthApi);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(oauthService.getAuthorizationUrl()));
context.startActivity(intent);
}
}
}
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void access_token(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getJSONObject("access").getString("client_id");
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
if(access_token != null) {
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject error = new JSONObject();
error.put("data", "access token not found");
JasonHelper.next("error", action, error, event, context);
}
} catch(JSONException e) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
public void oauth_callback(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
if (options.has("version") && options.getString("version").equals("1")) {
//OAuth 1
if(action.has("uri")) {
Uri uri = Uri.parse(action.getString("uri"));
String oauth_token = uri.getQueryParameter("oauth_token");
String oauth_verifier = uri.getQueryParameter("oauth_verifier");
JSONObject access_options = options.getJSONObject("access");
if(
oauth_token.length() > 0 && oauth_verifier.length() > 0
&& access_options.has("scheme") && access_options.getString("scheme").length() > 0
&& access_options.has("host") && access_options.getString("host").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("path") && access_options.getString("path").length() > 0
&& access_options.has("client_id") && access_options.getString("client_id").length() > 0
&& access_options.has("client_secret") && access_options.getString("client_secret").length() > 0
) {
String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(access_options.getString("scheme"))
.encodedAuthority(access_options.getString("host"))
.encodedPath(access_options.getString("path"));
final String accessUri = uriBuilder.build().toString();
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() {
return accessUri.toString();
}
};
final OAuth10aService oauthService = new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.build(oauthApi);
new AsyncTask<String, Void, Void>() {
@Override
protected Void doInBackground(String... params) {
try {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String string_oauth_token = params[0];
String oauth_verifier = params[1];
String client_id = params[2];
String oauth_token_secret = preferences.getString(client_id + "_request_token_secret", null);
OAuth1RequestToken oauthToken = new OAuth1RequestToken(string_oauth_token, oauth_token_secret);
OAuth1AccessToken access_token = oauthService.getAccessToken(oauthToken, oauth_verifier);
preferences.edit().putString(client_id, access_token.getToken()).apply();
preferences.edit().putString(client_id + "_access_token_secret", access_token.getTokenSecret()).apply();
JSONObject result = new JSONObject();
result.put("token", access_token.getToken());
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute(oauth_token, oauth_verifier, client_id);
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
JasonHelper.next("error", action, data, event, context);
}
} else {
// OAuth 2
Uri uri = Uri.parse(action.getString("uri"));
String access_token = uri.getQueryParameter("access_token"); // get access token from url here
JSONObject authorize_options = options.getJSONObject("authorize");
if (access_token != null && access_token.length() > 0) {
String client_id = authorize_options.getString("client_id");
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
result.put("token", access_token);
JasonHelper.next("success", action, result, event, context);
} else {
JSONObject access_options = options.getJSONObject("access");
final String client_id = access_options.getString("client_id");
String client_secret = access_options.getString("client_secret");
String redirect_uri = "";
if(access_options.has("redirect_uri")) {
redirect_uri = access_options.getString("redirect_uri");
}
final String code = uri.getQueryParameter("code");
if (access_options.length() == 0
|| !access_options.has("scheme") || access_options.getString("scheme").length() == 0
|| !access_options.has("host") || access_options.getString("host").length() == 0
|| !access_options.has("path") || access_options.getString("path").length() == 0
) {
JasonHelper.next("error", action, data, event, context);
} else {
final Uri.Builder builder = new Uri.Builder();
builder.scheme(access_options.getString("scheme"))
.authority(access_options.getString("host"))
.appendEncodedPath(access_options.getString("path"));
if(redirect_uri != "") {
builder.appendQueryParameter("redirect_uri", redirect_uri);
}
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return builder.build().toString();
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
serviceBuilder.apiSecret(client_secret);
if(redirect_uri != "") {
serviceBuilder.callback(redirect_uri);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
String access_token = oauthService.getAccessToken(code).getAccessToken();
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().putString(client_id, access_token).apply();
JSONObject result = new JSONObject();
try {
result.put("token", access_token);
} catch(JSONException e) {
handleError(e, action, event, context);
}
JasonHelper.next("success", action, result, event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
}
}
}
catch(JSONException e) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
public void reset(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
final JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
if(options.has("version") && options.getString("version").equals("1")) {
//TODO
} else {
SharedPreferences preferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
preferences.edit().remove(client_id).apply();
JasonHelper.next("success", action, data, event, context);
}
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
public void request(final JSONObject action, final JSONObject data, final JSONObject event, final Context context) {
try {
JSONObject options = action.getJSONObject("options");
String client_id = options.getString("client_id");
String client_secret = "";
if(options.has("client_secret") && options.getString("client_secret").length() > 0) {
client_secret = options.getString("client_secret");
}
SharedPreferences sharedPreferences = context.getSharedPreferences("oauth", Context.MODE_PRIVATE);
String access_token = sharedPreferences.getString(client_id, null);
String path = options.getString("path");
String scheme = options.getString("scheme");
String host = options.getString("host");
String method;
if(options.has("method")) {
method = options.getString("method");
} else {
method = "GET";
}
if(access_token != null && access_token.length() > 0) {
JSONObject params = new JSONObject();
if(options.has("data")) {
params = options.getJSONObject("data");
}
JSONObject headers = new JSONObject();
if(options.has("headers")) {
headers = options.getJSONObject("headers");
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.encodedAuthority(host);
uriBuilder.path(path);
Uri uri = uriBuilder.build();
String url = uri.toString();
final OAuthRequest request = new OAuthRequest(Verb.valueOf(method), url);
Iterator paramKeys = params.keys();
while(paramKeys.hasNext()) {
String key = (String)paramKeys.next();
String value = params.getString(key);
request.addParameter(key, value);
}
Iterator headerKeys = headers.keys();
while(headerKeys.hasNext()) {
String key = (String)headerKeys.next();
String value = headers.getString(key);
request.addHeader(key, value);
}
if(options.has("version") && options.getString("version").equals("1")) {
DefaultApi10a oauthApi = new DefaultApi10a() {
@Override
public String getRequestTokenEndpoint() { return null; }
@Override
public String getAccessTokenEndpoint() { return null; }
@Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) { return null; }
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth10aService oauthService = serviceBuilder.build(oauthApi);
String access_token_secret = sharedPreferences.getString(client_id + "_access_token_secret", null);
oauthService.signRequest(new OAuth1AccessToken(access_token, access_token_secret), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
} else {
DefaultApi20 oauthApi = new DefaultApi20() {
@Override
public String getAccessTokenEndpoint() {
return null;
}
@Override
protected String getAuthorizationBaseUrl() {
return null;
}
};
ServiceBuilder serviceBuilder = new ServiceBuilder();
serviceBuilder.apiKey(client_id);
if(client_secret.length() > 0) {
serviceBuilder.apiSecret(client_secret);
}
final OAuth20Service oauthService = serviceBuilder.build(oauthApi);
oauthService.signRequest(new OAuth2AccessToken(access_token), request);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
Response response = oauthService.execute(request);
JasonHelper.next("success", action, response.getBody(), event, context);
} catch(Exception e) {
handleError(e, action, event, context);
}
return null;
}
}.execute();
}
} else {
JasonHelper.next("error", action, data, event, context);
}
//change exception
} catch(JSONException e) {
handleError(e, action, event, context);
}
}
private void handleError(Exception e, JSONObject action, JSONObject event, Context context) {
try {
JSONObject error = new JSONObject();
error.put("data", e.toString());
JasonHelper.next("error", action, error, event, context);
} catch(JSONException error) {
Log.d("Error", error.toString());
}
}
}
|
Fixing OAuth2 auth phase
|
app/src/main/java/com/jasonette/seed/Action/JasonOauthAction.java
|
Fixing OAuth2 auth phase
|
|
Java
|
mit
|
5539744098eb4339663adec5a9dd3f4d0bfa06d2
| 0
|
lokra-platform/seaweedfs-client
|
/*
* Copyright (c) 2016 Lokra Studio
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.lokra.seaweedfs.test;
import org.lokra.seaweedfs.FileSystemManager;
import java.io.IOException;
/**
* @author Chiho Sin
*/
public class ConnectionManagerUtil {
public static FileSystemManager connectionManager;
static {
connectionManager = new FileSystemManager();
connectionManager.setHost("127.0.0.1");
connectionManager.setPort(9333);
}
public static void startup() throws IOException {
connectionManager.startup();
}
public static void shutdown() {
connectionManager.shutdown();
}
}
|
src/test/java/org/lokra/seaweedfs/test/ConnectionManagerUtil.java
|
/*
* Copyright (c) 2016 Lokra Studio
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.lokra.seaweedfs.test;
import org.lokra.seaweedfs.FileSystemManager;
import java.io.IOException;
/**
* @author Chiho Sin
*/
public class ConnectionManagerUtil {
public static FileSystemManager connectionManager;
static {
connectionManager = new FileSystemManager();
connectionManager.setHost("0.0.0.0");
connectionManager.setPort(9333);
}
public static void startup() throws IOException {
connectionManager.startup();
}
public static void shutdown() {
connectionManager.shutdown();
}
}
|
Chore travis ci.
|
src/test/java/org/lokra/seaweedfs/test/ConnectionManagerUtil.java
|
Chore travis ci.
|
|
Java
|
mit
|
92e59f7e008e540a86eac9b23ae9ecaf7687c175
| 0
|
EinsamHauer/disthene-reader,EinsamHauer/disthene-reader,EinsamHauer/disthene-reader
|
package net.iponweb.disthene.reader.graphite.utils;
import com.google.common.math.DoubleMath;
import java.math.BigDecimal;
/**
* @author Andrei Ivanov
*/
public class GraphiteUtils {
private static double THRESHOLD = 0.00000000001;
public static double formatUnitValue(double value, double step, UnitSystem unitSystem) {
value = magicRound(value);
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) {
double v2 = value / unit.getValue();
if (v2 - Math.floor(v2) < THRESHOLD && value > 1) {
v2 = Math.floor(v2);
}
return v2;
}
}
if (value - Math.floor(value) < THRESHOLD && value > 1) {
return Math.floor(value);
}
return value;
}
public static double formatUnitValue(double value, UnitSystem unitSystem) {
/*
// Firstly, round the value a bit
if (value > 0 && value < 1.0) {
BigDecimal bd = BigDecimal.valueOf(value);
value = bd.setScale(bd.scale() - 1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
*/
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue()) {
double v2 = value / unit.getValue();
if (v2 - Math.floor(v2) < THRESHOLD && value > 1) {
v2 = Math.floor(v2);
}
return v2;
}
}
if (value - Math.floor(value) < THRESHOLD && value > 1) {
return Math.floor(value);
}
return value;
}
public static String formatUnitPrefix(double value, double step, UnitSystem unitSystem) {
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) {
return unit.getPrefix();
}
}
return "";
}
public static String formatUnitPrefix(double value, UnitSystem unitSystem) {
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue()) {
return unit.getPrefix();
}
}
return "";
}
public static String formatValue(double value, UnitSystem unitSystem) {
return String.format("%s%s", formatDoubleSpecialSmart(formatUnitValue(value, unitSystem)), formatUnitPrefix(value, unitSystem));
}
public static String formatDoubleSpecialPlain(Double value) {
BigDecimal bigDecimal = BigDecimal.valueOf(value);
// do not do this for math integers
if (!DoubleMath.isMathematicalInteger(value)) {
// precision is just like in graphite (scale check redundant but let it be)
if (bigDecimal.precision() > 12 && bigDecimal.scale() > 0) {
int roundTo = bigDecimal.scale() - bigDecimal.precision() + 12 > 0 ? bigDecimal.scale() - bigDecimal.precision() + 12 : 0;
bigDecimal = bigDecimal.setScale(roundTo, BigDecimal.ROUND_HALF_UP);
}
}
return bigDecimal.stripTrailingZeros().toPlainString();
}
public static String formatDoubleSpecialSmart(Double value) {
BigDecimal bigDecimal = BigDecimal.valueOf(value);
// do not do this for math integers
if (!DoubleMath.isMathematicalInteger(value)) {
// precision is just like in graphite (scale check redundant but let it be)
if (bigDecimal.precision() > 12 && bigDecimal.scale() > 0) {
int roundTo = bigDecimal.scale() - bigDecimal.precision() + 12 > 0 ? bigDecimal.scale() - bigDecimal.precision() + 12 : 0;
bigDecimal = bigDecimal.setScale(roundTo, BigDecimal.ROUND_HALF_UP);
}
}
return (bigDecimal.precision() + bigDecimal.scale() > 12) ?
bigDecimal.stripTrailingZeros().toEngineeringString() : bigDecimal.stripTrailingZeros().toPlainString();
}
// todo: this "magic rounding" is a complete atrocity - fix it!
public static double magicRound(double value) {
if (value > -1.0 && value < 1.0) {
return new BigDecimal(value).setScale(2 - (int) Math.log10(Math.abs(value)), BigDecimal.ROUND_HALF_UP).doubleValue();
} else {
return value;
}
}
private final static BigDecimal ONE = BigDecimal.valueOf(1.0);
private final static BigDecimal MINUS_ONE = BigDecimal.valueOf(-1.0);
public static BigDecimal magicRound(BigDecimal value) {
if (value.compareTo(MINUS_ONE) > 0 && value.compareTo(ONE) < 0) {
return value.setScale(2 - (int) Math.log10(Math.abs(value.doubleValue())), BigDecimal.ROUND_HALF_UP);
} else {
return value;
}
}
}
|
src/main/java/net/iponweb/disthene/reader/graphite/utils/GraphiteUtils.java
|
package net.iponweb.disthene.reader.graphite.utils;
import java.math.BigDecimal;
/**
* @author Andrei Ivanov
*/
public class GraphiteUtils {
private static double THRESHOLD = 0.00000000001;
public static double formatUnitValue(double value, double step, UnitSystem unitSystem) {
value = magicRound(value);
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) {
double v2 = value / unit.getValue();
if (v2 - Math.floor(v2) < THRESHOLD && value > 1) {
v2 = Math.floor(v2);
}
return v2;
}
}
if (value - Math.floor(value) < THRESHOLD && value > 1) {
return Math.floor(value);
}
return value;
}
public static double formatUnitValue(double value, UnitSystem unitSystem) {
/*
// Firstly, round the value a bit
if (value > 0 && value < 1.0) {
BigDecimal bd = BigDecimal.valueOf(value);
value = bd.setScale(bd.scale() - 1, BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
*/
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue()) {
double v2 = value / unit.getValue();
if (v2 - Math.floor(v2) < THRESHOLD && value > 1) {
v2 = Math.floor(v2);
}
return v2;
}
}
if (value - Math.floor(value) < THRESHOLD && value > 1) {
return Math.floor(value);
}
return value;
}
public static String formatUnitPrefix(double value, double step, UnitSystem unitSystem) {
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue() && step >= unit.getValue()) {
return unit.getPrefix();
}
}
return "";
}
public static String formatUnitPrefix(double value, UnitSystem unitSystem) {
for (Unit unit : unitSystem.getPrefixes()) {
if (Math.abs(value) >= unit.getValue()) {
return unit.getPrefix();
}
}
return "";
}
public static String formatValue(double value, UnitSystem unitSystem) {
return String.format("%s%s", formatDoubleSpecialSmart(formatUnitValue(value, unitSystem)), formatUnitPrefix(value, unitSystem));
}
public static String formatDoubleSpecialPlain(Double value) {
BigDecimal bigDecimal = BigDecimal.valueOf(value);
if (bigDecimal.precision() > 10) {
bigDecimal = bigDecimal.setScale(bigDecimal.scale() - 1, BigDecimal.ROUND_HALF_UP);
}
return bigDecimal.stripTrailingZeros().toPlainString();
}
public static String formatDoubleSpecialSmart(Double value) {
BigDecimal bigDecimal = BigDecimal.valueOf(value);
if (bigDecimal.precision() > 10) {
bigDecimal = bigDecimal.setScale(bigDecimal.scale() - 1, BigDecimal.ROUND_HALF_UP);
}
return bigDecimal.stripTrailingZeros().toEngineeringString();
}
// todo: this "magic rounding" is a complete atrocity - fix it!
public static double magicRound(double value) {
if (value > -1.0 && value < 1.0) {
return new BigDecimal(value).setScale(2 - (int) Math.log10(Math.abs(value)), BigDecimal.ROUND_HALF_UP).doubleValue();
} else {
return value;
}
}
private final static BigDecimal ONE = BigDecimal.valueOf(1.0);
private final static BigDecimal MINUS_ONE = BigDecimal.valueOf(-1.0);
public static BigDecimal magicRound(BigDecimal value) {
if (value.compareTo(MINUS_ONE) > 0 && value.compareTo(ONE) < 0) {
return value.setScale(2 - (int) Math.log10(Math.abs(value.doubleValue())), BigDecimal.ROUND_HALF_UP);
} else {
return value;
}
}
}
|
fixed formatting of numbers
|
src/main/java/net/iponweb/disthene/reader/graphite/utils/GraphiteUtils.java
|
fixed formatting of numbers
|
|
Java
|
mit
|
3d465392f2e4a423f39bd6a375ea09f1647f98f1
| 0
|
effine/shopping
|
/**
* @author verphen
* @date 2014年10月2日 上午12:21:12
*/
package com.verphen.dao.impl;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.verphen.inter.IUserOperation;
import com.verphen.model.User;
public class UserDaoImplTest {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
//==================== 第二部分:面向接口编程 ==============================//
//使用时必须先注册:sqlSessionFactory.getConfiguration().addMapper(IUserOperation.class);
//然后必须在接口上添加注释:@Select("select * from user")
IUserOperation userOperation = session.getMapper(IUserOperation.class);
User user1 = userOperation.selectUserByID(1);
System.out.println(user1.getName());
List<User> list1 = userOperation.selectUserList("verphen");
System.out.println(list1.size());
/* 插入数据 */
//User userAdd = new User();
//userAdd.setName("test1");
//userAdd.setPassword("test1");
//userOperation.add(userAdd);
//必须提交事务,写入数据库
//session.commit();
/* 更新数据 */
//User userUpdate = new User();
//userUpdate.setId(1);
//userUpdate.setName("test0");
//userUpdate.setPassword("test0");
//userOperation.update(userUpdate);
//session.commit();
/*删除数据*/
//userOperation.delete(1);
//session.commit();
/* 两表联合查询 */
userOperation.getUserArticles(1);
} finally {
session.close();
}
}
public boolean add(){
return false;
}
public static void main(String[] args){
System.out.println("------------------");
}
}
|
src/test/java/com/verphen/dao/impl/UserDaoImplTest.java
|
/**
* @author verphen
* @date 2014年10月2日 上午12:21:12
*/
package com.verphen.dao.impl;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.verphen.inter.IUserOperation;
import com.verphen.model.User;
public class UserDaoImplTest {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSession() {
return sqlSessionFactory;
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
//==================== 第二部分:面向接口编程 ==============================//
//使用时必须先注册:sqlSessionFactory.getConfiguration().addMapper(IUserOperation.class);
//然后必须在接口上添加注释:@Select("select * from user")
IUserOperation userOperation = session.getMapper(IUserOperation.class);
User user1 = userOperation.selectUserByID(1);
System.out.println(user1.getName());
List<User> list1 = userOperation.selectUserList("verphen");
System.out.println(list1.size());
/* 插入数据 */
//User userAdd = new User();
//userAdd.setName("test1");
//userAdd.setPassword("test1");
//userOperation.add(userAdd);
//必须提交事务,写入数据库
//session.commit();
/* 更新数据 */
//User userUpdate = new User();
//userUpdate.setId(1);
//userUpdate.setName("test0");
//userUpdate.setPassword("test0");
//userOperation.update(userUpdate);
//session.commit();
/*删除数据*/
//userOperation.delete(1);
//session.commit();
/* 两表联合查询 */
userOperation.getUserArticles(1);
} finally {
session.close();
}
}
public boolean add(){
return false;
}
}
|
test git fetch
|
src/test/java/com/verphen/dao/impl/UserDaoImplTest.java
|
test git fetch
|
|
Java
|
epl-1.0
|
79d7915ca46e3db035f2d24bdc7546cf663c95ba
| 0
|
sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt
|
/*
*************************************************************************
* Copyright (c) 2004, 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.executor;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.IOdaDataSetDesign;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.QueryExecutionStrategyUtil.Strategy;
import org.eclipse.birt.data.engine.executor.dscache.DataSetToCache;
import org.eclipse.birt.data.engine.executor.transform.CachedResultSet;
import org.eclipse.birt.data.engine.executor.transform.SimpleResultSet;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.DataEngineImpl;
import org.eclipse.birt.data.engine.impl.DataEngineSession;
import org.eclipse.birt.data.engine.impl.ICancellable;
import org.eclipse.birt.data.engine.impl.IQueryContextVisitor;
import org.eclipse.birt.data.engine.impl.QueryContextVisitorUtil;
import org.eclipse.birt.data.engine.impl.StopSign;
import org.eclipse.birt.data.engine.impl.document.viewing.ExprMetaUtil;
import org.eclipse.birt.data.engine.odaconsumer.ColumnHint;
import org.eclipse.birt.data.engine.odaconsumer.ParameterHint;
import org.eclipse.birt.data.engine.odaconsumer.PreparedStatement;
import org.eclipse.birt.data.engine.odaconsumer.QuerySpecHelper;
import org.eclipse.birt.data.engine.odaconsumer.ResultSet;
import org.eclipse.birt.data.engine.odi.IDataSourceQuery;
import org.eclipse.birt.data.engine.odi.IEventHandler;
import org.eclipse.birt.data.engine.odi.IParameterMetaData;
import org.eclipse.birt.data.engine.odi.IPreparedDSQuery;
import org.eclipse.birt.data.engine.odi.IResultClass;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.datatools.connectivity.oda.IBlob;
import org.eclipse.datatools.connectivity.oda.IClob;
import org.eclipse.datatools.connectivity.oda.spec.QuerySpecification;
/**
* Structure to hold info of a custom field.
*/
final class CustomField
{
String name;
int dataType = -1;
CustomField( String name, int dataType)
{
this.name = name;
this.dataType = dataType;
}
CustomField()
{}
public int getDataType()
{
return dataType;
}
public void setDataType(int dataType)
{
this.dataType = dataType;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
/**
* Structure to hold Parameter binding info
* @author lzhu
*
*/
class ParameterBinding
{
private String name;
private int position = -1;
private Object value;
ParameterBinding( String name, int position, Object value )
{
this.name = name;
this.value = value;
this.position = position;
}
ParameterBinding( int position, Object value )
{
this.position = position;
this.value = value;
}
public int getPosition()
{
return position;
}
public String getName()
{
return name;
}
public Object getValue()
{
return value;
}
}
/**
* Implementation of ODI's IDataSourceQuery interface
*/
public class DataSourceQuery extends BaseQuery implements IDataSourceQuery, IPreparedDSQuery
{
protected DataSource dataSource;
protected String queryText;
protected String queryType;
protected PreparedStatement odaStatement;
// Collection of ColumnHint objects
protected Collection resultHints;
// Collection of CustomField objects
protected Collection customFields;
protected IResultClass resultMetadata;
// Names (or aliases) of columns in the projected result set
protected String[] projectedFields;
// input/output parameter hints (collection of ParameterHint objects)
private Collection parameterHints;
private QuerySpecification querySpecificaton;
// input parameter values
private Collection inputParamValues;
// Properties added by addProperty()
private ArrayList propNames;
private ArrayList propValues;
private DataEngineSession session;
private IQueryContextVisitor qcv;
/**
* Constructor.
*
* @param dataSource
* @param queryType
* @param queryText
*/
DataSourceQuery( DataSource dataSource, String queryType, String queryText, DataEngineSession session, IQueryContextVisitor qcv )
{
this.dataSource = dataSource;
this.queryText = queryText;
this.queryType = queryType;
this.session = session;
this.qcv = qcv;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#setResultHints(java.util.Collection)
*/
public void setResultHints(Collection columnDefns)
{
resultHints = columnDefns;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#setResultProjection(java.lang.String[])
*/
public void setResultProjection(String[] fieldNames) throws DataException
{
if ( fieldNames == null || fieldNames.length == 0 )
return; // nothing to set
this.projectedFields = fieldNames;
}
public void setParameterHints( Collection parameterHints )
{
// assign to placeholder, for use later during prepare()
this.parameterHints = parameterHints;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#addProperty(java.lang.String, java.lang.String)
*/
public void addProperty(String name, String value ) throws DataException
{
if ( name == null )
throw new NullPointerException("Property name is null");
// Must be called before prepare() per interface spec
if ( odaStatement != null )
throw new DataException( ResourceConstants.QUERY_HAS_PREPARED );
if ( propNames == null )
{
assert propValues == null;
propNames = new ArrayList();
propValues = new ArrayList();
}
assert propValues != null;
propNames.add( name );
propValues.add( value );
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#declareCustomField(java.lang.String, int)
*/
public void declareCustomField( String fieldName, int dataType ) throws DataException
{
if ( fieldName == null || fieldName.length() == 0 )
throw new DataException( ResourceConstants.CUSTOM_FIELD_EMPTY );
if ( customFields == null )
{
customFields = new ArrayList();
}
else
{
Iterator cfIt = customFields.iterator( );
while ( cfIt.hasNext( ) )
{
CustomField cf = (CustomField) cfIt.next();
if ( cf.name.equals( fieldName ) )
{
throw new DataException( ResourceConstants.DUP_CUSTOM_FIELD_NAME, fieldName );
}
}
}
customFields.add( new CustomField( fieldName, dataType ) );
}
/* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#prepare()
*/
@SuppressWarnings("restriction")
public IPreparedDSQuery prepare() throws DataException
{
if ( odaStatement != null )
throw new DataException( ResourceConstants.QUERY_HAS_PREPARED );
// create and populate a query specification for preparing a statement
populateQuerySpecification();
odaStatement = dataSource.prepareStatement( queryText, queryType, this.querySpecificaton );
// Add custom properties to odaStatement
addPropertiesToPreparedStatement( );
// Adds input and output parameter hints to odaStatement.
// This step must be done before odaStatement.setColumnsProjection()
// for some jdbc driver need to carry out a query execution before the metadata can be achieved
// and only when the Parameters are successfully set the query execution can succeed.
addParameterDefns();
IOdaDataSetDesign design = null;
if( session.getDataSetCacheManager( ).getCurrentDataSetDesign( ) instanceof IOdaDataSetDesign )
design = (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( );
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
// Ordering is important for the following operations. Column hints
// should be defined
// after custom fields are declared (since hints may be given to
// those custom fields).
// Column projection comes last because it needs hints and
// custom
// column information
addCustomFields( design.getPrimaryResultSetName( ), odaStatement );
addColumnHints( design.getPrimaryResultSetName( ), odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( design.getPrimaryResultSetName( ), this.projectedFields );
}
else if( canAccessResultSetByNumber( design ) )
{
addCustomFields( design.getPrimaryResultSetNumber( ), odaStatement );
addColumnHints( design.getPrimaryResultSetNumber( ), odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( design.getPrimaryResultSetNumber( ), this.projectedFields );
}
else
{
prepareColumns( );
}
}else
{
prepareColumns( );
}
//Here the "max rows" means the max number of rows that can fetch from data source.
odaStatement.setMaxRows( this.getRowFetchLimit( ) );
// If ODA can provide result metadata, get it now
try
{
resultMetadata = getMetaData( (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( ), odaStatement );
}
catch ( DataException e )
{
// Assume metadata not available at prepare time; ignore the exception
resultMetadata = null;
}
return this;
}
private boolean canAccessResultSetByName( IOdaDataSetDesign design )
throws DataException
{
return design.getPrimaryResultSetName( ) != null && odaStatement.supportsNamedResults( );
}
private boolean canAccessResultSetByNumber( IOdaDataSetDesign design )
throws DataException
{
return design.getPrimaryResultSetNumber( ) > 0 && odaStatement.supportsMultipleResultSets( );
}
private void prepareColumns( ) throws DataException
{
addCustomFields( odaStatement );
addColumnHints( odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( this.projectedFields );
}
/**
*
* @param design
* @param odaStatement
* @return
* @throws DataException
*/
private IResultClass getMetaData( IOdaDataSetDesign design, PreparedStatement odaStatement ) throws DataException
{
IResultClass result = null;
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
try
{
result = odaStatement.getMetaData( design.getPrimaryResultSetName( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetName( ) );
}
}
else if ( canAccessResultSetByNumber( design ) )
{
try
{
result = odaStatement.getMetaData( design.getPrimaryResultSetNumber( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetNumber( ) );
}
}
}
if( result == null )
result = odaStatement.getMetaData();
if ( design != null )
{
List hintList = design.getResultSetHints( );
for ( int i = 0; i < hintList.size( ); i++ )
{
IColumnDefinition columnDefinition = (IColumnDefinition) hintList.get( i );
for ( int j = 1; j <= result.getFieldCount( ); j++ )
{
ResultFieldMetadata resultFieldMetadata = result.getFieldMetaData( j );
if ( columnDefinition.getColumnName( )
.equals( resultFieldMetadata.getName( ) ) )
{
resultFieldMetadata.setAlias( columnDefinition.getAlias( ) );
resultFieldMetadata.setAnalysisType( columnDefinition.getAnalysisType( ) );
resultFieldMetadata.setAnalysisColumn( columnDefinition.getAnalysisColumn( ) );
resultFieldMetadata.setIndexColumn( columnDefinition.isIndexColumn( ) );
resultFieldMetadata.setCompressedColumn( columnDefinition.isCompressedColumn( ) );
break;
}
}
}
}
return result;
}
/*
* Prepare a query specification with the property and input parameter values,
* for use by an ODA driver before IQuery#prepare.
*/
@SuppressWarnings("restriction")
private QuerySpecification populateQuerySpecification() throws DataException
{
if ( this.querySpecificaton == null )
{
QuerySpecHelper querySpecHelper = new QuerySpecHelper( dataSource.getDriverName( ),
queryType );
this.querySpecificaton = querySpecHelper.getFactoryHelper( )
.createQuerySpecification( );
}
// add custom properties
addPropertiesToQuerySpec( querySpecificaton );
// add parameter defns
addParametersToQuerySpec( querySpecificaton );
return querySpecificaton;
}
/**
* Adds custom properties to the QuerySpecification.
*/
@SuppressWarnings("restriction")
private void addPropertiesToQuerySpec( QuerySpecification querySpec )
{
if ( propNames == null )
return; // nothing to add
assert propValues != null;
Iterator it_name = propNames.iterator();
Iterator it_val = propValues.iterator();
while ( it_name.hasNext() )
{
assert it_val.hasNext();
String name = (String) it_name.next();
String val = (String) it_val.next();
querySpec.setProperty( name, val );
}
}
/**
* Adds custom properties to prepared oda statement;
* use the same properties already set in querySpec before prepare
*/
@SuppressWarnings("restriction")
private void addPropertiesToPreparedStatement( ) throws DataException
{
if( this.querySpecificaton == null || this.querySpecificaton.getProperties().isEmpty() )
return; // no properties to add
assert odaStatement != null;
Map<String,Object> propertyMap = this.querySpecificaton.getProperties();
Iterator<Entry<String, Object>> iter = propertyMap.entrySet().iterator();
while( iter.hasNext() )
{
Entry<String, Object> property = iter.next();
String value = ( property.getValue() == null ) ? null : property.getValue().toString();
odaStatement.setProperty( property.getKey(), value );
}
}
/**
* Adds input parameter values to the QuerySpecification.
*/
@SuppressWarnings("restriction")
private void addParametersToQuerySpec( QuerySpecification querySpec )
throws DataException
{
if ( this.parameterHints == null )
return; // nothing to add
// iterate thru the collection to add parameter hints
Iterator it = this.parameterHints.iterator( );
while ( it.hasNext( ) )
{
ParameterHint parameterHint = (ParameterHint) it.next();
//If the parameter is input parameter, add its value to query spec
if ( parameterHint.isInputMode( ) )
{
Object inputValue = getParameterInputValue( parameterHint );
QuerySpecHelper.setParameterValue( querySpec, parameterHint, inputValue );
}
}
}
/**
* Adds input and output parameter hints to odaStatement
*/
private void addParameterDefns() throws DataException
{
assert odaStatement!= null;
if ( this.parameterHints == null )
return; // nothing to add
// iterate thru the collection to add parameter hints
Iterator it = this.parameterHints.iterator( );
while ( it.hasNext( ) )
{
ParameterHint parameterHint = (ParameterHint) it.next();
odaStatement.addParameterHint( parameterHint );
//If the parameter is input parameter then add it to input value list.
if ( parameterHint.isInputMode( ) )
{
Object inputValue = getParameterInputValue( parameterHint );
if ( parameterHint.getPosition( ) <= 0 || odaStatement.supportsNamedParameter( ))
{
this.setInputParamValue( parameterHint.getName( ), parameterHint.getPosition( ),
inputValue );
}
else
{
this.setInputParamValue( parameterHint.getPosition( ),
inputValue );
}
}
}
this.setInputParameterBinding();
}
private Object getParameterInputValue( ParameterHint parameterHint )
throws DataException
{
assert parameterHint.isInputMode( );
Class paramHintDataType = parameterHint.getDataType();
// since a Date may have extended types,
// use the type of Date that is most effective for data conversion
if( paramHintDataType == Date.class )
paramHintDataType = parameterHint.getEffectiveDataType(
dataSource.getDriverName(), queryType );
Object inputValue = parameterHint.getDefaultInputValue( );
if ( inputValue != null )
{
if ( inputValue.getClass( ).isArray( ) )
{
//if multi-value type report parameter is linked with data set parameter
//only take the first provided value to pass it to data set
if ( Array.getLength( inputValue ) == 0 )
{
inputValue = null;
}
else
{
inputValue = Array.get( inputValue, 0 );
}
}
}
// neither IBlob nor IClob will be converted
if ( paramHintDataType != IBlob.class && paramHintDataType != IClob.class )
inputValue = convertToValue( inputValue,
paramHintDataType );
return inputValue;
}
/**
* @param inputParamName
* @param paramValue
* @throws DataException
*/
private void setInputParamValue( String inputParamName, int position, Object paramValue )
throws DataException
{
ParameterBinding pb = new ParameterBinding( inputParamName, position, paramValue );
getInputParamValues().add( pb );
}
/**
* @param inputParamPos
* @param paramValue
* @throws DataException
*/
private void setInputParamValue( int inputParamPos, Object paramValue )
throws DataException
{
ParameterBinding pb = new ParameterBinding( inputParamPos, paramValue );
getInputParamValues().add( pb );
}
/**
* Declares custom fields on Oda statement
*
* @param stmt
* @throws DataException
*/
private void addCustomFields( PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
private void addCustomFields( String rsetName, PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( rsetName, customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
private void addCustomFields( int rsetNumber, PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( rsetNumber, customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
/**
* Adds Odi column hints to ODA statement
*
* @param stmt
* @throws DataException
*/
private void addColumnHints( PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( colHint );
}
}
private void addColumnHints( String rsetName, PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( rsetName, colHint );
}
}
private void addColumnHints( int rsetNumber, PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( rsetNumber, colHint );
}
}
private ColumnHint prepareOdiHint( IDataSourceQuery.ResultFieldHint odiHint )
{
ColumnHint colHint = new ColumnHint( odiHint.getName() );
colHint.setAlias( odiHint.getAlias() );
if ( odiHint.getDataType( ) == DataType.ANY_TYPE )
colHint.setDataType( null );
else
colHint.setDataType( DataType.getClass( odiHint.getDataType( ) ) );
colHint.setNativeDataType( odiHint.getNativeDataType() );
if ( odiHint.getPosition() > 0 )
colHint.setPosition( odiHint.getPosition());
return colHint;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getResultClass()
*/
public IResultClass getResultClass()
{
// Note the return value can be null if resultMetadata was
// not available during prepare() time
return resultMetadata;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterMetaData()
*/
public Collection getParameterMetaData()
throws DataException
{
if ( odaStatement == null )
throw new DataException( ResourceConstants.QUERY_HAS_NOT_PREPARED );
Collection odaParamsInfo = odaStatement.getParameterMetaData();
if ( odaParamsInfo == null || odaParamsInfo.isEmpty() )
return null;
// iterates thru the most up-to-date collection, and
// wraps each of the odaconsumer parameter metadata object
ArrayList paramMetaDataList = new ArrayList( odaParamsInfo.size() );
Iterator odaParamMDIter = odaParamsInfo.iterator();
while ( odaParamMDIter.hasNext() )
{
org.eclipse.birt.data.engine.odaconsumer.ParameterMetaData odaMetaData =
(org.eclipse.birt.data.engine.odaconsumer.ParameterMetaData) odaParamMDIter.next();
paramMetaDataList.add( new ParameterMetaData( odaMetaData ) );
}
return paramMetaDataList;
}
/**
* Return the input parameter value list
*
* @return
*/
private Collection getInputParamValues()
{
if ( inputParamValues == null )
inputParamValues = new ArrayList();
return inputParamValues;
}
private IResultClass copyResultClass( IResultClass meta )
throws DataException
{
List<ResultFieldMetadata> list = new ArrayList<ResultFieldMetadata>( );
for ( int i = 1; i <= meta.getFieldCount( ); i++ )
{
if ( !meta.getFieldName( i ).equals( ExprMetaUtil.POS_NAME ) )
{
int m_driverPosition = meta.getFieldMetaData( i ).getDriverPosition( );
String m_name = meta.getFieldMetaData( i ).getName( );
String m_label = meta.getFieldMetaData( i ).getLabel( );
Class m_dataType = meta.getFieldMetaData( i ).getDataType( );
String m_nativeTypeName = meta.getFieldMetaData( i ).getNativeTypeName( );
boolean m_isCustom = meta.getFieldMetaData( i ).isCustom( );
Class m_driverProvidedDataType = meta.getFieldMetaData( i ).getDriverProvidedDataType( );
int m_analysisType = meta.getFieldMetaData( i ).getAnalysisType( );
String m_analysisColumn = meta.getFieldMetaData( i ).getAnalysisColumn( );
boolean m_indexColumn = meta.getFieldMetaData( i ).isIndexColumn( );
boolean m_compressedColumn = meta.getFieldMetaData( i ).isCompressedColumn( );
ResultFieldMetadata metadata = new ResultFieldMetadata( m_driverPosition, m_name,
m_label, m_dataType,
m_nativeTypeName,m_isCustom, m_analysisType, m_analysisColumn, m_indexColumn, m_compressedColumn );
metadata.setDriverProvidedDataType( m_driverProvidedDataType );
metadata.setAlias( meta.getFieldMetaData( i ).getAlias( ) );
list.add( metadata );
}
}
IResultClass resultClass = new ResultClass( list );
return resultClass;
}
private IResultClass mergeResultHint ( List modelResultHints, IResultClass meta )
{
if ( modelResultHints == null || modelResultHints.isEmpty( ) )
return meta;
IResultClass newResultClass;
try
{
newResultClass = copyResultClass( meta );
}
catch ( Exception ex )
{
return meta;
}
int count = newResultClass.getFieldCount( );
try
{
for ( int i = 1; i <= count; i++ )
{
String fieldName = newResultClass.getFieldName( i );
Class odaType = newResultClass.getFieldMetaData( i )
.getDataType( );
for ( int j = 0; j < modelResultHints.size( ); j++ )
{
if ( ( (IColumnDefinition) modelResultHints.get( j ) ).getColumnName( )
.equals( fieldName ) )
{
int apiType = ( (IColumnDefinition) modelResultHints.get( j ) ).getDataType( );
if ( apiType > 0
&& DataTypeUtil.toApiDataType( odaType ) != apiType )
{
newResultClass.getFieldMetaData( i )
.setDataType( DataType.getClass( apiType ) );
}
break;
}
}
}
}
catch ( Exception ex )
{
}
return newResultClass;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#execute()
*/
public IResultIterator execute( IEventHandler eventHandler )
throws DataException
{
assert odaStatement != null;
IResultIterator ri = null;
this.setInputParameterBinding();
IOdaDataSetDesign design = null;
if( session.getDataSetCacheManager( ).getCurrentDataSetDesign( ) instanceof IOdaDataSetDesign )
design = (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( );
if ( session.getDataSetCacheManager( ).doesSaveToCache( ) )
{
int fetchRowLimit = 0;
if ( design != null )
{
fetchRowLimit = session.getDataSetCacheManager( )
.getCurrentDataSetDesign( )
.getRowFetchLimit( );
}
if ( fetchRowLimit != 0 )
{
odaStatement.setMaxRows( fetchRowLimit );
}
}
ICancellable queryCanceller = new OdaQueryCanceller( odaStatement, session.getStopSign() );
this.session.getCancelManager( ).register( queryCanceller );
odaStatement.execute( );
QueryContextVisitorUtil.populateEffectiveQueryText( qcv,
odaStatement.getEffectiveQueryText( ) );
if ( queryCanceller.collectException( ) != null )
{
if ( !( queryCanceller.collectException( ).getCause( ) instanceof UnsupportedOperationException ) )
throw queryCanceller.collectException( );
}
this.session.getCancelManager( ).deregister( queryCanceller );
ResultSet rs = null;
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
try
{
rs = odaStatement.getResultSet( design.getPrimaryResultSetName( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetName( ) );
}
}
else if ( canAccessResultSetByNumber( design ) )
{
try
{
rs = odaStatement.getResultSet( design.getPrimaryResultSetNumber( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetNumber( ) );
}
}
}
if( rs == null )
{
rs = odaStatement.getResultSet( );
}
List modelResultHints = design.getResultSetHints( );
// If we did not get a result set metadata at prepare() time, get it now
if ( resultMetadata == null )
{
resultMetadata = rs.getMetaData( );
if ( resultMetadata == null )
throw new DataException( ResourceConstants.METADATA_NOT_AVAILABLE );
}
IResultClass newResultClass = mergeResultHint( modelResultHints , resultMetadata );
// Initialize CachedResultSet using the ODA result set
if ( session.getDataSetCacheManager( ).doesSaveToCache( ) == false )
{
if ( ( ( session.getEngineContext( ).getMode( ) == DataEngineContext.DIRECT_PRESENTATION || session.getEngineContext( )
.getMode( ) == DataEngineContext.MODE_GENERATION ) )
&& this.getQueryDefinition( ) instanceof IQueryDefinition )
{
IQueryDefinition queryDefn = (IQueryDefinition) this.getQueryDefinition( );
if ( QueryExecutionStrategyUtil.getQueryExecutionStrategy( queryDefn,
queryDefn.getDataSetName( ) == null
? null
: ( (DataEngineImpl) this.session.getEngine( ) ).getDataSetDesign( queryDefn.getDataSetName( ) ) ) == Strategy.Simple )
{
IResultIterator it = new SimpleResultSet( this,
rs,
newResultClass,
eventHandler );
eventHandler.handleEndOfDataSetProcess( it );
return it;
}
}
ri = new CachedResultSet( this,
newResultClass,
rs,
eventHandler,
session );
}
else
ri = new CachedResultSet( this,
newResultClass,
new DataSetToCache( rs, newResultClass, session ),
eventHandler, session );
if ( ri != null )
( (CachedResultSet) ri ).setOdaResultSet( rs );
return ri;
}
private static class OdaQueryCanceller implements ICancellable
{
private PreparedStatement statement;
private StopSign stop;
private DataException exception;
OdaQueryCanceller( PreparedStatement statement, StopSign stop )
{
this.statement = statement;
this.stop = stop;
}
/**
* Collect the exception throw during statement execution.
*
* @return
*/
public DataException collectException()
{
return this.exception;
}
/**
*
*/
public void cancel( )
{
try
{
this.statement.cancel( );
}
catch ( DataException e )
{
this.exception = e;
}
}
/**
*
*/
public boolean doCancel( )
{
return this.stop.isStopped( );
}
}
/**
* set input parameter bindings
*/
private void setInputParameterBinding() throws DataException
{
assert odaStatement!= null;
// set input parameter bindings
Iterator inputParamValueslist = getInputParamValues().iterator( );
while ( inputParamValueslist.hasNext( ) )
{
ParameterBinding paramBind = (ParameterBinding) inputParamValueslist.next( );
if ( paramBind.getPosition( ) <= 0 || odaStatement.supportsNamedParameter( ))
{
try
{
odaStatement.setParameterValue( paramBind.getName( ),
paramBind.getValue( ) );
}
catch ( DataException e )
{
if ( paramBind.getPosition( ) <= 0 )
{
throw e;
}
else
{
odaStatement.setParameterValue( paramBind.getPosition( ),
paramBind.getValue( ) );
}
}
}
else
{
odaStatement.setParameterValue( paramBind.getPosition( ),
paramBind.getValue() );
}
}
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterValue(int)
*/
public Object getOutputParameterValue( int index ) throws DataException
{
assert odaStatement != null;
int newIndex = getCorrectParamIndex( index );
return odaStatement.getParameterValue( newIndex );
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterValue(java.lang.String)
*/
public Object getOutputParameterValue( String name ) throws DataException
{
assert odaStatement != null;
checkOutputParamNameValid( name );
return odaStatement.getParameterValue( name );
}
/**
* In oda layer, it does not differentiate the value retrievation of input
* parameter value and ouput parameter value. They will be put in a same
* sequence list. However, in odi layer, we need to clearly distinguish them
* since only retrieving output parameter is suppored and it should be based
* on its own output parameter index. Therefore, this method will do such a
* conversion from the output parameter index to the parameter index.
*
* @param index based on output parameter order
* @return index based on the whole parameters order
* @throws DataException
*/
private int getCorrectParamIndex( int index ) throws DataException
{
if ( index <= 0 )
throw new DataException( ResourceConstants.INVALID_OUTPUT_PARAMETER_INDEX, Integer.valueOf( index ) );
int newIndex = 0; // 1-based
int curOutputIndex = 0; // 1-based
Collection collection = getParameterMetaData( );
if ( collection != null )
{
Iterator it = collection.iterator( );
while ( it.hasNext( ) )
{
newIndex++;
IParameterMetaData metaData = (IParameterMetaData) it.next( );
if ( metaData.isOutputMode( ).booleanValue( ) == true )
{
curOutputIndex++;
if ( curOutputIndex == index )
break;
}
}
}
if ( curOutputIndex < index )
throw new DataException( ResourceConstants.OUTPUT_PARAMETER_OUT_OF_BOUND,
Integer.valueOf( index ) );
return newIndex;
}
/**
* Validate the name of output parameter
*
* @param name
* @throws DataException
*/
private void checkOutputParamNameValid( String name ) throws DataException
{
assert name != null;
boolean isValid = false;
Collection collection = getParameterMetaData( );
if ( collection != null )
{
Iterator it = collection.iterator( );
while ( it.hasNext( ) )
{
IParameterMetaData metaData = (IParameterMetaData) it.next( );
String paramName = metaData.getName( );
if ( paramName.equals( name ) )
{
isValid = metaData.isOutputMode( ).booleanValue( );
break;
}
}
}
if ( isValid == false )
throw new DataException( ResourceConstants.INVALID_OUTPUT_PARAMETER_NAME, name );
}
/*
* @see org.eclipse.birt.data.engine.odi.IQuery#close()
*/
public void close()
{
if ( odaStatement != null )
{
this.dataSource.closeStatement( odaStatement );
odaStatement = null;
}
this.dataSource = null;
// TODO: close all CachedResultSets created by us
}
/**
* convert the String value to Object according to it's datatype.
*
* @param inputValue
* @param type
* @return
* @throws DataException
*/
private static Object convertToValue( Object inputValue, Class typeClass )
throws DataException
{
try
{
return DataTypeUtil.convert( inputValue, typeClass);
}
catch ( Exception ex )
{
throw new DataException( ResourceConstants.CANNOT_CONVERT_PARAMETER_TYPE,
ex,
new Object[]{
inputValue, typeClass
} );
}
}
public void setQuerySpecification( QuerySpecification spec )
{
this.querySpecificaton = spec;
}
}
|
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/DataSourceQuery.java
|
/*
*************************************************************************
* Copyright (c) 2004, 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.executor;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.IOdaDataSetDesign;
import org.eclipse.birt.data.engine.api.IQueryDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.QueryExecutionStrategyUtil.Strategy;
import org.eclipse.birt.data.engine.executor.dscache.DataSetToCache;
import org.eclipse.birt.data.engine.executor.transform.CachedResultSet;
import org.eclipse.birt.data.engine.executor.transform.SimpleResultSet;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.DataEngineImpl;
import org.eclipse.birt.data.engine.impl.DataEngineSession;
import org.eclipse.birt.data.engine.impl.ICancellable;
import org.eclipse.birt.data.engine.impl.IQueryContextVisitor;
import org.eclipse.birt.data.engine.impl.QueryContextVisitorUtil;
import org.eclipse.birt.data.engine.impl.StopSign;
import org.eclipse.birt.data.engine.impl.document.viewing.ExprMetaUtil;
import org.eclipse.birt.data.engine.odaconsumer.ColumnHint;
import org.eclipse.birt.data.engine.odaconsumer.ParameterHint;
import org.eclipse.birt.data.engine.odaconsumer.PreparedStatement;
import org.eclipse.birt.data.engine.odaconsumer.QuerySpecHelper;
import org.eclipse.birt.data.engine.odaconsumer.ResultSet;
import org.eclipse.birt.data.engine.odi.IDataSourceQuery;
import org.eclipse.birt.data.engine.odi.IEventHandler;
import org.eclipse.birt.data.engine.odi.IParameterMetaData;
import org.eclipse.birt.data.engine.odi.IPreparedDSQuery;
import org.eclipse.birt.data.engine.odi.IResultClass;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.datatools.connectivity.oda.IBlob;
import org.eclipse.datatools.connectivity.oda.IClob;
import org.eclipse.datatools.connectivity.oda.spec.QuerySpecification;
/**
* Structure to hold info of a custom field.
*/
final class CustomField
{
String name;
int dataType = -1;
CustomField( String name, int dataType)
{
this.name = name;
this.dataType = dataType;
}
CustomField()
{}
public int getDataType()
{
return dataType;
}
public void setDataType(int dataType)
{
this.dataType = dataType;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
/**
* Structure to hold Parameter binding info
* @author lzhu
*
*/
class ParameterBinding
{
private String name;
private int position = -1;
private Object value;
ParameterBinding( String name, int position, Object value )
{
this.name = name;
this.value = value;
this.position = position;
}
ParameterBinding( int position, Object value )
{
this.position = position;
this.value = value;
}
public int getPosition()
{
return position;
}
public String getName()
{
return name;
}
public Object getValue()
{
return value;
}
}
/**
* Implementation of ODI's IDataSourceQuery interface
*/
public class DataSourceQuery extends BaseQuery implements IDataSourceQuery, IPreparedDSQuery
{
protected DataSource dataSource;
protected String queryText;
protected String queryType;
protected PreparedStatement odaStatement;
// Collection of ColumnHint objects
protected Collection resultHints;
// Collection of CustomField objects
protected Collection customFields;
protected IResultClass resultMetadata;
// Names (or aliases) of columns in the projected result set
protected String[] projectedFields;
// input/output parameter hints (collection of ParameterHint objects)
private Collection parameterHints;
private QuerySpecification querySpecificaton;
// input parameter values
private Collection inputParamValues;
// Properties added by addProperty()
private ArrayList propNames;
private ArrayList propValues;
private DataEngineSession session;
private IQueryContextVisitor qcv;
/**
* Constructor.
*
* @param dataSource
* @param queryType
* @param queryText
*/
DataSourceQuery( DataSource dataSource, String queryType, String queryText, DataEngineSession session, IQueryContextVisitor qcv )
{
this.dataSource = dataSource;
this.queryText = queryText;
this.queryType = queryType;
this.session = session;
this.qcv = qcv;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#setResultHints(java.util.Collection)
*/
public void setResultHints(Collection columnDefns)
{
resultHints = columnDefns;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#setResultProjection(java.lang.String[])
*/
public void setResultProjection(String[] fieldNames) throws DataException
{
if ( fieldNames == null || fieldNames.length == 0 )
return; // nothing to set
this.projectedFields = fieldNames;
}
public void setParameterHints( Collection parameterHints )
{
// assign to placeholder, for use later during prepare()
this.parameterHints = parameterHints;
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#addProperty(java.lang.String, java.lang.String)
*/
public void addProperty(String name, String value ) throws DataException
{
if ( name == null )
throw new NullPointerException("Property name is null");
// Must be called before prepare() per interface spec
if ( odaStatement != null )
throw new DataException( ResourceConstants.QUERY_HAS_PREPARED );
if ( propNames == null )
{
assert propValues == null;
propNames = new ArrayList();
propValues = new ArrayList();
}
assert propValues != null;
propNames.add( name );
propValues.add( value );
}
/*
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#declareCustomField(java.lang.String, int)
*/
public void declareCustomField( String fieldName, int dataType ) throws DataException
{
if ( fieldName == null || fieldName.length() == 0 )
throw new DataException( ResourceConstants.CUSTOM_FIELD_EMPTY );
if ( customFields == null )
{
customFields = new ArrayList();
}
else
{
Iterator cfIt = customFields.iterator( );
while ( cfIt.hasNext( ) )
{
CustomField cf = (CustomField) cfIt.next();
if ( cf.name.equals( fieldName ) )
{
throw new DataException( ResourceConstants.DUP_CUSTOM_FIELD_NAME, fieldName );
}
}
}
customFields.add( new CustomField( fieldName, dataType ) );
}
/* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IDataSourceQuery#prepare()
*/
@SuppressWarnings("restriction")
public IPreparedDSQuery prepare() throws DataException
{
if ( odaStatement != null )
throw new DataException( ResourceConstants.QUERY_HAS_PREPARED );
// create and populate a query specification for preparing a statement
populateQuerySpecification();
odaStatement = dataSource.prepareStatement( queryText, queryType, this.querySpecificaton );
// Add custom properties to odaStatement
addPropertiesToPreparedStatement( );
// Adds input and output parameter hints to odaStatement.
// This step must be done before odaStatement.setColumnsProjection()
// for some jdbc driver need to carry out a query execution before the metadata can be achieved
// and only when the Parameters are successfully set the query execution can succeed.
addParameterDefns();
IOdaDataSetDesign design = null;
if( session.getDataSetCacheManager( ).getCurrentDataSetDesign( ) instanceof IOdaDataSetDesign )
design = (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( );
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
// Ordering is important for the following operations. Column hints
// should be defined
// after custom fields are declared (since hints may be given to
// those custom fields).
// Column projection comes last because it needs hints and
// custom
// column information
addCustomFields( design.getPrimaryResultSetName( ), odaStatement );
addColumnHints( design.getPrimaryResultSetName( ), odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( design.getPrimaryResultSetName( ), this.projectedFields );
}
else if( canAccessResultSetByNumber( design ) )
{
addCustomFields( design.getPrimaryResultSetNumber( ), odaStatement );
addColumnHints( design.getPrimaryResultSetNumber( ), odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( design.getPrimaryResultSetNumber( ), this.projectedFields );
}
else
{
prepareColumns( );
}
}else
{
prepareColumns( );
}
//Here the "max rows" means the max number of rows that can fetch from data source.
odaStatement.setMaxRows( this.getRowFetchLimit( ) );
// If ODA can provide result metadata, get it now
try
{
resultMetadata = getMetaData( (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( ), odaStatement );
}
catch ( DataException e )
{
// Assume metadata not available at prepare time; ignore the exception
resultMetadata = null;
}
return this;
}
private boolean canAccessResultSetByName( IOdaDataSetDesign design )
throws DataException
{
return design.getPrimaryResultSetName( ) != null && odaStatement.supportsNamedResults( );
}
private boolean canAccessResultSetByNumber( IOdaDataSetDesign design )
throws DataException
{
return design.getPrimaryResultSetNumber( ) > 0 && odaStatement.supportsMultipleResultSets( );
}
private void prepareColumns( ) throws DataException
{
addCustomFields( odaStatement );
addColumnHints( odaStatement );
if ( this.projectedFields != null )
odaStatement.setColumnsProjection( this.projectedFields );
}
/**
*
* @param design
* @param odaStatement
* @return
* @throws DataException
*/
private IResultClass getMetaData( IOdaDataSetDesign design, PreparedStatement odaStatement ) throws DataException
{
IResultClass result = null;
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
try
{
result = odaStatement.getMetaData( design.getPrimaryResultSetName( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetName( ) );
}
}
else if ( canAccessResultSetByNumber( design ) )
{
try
{
result = odaStatement.getMetaData( design.getPrimaryResultSetNumber( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetNumber( ) );
}
}
}
if( result == null )
result = odaStatement.getMetaData();
if ( design != null )
{
List hintList = design.getResultSetHints( );
for ( int i = 0; i < hintList.size( ); i++ )
{
IColumnDefinition columnDefinition = (IColumnDefinition) hintList.get( i );
for ( int j = 1; j <= result.getFieldCount( ); j++ )
{
ResultFieldMetadata resultFieldMetadata = result.getFieldMetaData( j );
if ( columnDefinition.getColumnName( )
.equals( resultFieldMetadata.getName( ) ) )
{
resultFieldMetadata.setAlias( columnDefinition.getAlias( ) );
resultFieldMetadata.setAnalysisType( columnDefinition.getAnalysisType( ) );
resultFieldMetadata.setAnalysisColumn( columnDefinition.getAnalysisColumn( ) );
resultFieldMetadata.setIndexColumn( columnDefinition.isIndexColumn( ) );
resultFieldMetadata.setCompressedColumn( columnDefinition.isCompressedColumn( ) );
break;
}
}
}
}
return result;
}
/*
* Prepare a query specification with the property and input parameter values,
* for use by an ODA driver before IQuery#prepare.
*/
@SuppressWarnings("restriction")
private QuerySpecification populateQuerySpecification() throws DataException
{
if ( this.querySpecificaton == null )
{
QuerySpecHelper querySpecHelper = new QuerySpecHelper( dataSource.getDriverName( ),
queryType );
this.querySpecificaton = querySpecHelper.getFactoryHelper( )
.createQuerySpecification( );
}
// add custom properties
addPropertiesToQuerySpec( querySpecificaton );
// add parameter defns
addParametersToQuerySpec( querySpecificaton );
return querySpecificaton;
}
/**
* Adds custom properties to the QuerySpecification.
*/
@SuppressWarnings("restriction")
private void addPropertiesToQuerySpec( QuerySpecification querySpec )
{
if ( propNames == null )
return; // nothing to add
assert propValues != null;
Iterator it_name = propNames.iterator();
Iterator it_val = propValues.iterator();
while ( it_name.hasNext() )
{
assert it_val.hasNext();
String name = (String) it_name.next();
String val = (String) it_val.next();
querySpec.setProperty( name, val );
}
}
/**
* Adds custom properties to prepared oda statement;
* use the same properties already set in querySpec before prepare
*/
@SuppressWarnings("restriction")
private void addPropertiesToPreparedStatement( ) throws DataException
{
if( this.querySpecificaton == null || this.querySpecificaton.getProperties().isEmpty() )
return; // no properties to add
assert odaStatement != null;
Map<String,Object> propertyMap = this.querySpecificaton.getProperties();
Iterator<Entry<String, Object>> iter = propertyMap.entrySet().iterator();
while( iter.hasNext() )
{
Entry<String, Object> property = iter.next();
String value = ( property.getValue() == null ) ? null : property.getValue().toString();
odaStatement.setProperty( property.getKey(), value );
}
}
/**
* Adds input parameter values to the QuerySpecification.
*/
@SuppressWarnings("restriction")
private void addParametersToQuerySpec( QuerySpecification querySpec )
throws DataException
{
if ( this.parameterHints == null )
return; // nothing to add
// iterate thru the collection to add parameter hints
Iterator it = this.parameterHints.iterator( );
while ( it.hasNext( ) )
{
ParameterHint parameterHint = (ParameterHint) it.next();
//If the parameter is input parameter, add its value to query spec
if ( parameterHint.isInputMode( ) )
{
Object inputValue = getParameterInputValue( parameterHint );
QuerySpecHelper.setParameterValue( querySpec, parameterHint, inputValue );
}
}
}
/**
* Adds input and output parameter hints to odaStatement
*/
private void addParameterDefns() throws DataException
{
assert odaStatement!= null;
if ( this.parameterHints == null )
return; // nothing to add
// iterate thru the collection to add parameter hints
Iterator it = this.parameterHints.iterator( );
while ( it.hasNext( ) )
{
ParameterHint parameterHint = (ParameterHint) it.next();
odaStatement.addParameterHint( parameterHint );
//If the parameter is input parameter then add it to input value list.
if ( parameterHint.isInputMode( ) )
{
Object inputValue = getParameterInputValue( parameterHint );
if ( parameterHint.getPosition( ) <= 0 || odaStatement.supportsNamedParameter( ))
{
this.setInputParamValue( parameterHint.getName( ), parameterHint.getPosition( ),
inputValue );
}
else
{
this.setInputParamValue( parameterHint.getPosition( ),
inputValue );
}
}
}
this.setInputParameterBinding();
}
private Object getParameterInputValue( ParameterHint parameterHint )
throws DataException
{
assert parameterHint.isInputMode( );
Class paramHintDataType = parameterHint.getDataType();
// since a Date may have extended types,
// use the type of Date that is most effective for data conversion
if( paramHintDataType == Date.class )
paramHintDataType = parameterHint.getEffectiveDataType(
dataSource.getDriverName(), queryType );
Object inputValue = parameterHint.getDefaultInputValue( );
if ( inputValue != null )
{
if ( inputValue.getClass( ).isArray( ) )
{
//if multi-value type report parameter is linked with data set parameter
//only take the first provided value to pass it to data set
if ( Array.getLength( inputValue ) == 0 )
{
inputValue = null;
}
else
{
inputValue = Array.get( inputValue, 0 );
}
}
}
// neither IBlob nor IClob will be converted
if ( paramHintDataType != IBlob.class && paramHintDataType != IClob.class )
inputValue = convertToValue( inputValue,
paramHintDataType );
return inputValue;
}
/**
* @param inputParamName
* @param paramValue
* @throws DataException
*/
private void setInputParamValue( String inputParamName, int position, Object paramValue )
throws DataException
{
ParameterBinding pb = new ParameterBinding( inputParamName, position, paramValue );
getInputParamValues().add( pb );
}
/**
* @param inputParamPos
* @param paramValue
* @throws DataException
*/
private void setInputParamValue( int inputParamPos, Object paramValue )
throws DataException
{
ParameterBinding pb = new ParameterBinding( inputParamPos, paramValue );
getInputParamValues().add( pb );
}
/**
* Declares custom fields on Oda statement
*
* @param stmt
* @throws DataException
*/
private void addCustomFields( PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
private void addCustomFields( String rsetName, PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( rsetName, customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
private void addCustomFields( int rsetNumber, PreparedStatement stmt ) throws DataException
{
if ( this.customFields != null )
{
Iterator it = this.customFields.iterator( );
while ( it.hasNext( ) )
{
CustomField customField = (CustomField) it.next( );
stmt.declareCustomColumn( rsetNumber, customField.getName( ),
DataType.getClass( customField.getDataType() ) );
}
}
}
/**
* Adds Odi column hints to ODA statement
*
* @param stmt
* @throws DataException
*/
private void addColumnHints( PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( colHint );
}
}
private void addColumnHints( String rsetName, PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( rsetName, colHint );
}
}
private void addColumnHints( int rsetNumber, PreparedStatement stmt ) throws DataException
{
assert stmt != null;
if ( resultHints == null || resultHints.size() == 0 )
return;
Iterator it = resultHints.iterator();
while ( it.hasNext())
{
ColumnHint colHint = prepareOdiHint( (IDataSourceQuery.ResultFieldHint) it.next() );
stmt.addColumnHint( rsetNumber, colHint );
}
}
private ColumnHint prepareOdiHint( IDataSourceQuery.ResultFieldHint odiHint )
{
ColumnHint colHint = new ColumnHint( odiHint.getName() );
colHint.setAlias( odiHint.getAlias() );
if ( odiHint.getDataType( ) == DataType.ANY_TYPE )
colHint.setDataType( null );
else
colHint.setDataType( DataType.getClass( odiHint.getDataType( ) ) );
colHint.setNativeDataType( odiHint.getNativeDataType() );
if ( odiHint.getPosition() > 0 )
colHint.setPosition( odiHint.getPosition());
return colHint;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getResultClass()
*/
public IResultClass getResultClass()
{
// Note the return value can be null if resultMetadata was
// not available during prepare() time
return resultMetadata;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterMetaData()
*/
public Collection getParameterMetaData()
throws DataException
{
if ( odaStatement == null )
throw new DataException( ResourceConstants.QUERY_HAS_NOT_PREPARED );
Collection odaParamsInfo = odaStatement.getParameterMetaData();
if ( odaParamsInfo == null || odaParamsInfo.isEmpty() )
return null;
// iterates thru the most up-to-date collection, and
// wraps each of the odaconsumer parameter metadata object
ArrayList paramMetaDataList = new ArrayList( odaParamsInfo.size() );
Iterator odaParamMDIter = odaParamsInfo.iterator();
while ( odaParamMDIter.hasNext() )
{
org.eclipse.birt.data.engine.odaconsumer.ParameterMetaData odaMetaData =
(org.eclipse.birt.data.engine.odaconsumer.ParameterMetaData) odaParamMDIter.next();
paramMetaDataList.add( new ParameterMetaData( odaMetaData ) );
}
return paramMetaDataList;
}
/**
* Return the input parameter value list
*
* @return
*/
private Collection getInputParamValues()
{
if ( inputParamValues == null )
inputParamValues = new ArrayList();
return inputParamValues;
}
private IResultClass copyResultClass( IResultClass meta )
throws DataException
{
List<ResultFieldMetadata> list = new ArrayList<ResultFieldMetadata>( );
for ( int i = 1; i <= meta.getFieldCount( ); i++ )
{
if ( !meta.getFieldName( i ).equals( ExprMetaUtil.POS_NAME ) )
{
int m_driverPosition = meta.getFieldMetaData( i ).getDriverPosition( );
String m_name = meta.getFieldMetaData( i ).getName( );
String m_label = meta.getFieldMetaData( i ).getLabel( );
Class m_dataType = meta.getFieldMetaData( i ).getDataType( );
String m_nativeTypeName = meta.getFieldMetaData( i ).getNativeTypeName( );
boolean m_isCustom = meta.getFieldMetaData( i ).isCustom( );
Class m_driverProvidedDataType = meta.getFieldMetaData( i ).getDriverProvidedDataType( );
int m_analysisType = meta.getFieldMetaData( i ).getAnalysisType( );
String m_analysisColumn = meta.getFieldMetaData( i ).getAnalysisColumn( );
boolean m_indexColumn = meta.getFieldMetaData( i ).isIndexColumn( );
boolean m_compressedColumn = meta.getFieldMetaData( i ).isCompressedColumn( );
ResultFieldMetadata metadata = new ResultFieldMetadata( m_driverPosition, m_name,
m_label, m_dataType,
m_nativeTypeName,m_isCustom, m_analysisType, m_analysisColumn, m_indexColumn, m_compressedColumn );
metadata.setDriverProvidedDataType( m_driverProvidedDataType );
metadata.setAlias( meta.getFieldMetaData( i ).getAlias( ) );
list.add( metadata );
}
}
IResultClass resultClass = new ResultClass( list );
return resultClass;
}
private IResultClass mergeResultHint ( List modelResultHints, IResultClass meta )
{
if ( modelResultHints == null || modelResultHints.isEmpty( ) )
return meta;
IResultClass newResultClass;
try
{
newResultClass = copyResultClass( meta );
}
catch ( Exception ex )
{
return meta;
}
int count = newResultClass.getFieldCount( );
try
{
for ( int i = 1; i <= count; i++ )
{
String fieldName = newResultClass.getFieldName( i );
Class odaType = newResultClass.getFieldMetaData( i )
.getDataType( );
for ( int j = 0; j < modelResultHints.size( ); j++ )
{
if ( ( (IColumnDefinition) modelResultHints.get( j ) ).getColumnName( )
.equals( fieldName ) )
{
int apiType = ( (IColumnDefinition) modelResultHints.get( j ) ).getDataType( );
if ( DataTypeUtil.toApiDataType( odaType ) != apiType )
{
newResultClass.getFieldMetaData( i ).setDataType( DataType.getClass( apiType ) );
}
break;
}
}
}
}
catch ( Exception ex )
{
}
return newResultClass;
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#execute()
*/
public IResultIterator execute( IEventHandler eventHandler )
throws DataException
{
assert odaStatement != null;
IResultIterator ri = null;
this.setInputParameterBinding();
IOdaDataSetDesign design = null;
if( session.getDataSetCacheManager( ).getCurrentDataSetDesign( ) instanceof IOdaDataSetDesign )
design = (IOdaDataSetDesign)session.getDataSetCacheManager( ).getCurrentDataSetDesign( );
if ( session.getDataSetCacheManager( ).doesSaveToCache( ) )
{
int fetchRowLimit = 0;
if ( design != null )
{
fetchRowLimit = session.getDataSetCacheManager( )
.getCurrentDataSetDesign( )
.getRowFetchLimit( );
}
if ( fetchRowLimit != 0 )
{
odaStatement.setMaxRows( fetchRowLimit );
}
}
ICancellable queryCanceller = new OdaQueryCanceller( odaStatement, session.getStopSign() );
this.session.getCancelManager( ).register( queryCanceller );
odaStatement.execute( );
QueryContextVisitorUtil.populateEffectiveQueryText( qcv,
odaStatement.getEffectiveQueryText( ) );
if ( queryCanceller.collectException( ) != null )
{
if ( !( queryCanceller.collectException( ).getCause( ) instanceof UnsupportedOperationException ) )
throw queryCanceller.collectException( );
}
this.session.getCancelManager( ).deregister( queryCanceller );
ResultSet rs = null;
if ( design != null )
{
if ( canAccessResultSetByName( design ) )
{
try
{
rs = odaStatement.getResultSet( design.getPrimaryResultSetName( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetName( ) );
}
}
else if ( canAccessResultSetByNumber( design ) )
{
try
{
rs = odaStatement.getResultSet( design.getPrimaryResultSetNumber( ) );
}
catch ( DataException e )
{
throw new DataException( ResourceConstants.ERROR_HAPPEN_WHEN_RETRIEVE_RESULTSET,
design.getPrimaryResultSetNumber( ) );
}
}
}
if( rs == null )
{
rs = odaStatement.getResultSet( );
}
List modelResultHints = design.getResultSetHints( );
// If we did not get a result set metadata at prepare() time, get it now
if ( resultMetadata == null )
{
resultMetadata = rs.getMetaData( );
if ( resultMetadata == null )
throw new DataException( ResourceConstants.METADATA_NOT_AVAILABLE );
}
IResultClass newResultClass = mergeResultHint( modelResultHints , resultMetadata );
// Initialize CachedResultSet using the ODA result set
if ( session.getDataSetCacheManager( ).doesSaveToCache( ) == false )
{
if ( ( ( session.getEngineContext( ).getMode( ) == DataEngineContext.DIRECT_PRESENTATION || session.getEngineContext( )
.getMode( ) == DataEngineContext.MODE_GENERATION ) )
&& this.getQueryDefinition( ) instanceof IQueryDefinition )
{
IQueryDefinition queryDefn = (IQueryDefinition) this.getQueryDefinition( );
if ( QueryExecutionStrategyUtil.getQueryExecutionStrategy( queryDefn,
queryDefn.getDataSetName( ) == null
? null
: ( (DataEngineImpl) this.session.getEngine( ) ).getDataSetDesign( queryDefn.getDataSetName( ) ) ) == Strategy.Simple )
{
IResultIterator it = new SimpleResultSet( this,
rs,
newResultClass,
eventHandler );
eventHandler.handleEndOfDataSetProcess( it );
return it;
}
}
ri = new CachedResultSet( this,
newResultClass,
rs,
eventHandler,
session );
}
else
ri = new CachedResultSet( this,
newResultClass,
new DataSetToCache( rs, newResultClass, session ),
eventHandler, session );
if ( ri != null )
( (CachedResultSet) ri ).setOdaResultSet( rs );
return ri;
}
private static class OdaQueryCanceller implements ICancellable
{
private PreparedStatement statement;
private StopSign stop;
private DataException exception;
OdaQueryCanceller( PreparedStatement statement, StopSign stop )
{
this.statement = statement;
this.stop = stop;
}
/**
* Collect the exception throw during statement execution.
*
* @return
*/
public DataException collectException()
{
return this.exception;
}
/**
*
*/
public void cancel( )
{
try
{
this.statement.cancel( );
}
catch ( DataException e )
{
this.exception = e;
}
}
/**
*
*/
public boolean doCancel( )
{
return this.stop.isStopped( );
}
}
/**
* set input parameter bindings
*/
private void setInputParameterBinding() throws DataException
{
assert odaStatement!= null;
// set input parameter bindings
Iterator inputParamValueslist = getInputParamValues().iterator( );
while ( inputParamValueslist.hasNext( ) )
{
ParameterBinding paramBind = (ParameterBinding) inputParamValueslist.next( );
if ( paramBind.getPosition( ) <= 0 || odaStatement.supportsNamedParameter( ))
{
try
{
odaStatement.setParameterValue( paramBind.getName( ),
paramBind.getValue( ) );
}
catch ( DataException e )
{
if ( paramBind.getPosition( ) <= 0 )
{
throw e;
}
else
{
odaStatement.setParameterValue( paramBind.getPosition( ),
paramBind.getValue( ) );
}
}
}
else
{
odaStatement.setParameterValue( paramBind.getPosition( ),
paramBind.getValue() );
}
}
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterValue(int)
*/
public Object getOutputParameterValue( int index ) throws DataException
{
assert odaStatement != null;
int newIndex = getCorrectParamIndex( index );
return odaStatement.getParameterValue( newIndex );
}
/*
* @see org.eclipse.birt.data.engine.odi.IPreparedDSQuery#getParameterValue(java.lang.String)
*/
public Object getOutputParameterValue( String name ) throws DataException
{
assert odaStatement != null;
checkOutputParamNameValid( name );
return odaStatement.getParameterValue( name );
}
/**
* In oda layer, it does not differentiate the value retrievation of input
* parameter value and ouput parameter value. They will be put in a same
* sequence list. However, in odi layer, we need to clearly distinguish them
* since only retrieving output parameter is suppored and it should be based
* on its own output parameter index. Therefore, this method will do such a
* conversion from the output parameter index to the parameter index.
*
* @param index based on output parameter order
* @return index based on the whole parameters order
* @throws DataException
*/
private int getCorrectParamIndex( int index ) throws DataException
{
if ( index <= 0 )
throw new DataException( ResourceConstants.INVALID_OUTPUT_PARAMETER_INDEX, Integer.valueOf( index ) );
int newIndex = 0; // 1-based
int curOutputIndex = 0; // 1-based
Collection collection = getParameterMetaData( );
if ( collection != null )
{
Iterator it = collection.iterator( );
while ( it.hasNext( ) )
{
newIndex++;
IParameterMetaData metaData = (IParameterMetaData) it.next( );
if ( metaData.isOutputMode( ).booleanValue( ) == true )
{
curOutputIndex++;
if ( curOutputIndex == index )
break;
}
}
}
if ( curOutputIndex < index )
throw new DataException( ResourceConstants.OUTPUT_PARAMETER_OUT_OF_BOUND,
Integer.valueOf( index ) );
return newIndex;
}
/**
* Validate the name of output parameter
*
* @param name
* @throws DataException
*/
private void checkOutputParamNameValid( String name ) throws DataException
{
assert name != null;
boolean isValid = false;
Collection collection = getParameterMetaData( );
if ( collection != null )
{
Iterator it = collection.iterator( );
while ( it.hasNext( ) )
{
IParameterMetaData metaData = (IParameterMetaData) it.next( );
String paramName = metaData.getName( );
if ( paramName.equals( name ) )
{
isValid = metaData.isOutputMode( ).booleanValue( );
break;
}
}
}
if ( isValid == false )
throw new DataException( ResourceConstants.INVALID_OUTPUT_PARAMETER_NAME, name );
}
/*
* @see org.eclipse.birt.data.engine.odi.IQuery#close()
*/
public void close()
{
if ( odaStatement != null )
{
this.dataSource.closeStatement( odaStatement );
odaStatement = null;
}
this.dataSource = null;
// TODO: close all CachedResultSets created by us
}
/**
* convert the String value to Object according to it's datatype.
*
* @param inputValue
* @param type
* @return
* @throws DataException
*/
private static Object convertToValue( Object inputValue, Class typeClass )
throws DataException
{
try
{
return DataTypeUtil.convert( inputValue, typeClass);
}
catch ( Exception ex )
{
throw new DataException( ResourceConstants.CANNOT_CONVERT_PARAMETER_TYPE,
ex,
new Object[]{
inputValue, typeClass
} );
}
}
public void setQuerySpecification( QuerySpecification spec )
{
this.querySpecificaton = spec;
}
}
|
CheckIn:Fix issue Project 1292: Failed to generate .data if computed column set index[35342]
|
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/DataSourceQuery.java
|
CheckIn:Fix issue Project 1292: Failed to generate .data if computed column set index[35342]
|
|
Java
|
epl-1.0
|
ba61346e8a22993c4645253d60d27b12d80c5bf4
| 0
|
mareknovotny/windup,johnsteele/windup,lincolnthree/windup,sgilda/windup,mbriskar/windup,johnsteele/windup,windup/windup,mareknovotny/windup,Maarc/windup,windup/windup,lincolnthree/windup,windup/windup-legacy,jsight/windup,d-s/windup,Ladicek/windup,sgilda/windup,mareknovotny/windup,Ladicek/windup,windup/windup-sample-apps,bradsdavis/windup,bradsdavis/windup,mareknovotny/windup,OndraZizka/windup,windup/windup-legacy,johnsteele/windup,jsight/windup,d-s/windup,OndraZizka/windup,d-s/windup,sgilda/windup,windup/windup-legacy,jsight/windup,Ladicek/windup,Maarc/windup,mbriskar/windup,windup/windup,bradsdavis/windup,windup/windup,sgilda/windup,d-s/windup,lincolnthree/windup,jsight/windup,mbriskar/windup,Ladicek/windup,Maarc/windup,OndraZizka/windup,Maarc/windup,johnsteele/windup,lincolnthree/windup,mbriskar/windup,OndraZizka/windup
|
package org.jboss.windup.engine.provider;
import com.google.common.collect.Lists;
import java.util.List;
import javax.inject.Inject;
import org.jboss.forge.furnace.services.Imported;
import org.jboss.windup.engine.visitor.GraphVisitor;
/**
* Gets the GraphVisitor instances from Furnace and provides a sorted copy of that list.
*/
public class VisitorChainProvider
{
@Inject
private Imported<GraphVisitor> visitors;
/**
* Returns a sorted copy of GraphVisitor instances list from Furnace.
*/
public List<GraphVisitor> getSortedVisitorChain()
{
List<GraphVisitor> chain = Lists.newArrayList(this.visitors);
chain = new GraphVisitorSorter().sort(chain);
return chain;
}
public void disposeVisitors(List<GraphVisitor> visitorsToDispose)
{
for (GraphVisitor v : visitorsToDispose)
{
this.visitors.release(v);
}
}
}
|
engine/rules/impl/src/main/java/org/jboss/windup/engine/provider/VisitorChainProvider.java
|
package org.jboss.windup.engine.provider;
import com.google.common.collect.Lists;
import java.util.List;
import javax.inject.Inject;
import org.jboss.forge.furnace.services.Imported;
import org.jboss.windup.engine.visitor.GraphVisitor;
/**
* Gets the GraphVisitor instances from Furnace and provides a sorted copy of that list.
*/
public class VisitorChainProvider
{
@Inject
private Imported<GraphVisitor> visitors;
/**
* Returns a sorted copy of GraphVisitor instances list from Forge.
*/
public List<GraphVisitor> getSortedVisitorChain()
{
List<GraphVisitor> chain = Lists.newArrayList(this.visitors);
chain = new GraphVisitorSorter().sort(chain);
return chain;
}
public void disposeVisitors(List<GraphVisitor> visitorsToDispose)
{
for (GraphVisitor v : visitorsToDispose)
{
this.visitors.release(v);
}
}
}
|
Changed name from "Forge" to "Furnace"
|
engine/rules/impl/src/main/java/org/jboss/windup/engine/provider/VisitorChainProvider.java
|
Changed name from "Forge" to "Furnace"
|
|
Java
|
epl-1.0
|
9ef98ba8d32036591bb918b457906703ef1a1469
| 0
|
debrief/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief
|
/*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.mwc.debrief.track_shift.views;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.Vector;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.DefaultXYItemRenderer;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.TimeSeriesDataItem;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.TextAnchor;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackDataListener;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackShiftListener;
import org.mwc.cmap.core.DataTypes.TrackData.TrackManager;
import org.mwc.cmap.core.property_support.EditableWrapper;
import org.mwc.cmap.core.ui_support.PartMonitor;
import org.mwc.debrief.core.actions.DragSegment;
import org.mwc.debrief.core.editors.PlotOutlinePage;
import org.mwc.debrief.track_shift.Activator;
import org.mwc.debrief.track_shift.controls.ZoneChart;
import org.mwc.debrief.track_shift.controls.ZoneChart.Zone;
import org.mwc.debrief.track_shift.controls.ZoneChart.ZoneSlicer;
import org.mwc.debrief.track_shift.zig_detector.LegOfData;
import org.mwc.debrief.track_shift.zig_detector.OwnshipLegDetector;
import org.mwc.debrief.track_shift.zig_detector.Precision;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import MWC.GUI.Editable;
import MWC.GUI.ErrorLogger;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.Layers.DataListener;
import MWC.GUI.JFreeChart.ColourStandardXYItemRenderer;
import MWC.GUI.JFreeChart.DateAxisEditor;
import MWC.GUI.Properties.DebriefColors;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WatchableList;
/**
*/
abstract public class BaseStackedDotsView extends ViewPart implements
ErrorLogger
{
private static final String SHOW_DOT_PLOT = "SHOW_DOT_PLOT";
private static final String SHOW_OVERVIEW = "SHOW_OVERVIEW";
private static final String SHOW_LINE_PLOT = "SHOW_LINE_PLOT";
private static final String SELECT_ON_CLICK = "SELECT_ON_CLICK";
private static final String SHOW_ONLY_VIS = "ONLY_SHOW_VIS";
/**
* helper application to help track creation/activation of new plots
*/
private PartMonitor _myPartMonitor;
/**
* the errors we're plotting
*/
XYPlot _dotPlot;
/**
* and the actual values
*
*/
XYPlot _linePlot;
/**
* and the actual values
*
*/
XYPlot _targetOverviewPlot;
/**
* declare the tgt course dataset, we need to give it to the renderer
*
*/
final TimeSeriesCollection _targetCourseSeries = new TimeSeriesCollection();
/**
* declare the tgt speed dataset, we need to give it to the renderer
*
*/
final TimeSeriesCollection _targetSpeedSeries = new TimeSeriesCollection();
/**
* legacy helper class
*/
final StackedDotHelper _myHelper;
/**
* our track-data provider
*/
protected TrackManager _theTrackDataListener;
/**
* our listener for tracks being shifted...
*/
protected TrackShiftListener _myShiftListener;
/**
* buttons for which plots to show
*
*/
protected Action _showLinePlot;
protected Action _showDotPlot;
protected Action _showTargetOverview;
/**
* flag indicating whether we should only show stacked dots for visible fixes
*/
Action _onlyVisible;
/**
* flag indicating whether we should select the clicked item in the Outline View
*/
Action _selectOnClick;
/**
* our layers listener...
*/
protected DataListener _layersListener;
/**
* the set of layers we're currently listening to
*/
protected Layers _ourLayersSubject;
protected TrackDataProvider _myTrackDataProvider;
ChartComposite _holder;
JFreeChart _myChart;
private Vector<Action> _customActions;
protected Action _autoResize;
protected Action _showSlices;
private CombinedDomainXYPlot _combined;
protected TrackDataListener _myTrackDataListener;
/**
* does our output need bearing in the data?
*
*/
private final boolean _needBrg;
/**
* does our output need frequency in the data?
*
*/
private final boolean _needFreq;
// private Action _magicBtn;
protected Vector<ISelectionProvider> _selProviders;
protected ISelectionChangedListener _mySelListener;
protected Vector<DraggableItem> _draggableSelection;
protected boolean _itemSelectedPending = false;
private ZoneChart ownshipZoneChart;
private ZoneChart targetZoneChart;
protected TimeSeries ownshipCourseSeries;
protected TimeSeries targetBearingSeries;
/**
*
* @param needBrg
* if the algorithm needs bearing data
* @param needFreq
* if the agorithm needs frequency data
*/
protected BaseStackedDotsView(final boolean needBrg, final boolean needFreq)
{
_myHelper = new StackedDotHelper();
_needBrg = needBrg;
_needFreq = needFreq;
// create the actions - the 'centre-y axis' action may get called before
// the
// interface is shown
makeActions();
}
abstract protected String getUnits();
abstract protected String getType();
abstract protected void updateData(boolean updateDoublets);
private void contributeToActionBars()
{
final IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
protected void fillLocalToolBar(final IToolBarManager toolBarManager)
{
// fit to window
toolBarManager.add(_autoResize);
toolBarManager.add(_onlyVisible);
toolBarManager.add(_selectOnClick);
toolBarManager.add(_showLinePlot);
toolBarManager.add(_showDotPlot);
toolBarManager.add(_showTargetOverview);
toolBarManager.add(_showSlices);
addExtras(toolBarManager);
// and a separator
toolBarManager.add(new Separator());
final Vector<Action> actions = DragSegment.getDragModes();
for (final Iterator<Action> iterator = actions.iterator(); iterator
.hasNext();)
{
final Action action = iterator.next();
toolBarManager.add(action);
}
}
/**
* additional method, to allow extra items to be added before the segment modes
*
* @param toolBarManager
*/
protected void addExtras(IToolBarManager toolBarManager)
{
}
/**
* This is a callback that will allow us to create the viewer and initialize it.
*/
@SuppressWarnings("deprecation")
@Override
public void createPartControl(final Composite parent)
{
parent.setLayout(new FillLayout(SWT.VERTICAL));
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
_holder =
new ChartComposite(sashForm, SWT.NONE, null, 400, 600, 300, 200, 1800,
1800, true, true, true, true, true, true)
{
@Override
public void mouseUp(MouseEvent event)
{
super.mouseUp(event);
JFreeChart c = getChart();
if (c != null)
{
c.setNotify(true); // force redraw
}
}
};
// hey - now create the stacked plot!
createStackedPlot();
// /////////////////////////////////////////
// ok - listen out for changes in the view
// /////////////////////////////////////////
_selProviders = new Vector<ISelectionProvider>();
_mySelListener = new ISelectionChangedListener()
{
@Override
public void selectionChanged(final SelectionChangedEvent event)
{
final ISelection sel = event.getSelection();
final Vector<DraggableItem> dragees = new Vector<DraggableItem>();
if (sel instanceof StructuredSelection)
{
final StructuredSelection str = (StructuredSelection) sel;
final Iterator<?> iter = str.iterator();
while (iter.hasNext())
{
final Object object = (Object) iter.next();
if (object instanceof EditableWrapper)
{
final EditableWrapper ew = (EditableWrapper) object;
final Editable item = ew.getEditable();
if (item instanceof DraggableItem)
{
dragees.add((DraggableItem) item);
}
}
else
{
return;
}
}
// ok, we've just got draggable items - override the current
// item
_draggableSelection = dragees;
}
}
};
// sort out the part monitor
_myPartMonitor =
new PartMonitor(getSite().getWorkbenchWindow().getPartService());
// now start listening out for people's parts
watchMyParts();
// put the actions in the UI
contributeToActionBars();
// we will also listen out for zone changes
@SuppressWarnings("unused")
ZoneChart.ZoneListener ownshipListener = getOwnshipListener();
@SuppressWarnings("unused")
ZoneChart.ZoneListener targetListener = getTargetListener();
Zone[] osZones =
new ZoneChart.Zone[]
{
// new ZoneChart.Zone(new Date("2016/10/10 11:05").getTime(),
// new Date("2016/10/10 11:42").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:25").getTime(),
// new Date("2016/10/10 12:40").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:55:01").getTime(),
// new Date("2016/10/10 13:23:12").getTime())
};
long[] osTimeValues = new long[]{};
long[] osAngleValues = new long[]{};
// create the zone charts
// TODO: pending
ZoneChart.ColorProvider blueProv = new ZoneChart.ColorProvider()
{
@Override
public Color getColorFor(Zone zone)
{
return DebriefColors.BLUE;
}
};
// put the courses into a TimeSeries
ownshipCourseSeries = new TimeSeries("Ownship course");
ZoneSlicer ownshipLegSlicer = new ZoneSlicer(){
@Override
public ArrayList<Zone> performSlicing()
{
return sliceOwnship(ownshipCourseSeries);
}};
ownshipZoneChart =
ZoneChart.create("Ownship Legs", "Course", sashForm, osZones, ownshipCourseSeries,
osTimeValues, blueProv, DebriefColors.BLUE, ownshipLegSlicer );
// assign the listeners
// TODO: pending
Zone[] tgtZones =
new ZoneChart.Zone[]
{
// new ZoneChart.Zone(new Date("2016/10/10 10:17").getTime(),
// new Date("2016/10/10 10:40").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:02:01").getTime(),
// new Date("2016/10/10 12:23:12").getTime())
};
long[] tgtTimeValues =
new long[]{};
long[] tgtAngleValues = new long[]
{};
ZoneChart.ColorProvider randomProv = new ZoneChart.ColorProvider()
{
@Override
public Color getColorFor(Zone zone)
{
Random random = new Random();
final float hue = random.nextFloat();
// Saturation between 0.1 and 0.3
final float saturation = (random.nextInt(2000) + 7000) / 10000f;
final float luminance = 0.9f;
final Color color = Color.getHSBColor(hue, saturation, luminance);
return color;
}
};
// put the bearings into a TimeSeries
targetBearingSeries = new TimeSeries("Bearing");
targetZoneChart =
ZoneChart.create("Target Legs", "Bearing", sashForm, tgtZones,
targetBearingSeries, tgtTimeValues, randomProv, DebriefColors.RED, null);
// and set the proportions of space allowed
sashForm.setWeights(new int[]{4,1,1});
sashForm.setBackground(sashForm.getDisplay().getSystemColor( SWT.COLOR_GRAY));
}
protected ArrayList<Zone> sliceOwnship(TimeSeries osCourse)
{
OwnshipLegDetector detector = new OwnshipLegDetector();
final int num = osCourse.getItemCount();
long[] times = new long[num];
double[] speeds = new double[num];
double[] courses = new double[num];
for(int ctr = 0;ctr<num;ctr++)
{
TimeSeriesDataItem thisItem = osCourse.getDataItem(ctr);
FixedMillisecond thisM = (FixedMillisecond) thisItem.getPeriod();
times[ctr] = thisM.getMiddleMillisecond();
speeds[ctr] = 0;
courses[ctr] = (Double) thisItem.getValue();
}
List<LegOfData> legs = detector.identifyOwnshipLegs(times, speeds, courses, 5, Precision.LOW);
ArrayList<Zone> res = new ArrayList<Zone>();
for(LegOfData leg : legs)
{
Zone newZone = new Zone(leg.getStart(), leg.getEnd());
res.add(newZone);
}
return res;
}
private ZoneChart.ZoneListener getOwnshipListener()
{
// TODO: fire the ownship legs to the target zig generator
return new ZoneChart.ZoneAdapter();
}
private ZoneChart.ZoneListener getTargetListener()
{
// TODO reflect the new target legs on the bearing residuals
return new ZoneChart.ZoneAdapter();
}
/**
* method to create a working plot (to contain our data)
*
* @return the chart, in it's own panel
*/
@SuppressWarnings("deprecation")
protected void createStackedPlot()
{
// first create the x (time) axis
final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss");
_df.setTimeZone(TimeZone.getTimeZone("GMT"));
final DateAxis xAxis = new CachedTickDateAxis("");
xAxis.setDateFormatOverride(_df);
Font tickLabelFont = new Font("Courier", Font.PLAIN, 13);
xAxis.setTickLabelFont(tickLabelFont);
xAxis.setTickLabelPaint(Color.BLACK);
xAxis.setStandardTickUnits(DateAxisEditor
.createStandardDateTickUnitsAsTickUnits());
xAxis.setAutoTickUnitSelection(true);
// create the special stepper plot
_dotPlot = new XYPlot();
NumberAxis errorAxis = new NumberAxis("Error (" + getUnits() + ")");
Font axisLabelFont = new Font("Courier", Font.PLAIN, 16);
errorAxis.setLabelFont(axisLabelFont);
errorAxis.setTickLabelFont(tickLabelFont);
_dotPlot.setRangeAxis(errorAxis);
_dotPlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
_dotPlot
.setRenderer(new ColourStandardXYItemRenderer(null, null, _dotPlot));
_dotPlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_dotPlot.setRangeGridlineStroke(new BasicStroke(2));
_dotPlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_dotPlot.setDomainGridlineStroke(new BasicStroke(2));
// now try to do add a zero marker on the error bar
final Paint thePaint = Color.DARK_GRAY;
final Stroke theStroke = new BasicStroke(3);
final ValueMarker zeroMarker = new ValueMarker(0.0, thePaint, theStroke);
_dotPlot.addRangeMarker(zeroMarker);
_linePlot = new XYPlot();
final NumberAxis absBrgAxis =
new NumberAxis("Absolute (" + getUnits() + ")");
absBrgAxis.setLabelFont(axisLabelFont);
absBrgAxis.setTickLabelFont(tickLabelFont);
_linePlot.setRangeAxis(absBrgAxis);
absBrgAxis.setAutoRangeIncludesZero(false);
_linePlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
final DefaultXYItemRenderer lineRend =
new ColourStandardXYItemRenderer(null, null, _linePlot);
lineRend.setPaint(Color.DARK_GRAY);
_linePlot.setRenderer(lineRend);
_linePlot.setDomainCrosshairVisible(true);
_linePlot.setRangeCrosshairVisible(true);
_linePlot.setDomainCrosshairPaint(Color.GRAY);
_linePlot.setRangeCrosshairPaint(Color.GRAY);
_linePlot.setDomainCrosshairStroke(new BasicStroke(3.0f));
_linePlot.setRangeCrosshairStroke(new BasicStroke(3.0f));
_linePlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_linePlot.setRangeGridlineStroke(new BasicStroke(2));
_linePlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_linePlot.setDomainGridlineStroke(new BasicStroke(2));
_targetOverviewPlot = new XYPlot();
final NumberAxis overviewCourse = new NumberAxis("Course (\u00b0)")
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public NumberTickUnit getTickUnit()
{
final NumberTickUnit tickUnit = super.getTickUnit();
if (tickUnit.getSize() < 15)
{
return tickUnit;
}
else if (tickUnit.getSize() < 45)
{
return new NumberTickUnit(20);
}
else if (tickUnit.getSize() < 90)
{
return new NumberTickUnit(30);
}
else if (tickUnit.getSize() < 180)
{
return new NumberTickUnit(45);
}
else
{
return new NumberTickUnit(90);
}
}
};
overviewCourse.setUpperMargin(0);
overviewCourse.setLabelFont(axisLabelFont);
overviewCourse.setTickLabelFont(tickLabelFont);
final NumberAxis overviewSpeed = new NumberAxis("Speed (Kts)");
overviewSpeed.setLabelFont(axisLabelFont);
overviewSpeed.setTickLabelFont(tickLabelFont);
_targetOverviewPlot.setRangeAxis(overviewCourse);
_targetOverviewPlot.setRangeAxis(1, overviewSpeed);
absBrgAxis.setAutoRangeIncludesZero(false);
_targetOverviewPlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
final DefaultXYItemRenderer overviewCourseRenderer =
new WrappingResidualRenderer(null, null, _targetCourseSeries, 0, 360);
overviewCourseRenderer.setSeriesPaint(0, DebriefColors.RED.brighter());
overviewCourseRenderer.setSeriesPaint(1, DebriefColors.BLUE);
overviewCourseRenderer.setSeriesShape(0, new Ellipse2D.Double(-4.0, -4.0,
8.0, 8.0));
overviewCourseRenderer.setSeriesShapesVisible(1, false);
overviewCourseRenderer.setSeriesStroke(0, new BasicStroke(2f));
overviewCourseRenderer.setSeriesStroke(1, new BasicStroke(2f));
final DefaultXYItemRenderer overviewSpeedRenderer =
new ResidualXYItemRenderer(null, null, _targetSpeedSeries);
overviewSpeedRenderer.setPaint(DebriefColors.RED.darker());
overviewSpeedRenderer.setSeriesShape(0, new Rectangle2D.Double(-4.0, -4.0,
8.0, 8.0));
overviewSpeedRenderer.setSeriesStroke(0, new BasicStroke(2f));
_targetOverviewPlot.setRenderer(0, overviewCourseRenderer);
_targetOverviewPlot.setRenderer(1, overviewSpeedRenderer);
_targetOverviewPlot.mapDatasetToRangeAxis(0, 0);
_targetOverviewPlot.mapDatasetToRangeAxis(1, 1);
_targetOverviewPlot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
_targetOverviewPlot.setRangeAxisLocation(1, AxisLocation.TOP_OR_LEFT);
_targetOverviewPlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_targetOverviewPlot.setRangeGridlineStroke(new BasicStroke(2));
_targetOverviewPlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_targetOverviewPlot.setDomainGridlineStroke(new BasicStroke(2));
// and the plot object to display the cross hair value
final XYTextAnnotation annot = new XYTextAnnotation("-----", 2, 2);
annot.setTextAnchor(TextAnchor.TOP_LEFT);
Font annotationFont = new Font("Courier", Font.BOLD, 16);
annot.setFont(annotationFont);
annot.setPaint(Color.DARK_GRAY);
annot.setBackgroundPaint(Color.white);
_linePlot.addAnnotation(annot);
// give them a high contrast backdrop
_dotPlot.setBackgroundPaint(Color.white);
_linePlot.setBackgroundPaint(Color.white);
_targetOverviewPlot.setBackgroundPaint(Color.white);
// set the y axes to autocalculate
_dotPlot.getRangeAxis().setAutoRange(true);
_linePlot.getRangeAxis().setAutoRange(true);
_targetOverviewPlot.getRangeAxis().setAutoRange(true);
_combined = new CombinedDomainXYPlot(xAxis);
_combined.add(_linePlot);
_combined.add(_dotPlot);
_combined.add(_targetOverviewPlot);
_combined.setOrientation(PlotOrientation.HORIZONTAL);
// put the plot into a chart
_myChart = new JFreeChart(null, null, _combined, true);
final LegendItemSource[] sources =
{_linePlot, _targetOverviewPlot};
_myChart.getLegend().setSources(sources);
_myChart.addProgressListener(new ChartProgressListener()
{
public void chartProgress(final ChartProgressEvent cpe)
{
if (cpe.getType() != ChartProgressEvent.DRAWING_FINISHED)
return;
// is hte line plot visible?
if (!_showLinePlot.isChecked())
return;
// double-check our label is still in the right place
final double xVal = _linePlot.getRangeAxis().getLowerBound();
final double yVal = _linePlot.getDomainAxis().getUpperBound();
boolean annotChanged = false;
if (annot.getX() != yVal)
{
annot.setX(yVal);
annotChanged = true;
}
if (annot.getY() != xVal)
{
annot.setY(xVal);
annotChanged = true;
}
// and write the text
final String numA =
MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(_linePlot.getRangeCrosshairValue());
final Date newDate =
new Date((long) _linePlot.getDomainCrosshairValue());
final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss");
_df.setTimeZone(TimeZone.getTimeZone("GMT"));
final String dateVal = _df.format(newDate);
final String theMessage = " [" + dateVal + "," + numA + "]";
if (!theMessage.equals(annot.getText()))
{
annot.setText(theMessage);
annotChanged = true;
}
if (annotChanged)
{
_linePlot.removeAnnotation(annot);
_linePlot.addAnnotation(annot);
}
// ok, do we also have a selection event pending
if (_itemSelectedPending && _selectOnClick.isChecked())
{
_itemSelectedPending = false;
showFixAtThisTime(newDate);
}
}
});
// and insert into the panel
_holder.setChart(_myChart);
_holder.addChartMouseListener(new ChartMouseListener()
{
@Override
public void chartMouseMoved(ChartMouseEvent arg0)
{
}
@Override
public void chartMouseClicked(ChartMouseEvent arg0)
{
// ok, remember it was clicked
_itemSelectedPending = true;
}
});
// do a little tidying to reflect the memento settings
if (!_showLinePlot.isChecked())
_combined.remove(_linePlot);
if (!_showDotPlot.isChecked() && _showLinePlot.isChecked())
_combined.remove(_dotPlot);
if (!_showTargetOverview.isChecked())
_combined.remove(_targetOverviewPlot);
}
/**
* view is closing, shut down, preserve life
*/
@Override
public void dispose()
{
// get parent to ditch itself
super.dispose();
// ditch the actions
if (_customActions != null)
_customActions.removeAllElements();
// are we listening to any layers?
if (_ourLayersSubject != null)
_ourLayersSubject.removeDataReformattedListener(_layersListener);
if (_theTrackDataListener != null)
{
_theTrackDataListener.removeTrackShiftListener(_myShiftListener);
_theTrackDataListener.removeTrackDataListener(_myTrackDataListener);
}
// stop the part monitor
_myPartMonitor.ditch();
}
protected void fillLocalPullDown(final IMenuManager manager)
{
manager.add(_onlyVisible);
manager.add(_selectOnClick);
// and the help link
manager.add(new Separator());
manager.add(CorePlugin.createOpenHelpAction(
"org.mwc.debrief.help.TrackShifting", null, this));
}
protected void makeActions()
{
_autoResize = new Action("Auto resize", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
final boolean val = _autoResize.isChecked();
if (_showLinePlot.isChecked())
{
// ok - redraw the plot we may have changed the axis
// centreing
_linePlot.getRangeAxis().setAutoRange(val);
_linePlot.getDomainAxis().setAutoRange(val);
}
if (_showDotPlot.isChecked())
{
_dotPlot.getRangeAxis().setAutoRange(val);
_dotPlot.getDomainAxis().setAutoRange(val);
}
}
};
_autoResize.setChecked(true);
_autoResize.setToolTipText("Keep plot sized to show all data");
_autoResize.setImageDescriptor(CorePlugin
.getImageDescriptor("icons/24/fit_to_win.png"));
_showSlices = new Action("Show slicing charts", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showSlices.isChecked())
{
// show the charts
// hide the charts
ownshipZoneChart.setVisible(true);
targetZoneChart.setVisible(true);
ownshipZoneChart.getParent().layout(true);
}
else
{
// hide the charts
ownshipZoneChart.setVisible(false);
targetZoneChart.setVisible(false);
ownshipZoneChart.getParent().layout(true);
}
}
};
_showSlices.setChecked(true);
_showSlices.setToolTipText("Show the slicing graphs");
_showSlices.setImageDescriptor(CorePlugin
.getImageDescriptor("icons/24/GanttBars.png"));
_showLinePlot = new Action("Actuals plot", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showLinePlot.isChecked())
{
_combined.remove(_linePlot);
_combined.remove(_dotPlot);
_combined.add(_linePlot);
if (_showDotPlot.isChecked())
_combined.add(_dotPlot);
}
else
{
if (_combined.getSubplots().size() > 1)
_combined.remove(_linePlot);
}
}
};
_showLinePlot.setChecked(true);
_showLinePlot.setToolTipText("Show the actuals plot");
_showLinePlot.setImageDescriptor(Activator
.getImageDescriptor("icons/24/stacked_lines.png"));
_showDotPlot = new Action("Error plot", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showDotPlot.isChecked())
{
_combined.remove(_linePlot);
_combined.remove(_dotPlot);
if (_showLinePlot.isChecked())
_combined.add(_linePlot);
_combined.add(_dotPlot);
}
else
{
if (_combined.getSubplots().size() > 1)
_combined.remove(_dotPlot);
}
}
};
_showDotPlot.setChecked(true);
_showDotPlot.setToolTipText("Show the error plot");
_showDotPlot.setImageDescriptor(Activator
.getImageDescriptor("icons/24/stacked_dots.png"));
_showTargetOverview = new Action("Target Overview", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showTargetOverview.isChecked())
{
_combined.add(_targetOverviewPlot);
}
else
{
_combined.remove(_targetOverviewPlot);
}
}
};
_showTargetOverview.setChecked(true);
_showTargetOverview.setToolTipText("Show the overview plot");
_showTargetOverview.setImageDescriptor(Activator
.getImageDescriptor("icons/24/tgt_overview.png"));
// get an error logger
final ErrorLogger logger = this;
_onlyVisible =
new Action("Only draw dots for visible data points",
IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
// set the title, so there's something useful in there
_myChart.setTitle("");
// we need to get a fresh set of data pairs - the number may
// have
// changed
_myHelper.initialise(_theTrackDataListener, true, _onlyVisible
.isChecked(), _holder, logger, getType(), _needBrg, _needFreq);
// and a new plot please
updateStackedDots(true);
}
};
_onlyVisible.setText("Only plot visible data");
_onlyVisible.setChecked(true);
_onlyVisible.setToolTipText("Only draw dots for visible data points");
_onlyVisible.setImageDescriptor(Activator
.getImageDescriptor("icons/24/reveal.png"));
_selectOnClick =
new Action("Select TMA Fix in outline when clicked",
IAction.AS_CHECK_BOX)
{
};
_selectOnClick.setChecked(true);
_selectOnClick
.setToolTipText("Reveal the respective TMA Fix when an error clicked on plot");
_selectOnClick.setImageDescriptor(CorePlugin
.getImageDescriptor("icons/24/outline.png"));
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus()
{
}
public void logError(final int statusCode, final String string,
final Exception object)
{
// somehow, put the message into the UI
_myChart.setTitle(string);
// is it a fail status
if (statusCode != Status.OK)
{
// and store the problem into the log
CorePlugin.logError(statusCode, string, object);
// also ditch the data in the plots - to blank them out
clearPlots();
}
}
@Override
public void logStack(int status, String text)
{
CorePlugin.logError(status, text, null, true);
}
/**
* the track has been moved, update the dots
*/
void clearPlots()
{
if (Thread.currentThread() == Display.getDefault().getThread())
{
// it's ok we're already in a display thread
_dotPlot.setDataset(null);
_linePlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
else
{
// we're not in the display thread - make it so!
Display.getDefault().syncExec(new Runnable()
{
public void run()
{
_dotPlot.setDataset(null);
_linePlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
});
}
}
/**
* the track has been moved, update the dots
*/
void updateStackedDots(final boolean updateDoublets)
{
if (Thread.currentThread() == Display.getDefault().getThread())
{
// it's ok we're already in a display thread
wrappedUpdateStackedDots(updateDoublets);
}
else
{
// we're not in the display thread - make it so!
Display.getDefault().syncExec(new Runnable()
{
public void run()
{
// update the current datasets
wrappedUpdateStackedDots(updateDoublets);
}
});
}
}
/**
* the track has been moved, update the dots
*/
void wrappedUpdateStackedDots(final boolean updateDoublets)
{
// update the current datasets
updateData(updateDoublets);
// right, are we updating the range data?
if (_autoResize.isChecked())
{
if (_showDotPlot.isChecked())
{
_dotPlot.getRangeAxis().setAutoRange(false);
_dotPlot.getRangeAxis().setAutoRange(true);
}
if (_showLinePlot.isChecked())
{
_linePlot.getRangeAxis().setAutoRange(false);
_linePlot.getRangeAxis().setAutoRange(true);
}
if (_showTargetOverview.isChecked())
{
_targetOverviewPlot.getRangeAxis().setAutoRange(false);
_targetOverviewPlot.getRangeAxis().setAutoRange(true);
}
}
// note, we also update the domain axis if we're updating the data in
// question
if (updateDoublets)
{
// trigger recalculation of date axis ticks
final CachedTickDateAxis date =
(CachedTickDateAxis) _combined.getDomainAxis();
date.clearTicks();
if (_showDotPlot.isChecked())
{
_dotPlot.getDomainAxis().setAutoRange(false);
_dotPlot.getDomainAxis().setAutoRange(true);
_dotPlot.getDomainAxis().setAutoRange(false);
}
if (_showLinePlot.isChecked())
{
_linePlot.getDomainAxis().setAutoRange(false);
_linePlot.getDomainAxis().setAutoRange(true);
_linePlot.getDomainAxis().setAutoRange(false);
}
if (_showTargetOverview.isChecked())
{
_targetOverviewPlot.getDomainAxis().setAutoRange(false);
_targetOverviewPlot.getDomainAxis().setAutoRange(true);
_targetOverviewPlot.getDomainAxis().setAutoRange(false);
}
}
}
/**
* sort out what we're listening to...
*/
private final void watchMyParts()
{
final ErrorLogger logger = this;
_myPartMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final ISelectionProvider prov = (ISelectionProvider) part;
// am I already listning to this
if (_selProviders.contains(prov))
{
// ignore, we're already listening to it
}
else
{
prov.addSelectionChangedListener(_mySelListener);
_selProviders.add(prov);
}
}
});
_myPartMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.CLOSED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final ISelectionProvider prov = (ISelectionProvider) part;
// am I already listning to this
if (_selProviders.contains(prov))
{
// ok, ditch this listener
_selProviders.remove(prov);
// and stop listening
prov.removeSelectionChangedListener(_mySelListener);
}
else
{
// hey, we're not even listening to it.
}
}
});
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// is it a new one?
if (part != _theTrackDataListener)
{
// cool, remember about it.
_theTrackDataListener = (TrackManager) part;
// set the title, so there's something useful in
// there
_myChart.setTitle("");
// ok - fire off the event for the new tracks
_myHelper
.initialise(_theTrackDataListener, false, _onlyVisible
.isChecked(), _holder, logger, getType(), _needBrg,
_needFreq);
// just in case we're ready to start plotting, go
// for it!
updateStackedDots(true);
}
}
});
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// ok, ditch it.
_theTrackDataListener = null;
_myHelper.reset();
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// cool, remember about it.
final TrackDataProvider dataP = (TrackDataProvider) part;
// do we need to generate the shift listener?
if (_myShiftListener == null)
{
_myShiftListener = new TrackShiftListener()
{
public void trackShifted(final WatchableList subject)
{
// the tracks have moved, we haven't changed
// the tracks or
// anything like that...
updateStackedDots(false);
}
};
_myTrackDataListener = new TrackDataListener()
{
public void tracksUpdated(final WatchableList primary,
final WatchableList[] secondaries)
{
_myHelper.initialise(_theTrackDataListener, false,
_onlyVisible.isChecked(), _holder, logger, getType(),
_needBrg, _needFreq);
// ahh, the tracks have changed, better
// update the doublets
// ok, do the recalc
updateStackedDots(true);
// ok - if we're on auto update, do the
// update
updateLinePlotRanges();
}
};
}
// is this the one we're already listening to?
if (_myTrackDataProvider != dataP)
{
// ok - let's start off with a clean plot
_dotPlot.setDataset(null);
// nope, better stop listening then
if (_myTrackDataProvider != null)
{
_myTrackDataProvider.removeTrackShiftListener(_myShiftListener);
_myTrackDataProvider
.removeTrackDataListener(_myTrackDataListener);
}
// ok, start listening to it anyway
_myTrackDataProvider = dataP;
_myTrackDataProvider.addTrackShiftListener(_myShiftListener);
_myTrackDataProvider.addTrackDataListener(_myTrackDataListener);
// hey - fire a dot update
updateStackedDots(true);
}
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final TrackDataProvider tdp = (TrackDataProvider) part;
tdp.removeTrackShiftListener(_myShiftListener);
tdp.removeTrackDataListener(_myTrackDataListener);
if (tdp == _myTrackDataProvider)
{
_myTrackDataProvider = null;
}
// hey - lets clear our plot
updateStackedDots(true);
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final Layers theLayers = (Layers) part;
// do we need to create our listener
if (_layersListener == null)
{
_layersListener = new Layers.DataListener()
{
public void dataExtended(final Layers theData)
{
}
public void dataModified(final Layers theData,
final Layer changedLayer)
{
}
public void dataReformatted(final Layers theData,
final Layer changedLayer)
{
_myHelper.initialise(_theTrackDataListener, false,
_onlyVisible.isChecked(), _holder, logger, getType(),
_needBrg, _needFreq);
updateStackedDots(true);
}
};
}
// is this what we're listening to?
if (_ourLayersSubject != theLayers)
{
// nope, stop listening to the old one (if there is
// one!)
if (_ourLayersSubject != null)
_ourLayersSubject
.removeDataReformattedListener(_layersListener);
// and remember the new one
_ourLayersSubject = theLayers;
}
// now start listening to the new one.
theLayers.addDataReformattedListener(_layersListener);
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final Layers theLayers = (Layers) part;
// is this what we're listening to?
if (_ourLayersSubject == theLayers)
{
// yup, stop listening
_ourLayersSubject.removeDataReformattedListener(_layersListener);
_linePlot.setDataset(null);
_dotPlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
}
});
// ok we're all ready now. just try and see if the current part is valid
_myPartMonitor.fireActivePart(getSite().getWorkbenchWindow()
.getActivePage());
}
/**
* some data has changed. if we're auto ranging, update the axes
*
*/
protected void updateLinePlotRanges()
{
// have a look at the auto resize
if (_autoResize.isChecked())
{
if (_showLinePlot.isChecked())
{
_linePlot.getRangeAxis().setAutoRange(false);
_linePlot.getDomainAxis().setAutoRange(false);
_linePlot.getRangeAxis().setAutoRange(true);
_linePlot.getDomainAxis().setAutoRange(true);
}
}
}
@Override
public void init(final IViewSite site, final IMemento memento)
throws PartInitException
{
super.init(site, memento);
if (memento != null)
{
final Boolean showLineVal = memento.getBoolean(SHOW_LINE_PLOT);
final Boolean showDotVal = memento.getBoolean(SHOW_DOT_PLOT);
final Boolean showOverview = memento.getBoolean(SHOW_OVERVIEW);
final Boolean doSelectOnClick = memento.getBoolean(SELECT_ON_CLICK);
final Boolean showOnlyVis = memento.getBoolean(SHOW_ONLY_VIS);
if (showLineVal != null)
{
_showLinePlot.setChecked(showLineVal);
}
if (showDotVal != null)
{
_showDotPlot.setChecked(showDotVal);
}
if (doSelectOnClick != null)
{
_selectOnClick.setChecked(doSelectOnClick);
}
if (showOnlyVis != null)
{
_onlyVisible.setChecked(showOnlyVis);
}
if (showOverview != null)
{
_showTargetOverview.setChecked(showOverview);
}
}
}
@Override
public void saveState(final IMemento memento)
{
super.saveState(memento);
// remember if we're showing the error plot
memento.putBoolean(SHOW_LINE_PLOT, _showLinePlot.isChecked());
memento.putBoolean(SHOW_DOT_PLOT, _showDotPlot.isChecked());
memento.putBoolean(SHOW_OVERVIEW, _showTargetOverview.isChecked());
memento.putBoolean(SELECT_ON_CLICK, _selectOnClick.isChecked());
memento.putBoolean(SHOW_ONLY_VIS, _onlyVisible.isChecked());
}
private void showFixAtThisTime(final Date newDate)
{
if (_myTrackDataProvider != null)
{
if (_myTrackDataProvider.getSecondaryTracks().length != 1)
return;
HiResDate theDate = new HiResDate(newDate);
EditableWrapper subject = null;
// ok, get the editor
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = win.getActivePage();
final IEditorPart editor = page.getActiveEditor();
Layers layers = (Layers) editor.getAdapter(Layers.class);
// did we find the layers
if (layers == null)
return;
TrackWrapper secTrack =
(TrackWrapper) _myTrackDataProvider.getSecondaryTracks()[0];
SegmentList segs = secTrack.getSegments();
Enumeration<Editable> sIter = segs.elements();
while (sIter.hasMoreElements())
{
TrackSegment thisSeg = (TrackSegment) sIter.nextElement();
if (thisSeg.startDTG().lessThanOrEqualTo(theDate)
&& thisSeg.endDTG().greaterThanOrEqualTo(theDate))
{
// ok, loop through them
Enumeration<Editable> pts = thisSeg.elements();
while (pts.hasMoreElements())
{
FixWrapper fix = (FixWrapper) pts.nextElement();
if (fix.getDTG().equals(theDate))
{
// done.
EditableWrapper parentP =
new EditableWrapper(secTrack, null, layers);
subject = new EditableWrapper(fix, parentP, null);
break;
}
}
}
}
if (subject != null)
{
IStructuredSelection selection = new StructuredSelection(subject);
IContentOutlinePage outline =
(IContentOutlinePage) editor.getAdapter(IContentOutlinePage.class);
// did we find an outline?
if (outline != null)
{
// now set the selection
outline.setSelection(selection);
// see uf we can expand the selection
if (outline instanceof PlotOutlinePage)
{
PlotOutlinePage plotOutline = (PlotOutlinePage) outline;
plotOutline.editableSelected(selection, subject);
}
}
}
}
}
}
|
org.mwc.debrief.track_shift/src/org/mwc/debrief/track_shift/views/BaseStackedDotsView.java
|
/*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.mwc.debrief.track_shift.views;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.Vector;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.DefaultXYItemRenderer;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.TimeSeriesDataItem;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.TextAnchor;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackDataListener;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackShiftListener;
import org.mwc.cmap.core.DataTypes.TrackData.TrackManager;
import org.mwc.cmap.core.property_support.EditableWrapper;
import org.mwc.cmap.core.ui_support.PartMonitor;
import org.mwc.debrief.core.actions.DragSegment;
import org.mwc.debrief.core.editors.PlotOutlinePage;
import org.mwc.debrief.track_shift.Activator;
import org.mwc.debrief.track_shift.controls.ZoneChart;
import org.mwc.debrief.track_shift.controls.ZoneChart.Zone;
import org.mwc.debrief.track_shift.controls.ZoneChart.ZoneSlicer;
import org.mwc.debrief.track_shift.zig_detector.LegOfData;
import org.mwc.debrief.track_shift.zig_detector.OwnshipLegDetector;
import org.mwc.debrief.track_shift.zig_detector.Precision;
import Debrief.Wrappers.FixWrapper;
import Debrief.Wrappers.TrackWrapper;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import MWC.GUI.Editable;
import MWC.GUI.ErrorLogger;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.Layers.DataListener;
import MWC.GUI.JFreeChart.ColourStandardXYItemRenderer;
import MWC.GUI.JFreeChart.DateAxisEditor;
import MWC.GUI.Properties.DebriefColors;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GenericData.HiResDate;
import MWC.GenericData.WatchableList;
/**
*/
abstract public class BaseStackedDotsView extends ViewPart implements
ErrorLogger
{
private static final String SHOW_DOT_PLOT = "SHOW_DOT_PLOT";
private static final String SHOW_OVERVIEW = "SHOW_OVERVIEW";
private static final String SHOW_LINE_PLOT = "SHOW_LINE_PLOT";
private static final String SELECT_ON_CLICK = "SELECT_ON_CLICK";
private static final String SHOW_ONLY_VIS = "ONLY_SHOW_VIS";
/**
* helper application to help track creation/activation of new plots
*/
private PartMonitor _myPartMonitor;
/**
* the errors we're plotting
*/
XYPlot _dotPlot;
/**
* and the actual values
*
*/
XYPlot _linePlot;
/**
* and the actual values
*
*/
XYPlot _targetOverviewPlot;
/**
* declare the tgt course dataset, we need to give it to the renderer
*
*/
final TimeSeriesCollection _targetCourseSeries = new TimeSeriesCollection();
/**
* declare the tgt speed dataset, we need to give it to the renderer
*
*/
final TimeSeriesCollection _targetSpeedSeries = new TimeSeriesCollection();
/**
* legacy helper class
*/
final StackedDotHelper _myHelper;
/**
* our track-data provider
*/
protected TrackManager _theTrackDataListener;
/**
* our listener for tracks being shifted...
*/
protected TrackShiftListener _myShiftListener;
/**
* buttons for which plots to show
*
*/
protected Action _showLinePlot;
protected Action _showDotPlot;
protected Action _showTargetOverview;
/**
* flag indicating whether we should only show stacked dots for visible fixes
*/
Action _onlyVisible;
/**
* flag indicating whether we should select the clicked item in the Outline View
*/
Action _selectOnClick;
/**
* our layers listener...
*/
protected DataListener _layersListener;
/**
* the set of layers we're currently listening to
*/
protected Layers _ourLayersSubject;
protected TrackDataProvider _myTrackDataProvider;
ChartComposite _holder;
JFreeChart _myChart;
private Vector<Action> _customActions;
protected Action _autoResize;
private CombinedDomainXYPlot _combined;
protected TrackDataListener _myTrackDataListener;
/**
* does our output need bearing in the data?
*
*/
private final boolean _needBrg;
/**
* does our output need frequency in the data?
*
*/
private final boolean _needFreq;
// private Action _magicBtn;
protected Vector<ISelectionProvider> _selProviders;
protected ISelectionChangedListener _mySelListener;
protected Vector<DraggableItem> _draggableSelection;
protected boolean _itemSelectedPending = false;
@SuppressWarnings("unused")
private ZoneChart ownshipZoneChart;
protected TimeSeries ownshipCourseSeries;
protected TimeSeries targetBearingSeries;
/**
*
* @param needBrg
* if the algorithm needs bearing data
* @param needFreq
* if the agorithm needs frequency data
*/
protected BaseStackedDotsView(final boolean needBrg, final boolean needFreq)
{
_myHelper = new StackedDotHelper();
_needBrg = needBrg;
_needFreq = needFreq;
// create the actions - the 'centre-y axis' action may get called before
// the
// interface is shown
makeActions();
}
abstract protected String getUnits();
abstract protected String getType();
abstract protected void updateData(boolean updateDoublets);
private void contributeToActionBars()
{
final IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
protected void fillLocalToolBar(final IToolBarManager toolBarManager)
{
// fit to window
toolBarManager.add(_autoResize);
toolBarManager.add(_onlyVisible);
toolBarManager.add(_selectOnClick);
toolBarManager.add(_showLinePlot);
toolBarManager.add(_showDotPlot);
toolBarManager.add(_showTargetOverview);
addExtras(toolBarManager);
// and a separator
toolBarManager.add(new Separator());
final Vector<Action> actions = DragSegment.getDragModes();
for (final Iterator<Action> iterator = actions.iterator(); iterator
.hasNext();)
{
final Action action = iterator.next();
toolBarManager.add(action);
}
}
/**
* additional method, to allow extra items to be added before the segment modes
*
* @param toolBarManager
*/
protected void addExtras(IToolBarManager toolBarManager)
{
}
/**
* This is a callback that will allow us to create the viewer and initialize it.
*/
@SuppressWarnings("deprecation")
@Override
public void createPartControl(final Composite parent)
{
parent.setLayout(new FillLayout(SWT.VERTICAL));
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
_holder =
new ChartComposite(sashForm, SWT.NONE, null, 400, 600, 300, 200, 1800,
1800, true, true, true, true, true, true)
{
@Override
public void mouseUp(MouseEvent event)
{
super.mouseUp(event);
JFreeChart c = getChart();
if (c != null)
{
c.setNotify(true); // force redraw
}
}
};
// hey - now create the stacked plot!
createStackedPlot();
// /////////////////////////////////////////
// ok - listen out for changes in the view
// /////////////////////////////////////////
_selProviders = new Vector<ISelectionProvider>();
_mySelListener = new ISelectionChangedListener()
{
@Override
public void selectionChanged(final SelectionChangedEvent event)
{
final ISelection sel = event.getSelection();
final Vector<DraggableItem> dragees = new Vector<DraggableItem>();
if (sel instanceof StructuredSelection)
{
final StructuredSelection str = (StructuredSelection) sel;
final Iterator<?> iter = str.iterator();
while (iter.hasNext())
{
final Object object = (Object) iter.next();
if (object instanceof EditableWrapper)
{
final EditableWrapper ew = (EditableWrapper) object;
final Editable item = ew.getEditable();
if (item instanceof DraggableItem)
{
dragees.add((DraggableItem) item);
}
}
else
{
return;
}
}
// ok, we've just got draggable items - override the current
// item
_draggableSelection = dragees;
}
}
};
// sort out the part monitor
_myPartMonitor =
new PartMonitor(getSite().getWorkbenchWindow().getPartService());
// now start listening out for people's parts
watchMyParts();
// put the actions in the UI
contributeToActionBars();
// we will also listen out for zone changes
@SuppressWarnings("unused")
ZoneChart.ZoneListener ownshipListener = getOwnshipListener();
@SuppressWarnings("unused")
ZoneChart.ZoneListener targetListener = getTargetListener();
Zone[] osZones =
new ZoneChart.Zone[]
{
// new ZoneChart.Zone(new Date("2016/10/10 11:05").getTime(),
// new Date("2016/10/10 11:42").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:25").getTime(),
// new Date("2016/10/10 12:40").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:55:01").getTime(),
// new Date("2016/10/10 13:23:12").getTime())
};
long[] osTimeValues = new long[]{};
long[] osAngleValues = new long[]{};
// create the zone charts
// TODO: pending
ZoneChart.ColorProvider blueProv = new ZoneChart.ColorProvider()
{
@Override
public Color getColorFor(Zone zone)
{
return DebriefColors.BLUE;
}
};
// put the courses into a TimeSeries
ownshipCourseSeries = new TimeSeries("Ownship course");
ZoneSlicer ownshipLegSlicer = new ZoneSlicer(){
@Override
public ArrayList<Zone> performSlicing()
{
return sliceOwnship(ownshipCourseSeries);
}};
ownshipZoneChart =
ZoneChart.create("Ownship Legs", "Course", sashForm, osZones, ownshipCourseSeries,
osTimeValues, blueProv, DebriefColors.BLUE, ownshipLegSlicer );
// assign the listeners
// TODO: pending
Zone[] tgtZones =
new ZoneChart.Zone[]
{
// new ZoneChart.Zone(new Date("2016/10/10 10:17").getTime(),
// new Date("2016/10/10 10:40").getTime()),
// new ZoneChart.Zone(new Date("2016/10/10 12:02:01").getTime(),
// new Date("2016/10/10 12:23:12").getTime())
};
long[] tgtTimeValues =
new long[]{};
long[] tgtAngleValues = new long[]
{};
ZoneChart.ColorProvider randomProv = new ZoneChart.ColorProvider()
{
@Override
public Color getColorFor(Zone zone)
{
Random random = new Random();
final float hue = random.nextFloat();
// Saturation between 0.1 and 0.3
final float saturation = (random.nextInt(2000) + 7000) / 10000f;
final float luminance = 0.9f;
final Color color = Color.getHSBColor(hue, saturation, luminance);
return color;
}
};
// put the bearings into a TimeSeries
targetBearingSeries = new TimeSeries("Bearing");
@SuppressWarnings("unused")
ZoneChart tgtZoneChart =
ZoneChart.create("Target Legs", "Bearing", sashForm, tgtZones,
targetBearingSeries, tgtTimeValues, randomProv, DebriefColors.RED, null);
// and set the proportions of space allowed
sashForm.setWeights(new int[]{4,1,1});
sashForm.setBackground(sashForm.getDisplay().getSystemColor( SWT.COLOR_GRAY));
}
protected ArrayList<Zone> sliceOwnship(TimeSeries osCourse)
{
OwnshipLegDetector detector = new OwnshipLegDetector();
final int num = osCourse.getItemCount();
long[] times = new long[num];
double[] speeds = new double[num];
double[] courses = new double[num];
for(int ctr = 0;ctr<num;ctr++)
{
TimeSeriesDataItem thisItem = osCourse.getDataItem(ctr);
FixedMillisecond thisM = (FixedMillisecond) thisItem.getPeriod();
times[ctr] = thisM.getMiddleMillisecond();
speeds[ctr] = 0;
courses[ctr] = (Double) thisItem.getValue();
}
List<LegOfData> legs = detector.identifyOwnshipLegs(times, speeds, courses, 5, Precision.LOW);
ArrayList<Zone> res = new ArrayList<Zone>();
for(LegOfData leg : legs)
{
Zone newZone = new Zone(leg.getStart(), leg.getEnd());
res.add(newZone);
}
return res;
}
private ZoneChart.ZoneListener getOwnshipListener()
{
// TODO: fire the ownship legs to the target zig generator
return new ZoneChart.ZoneAdapter();
}
private ZoneChart.ZoneListener getTargetListener()
{
// TODO reflect the new target legs on the bearing residuals
return new ZoneChart.ZoneAdapter();
}
/**
* method to create a working plot (to contain our data)
*
* @return the chart, in it's own panel
*/
@SuppressWarnings("deprecation")
protected void createStackedPlot()
{
// first create the x (time) axis
final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss");
_df.setTimeZone(TimeZone.getTimeZone("GMT"));
final DateAxis xAxis = new CachedTickDateAxis("");
xAxis.setDateFormatOverride(_df);
Font tickLabelFont = new Font("Courier", Font.PLAIN, 13);
xAxis.setTickLabelFont(tickLabelFont);
xAxis.setTickLabelPaint(Color.BLACK);
xAxis.setStandardTickUnits(DateAxisEditor
.createStandardDateTickUnitsAsTickUnits());
xAxis.setAutoTickUnitSelection(true);
// create the special stepper plot
_dotPlot = new XYPlot();
NumberAxis errorAxis = new NumberAxis("Error (" + getUnits() + ")");
Font axisLabelFont = new Font("Courier", Font.PLAIN, 16);
errorAxis.setLabelFont(axisLabelFont);
errorAxis.setTickLabelFont(tickLabelFont);
_dotPlot.setRangeAxis(errorAxis);
_dotPlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
_dotPlot
.setRenderer(new ColourStandardXYItemRenderer(null, null, _dotPlot));
_dotPlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_dotPlot.setRangeGridlineStroke(new BasicStroke(2));
_dotPlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_dotPlot.setDomainGridlineStroke(new BasicStroke(2));
// now try to do add a zero marker on the error bar
final Paint thePaint = Color.DARK_GRAY;
final Stroke theStroke = new BasicStroke(3);
final ValueMarker zeroMarker = new ValueMarker(0.0, thePaint, theStroke);
_dotPlot.addRangeMarker(zeroMarker);
_linePlot = new XYPlot();
final NumberAxis absBrgAxis =
new NumberAxis("Absolute (" + getUnits() + ")");
absBrgAxis.setLabelFont(axisLabelFont);
absBrgAxis.setTickLabelFont(tickLabelFont);
_linePlot.setRangeAxis(absBrgAxis);
absBrgAxis.setAutoRangeIncludesZero(false);
_linePlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
final DefaultXYItemRenderer lineRend =
new ColourStandardXYItemRenderer(null, null, _linePlot);
lineRend.setPaint(Color.DARK_GRAY);
_linePlot.setRenderer(lineRend);
_linePlot.setDomainCrosshairVisible(true);
_linePlot.setRangeCrosshairVisible(true);
_linePlot.setDomainCrosshairPaint(Color.GRAY);
_linePlot.setRangeCrosshairPaint(Color.GRAY);
_linePlot.setDomainCrosshairStroke(new BasicStroke(3.0f));
_linePlot.setRangeCrosshairStroke(new BasicStroke(3.0f));
_linePlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_linePlot.setRangeGridlineStroke(new BasicStroke(2));
_linePlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_linePlot.setDomainGridlineStroke(new BasicStroke(2));
_targetOverviewPlot = new XYPlot();
final NumberAxis overviewCourse = new NumberAxis("Course (\u00b0)")
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public NumberTickUnit getTickUnit()
{
final NumberTickUnit tickUnit = super.getTickUnit();
if (tickUnit.getSize() < 15)
{
return tickUnit;
}
else if (tickUnit.getSize() < 45)
{
return new NumberTickUnit(20);
}
else if (tickUnit.getSize() < 90)
{
return new NumberTickUnit(30);
}
else if (tickUnit.getSize() < 180)
{
return new NumberTickUnit(45);
}
else
{
return new NumberTickUnit(90);
}
}
};
overviewCourse.setUpperMargin(0);
overviewCourse.setLabelFont(axisLabelFont);
overviewCourse.setTickLabelFont(tickLabelFont);
final NumberAxis overviewSpeed = new NumberAxis("Speed (Kts)");
overviewSpeed.setLabelFont(axisLabelFont);
overviewSpeed.setTickLabelFont(tickLabelFont);
_targetOverviewPlot.setRangeAxis(overviewCourse);
_targetOverviewPlot.setRangeAxis(1, overviewSpeed);
absBrgAxis.setAutoRangeIncludesZero(false);
_targetOverviewPlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
final DefaultXYItemRenderer overviewCourseRenderer =
new WrappingResidualRenderer(null, null, _targetCourseSeries, 0, 360);
overviewCourseRenderer.setSeriesPaint(0, DebriefColors.RED.brighter());
overviewCourseRenderer.setSeriesPaint(1, DebriefColors.BLUE);
overviewCourseRenderer.setSeriesShape(0, new Ellipse2D.Double(-4.0, -4.0,
8.0, 8.0));
overviewCourseRenderer.setSeriesShapesVisible(1, false);
overviewCourseRenderer.setSeriesStroke(0, new BasicStroke(2f));
overviewCourseRenderer.setSeriesStroke(1, new BasicStroke(2f));
final DefaultXYItemRenderer overviewSpeedRenderer =
new ResidualXYItemRenderer(null, null, _targetSpeedSeries);
overviewSpeedRenderer.setPaint(DebriefColors.RED.darker());
overviewSpeedRenderer.setSeriesShape(0, new Rectangle2D.Double(-4.0, -4.0,
8.0, 8.0));
overviewSpeedRenderer.setSeriesStroke(0, new BasicStroke(2f));
_targetOverviewPlot.setRenderer(0, overviewCourseRenderer);
_targetOverviewPlot.setRenderer(1, overviewSpeedRenderer);
_targetOverviewPlot.mapDatasetToRangeAxis(0, 0);
_targetOverviewPlot.mapDatasetToRangeAxis(1, 1);
_targetOverviewPlot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
_targetOverviewPlot.setRangeAxisLocation(1, AxisLocation.TOP_OR_LEFT);
_targetOverviewPlot.setRangeGridlinePaint(Color.LIGHT_GRAY);
_targetOverviewPlot.setRangeGridlineStroke(new BasicStroke(2));
_targetOverviewPlot.setDomainGridlinePaint(Color.LIGHT_GRAY);
_targetOverviewPlot.setDomainGridlineStroke(new BasicStroke(2));
// and the plot object to display the cross hair value
final XYTextAnnotation annot = new XYTextAnnotation("-----", 2, 2);
annot.setTextAnchor(TextAnchor.TOP_LEFT);
Font annotationFont = new Font("Courier", Font.BOLD, 16);
annot.setFont(annotationFont);
annot.setPaint(Color.DARK_GRAY);
annot.setBackgroundPaint(Color.white);
_linePlot.addAnnotation(annot);
// give them a high contrast backdrop
_dotPlot.setBackgroundPaint(Color.white);
_linePlot.setBackgroundPaint(Color.white);
_targetOverviewPlot.setBackgroundPaint(Color.white);
// set the y axes to autocalculate
_dotPlot.getRangeAxis().setAutoRange(true);
_linePlot.getRangeAxis().setAutoRange(true);
_targetOverviewPlot.getRangeAxis().setAutoRange(true);
_combined = new CombinedDomainXYPlot(xAxis);
_combined.add(_linePlot);
_combined.add(_dotPlot);
_combined.add(_targetOverviewPlot);
_combined.setOrientation(PlotOrientation.HORIZONTAL);
// put the plot into a chart
_myChart = new JFreeChart(null, null, _combined, true);
final LegendItemSource[] sources =
{_linePlot, _targetOverviewPlot};
_myChart.getLegend().setSources(sources);
_myChart.addProgressListener(new ChartProgressListener()
{
public void chartProgress(final ChartProgressEvent cpe)
{
if (cpe.getType() != ChartProgressEvent.DRAWING_FINISHED)
return;
// is hte line plot visible?
if (!_showLinePlot.isChecked())
return;
// double-check our label is still in the right place
final double xVal = _linePlot.getRangeAxis().getLowerBound();
final double yVal = _linePlot.getDomainAxis().getUpperBound();
boolean annotChanged = false;
if (annot.getX() != yVal)
{
annot.setX(yVal);
annotChanged = true;
}
if (annot.getY() != xVal)
{
annot.setY(xVal);
annotChanged = true;
}
// and write the text
final String numA =
MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(_linePlot.getRangeCrosshairValue());
final Date newDate =
new Date((long) _linePlot.getDomainCrosshairValue());
final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss");
_df.setTimeZone(TimeZone.getTimeZone("GMT"));
final String dateVal = _df.format(newDate);
final String theMessage = " [" + dateVal + "," + numA + "]";
if (!theMessage.equals(annot.getText()))
{
annot.setText(theMessage);
annotChanged = true;
}
if (annotChanged)
{
_linePlot.removeAnnotation(annot);
_linePlot.addAnnotation(annot);
}
// ok, do we also have a selection event pending
if (_itemSelectedPending && _selectOnClick.isChecked())
{
_itemSelectedPending = false;
showFixAtThisTime(newDate);
}
}
});
// and insert into the panel
_holder.setChart(_myChart);
_holder.addChartMouseListener(new ChartMouseListener()
{
@Override
public void chartMouseMoved(ChartMouseEvent arg0)
{
}
@Override
public void chartMouseClicked(ChartMouseEvent arg0)
{
// ok, remember it was clicked
_itemSelectedPending = true;
}
});
// do a little tidying to reflect the memento settings
if (!_showLinePlot.isChecked())
_combined.remove(_linePlot);
if (!_showDotPlot.isChecked() && _showLinePlot.isChecked())
_combined.remove(_dotPlot);
if (!_showTargetOverview.isChecked())
_combined.remove(_targetOverviewPlot);
}
/**
* view is closing, shut down, preserve life
*/
@Override
public void dispose()
{
// get parent to ditch itself
super.dispose();
// ditch the actions
if (_customActions != null)
_customActions.removeAllElements();
// are we listening to any layers?
if (_ourLayersSubject != null)
_ourLayersSubject.removeDataReformattedListener(_layersListener);
if (_theTrackDataListener != null)
{
_theTrackDataListener.removeTrackShiftListener(_myShiftListener);
_theTrackDataListener.removeTrackDataListener(_myTrackDataListener);
}
// stop the part monitor
_myPartMonitor.ditch();
}
protected void fillLocalPullDown(final IMenuManager manager)
{
manager.add(_onlyVisible);
manager.add(_selectOnClick);
// and the help link
manager.add(new Separator());
manager.add(CorePlugin.createOpenHelpAction(
"org.mwc.debrief.help.TrackShifting", null, this));
}
protected void makeActions()
{
_autoResize = new Action("Auto resize", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
final boolean val = _autoResize.isChecked();
if (_showLinePlot.isChecked())
{
// ok - redraw the plot we may have changed the axis
// centreing
_linePlot.getRangeAxis().setAutoRange(val);
_linePlot.getDomainAxis().setAutoRange(val);
}
if (_showDotPlot.isChecked())
{
_dotPlot.getRangeAxis().setAutoRange(val);
_dotPlot.getDomainAxis().setAutoRange(val);
}
}
};
_autoResize.setChecked(true);
_autoResize.setToolTipText("Keep plot sized to show all data");
_autoResize.setImageDescriptor(CorePlugin
.getImageDescriptor("icons/24/fit_to_win.png"));
_showLinePlot = new Action("Actuals plot", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showLinePlot.isChecked())
{
_combined.remove(_linePlot);
_combined.remove(_dotPlot);
_combined.add(_linePlot);
if (_showDotPlot.isChecked())
_combined.add(_dotPlot);
}
else
{
if (_combined.getSubplots().size() > 1)
_combined.remove(_linePlot);
}
}
};
_showLinePlot.setChecked(true);
_showLinePlot.setToolTipText("Show the actuals plot");
_showLinePlot.setImageDescriptor(Activator
.getImageDescriptor("icons/24/stacked_lines.png"));
_showDotPlot = new Action("Error plot", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showDotPlot.isChecked())
{
_combined.remove(_linePlot);
_combined.remove(_dotPlot);
if (_showLinePlot.isChecked())
_combined.add(_linePlot);
_combined.add(_dotPlot);
}
else
{
if (_combined.getSubplots().size() > 1)
_combined.remove(_dotPlot);
}
}
};
_showDotPlot.setChecked(true);
_showDotPlot.setToolTipText("Show the error plot");
_showDotPlot.setImageDescriptor(Activator
.getImageDescriptor("icons/24/stacked_dots.png"));
_showTargetOverview = new Action("Target Overview", IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
if (_showTargetOverview.isChecked())
{
_combined.add(_targetOverviewPlot);
}
else
{
_combined.remove(_targetOverviewPlot);
}
}
};
_showTargetOverview.setChecked(true);
_showTargetOverview.setToolTipText("Show the overview plot");
_showTargetOverview.setImageDescriptor(Activator
.getImageDescriptor("icons/24/tgt_overview.png"));
// get an error logger
final ErrorLogger logger = this;
_onlyVisible =
new Action("Only draw dots for visible data points",
IAction.AS_CHECK_BOX)
{
@Override
public void run()
{
super.run();
// set the title, so there's something useful in there
_myChart.setTitle("");
// we need to get a fresh set of data pairs - the number may
// have
// changed
_myHelper.initialise(_theTrackDataListener, true, _onlyVisible
.isChecked(), _holder, logger, getType(), _needBrg, _needFreq);
// and a new plot please
updateStackedDots(true);
}
};
_onlyVisible.setText("Only plot visible data");
_onlyVisible.setChecked(true);
_onlyVisible.setToolTipText("Only draw dots for visible data points");
_onlyVisible.setImageDescriptor(Activator
.getImageDescriptor("icons/24/reveal.png"));
_selectOnClick =
new Action("Select TMA Fix in outline when clicked",
IAction.AS_CHECK_BOX)
{
};
_selectOnClick.setChecked(true);
_selectOnClick
.setToolTipText("Reveal the respective TMA Fix when an error clicked on plot");
_selectOnClick.setImageDescriptor(CorePlugin
.getImageDescriptor("icons/24/outline.png"));
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus()
{
}
public void logError(final int statusCode, final String string,
final Exception object)
{
// somehow, put the message into the UI
_myChart.setTitle(string);
// is it a fail status
if (statusCode != Status.OK)
{
// and store the problem into the log
CorePlugin.logError(statusCode, string, object);
// also ditch the data in the plots - to blank them out
clearPlots();
}
}
@Override
public void logStack(int status, String text)
{
CorePlugin.logError(status, text, null, true);
}
/**
* the track has been moved, update the dots
*/
void clearPlots()
{
if (Thread.currentThread() == Display.getDefault().getThread())
{
// it's ok we're already in a display thread
_dotPlot.setDataset(null);
_linePlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
else
{
// we're not in the display thread - make it so!
Display.getDefault().syncExec(new Runnable()
{
public void run()
{
_dotPlot.setDataset(null);
_linePlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
});
}
}
/**
* the track has been moved, update the dots
*/
void updateStackedDots(final boolean updateDoublets)
{
if (Thread.currentThread() == Display.getDefault().getThread())
{
// it's ok we're already in a display thread
wrappedUpdateStackedDots(updateDoublets);
}
else
{
// we're not in the display thread - make it so!
Display.getDefault().syncExec(new Runnable()
{
public void run()
{
// update the current datasets
wrappedUpdateStackedDots(updateDoublets);
}
});
}
}
/**
* the track has been moved, update the dots
*/
void wrappedUpdateStackedDots(final boolean updateDoublets)
{
// update the current datasets
updateData(updateDoublets);
// right, are we updating the range data?
if (_autoResize.isChecked())
{
if (_showDotPlot.isChecked())
{
_dotPlot.getRangeAxis().setAutoRange(false);
_dotPlot.getRangeAxis().setAutoRange(true);
}
if (_showLinePlot.isChecked())
{
_linePlot.getRangeAxis().setAutoRange(false);
_linePlot.getRangeAxis().setAutoRange(true);
}
if (_showTargetOverview.isChecked())
{
_targetOverviewPlot.getRangeAxis().setAutoRange(false);
_targetOverviewPlot.getRangeAxis().setAutoRange(true);
}
}
// note, we also update the domain axis if we're updating the data in
// question
if (updateDoublets)
{
// trigger recalculation of date axis ticks
final CachedTickDateAxis date =
(CachedTickDateAxis) _combined.getDomainAxis();
date.clearTicks();
if (_showDotPlot.isChecked())
{
_dotPlot.getDomainAxis().setAutoRange(false);
_dotPlot.getDomainAxis().setAutoRange(true);
_dotPlot.getDomainAxis().setAutoRange(false);
}
if (_showLinePlot.isChecked())
{
_linePlot.getDomainAxis().setAutoRange(false);
_linePlot.getDomainAxis().setAutoRange(true);
_linePlot.getDomainAxis().setAutoRange(false);
}
if (_showTargetOverview.isChecked())
{
_targetOverviewPlot.getDomainAxis().setAutoRange(false);
_targetOverviewPlot.getDomainAxis().setAutoRange(true);
_targetOverviewPlot.getDomainAxis().setAutoRange(false);
}
}
}
/**
* sort out what we're listening to...
*/
private final void watchMyParts()
{
final ErrorLogger logger = this;
_myPartMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final ISelectionProvider prov = (ISelectionProvider) part;
// am I already listning to this
if (_selProviders.contains(prov))
{
// ignore, we're already listening to it
}
else
{
prov.addSelectionChangedListener(_mySelListener);
_selProviders.add(prov);
}
}
});
_myPartMonitor.addPartListener(ISelectionProvider.class,
PartMonitor.CLOSED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final ISelectionProvider prov = (ISelectionProvider) part;
// am I already listning to this
if (_selProviders.contains(prov))
{
// ok, ditch this listener
_selProviders.remove(prov);
// and stop listening
prov.removeSelectionChangedListener(_mySelListener);
}
else
{
// hey, we're not even listening to it.
}
}
});
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// is it a new one?
if (part != _theTrackDataListener)
{
// cool, remember about it.
_theTrackDataListener = (TrackManager) part;
// set the title, so there's something useful in
// there
_myChart.setTitle("");
// ok - fire off the event for the new tracks
_myHelper
.initialise(_theTrackDataListener, false, _onlyVisible
.isChecked(), _holder, logger, getType(), _needBrg,
_needFreq);
// just in case we're ready to start plotting, go
// for it!
updateStackedDots(true);
}
}
});
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// ok, ditch it.
_theTrackDataListener = null;
_myHelper.reset();
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// cool, remember about it.
final TrackDataProvider dataP = (TrackDataProvider) part;
// do we need to generate the shift listener?
if (_myShiftListener == null)
{
_myShiftListener = new TrackShiftListener()
{
public void trackShifted(final WatchableList subject)
{
// the tracks have moved, we haven't changed
// the tracks or
// anything like that...
updateStackedDots(false);
}
};
_myTrackDataListener = new TrackDataListener()
{
public void tracksUpdated(final WatchableList primary,
final WatchableList[] secondaries)
{
_myHelper.initialise(_theTrackDataListener, false,
_onlyVisible.isChecked(), _holder, logger, getType(),
_needBrg, _needFreq);
// ahh, the tracks have changed, better
// update the doublets
// ok, do the recalc
updateStackedDots(true);
// ok - if we're on auto update, do the
// update
updateLinePlotRanges();
}
};
}
// is this the one we're already listening to?
if (_myTrackDataProvider != dataP)
{
// ok - let's start off with a clean plot
_dotPlot.setDataset(null);
// nope, better stop listening then
if (_myTrackDataProvider != null)
{
_myTrackDataProvider.removeTrackShiftListener(_myShiftListener);
_myTrackDataProvider
.removeTrackDataListener(_myTrackDataListener);
}
// ok, start listening to it anyway
_myTrackDataProvider = dataP;
_myTrackDataProvider.addTrackShiftListener(_myShiftListener);
_myTrackDataProvider.addTrackDataListener(_myTrackDataListener);
// hey - fire a dot update
updateStackedDots(true);
}
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final TrackDataProvider tdp = (TrackDataProvider) part;
tdp.removeTrackShiftListener(_myShiftListener);
tdp.removeTrackDataListener(_myTrackDataListener);
if (tdp == _myTrackDataProvider)
{
_myTrackDataProvider = null;
}
// hey - lets clear our plot
updateStackedDots(true);
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final Layers theLayers = (Layers) part;
// do we need to create our listener
if (_layersListener == null)
{
_layersListener = new Layers.DataListener()
{
public void dataExtended(final Layers theData)
{
}
public void dataModified(final Layers theData,
final Layer changedLayer)
{
}
public void dataReformatted(final Layers theData,
final Layer changedLayer)
{
_myHelper.initialise(_theTrackDataListener, false,
_onlyVisible.isChecked(), _holder, logger, getType(),
_needBrg, _needFreq);
updateStackedDots(true);
}
};
}
// is this what we're listening to?
if (_ourLayersSubject != theLayers)
{
// nope, stop listening to the old one (if there is
// one!)
if (_ourLayersSubject != null)
_ourLayersSubject
.removeDataReformattedListener(_layersListener);
// and remember the new one
_ourLayersSubject = theLayers;
}
// now start listening to the new one.
theLayers.addDataReformattedListener(_layersListener);
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
final Layers theLayers = (Layers) part;
// is this what we're listening to?
if (_ourLayersSubject == theLayers)
{
// yup, stop listening
_ourLayersSubject.removeDataReformattedListener(_layersListener);
_linePlot.setDataset(null);
_dotPlot.setDataset(null);
_targetOverviewPlot.setDataset(null);
}
}
});
// ok we're all ready now. just try and see if the current part is valid
_myPartMonitor.fireActivePart(getSite().getWorkbenchWindow()
.getActivePage());
}
/**
* some data has changed. if we're auto ranging, update the axes
*
*/
protected void updateLinePlotRanges()
{
// have a look at the auto resize
if (_autoResize.isChecked())
{
if (_showLinePlot.isChecked())
{
_linePlot.getRangeAxis().setAutoRange(false);
_linePlot.getDomainAxis().setAutoRange(false);
_linePlot.getRangeAxis().setAutoRange(true);
_linePlot.getDomainAxis().setAutoRange(true);
}
}
}
@Override
public void init(final IViewSite site, final IMemento memento)
throws PartInitException
{
super.init(site, memento);
if (memento != null)
{
final Boolean showLineVal = memento.getBoolean(SHOW_LINE_PLOT);
final Boolean showDotVal = memento.getBoolean(SHOW_DOT_PLOT);
final Boolean showOverview = memento.getBoolean(SHOW_OVERVIEW);
final Boolean doSelectOnClick = memento.getBoolean(SELECT_ON_CLICK);
final Boolean showOnlyVis = memento.getBoolean(SHOW_ONLY_VIS);
if (showLineVal != null)
{
_showLinePlot.setChecked(showLineVal);
}
if (showDotVal != null)
{
_showDotPlot.setChecked(showDotVal);
}
if (doSelectOnClick != null)
{
_selectOnClick.setChecked(doSelectOnClick);
}
if (showOnlyVis != null)
{
_onlyVisible.setChecked(showOnlyVis);
}
if (showOverview != null)
{
_showTargetOverview.setChecked(showOverview);
}
}
}
@Override
public void saveState(final IMemento memento)
{
super.saveState(memento);
// remember if we're showing the error plot
memento.putBoolean(SHOW_LINE_PLOT, _showLinePlot.isChecked());
memento.putBoolean(SHOW_DOT_PLOT, _showDotPlot.isChecked());
memento.putBoolean(SHOW_OVERVIEW, _showTargetOverview.isChecked());
memento.putBoolean(SELECT_ON_CLICK, _selectOnClick.isChecked());
memento.putBoolean(SHOW_ONLY_VIS, _onlyVisible.isChecked());
}
private void showFixAtThisTime(final Date newDate)
{
if (_myTrackDataProvider != null)
{
if (_myTrackDataProvider.getSecondaryTracks().length != 1)
return;
HiResDate theDate = new HiResDate(newDate);
EditableWrapper subject = null;
// ok, get the editor
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = win.getActivePage();
final IEditorPart editor = page.getActiveEditor();
Layers layers = (Layers) editor.getAdapter(Layers.class);
// did we find the layers
if (layers == null)
return;
TrackWrapper secTrack =
(TrackWrapper) _myTrackDataProvider.getSecondaryTracks()[0];
SegmentList segs = secTrack.getSegments();
Enumeration<Editable> sIter = segs.elements();
while (sIter.hasMoreElements())
{
TrackSegment thisSeg = (TrackSegment) sIter.nextElement();
if (thisSeg.startDTG().lessThanOrEqualTo(theDate)
&& thisSeg.endDTG().greaterThanOrEqualTo(theDate))
{
// ok, loop through them
Enumeration<Editable> pts = thisSeg.elements();
while (pts.hasMoreElements())
{
FixWrapper fix = (FixWrapper) pts.nextElement();
if (fix.getDTG().equals(theDate))
{
// done.
EditableWrapper parentP =
new EditableWrapper(secTrack, null, layers);
subject = new EditableWrapper(fix, parentP, null);
break;
}
}
}
}
if (subject != null)
{
IStructuredSelection selection = new StructuredSelection(subject);
IContentOutlinePage outline =
(IContentOutlinePage) editor.getAdapter(IContentOutlinePage.class);
// did we find an outline?
if (outline != null)
{
// now set the selection
outline.setSelection(selection);
// see uf we can expand the selection
if (outline instanceof PlotOutlinePage)
{
PlotOutlinePage plotOutline = (PlotOutlinePage) outline;
plotOutline.editableSelected(selection, subject);
}
}
}
}
}
}
|
Introduce button to show/hide leg slicing graphs
|
org.mwc.debrief.track_shift/src/org/mwc/debrief/track_shift/views/BaseStackedDotsView.java
|
Introduce button to show/hide leg slicing graphs
|
|
Java
|
mpl-2.0
|
b166dd96322818e02f47fcc56b9328b7f44b33b6
| 0
|
CrafterKina/Pipes
|
package jp.crafterkina.pipes.common.pipe.strategy;
import jp.crafterkina.pipes.api.pipe.FlowItem;
import jp.crafterkina.pipes.api.pipe.IStrategy;
import jp.crafterkina.pipes.api.render.ISpecialRenderer;
import jp.crafterkina.pipes.client.tesr.processor.ExtractionProcessorRenderer;
import jp.crafterkina.pipes.common.block.entity.TileEntityPipe;
import jp.crafterkina.pipes.common.item.ItemProcessor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.BiFunction;
/**
* Created by Kina on 2016/12/23.
*/
public class StrategyOneway implements IStrategy{
private final ItemStack stack;
private final EnumFacing to;
private StrategyOneway(ItemStack stack, EnumFacing to){
this.stack = stack;
this.to = to;
}
@Override
public FlowItem turn(FlowItem item, Vec3d... connecting){
return new FlowItem(item.getStack(), to, item.getSpeed());
}
@Override
public IStrategy rotate(EnumFacing axis){
return new StrategyOneway(stack, to);
}
public static class ItemOnewayProcessor extends ItemProcessor{
public ItemOnewayProcessor(){
setUnlocalizedName("oneway");
setMaxStackSize(1);
}
public static int getColor(ItemStack stack, int layer){
return layer == 1 ? 0x535353 : 0xffffff;
}
@Override
protected ItemStack attachItem(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){
if(!(worldIn.getTileEntity(pos) instanceof TileEntityPipe)) return ItemStack.EMPTY;
ItemStack stack = player.getHeldItem(hand);
NBTTagCompound compound = stack.getTagCompound();
if(compound == null){
compound = new NBTTagCompound();
stack.setTagCompound(compound);
}
compound.setByte("to", (byte) facing.getIndex());
return stack;
}
@Override
protected BiFunction<ItemStack, TileEntity, IStrategy> getStrategy(){
return (s, t) -> {
if(!(t instanceof TileEntityPipe)) return null;
NBTTagCompound compound = s.getTagCompound();
if(compound == null) return null;
EnumFacing to = EnumFacing.VALUES[compound.getByte("to")];
return new StrategyOneway(s, to);
};
}
@SuppressWarnings("MethodCallSideOnly")
@Override
protected boolean hasAdditionalCapability(ItemStack stack, @Nonnull Capability<?> capability, @Nullable EnumFacing facing){
return FMLCommonHandler.instance().getSide().isClient() && hasCapabilityClient(stack, capability, facing);
}
@SuppressWarnings("MethodCallSideOnly")
@Nullable
@Override
protected <T> T getAdditionalCapability(ItemStack stack, @Nonnull Capability<T> capability, @Nullable EnumFacing facing){
if(FMLCommonHandler.instance().getSide().isClient())
return getCapabilityClient(stack, capability, facing);
return null;
}
@SideOnly(Side.CLIENT)
private boolean hasCapabilityClient(@SuppressWarnings("unused") ItemStack stack, @Nonnull Capability<?> capability, @Nullable EnumFacing facing){
return capability == ISpecialRenderer.CAPABILITY;
}
@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)
private <T> T getCapabilityClient(ItemStack stack, @Nonnull Capability<T> capability, @Nullable EnumFacing facing){
if(capability == ISpecialRenderer.CAPABILITY)
return (T) new ExtractionProcessorRenderer(stack, EnumFacing.VALUES[stack.getTagCompound().getByte("to")], 1);
return null;
}
}
}
|
src/main/java/jp/crafterkina/pipes/common/pipe/strategy/StrategyOneway.java
|
package jp.crafterkina.pipes.common.pipe.strategy;
import jp.crafterkina.pipes.api.pipe.FlowItem;
import jp.crafterkina.pipes.api.pipe.IStrategy;
import jp.crafterkina.pipes.api.render.ISpecialRenderer;
import jp.crafterkina.pipes.client.tesr.processor.ExtractionProcessorRenderer;
import jp.crafterkina.pipes.common.block.entity.TileEntityPipe;
import jp.crafterkina.pipes.common.item.ItemProcessor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.BiFunction;
/**
* Created by Kina on 2016/12/23.
*/
public class StrategyOneway implements IStrategy{
private final ItemStack stack;
private final EnumFacing to;
private StrategyOneway(ItemStack stack, EnumFacing to){
this.stack = stack;
this.to = to;
}
@Override
public FlowItem turn(FlowItem item, Vec3d... connecting){
return new FlowItem(item.getStack(), to, item.getSpeed());
}
@Override
public IStrategy rotate(EnumFacing axis){
return new StrategyOneway(stack, to);
}
public static class ItemOnewayProcessor extends ItemProcessor{
public ItemOnewayProcessor(){
setUnlocalizedName("oneway");
setMaxStackSize(1);
}
public static int getColor(ItemStack stack, int layer){
return layer == 1 ? 0x535353 : 0xffffff;
}
@Override
protected ItemStack attachItem(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){
if(!(worldIn.getTileEntity(pos) instanceof TileEntityPipe)) return ItemStack.EMPTY;
ItemStack stack = player.getHeldItem(hand);
NBTTagCompound compound = stack.getTagCompound();
if(compound == null){
compound = new NBTTagCompound();
stack.setTagCompound(compound);
}
compound.setByte("to", (byte) facing.getIndex());
return stack;
}
@Override
protected BiFunction<ItemStack, TileEntity, IStrategy> getStrategy(){
return (s, t) -> {
if(!(t instanceof TileEntityPipe)) return null;
NBTTagCompound compound = s.getTagCompound();
if(compound == null) return null;
EnumFacing to = EnumFacing.VALUES[compound.getByte("to")];
return new StrategyOneway(s, to);
};
}
@SuppressWarnings("MethodCallSideOnly")
@Override
protected boolean hasAdditionalCapability(ItemStack stack, @Nonnull Capability<?> capability, @Nullable EnumFacing facing){
return FMLCommonHandler.instance().getSide().isClient() && hasCapabilityClient(stack, capability, facing);
}
@SuppressWarnings("MethodCallSideOnly")
@Nullable
@Override
protected <T> T getAdditionalCapability(ItemStack stack, @Nonnull Capability<T> capability, @Nullable EnumFacing facing){
if(FMLCommonHandler.instance().getSide().isClient())
return getCapabilityClient(stack, capability, facing);
return null;
}
@SideOnly(Side.CLIENT)
private boolean hasCapabilityClient(@SuppressWarnings("unused") ItemStack stack, @Nonnull Capability<?> capability, @Nullable EnumFacing facing){
return capability == ISpecialRenderer.CAPABILITY;
}
@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)
private <T> T getCapabilityClient(ItemStack stack, @Nonnull Capability<T> capability, @Nullable EnumFacing facing){
if(capability == ISpecialRenderer.CAPABILITY)
return (T) new ExtractionProcessorRenderer(stack, facing, 1);
return null;
}
}
}
|
Fix null face
(cherry picked from commit 042077d)
|
src/main/java/jp/crafterkina/pipes/common/pipe/strategy/StrategyOneway.java
|
Fix null face
|
|
Java
|
lgpl-2.1
|
48978b2c12733c2c5e34001dffa494dffe7a9fb4
| 0
|
rekii/toxiclibs,ruby-processing/toxiclibs,postspectacular/toxiclibs,postspectacular/toxiclibs,rekii/toxiclibs
|
/*
* __ .__ .__ ._____.
* _/ |_ _______ __|__| ____ | | |__\_ |__ ______
* \ __\/ _ \ \/ / |/ ___\| | | || __ \ / ___/
* | | ( <_> > <| \ \___| |_| || \_\ \\___ \
* |__| \____/__/\_ \__|\___ >____/__||___ /____ >
* \/ \/ \/ \/
*
* Copyright (c) 2006-2011 Karsten Schmidt
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
package toxi.geom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import toxi.geom.Line2D.LineIntersection;
import toxi.geom.Line2D.LineIntersection.Type;
import toxi.math.MathUtils;
public class LineStrip2D implements Iterable<Vec2D> {
@XmlElement(name = "v")
protected List<Vec2D> vertices = new ArrayList<Vec2D>();
protected float[] arcLenIndex;
public LineStrip2D() {
}
public LineStrip2D(Collection<? extends Vec2D> vertices) {
this.vertices = new ArrayList<Vec2D>(vertices);
}
public LineStrip2D add(float x, float y) {
vertices.add(new Vec2D(x, y));
return this;
}
public LineStrip2D add(ReadonlyVec2D p) {
vertices.add(p.copy());
return this;
}
public LineStrip2D add(Vec2D p) {
vertices.add(p);
return this;
}
/**
* Returns the vertex at the given index. This function follows Python
* convention, in that if the index is negative, it is considered relative
* to the list end. Therefore the vertex at index -1 is the last vertex in
* the list.
*
* @param i
* index
* @return vertex
*/
public Vec2D get(int i) {
if (i < 0) {
i += vertices.size();
}
return vertices.get(i);
}
public Circle getBoundingCircle() {
return Circle.newBoundingCircle(vertices);
}
public Rect getBounds() {
return Rect.getBoundingRect(vertices);
}
public Vec2D getCentroid() {
int num = vertices.size();
if (num > 0) {
Vec2D centroid = new Vec2D();
for (Vec2D v : vertices) {
centroid.addSelf(v);
}
return centroid.scaleSelf(1f / num);
}
return null;
}
/**
* Computes a list of points along the spline which are uniformly separated
* by the given step distance.
*
* @param step
* @return point list
*/
public List<Vec2D> getDecimatedVertices(float step) {
return getDecimatedVertices(step, true);
}
/**
* Computes a list of points along the spline which are close to uniformly
* separated by the given step distance. The uniform distribution is only an
* approximation and is based on the estimated arc length of the polyline.
* The distance between returned points might vary in places, especially if
* there're sharp angles between line segments.
*
* @param step
* @param doAddFinalVertex
* true, if the last vertex computed should be added regardless
* of its distance.
* @return point list
*/
public List<Vec2D> getDecimatedVertices(float step, boolean doAddFinalVertex) {
ArrayList<Vec2D> uniform = new ArrayList<Vec2D>();
if (vertices.size() < 3) {
if (vertices.size() == 2) {
new Line2D(vertices.get(0), vertices.get(1)).splitIntoSegments(
uniform, step, true);
if (!doAddFinalVertex) {
uniform.remove(uniform.size() - 1);
}
} else {
return null;
}
}
float arcLen = getLength();
if (arcLen > 0) {
double delta = step / arcLen;
int currIdx = 0;
for (double t = 0; t < 1.0; t += delta) {
double currT = t * arcLen;
while (currT >= arcLenIndex[currIdx]) {
currIdx++;
}
ReadonlyVec2D p = vertices.get(currIdx - 1);
ReadonlyVec2D q = vertices.get(currIdx);
float frac = (float) ((currT - arcLenIndex[currIdx - 1]) / (arcLenIndex[currIdx] - arcLenIndex[currIdx - 1]));
Vec2D i = p.interpolateTo(q, frac);
uniform.add(i);
}
if (doAddFinalVertex) {
uniform.add(vertices.get(vertices.size() - 1).copy());
}
}
return uniform;
}
/**
* Returns a list of {@link Line2D} segments representing the segments
* between the vertices of this strip.
*
* @return list of lines
*/
public List<Line2D> getEdges() {
int num = vertices.size();
List<Line2D> edges = new ArrayList<Line2D>(num - 1);
for (int i = 1; i < num; i++) {
edges.add(new Line2D(vertices.get(i - 1), vertices.get(i)));
}
return edges;
}
public float getLength() {
if (arcLenIndex == null
|| (arcLenIndex != null && arcLenIndex.length != vertices
.size())) {
arcLenIndex = new float[vertices.size()];
}
float arcLen = 0;
for (int i = 1; i < arcLenIndex.length; i++) {
ReadonlyVec2D p = vertices.get(i - 1);
ReadonlyVec2D q = vertices.get(i);
arcLen += p.distanceTo(q);
arcLenIndex[i] = arcLen;
}
return arcLen;
}
/**
* Computes point at position t, where t is the normalized position along
* the strip. If t<0 then the first vertex of the strip is returned. If
* t>=1.0 the last vertex is returned. If the strip contains less than 2
* vertices, this method returns null.
*
* @param t
* @return
*/
public Vec2D getPointAt(float t) {
int num = vertices.size();
if (num > 1) {
if (t <= 0.0) {
return vertices.get(0);
} else if (t >= 1.0) {
return vertices.get(num - 1);
}
float totalLength = this.getLength();
double offp = 0, offq = 0;
for (int i = 1; i < num; i++) {
Vec2D p = vertices.get(i - 1);
Vec2D q = vertices.get(i);
offq += q.distanceTo(p) / totalLength;
if (offp <= t && offq >= t) {
return p.interpolateTo(q, (float) MathUtils.mapInterval(t,
offp, offq, 0.0, 1.0));
}
offp = offq;
}
}
return null;
}
public List<Line2D> getSegments() {
final int num = vertices.size();
List<Line2D> segments = new ArrayList<Line2D>(num - 1);
for (int i = 1; i < num; i++) {
segments.add(new Line2D(vertices.get(i - 1), vertices.get(i)));
}
return segments;
}
/**
* @return the vertices
*/
public List<Vec2D> getVertices() {
return vertices;
}
public LineIntersection intersectLine(Line2D line) {
Line2D l = new Line2D(new Vec2D(), new Vec2D());
for (int i = 1, num = vertices.size(); i < num; i++) {
l.set(vertices.get(i - 1), vertices.get(i));
LineIntersection isec = l.intersectLine(line);
if (isec.getType() == Type.INTERSECTING
|| isec.getType() == Type.COINCIDENT) {
return isec;
}
}
return null;
}
public Iterator<Vec2D> iterator() {
return vertices.iterator();
}
public LineStrip2D rotate(float theta) {
for (Vec2D v : vertices) {
v.rotate(theta);
}
return this;
}
public LineStrip2D scale(float scale) {
return scale(scale, scale);
}
public LineStrip2D scale(float x, float y) {
for (Vec2D v : vertices) {
v.scaleSelf(x, y);
}
return this;
}
public LineStrip2D scale(ReadonlyVec2D scale) {
return scale(scale.x(), scale.y());
}
public LineStrip2D scaleSize(float scale) {
return scaleSize(scale, scale);
}
public LineStrip2D scaleSize(float x, float y) {
Vec2D centroid = getCentroid();
for (Vec2D v : vertices) {
v.subSelf(centroid).scaleSelf(x, y).addSelf(centroid);
}
return this;
}
public LineStrip2D scaleSize(ReadonlyVec2D scale) {
return scaleSize(scale.x(), scale.y());
}
/**
* @param vertices
* the vertices to set
*/
public void setVertices(List<Vec2D> vertices) {
this.vertices = vertices;
}
public LineStrip2D translate(float x, float y) {
for (Vec2D v : vertices) {
v.addSelf(x, y);
}
return this;
}
public LineStrip2D translate(ReadonlyVec2D offset) {
return translate(offset.x(), offset.y());
}
}
|
src.core/toxi/geom/LineStrip2D.java
|
/*
* __ .__ .__ ._____.
* _/ |_ _______ __|__| ____ | | |__\_ |__ ______
* \ __\/ _ \ \/ / |/ ___\| | | || __ \ / ___/
* | | ( <_> > <| \ \___| |_| || \_\ \\___ \
* |__| \____/__/\_ \__|\___ >____/__||___ /____ >
* \/ \/ \/ \/
*
* Copyright (c) 2006-2011 Karsten Schmidt
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
package toxi.geom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import toxi.geom.Line2D.LineIntersection;
import toxi.geom.Line2D.LineIntersection.Type;
import toxi.math.MathUtils;
public class LineStrip2D implements Iterable<Vec2D> {
@XmlElement(name = "v")
protected List<Vec2D> vertices = new ArrayList<Vec2D>();
protected float[] arcLenIndex;
public LineStrip2D() {
}
public LineStrip2D(Collection<? extends Vec2D> vertices) {
this.vertices = new ArrayList<Vec2D>(vertices);
}
public LineStrip2D add(float x, float y) {
vertices.add(new Vec2D(x, y));
return this;
}
public LineStrip2D add(ReadonlyVec2D p) {
vertices.add(p.copy());
return this;
}
public LineStrip2D add(Vec2D p) {
vertices.add(p);
return this;
}
/**
* Returns the vertex at the given index. This function follows Python
* convention, in that if the index is negative, it is considered relative
* to the list end. Therefore the vertex at index -1 is the last vertex in
* the list.
*
* @param i
* index
* @return vertex
*/
public Vec2D get(int i) {
if (i < 0) {
i += vertices.size();
}
return vertices.get(i);
}
public Circle getBoundingCircle() {
return Circle.newBoundingCircle(vertices);
}
public Rect getBounds() {
return Rect.getBoundingRect(vertices);
}
public Vec2D getCentroid() {
int num = vertices.size();
if (num > 0) {
Vec2D centroid = new Vec2D();
for (Vec2D v : vertices) {
centroid.addSelf(v);
}
return centroid.scaleSelf(1f / num);
}
return null;
}
/**
* Computes a list of points along the spline which are uniformly separated
* by the given step distance.
*
* @param step
* @return point list
*/
public List<Vec2D> getDecimatedVertices(float step) {
return getDecimatedVertices(step, true);
}
/**
* Computes a list of points along the spline which are close to uniformly
* separated by the given step distance. The uniform distribution is only an
* approximation and is based on the estimated arc length of the polyline.
* The distance between returned points might vary in places, especially if
* there're sharp angles between line segments.
*
* @param step
* @param doAddFinalVertex
* true, if the last vertex computed should be added regardless
* of its distance.
* @return point list
*/
public List<Vec2D> getDecimatedVertices(float step, boolean doAddFinalVertex) {
ArrayList<Vec2D> uniform = new ArrayList<Vec2D>();
if (vertices.size() < 3) {
if (vertices.size() == 2) {
new Line2D(vertices.get(0), vertices.get(1)).splitIntoSegments(
uniform, step, true);
if (!doAddFinalVertex) {
uniform.remove(uniform.size() - 1);
}
} else {
return null;
}
}
float arcLen = getLength();
if (arcLen > 0) {
double delta = step / arcLen;
int currIdx = 0;
for (double t = 0; t < 1.0; t += delta) {
double currT = t * arcLen;
while (currT >= arcLenIndex[currIdx]) {
currIdx++;
}
ReadonlyVec2D p = vertices.get(currIdx - 1);
ReadonlyVec2D q = vertices.get(currIdx);
float frac = (float) ((currT - arcLenIndex[currIdx - 1]) / (arcLenIndex[currIdx] - arcLenIndex[currIdx - 1]));
Vec2D i = p.interpolateTo(q, frac);
uniform.add(i);
}
if (doAddFinalVertex) {
uniform.add(vertices.get(vertices.size() - 1).copy());
}
}
return uniform;
}
public float getLength() {
if (arcLenIndex == null
|| (arcLenIndex != null && arcLenIndex.length != vertices
.size())) {
arcLenIndex = new float[vertices.size()];
}
float arcLen = 0;
for (int i = 1; i < arcLenIndex.length; i++) {
ReadonlyVec2D p = vertices.get(i - 1);
ReadonlyVec2D q = vertices.get(i);
arcLen += p.distanceTo(q);
arcLenIndex[i] = arcLen;
}
return arcLen;
}
/**
* Computes point at position t, where t is the normalized position along
* the strip. If t<0 then the first vertex of the strip is returned. If
* t>=1.0 the last vertex is returned. If the strip contains less than 2
* vertices, this method returns null.
*
* @param t
* @return
*/
public Vec2D getPointAt(float t) {
int num = vertices.size();
if (num > 1) {
if (t <= 0.0) {
return vertices.get(0);
} else if (t >= 1.0) {
return vertices.get(num - 1);
}
float totalLength = this.getLength();
double offp = 0, offq = 0;
for (int i = 1; i < num; i++) {
Vec2D p = vertices.get(i - 1);
Vec2D q = vertices.get(i);
offq += q.distanceTo(p) / totalLength;
if (offp <= t && offq >= t) {
return p.interpolateTo(q, (float) MathUtils.mapInterval(t,
offp, offq, 0.0, 1.0));
}
offp = offq;
}
}
return null;
}
public List<Line2D> getSegments() {
final int num = vertices.size();
List<Line2D> segments = new ArrayList<Line2D>(num - 1);
for (int i = 1; i < num; i++) {
segments.add(new Line2D(vertices.get(i - 1), vertices.get(i)));
}
return segments;
}
/**
* @return the vertices
*/
public List<Vec2D> getVertices() {
return vertices;
}
public LineIntersection intersectLine(Line2D line) {
Line2D l = new Line2D(new Vec2D(), new Vec2D());
for (int i = 1, num = vertices.size(); i < num; i++) {
l.set(vertices.get(i - 1), vertices.get(i));
LineIntersection isec = l.intersectLine(line);
if (isec.getType() == Type.INTERSECTING
|| isec.getType() == Type.COINCIDENT) {
return isec;
}
}
return null;
}
public Iterator<Vec2D> iterator() {
return vertices.iterator();
}
public LineStrip2D rotate(float theta) {
for (Vec2D v : vertices) {
v.rotate(theta);
}
return this;
}
public LineStrip2D scale(float scale) {
return scale(scale, scale);
}
public LineStrip2D scale(float x, float y) {
for (Vec2D v : vertices) {
v.scaleSelf(x, y);
}
return this;
}
public LineStrip2D scale(ReadonlyVec2D scale) {
return scale(scale.x(), scale.y());
}
public LineStrip2D scaleSize(float scale) {
return scaleSize(scale, scale);
}
public LineStrip2D scaleSize(float x, float y) {
Vec2D centroid = getCentroid();
for (Vec2D v : vertices) {
v.subSelf(centroid).scaleSelf(x, y).addSelf(centroid);
}
return this;
}
public LineStrip2D scaleSize(ReadonlyVec2D scale) {
return scaleSize(scale.x(), scale.y());
}
/**
* @param vertices
* the vertices to set
*/
public void setVertices(List<Vec2D> vertices) {
this.vertices = vertices;
}
public LineStrip2D translate(float x, float y) {
for (Vec2D v : vertices) {
v.addSelf(x, y);
}
return this;
}
public LineStrip2D translate(ReadonlyVec2D offset) {
return translate(offset.x(), offset.y());
}
}
|
adding getEdges()
--HG--
branch : spatialphysics
|
src.core/toxi/geom/LineStrip2D.java
|
adding getEdges()
|
|
Java
|
lgpl-2.1
|
8913119ed6ab7ab5aeabc1e82f50b3609fde46f0
| 0
|
Xiejiayun/soot-infoflow-android,Machiry/soot-infoflow-android,xph906/FlowDroidNew,secure-software-engineering/soot-infoflow-android,matedealer/soot-infoflow-android,kaunder/soot-infoflow-android,docteau/soot-infoflow-android,mohsinjuni/soot-infoflow-android,droidsec-cn/soot-infoflow-android,xph906/FlowDroidNew,lilicoding/soot-infoflow-android,jameswhang/flowdroid,wsnavely/soot-infoflow-android,uds-se/soot-infoflow-android
|
package soot.jimple.infoflow.android.data.parsers;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import soot.jimple.infoflow.android.data.AndroidMethod;
/**
* Parser for the permissions to method map of Adrienne Porter Felt.
*
* @author Siegfried Rasthofer
*/
public class PermissionMethodParser implements IPermissionMethodParser {
private static final int INITIAL_SET_SIZE = 10000;
private List<String> data;
private final String regex = "^<(.+):\\s*(.+)\\s+(.+)\\s*\\((.*)\\)>\\s*(.*?)(\\s+->\\s+(.*))?$";
// private final String regexNoRet = "^<(.+):\\s(.+)\\s?(.+)\\s*\\((.*)\\)>\\s+(.*?)(\\s+->\\s+(.*))?+$";
private final String regexNoRet = "^<(.+):\\s*(.+)\\s*\\((.*)\\)>\\s*(.*?)?(\\s+->\\s+(.*))?$";
public static PermissionMethodParser fromFile(String fileName) throws IOException {
PermissionMethodParser pmp = new PermissionMethodParser();
pmp.readFile(fileName);
return pmp;
}
public static PermissionMethodParser fromStringList(List<String> data) throws IOException {
PermissionMethodParser pmp = new PermissionMethodParser(data);
return pmp;
}
private PermissionMethodParser() {
}
private PermissionMethodParser(List<String> data) {
this.data = data;
}
private void readFile(String fileName) throws IOException{
String line;
this.data = new ArrayList<String>();
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
while((line = br.readLine()) != null)
this.data.add(line);
}
finally {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
}
public Set<AndroidMethod> parse() throws IOException{
Set<AndroidMethod> methodList = new HashSet<AndroidMethod>(INITIAL_SET_SIZE);
Pattern p = Pattern.compile(regex);
Pattern pNoRet = Pattern.compile(regexNoRet);
for(String line : this.data){
if (line.isEmpty() || line.startsWith("%"))
continue;
Matcher m = p.matcher(line);
if(m.find()) {
AndroidMethod singleMethod = parseMethod(m, true);
methodList.add(singleMethod);
}
else {
Matcher mNoRet = pNoRet.matcher(line);
if(mNoRet.find()) {
AndroidMethod singleMethod = parseMethod(mNoRet, false);
methodList.add(singleMethod);
}
else
System.err.println("Line does not match: " + line);
}
}
return methodList;
}
private AndroidMethod parseMethod(Matcher m, boolean hasReturnType) {
assert(m.group(1) != null && m.group(2) != null && m.group(3) != null
&& m.group(4) != null);
AndroidMethod singleMethod;
int groupIdx = 1;
//class name
String className = m.group(groupIdx++).trim();
String returnType = "";
if (hasReturnType) {
//return type
returnType = m.group(groupIdx++).trim();
}
//method name
String methodName = m.group(groupIdx++).trim();
//method parameter
List<String> methodParameters = new ArrayList<String>();
String params = m.group(groupIdx++).trim();
if (!params.isEmpty())
for (String parameter : params.split(","))
methodParameters.add(parameter.trim());
//permissions
String classData = "";
String permData = "";
Set<String> permissions = new HashSet<String>();
if (groupIdx < m.groupCount() && m.group(groupIdx) != null) {
permData = m.group(groupIdx);
if (permData.contains("->")) {
classData = permData.replace("->", "").trim();
permData = "";
}
groupIdx++;
}
if (!permData.isEmpty())
for(String permission : permData.split(" "))
permissions.add(permission);
//create method signature
singleMethod = new AndroidMethod(methodName, methodParameters, returnType, className, permissions);
if (classData.isEmpty())
if(m.group(groupIdx) != null) {
classData = m.group(groupIdx).replace("->", "").trim();
groupIdx++;
}
if (!classData.isEmpty())
for(String target : classData.split("\\s")) {
target = target.trim();
// Throw away categories
if (target.contains("|"))
target = target.substring(target.indexOf('|'));
if (!target.isEmpty() && !target.startsWith("|")) {
if(target.equals("_SOURCE_"))
singleMethod.setSource(true);
else if(target.equals("_SINK_"))
singleMethod.setSink(true);
else if(target.equals("_NONE_"))
singleMethod.setNeitherNor(true);
else
throw new RuntimeException("error in target definition: " + target);
}
}
return singleMethod;
}
}
|
src/soot/jimple/infoflow/android/data/parsers/PermissionMethodParser.java
|
package soot.jimple.infoflow.android.data.parsers;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import soot.jimple.infoflow.android.data.AndroidMethod;
/**
* Parser for the permissions to method map of Adrienne Porter Felt.
*
* @author Siegfried Rasthofer
*/
public class PermissionMethodParser implements IPermissionMethodParser {
private static final int INITIAL_SET_SIZE = 10000;
private List<String> data;
private final String regex = "^<(.+):\\s*(.+)\\s+(.+)\\s*\\((.*)\\)>\\s*(.*?)(\\s+->\\s+(.*))?$";
// private final String regexNoRet = "^<(.+):\\s(.+)\\s?(.+)\\s*\\((.*)\\)>\\s+(.*?)(\\s+->\\s+(.*))?+$";
private final String regexNoRet = "^<(.+):\\s*(.+)\\s*\\((.*)\\)>\\s*(.*?)?(\\s+->\\s+(.*))?$";
public static PermissionMethodParser fromFile(String fileName) throws IOException {
PermissionMethodParser pmp = new PermissionMethodParser();
pmp.readFile(fileName);
return pmp;
}
public static PermissionMethodParser fromStringList(List<String> data) throws IOException {
PermissionMethodParser pmp = new PermissionMethodParser(data);
return pmp;
}
private PermissionMethodParser() {
}
private PermissionMethodParser(List<String> data) {
this.data = data;
}
private void readFile(String fileName) throws IOException{
String line;
this.data = new ArrayList<String>();
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
while((line = br.readLine()) != null)
this.data.add(line);
}
finally {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
}
public Set<AndroidMethod> parse() throws IOException{
Set<AndroidMethod> methodList = new HashSet<AndroidMethod>(INITIAL_SET_SIZE);
Pattern p = Pattern.compile(regex);
Pattern pNoRet = Pattern.compile(regexNoRet);
for(String line : this.data){
if (line.startsWith("%"))
continue;
Matcher m = p.matcher(line);
if(m.find()) {
AndroidMethod singleMethod = parseMethod(m, true);
methodList.add(singleMethod);
}
else {
Matcher mNoRet = pNoRet.matcher(line);
if(mNoRet.find()) {
AndroidMethod singleMethod = parseMethod(mNoRet, false);
methodList.add(singleMethod);
}
else
System.err.println("Line does not match: " + line);
}
}
return methodList;
}
private AndroidMethod parseMethod(Matcher m, boolean hasReturnType) {
assert(m.group(1) != null && m.group(2) != null && m.group(3) != null
&& m.group(4) != null);
AndroidMethod singleMethod;
int groupIdx = 1;
//class name
String className = m.group(groupIdx++).trim();
String returnType = "";
if (hasReturnType) {
//return type
returnType = m.group(groupIdx++).trim();
}
//method name
String methodName = m.group(groupIdx++).trim();
//method parameter
List<String> methodParameters = new ArrayList<String>();
String params = m.group(groupIdx++).trim();
if (!params.isEmpty())
for (String parameter : params.split(","))
methodParameters.add(parameter.trim());
//permissions
String classData = "";
String permData = "";
Set<String> permissions = new HashSet<String>();
if (groupIdx < m.groupCount() && m.group(groupIdx) != null) {
permData = m.group(groupIdx);
if (permData.contains("->")) {
classData = permData.replace("->", "").trim();
permData = "";
}
groupIdx++;
}
if (!permData.isEmpty())
for(String permission : permData.split(" "))
permissions.add(permission);
//create method signature
singleMethod = new AndroidMethod(methodName, methodParameters, returnType, className, permissions);
if (classData.isEmpty())
if(m.group(groupIdx) != null) {
classData = m.group(groupIdx).replace("->", "").trim();
groupIdx++;
}
if (!classData.isEmpty())
for(String target : classData.split("\\s")) {
target = target.trim();
// Throw away categories
if (target.contains("|"))
target = target.substring(target.indexOf('|'));
if (!target.isEmpty() && !target.startsWith("|")) {
if(target.equals("_SOURCE_"))
singleMethod.setSource(true);
else if(target.equals("_SINK_"))
singleMethod.setSink(true);
else if(target.equals("_NONE_"))
singleMethod.setNeitherNor(true);
else
throw new RuntimeException("error in target definition: " + target);
}
}
return singleMethod;
}
}
|
now ignoring empty lines in source and sink definition file
|
src/soot/jimple/infoflow/android/data/parsers/PermissionMethodParser.java
|
now ignoring empty lines in source and sink definition file
|
|
Java
|
apache-2.0
|
5d48443a9830def64e40ed469d10a941fa5e8465
| 0
|
estebank/gitiles
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gitiles;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.http.server.ServletUtils;
import org.eclipse.jgit.http.server.glue.WrappedRequest;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
/** Filter to parse URLs and convert them to {@link GitilesView}s. */
public class ViewFilter extends AbstractHttpFilter {
private static final Logger log = LoggerFactory.getLogger(ViewFilter.class);
// TODO(dborowitz): Make this public in JGit (or implement getRegexGroup
// upstream).
private static final String REGEX_GROUPS_ATTRIBUTE =
"org.eclipse.jgit.http.server.glue.MetaServlet.serveRegex";
private static final String VIEW_ATTIRBUTE = ViewFilter.class.getName() + "/View";
private static final String CMD_ARCHIVE = "+archive";
private static final String CMD_AUTO = "+";
private static final String CMD_DESCRIBE = "+describe";
private static final String CMD_DIFF = "+diff";
private static final String CMD_LOG = "+log";
private static final String CMD_REFS = "+refs";
private static final String CMD_SHOW = "+show";
public static GitilesView getView(HttpServletRequest req) {
return (GitilesView) req.getAttribute(VIEW_ATTIRBUTE);
}
static String getRegexGroup(HttpServletRequest req, int groupId) {
WrappedRequest[] groups = (WrappedRequest[]) req.getAttribute(REGEX_GROUPS_ATTRIBUTE);
return checkNotNull(groups)[groupId].getPathInfo();
}
static void setView(HttpServletRequest req, GitilesView view) {
req.setAttribute(VIEW_ATTIRBUTE, view);
}
static String trimLeadingSlash(String str) {
return checkLeadingSlash(str).substring(1);
}
private static String checkLeadingSlash(String str) {
checkArgument(str.startsWith("/"), "expected string starting with a slash: %s", str);
return str;
}
private static boolean isEmptyOrSlash(String path) {
return path.isEmpty() || path.equals("/");
}
private final GitilesUrls urls;
private final GitilesAccess.Factory accessFactory;
private final VisibilityCache visibilityCache;
private final Set<String> archiveExts;
public ViewFilter(Config cfg, GitilesAccess.Factory accessFactory,
GitilesUrls urls, VisibilityCache visibilityCache) {
this.urls = checkNotNull(urls, "urls");
this.accessFactory = checkNotNull(accessFactory, "accessFactory");
this.visibilityCache = checkNotNull(visibilityCache, "visibilityCache");
this.archiveExts = Sets.newHashSet(ArchiveFormat.byExtension(cfg).keySet());
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException {
GitilesView.Builder view;
try {
view = parse(req);
} catch (IOException err) {
String name = urls.getHostName(req);
log.warn("Cannot parse view" + (name != null ? " for " + name : ""), err);
res.setStatus(SC_SERVICE_UNAVAILABLE);
return;
}
if (view == null) {
res.setStatus(SC_NOT_FOUND);
return;
}
@SuppressWarnings("unchecked")
Map<String, String[]> params = req.getParameterMap();
view.setHostName(urls.getHostName(req))
.setServletPath(req.getContextPath() + req.getServletPath())
.putAllParams(params);
setView(req, view.build());
try {
chain.doFilter(req, res);
} finally {
req.removeAttribute(VIEW_ATTIRBUTE);
}
}
private GitilesView.Builder parse(HttpServletRequest req) throws IOException {
String repoName = trimLeadingSlash(getRegexGroup(req, 1));
if (repoName.isEmpty()) {
return GitilesView.hostIndex();
}
String command = getRegexGroup(req, 2);
String path = getRegexGroup(req, 3);
if (command.isEmpty()) {
return parseNoCommand(req, repoName, path);
} else if (command.equals(CMD_ARCHIVE)) {
return parseArchiveCommand(req, repoName, path);
} else if (command.equals(CMD_AUTO)) {
return parseAutoCommand(req, repoName, path);
} else if (command.equals(CMD_DESCRIBE)) {
return parseDescribeCommand(req, repoName, path);
} else if (command.equals(CMD_DIFF)) {
return parseDiffCommand(req, repoName, path);
} else if (command.equals(CMD_LOG)) {
return parseLogCommand(req, repoName, path);
} else if (command.equals(CMD_REFS)) {
return parseRefsCommand(req, repoName, path);
} else if (command.equals(CMD_SHOW)) {
return parseShowCommand(req, repoName, path);
} else {
return null;
}
}
private GitilesView.Builder parseNoCommand(
HttpServletRequest req, String repoName, String path) {
return GitilesView.repositoryIndex().setRepositoryName(repoName);
}
private GitilesView.Builder parseArchiveCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
String ext = null;
for (String e : archiveExts) {
if (path.endsWith(e)) {
path = path.substring(0, path.length() - e.length());
ext = e;
break;
}
}
if (ext == null) {
return null;
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null || result.getOldRevision() != null) {
return null;
}
return GitilesView.archive()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setExtension(ext);
}
private GitilesView.Builder parseAutoCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
// Note: if you change the mapping for +, make sure to change
// GitilesView.toUrl() correspondingly.
if (path.isEmpty()) {
return null;
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null) {
return null;
}
if (result.getOldRevision() != null) {
return parseDiffCommand(repoName, result);
} else {
return parseShowCommand(repoName, result);
}
}
private GitilesView.Builder parseDescribeCommand(
HttpServletRequest req, String repoName, String path) {
if (isEmptyOrSlash(path)) {
return null;
}
return GitilesView.describe()
.setRepositoryName(repoName)
.setPathPart(path);
}
private GitilesView.Builder parseDiffCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
return parseDiffCommand(repoName, parseRevision(req, path));
}
private GitilesView.Builder parseDiffCommand(
String repoName, RevisionParser.Result result) {
if (result == null) {
return null;
}
return GitilesView.diff()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setOldRevision(result.getOldRevision())
.setPathPart(result.getPath());
}
private GitilesView.Builder parseLogCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
if (isEmptyOrSlash(path)) {
return GitilesView.log().setRepositoryName(repoName);
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null) {
return null;
}
return GitilesView.log()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setOldRevision(result.getOldRevision())
.setPathPart(result.getPath());
}
private GitilesView.Builder parseRefsCommand(
HttpServletRequest req, String repoName, String path) {
return GitilesView.refs()
.setRepositoryName(repoName)
.setPathPart(path);
}
private GitilesView.Builder parseShowCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
return parseShowCommand(repoName, parseRevision(req, path));
}
private GitilesView.Builder parseShowCommand(
String repoName, RevisionParser.Result result) {
if (result == null || result.getOldRevision() != null) {
return null;
}
if (result.getPath().isEmpty()) {
return GitilesView.revision()
.setRepositoryName(repoName)
.setRevision(result.getRevision());
} else {
return GitilesView.path()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setPathPart(result.getPath());
}
}
private RevisionParser.Result parseRevision(HttpServletRequest req, String path)
throws IOException {
RevisionParser revParser = new RevisionParser(
ServletUtils.getRepository(req), accessFactory.forRequest(req), visibilityCache);
return revParser.parse(checkLeadingSlash(path));
}
}
|
gitiles-servlet/src/main/java/com/google/gitiles/ViewFilter.java
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gitiles;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jgit.http.server.ServletUtils;
import org.eclipse.jgit.http.server.glue.WrappedRequest;
import org.eclipse.jgit.lib.Config;
import com.google.common.collect.Sets;
/** Filter to parse URLs and convert them to {@link GitilesView}s. */
public class ViewFilter extends AbstractHttpFilter {
// TODO(dborowitz): Make this public in JGit (or implement getRegexGroup
// upstream).
private static final String REGEX_GROUPS_ATTRIBUTE =
"org.eclipse.jgit.http.server.glue.MetaServlet.serveRegex";
private static final String VIEW_ATTIRBUTE = ViewFilter.class.getName() + "/View";
private static final String CMD_ARCHIVE = "+archive";
private static final String CMD_AUTO = "+";
private static final String CMD_DESCRIBE = "+describe";
private static final String CMD_DIFF = "+diff";
private static final String CMD_LOG = "+log";
private static final String CMD_REFS = "+refs";
private static final String CMD_SHOW = "+show";
public static GitilesView getView(HttpServletRequest req) {
return (GitilesView) req.getAttribute(VIEW_ATTIRBUTE);
}
static String getRegexGroup(HttpServletRequest req, int groupId) {
WrappedRequest[] groups = (WrappedRequest[]) req.getAttribute(REGEX_GROUPS_ATTRIBUTE);
return checkNotNull(groups)[groupId].getPathInfo();
}
static void setView(HttpServletRequest req, GitilesView view) {
req.setAttribute(VIEW_ATTIRBUTE, view);
}
static String trimLeadingSlash(String str) {
return checkLeadingSlash(str).substring(1);
}
private static String checkLeadingSlash(String str) {
checkArgument(str.startsWith("/"), "expected string starting with a slash: %s", str);
return str;
}
private static boolean isEmptyOrSlash(String path) {
return path.isEmpty() || path.equals("/");
}
private final GitilesUrls urls;
private final GitilesAccess.Factory accessFactory;
private final VisibilityCache visibilityCache;
private final Set<String> archiveExts;
public ViewFilter(Config cfg, GitilesAccess.Factory accessFactory,
GitilesUrls urls, VisibilityCache visibilityCache) {
this.urls = checkNotNull(urls, "urls");
this.accessFactory = checkNotNull(accessFactory, "accessFactory");
this.visibilityCache = checkNotNull(visibilityCache, "visibilityCache");
this.archiveExts = Sets.newHashSet(ArchiveFormat.byExtension(cfg).keySet());
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException {
GitilesView.Builder view = parse(req);
if (view == null) {
res.setStatus(SC_NOT_FOUND);
return;
}
@SuppressWarnings("unchecked")
Map<String, String[]> params = req.getParameterMap();
view.setHostName(urls.getHostName(req))
.setServletPath(req.getContextPath() + req.getServletPath())
.putAllParams(params);
setView(req, view.build());
try {
chain.doFilter(req, res);
} finally {
req.removeAttribute(VIEW_ATTIRBUTE);
}
}
private GitilesView.Builder parse(HttpServletRequest req) throws IOException {
String repoName = trimLeadingSlash(getRegexGroup(req, 1));
if (repoName.isEmpty()) {
return GitilesView.hostIndex();
}
String command = getRegexGroup(req, 2);
String path = getRegexGroup(req, 3);
if (command.isEmpty()) {
return parseNoCommand(req, repoName, path);
} else if (command.equals(CMD_ARCHIVE)) {
return parseArchiveCommand(req, repoName, path);
} else if (command.equals(CMD_AUTO)) {
return parseAutoCommand(req, repoName, path);
} else if (command.equals(CMD_DESCRIBE)) {
return parseDescribeCommand(req, repoName, path);
} else if (command.equals(CMD_DIFF)) {
return parseDiffCommand(req, repoName, path);
} else if (command.equals(CMD_LOG)) {
return parseLogCommand(req, repoName, path);
} else if (command.equals(CMD_REFS)) {
return parseRefsCommand(req, repoName, path);
} else if (command.equals(CMD_SHOW)) {
return parseShowCommand(req, repoName, path);
} else {
return null;
}
}
private GitilesView.Builder parseNoCommand(
HttpServletRequest req, String repoName, String path) {
return GitilesView.repositoryIndex().setRepositoryName(repoName);
}
private GitilesView.Builder parseArchiveCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
String ext = null;
for (String e : archiveExts) {
if (path.endsWith(e)) {
path = path.substring(0, path.length() - e.length());
ext = e;
break;
}
}
if (ext == null) {
return null;
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null || result.getOldRevision() != null) {
return null;
}
return GitilesView.archive()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setExtension(ext);
}
private GitilesView.Builder parseAutoCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
// Note: if you change the mapping for +, make sure to change
// GitilesView.toUrl() correspondingly.
if (path.isEmpty()) {
return null;
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null) {
return null;
}
if (result.getOldRevision() != null) {
return parseDiffCommand(repoName, result);
} else {
return parseShowCommand(repoName, result);
}
}
private GitilesView.Builder parseDescribeCommand(
HttpServletRequest req, String repoName, String path) {
if (isEmptyOrSlash(path)) {
return null;
}
return GitilesView.describe()
.setRepositoryName(repoName)
.setPathPart(path);
}
private GitilesView.Builder parseDiffCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
return parseDiffCommand(repoName, parseRevision(req, path));
}
private GitilesView.Builder parseDiffCommand(
String repoName, RevisionParser.Result result) {
if (result == null) {
return null;
}
return GitilesView.diff()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setOldRevision(result.getOldRevision())
.setPathPart(result.getPath());
}
private GitilesView.Builder parseLogCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
if (isEmptyOrSlash(path)) {
return GitilesView.log().setRepositoryName(repoName);
}
RevisionParser.Result result = parseRevision(req, path);
if (result == null) {
return null;
}
return GitilesView.log()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setOldRevision(result.getOldRevision())
.setPathPart(result.getPath());
}
private GitilesView.Builder parseRefsCommand(
HttpServletRequest req, String repoName, String path) {
return GitilesView.refs()
.setRepositoryName(repoName)
.setPathPart(path);
}
private GitilesView.Builder parseShowCommand(
HttpServletRequest req, String repoName, String path) throws IOException {
return parseShowCommand(repoName, parseRevision(req, path));
}
private GitilesView.Builder parseShowCommand(
String repoName, RevisionParser.Result result) {
if (result == null || result.getOldRevision() != null) {
return null;
}
if (result.getPath().isEmpty()) {
return GitilesView.revision()
.setRepositoryName(repoName)
.setRevision(result.getRevision());
} else {
return GitilesView.path()
.setRepositoryName(repoName)
.setRevision(result.getRevision())
.setPathPart(result.getPath());
}
}
private RevisionParser.Result parseRevision(HttpServletRequest req, String path)
throws IOException {
RevisionParser revParser = new RevisionParser(
ServletUtils.getRepository(req), accessFactory.forRequest(req), visibilityCache);
return revParser.parse(checkLeadingSlash(path));
}
}
|
Send 503 on IOException in ViewFilter.
Previously the filter propagated the IOException up the stack.
Explicitly log and send an 503 when an IOException occurs during parse
in ViewFilter.
Change-Id: Ibe77cd12d687f54abb2271b1caa326f524bad7d2
|
gitiles-servlet/src/main/java/com/google/gitiles/ViewFilter.java
|
Send 503 on IOException in ViewFilter.
|
|
Java
|
apache-2.0
|
04643aa8fc64b26571f3ddac6ef4f8ca5cf3e9c4
| 0
|
winklerm/drools,romartin/drools,manstis/drools,droolsjbpm/drools,droolsjbpm/drools,lanceleverich/drools,winklerm/drools,reynoldsm88/drools,manstis/drools,jomarko/drools,droolsjbpm/drools,winklerm/drools,manstis/drools,lanceleverich/drools,winklerm/drools,manstis/drools,lanceleverich/drools,manstis/drools,romartin/drools,reynoldsm88/drools,lanceleverich/drools,jomarko/drools,winklerm/drools,romartin/drools,romartin/drools,lanceleverich/drools,jomarko/drools,reynoldsm88/drools,reynoldsm88/drools,romartin/drools,droolsjbpm/drools,droolsjbpm/drools,jomarko/drools,reynoldsm88/drools,jomarko/drools
|
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.modelcompiler;
import org.drools.core.reteoo.AlphaNode;
import org.drools.javaparser.JavaParser;
import org.drools.model.Global;
import org.drools.model.Index.ConstraintType;
import org.drools.model.Model;
import org.drools.model.Query1;
import org.drools.model.Query2;
import org.drools.model.Rule;
import org.drools.model.Variable;
import org.drools.model.impl.ModelImpl;
import org.drools.modelcompiler.builder.KieBaseBuilder;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.runtime.ClassObjectFilter;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.QueryResults;
import java.util.Collection;
import static org.drools.model.DSL.*;
import static org.junit.Assert.*;
public class FlowTest {
public static class Result {
private Object value;
public Result() { }
public Result(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
public void setValue( Object value ) {
this.value = value;
}
@Override
public String toString() {
return value.toString();
}
}
@Test
public void testBeta() {
Result result = new Result();
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<Person> olderV = declarationOf( type( Person.class ) );
Rule rule = rule( "beta" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name", "age" ), // also react on age, see RuleDescr.lookAheadFieldsOfIdentifier
expr("exprB", olderV, p -> !p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.NOT_EQUAL, Person::getName, "Mark" )
.reactOn( "name" ),
expr("exprC", olderV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
.indexedBy( int.class, ConstraintType.GREATER_THAN, Person::getAge, Person::getAge )
.reactOn( "age" )
)
.then(on(olderV, markV)
.execute((p1, p2) -> result.value = p1.getName() + " is older than " + p2.getName()));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
FactHandle markFH = ksession.insert(mark);
FactHandle edsonFH = ksession.insert(edson);
FactHandle marioFH = ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mario is older than Mark", result.value);
result.value = null;
ksession.delete( marioFH );
ksession.fireAllRules();
assertNull(result.value);
mark.setAge( 34 );
ksession.update( markFH, mark, "age" );
ksession.fireAllRules();
assertEquals("Edson is older than Mark", result.value);
}
@Test
public void testBetaWithResult() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<Person> olderV = declarationOf( type( Person.class ) );
Variable<Result> resultV = declarationOf( type( Result.class ) );
Rule rule = rule( "beta" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name", "age" ), // also react on age, see RuleDescr.lookAheadFieldsOfIdentifier
expr("exprB", olderV, p -> !p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.NOT_EQUAL, Person::getName, "Mark" )
.reactOn( "name" ),
expr("exprC", olderV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
.indexedBy( int.class, ConstraintType.GREATER_THAN, Person::getAge, Person::getAge )
.reactOn( "age" )
)
.then(on(olderV, markV, resultV)
.execute((p1, p2, r) -> r.setValue( p1.getName() + " is older than " + p2.getName()) ));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Result result = new Result();
ksession.insert(result);
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
FactHandle markFH = ksession.insert(mark);
FactHandle edsonFH = ksession.insert(edson);
FactHandle marioFH = ksession.insert(mario);
ksession.fireAllRules();
assertEquals( "Mario is older than Mark", result.getValue() );
}
@Test
public void test3Patterns() {
Result result = new Result();
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<String> nameV = declarationOf( type( String.class ) );
Rule rule = rule( "myrule" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark")),
expr("exprB", personV, markV, (p1, p2) -> p1.getAge() > p2.getAge()),
expr("exprC", nameV, personV, (s, p) -> s.equals( p.getName() ))
)
.then(on(nameV)
.execute(s -> result.value = s));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( "Mario" );
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Mario", result.value);
}
@Test
public void testOr() {
Result result = new Result();
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<String> nameV = declarationOf( type( String.class ) );
Rule rule = rule( "or" )
.view(
or(
expr("exprA", personV, p -> p.getName().equals("Mark")),
and(
expr("exprA", markV, p -> p.getName().equals("Mark")),
expr("exprB", personV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
)
),
expr("exprC", nameV, personV, (s, p) -> s.equals( p.getName() ))
)
.then(on(nameV)
.execute(s -> result.value = s));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( "Mario" );
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Mario", result.value);
}
@Test
public void testNot() {
Result result = new Result();
Variable<Person> oldestV = declarationOf( type( Person.class ) );
Variable<Person> otherV = declarationOf( type( Person.class ) );
Rule rule = rule("not")
.view(
not(otherV, oldestV, (p1, p2) -> p1.getAge() > p2.getAge())
)
.then(on(oldestV)
.execute(p -> result.value = "Oldest person is " + p.getName()));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Oldest person is Mario", result.value);
}
@Test
public void testAccumulate1() {
Result result = new Result();
Variable<Person> person = declarationOf( type( Person.class ) );
Variable<Integer> resultSum = declarationOf( type( Integer.class ) );
Rule rule = rule("accumulate")
.view(
accumulate(expr(person, p -> p.getName().startsWith("M")),
sum((Person p) -> p.getAge()).as(resultSum))
)
.then( on(resultSum).execute(sum -> result.value = "total = " + sum) );
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("total = 77", result.value);
}
@Test
public void testAccumulate2() {
Result result = new Result();
Variable<Person> person = declarationOf( type( Person.class ) );
Variable<Integer> resultSum = declarationOf( type( Integer.class ) );
Variable<Double> resultAvg = declarationOf( type( Double.class ) );
Rule rule = rule("accumulate")
.view(
accumulate(expr(person, p -> p.getName().startsWith("M")),
sum(Person::getAge).as(resultSum),
avg(Person::getAge).as(resultAvg))
)
.then(
on(resultSum, resultAvg)
.execute((sum, avg) -> result.value = "total = " + sum + "; average = " + avg)
);
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("total = 77; average = 38.5", result.value);
}
@Test
public void testGlobalInConsequence() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Global<Result> resultG = globalOf( type( Result.class ), "org.mypkg" );
Rule rule = rule( "org.mypkg", "global" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name" )
)
.then(on(markV, resultG)
.execute((p, r) -> r.setValue( p.getName() + " is " + p.getAge() ) ) );
Model model = new ModelImpl().addRule( rule ).addGlobal( resultG );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Result result = new Result();
ksession.setGlobal( resultG.getName(), result );
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
ksession.insert(mark);
ksession.insert(edson);
ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mark is 37", result.value);
}
@Test
public void testGlobalInConstraint() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Global<Result> resultG = globalOf( type( Result.class ), "org.mypkg" );
Global<String> nameG = globalOf( type( String.class ), "org.mypkg" );
Rule rule = rule( "org.mypkg", "global" )
.view(
expr("exprA", markV, nameG, (p, n) -> p.getName().equals(n))
.reactOn( "name" )
)
.then(on(markV, resultG)
.execute((p, r) -> r.setValue( p.getName() + " is " + p.getAge() ) ) );
Model model = new ModelImpl().addRule( rule ).addGlobal( nameG ).addGlobal( resultG );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.setGlobal( nameG.getName(), "Mark" );
Result result = new Result();
ksession.setGlobal( resultG.getName(), result );
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
ksession.insert(mark);
ksession.insert(edson);
ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mark is 37", result.value);
}
@Test
public void testNotEmptyPredicate() {
Rule rule = rule("R")
.view(not(input(declarationOf(type(Person.class)))))
.then(execute((drools) -> drools.insert(new Result("ok")) ));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ReteDumper.checkRete(ksession, node -> !(node instanceof AlphaNode) );
Person mario = new Person("Mario", 40);
ksession.insert(mario);
ksession.fireAllRules();
assertTrue( ksession.getObjects(new ClassObjectFilter( Result.class ) ).isEmpty() );
}
@Test
public void testQuery() {
Variable<Person> personV = declarationOf( type( Person.class ), "$p" );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query1<Integer> query = query( "olderThan", ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Model model = new ModelImpl().addQuery( query );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
QueryResults results = ksession.getQueryResults( "olderThan", 40 );
assertEquals( 1, results.size() );
Person p = (Person) results.iterator().next().get( "$p" );
assertEquals( "Mario", p.getName() );
}
@Test
public void testQueryInRule() {
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query2<Person, Integer> query = query( "olderThan", personV, ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Rule rule = rule("R")
.view( query.call(personV, valueOf(40)) )
.then(on(personV)
.execute((drools, p) -> drools.insert(new Result(p.getName())) ));
Model model = new ModelImpl().addQuery( query ).addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
ksession.fireAllRules();
Collection<Result> results = (Collection<Result>) ksession.getObjects( new ClassObjectFilter( Result.class ) );
assertEquals( 1, results.size() );
assertEquals( "Mario", results.iterator().next().getValue() );
}
@Test
public void testQueryInRuleWithDeclaration() {
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query2<Person, Integer> query = query( "olderThan", personV, ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Rule rule = rule("R")
.view(
expr( "exprB", personV, p -> p.getName().startsWith( "M" ) ),
query.call(personV, valueOf(40))
)
.then(on(personV)
.execute((drools, p) -> drools.insert(new Result(p.getName())) ));
Model model = new ModelImpl().addQuery( query ).addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
ksession.insert( new Person( "Edson", 41 ) );
ksession.fireAllRules();
Collection<Result> results = (Collection<Result>) ksession.getObjects( new ClassObjectFilter( Result.class ) );
assertEquals( 1, results.size() );
assertEquals( "Mario", results.iterator().next().getValue() );
}
}
|
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/FlowTest.java
|
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.modelcompiler;
import org.drools.core.reteoo.AlphaNode;
import org.drools.javaparser.JavaParser;
import org.drools.model.Global;
import org.drools.model.Index.ConstraintType;
import org.drools.model.Model;
import org.drools.model.Query1;
import org.drools.model.Query2;
import org.drools.model.Rule;
import org.drools.model.Variable;
import org.drools.model.impl.ModelImpl;
import org.drools.modelcompiler.builder.KieBaseBuilder;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.runtime.ClassObjectFilter;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.QueryResults;
import java.util.Collection;
import static org.drools.model.DSL.*;
import static org.junit.Assert.*;
public class FlowTest {
public static class Result {
private Object value;
public Result() { }
public Result(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
public void setValue( Object value ) {
this.value = value;
}
@Override
public String toString() {
return value.toString();
}
}
@Test
public void testBeta() {
Result result = new Result();
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<Person> olderV = declarationOf( type( Person.class ) );
Rule rule = rule( "beta" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name", "age" ), // also react on age, see RuleDescr.lookAheadFieldsOfIdentifier
expr("exprB", olderV, p -> !p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.NOT_EQUAL, Person::getName, "Mark" )
.reactOn( "name" ),
expr("exprC", olderV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
.indexedBy( int.class, ConstraintType.GREATER_THAN, Person::getAge, Person::getAge )
.reactOn( "age" )
)
.then(on(olderV, markV)
.execute((p1, p2) -> result.value = p1.getName() + " is older than " + p2.getName()));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
FactHandle markFH = ksession.insert(mark);
FactHandle edsonFH = ksession.insert(edson);
FactHandle marioFH = ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mario is older than Mark", result.value);
result.value = null;
ksession.delete( marioFH );
ksession.fireAllRules();
assertNull(result.value);
mark.setAge( 34 );
ksession.update( markFH, mark, "age" );
ksession.fireAllRules();
assertEquals("Edson is older than Mark", result.value);
}
@Test
public void testBetaWithResult() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<Person> olderV = declarationOf( type( Person.class ) );
Variable<Result> resultV = declarationOf( type( Result.class ) );
Rule rule = rule( "beta" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name", "age" ), // also react on age, see RuleDescr.lookAheadFieldsOfIdentifier
expr("exprB", olderV, p -> !p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.NOT_EQUAL, Person::getName, "Mark" )
.reactOn( "name" ),
expr("exprC", olderV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
.indexedBy( int.class, ConstraintType.GREATER_THAN, Person::getAge, Person::getAge )
.reactOn( "age" )
)
.then(on(olderV, markV, resultV)
.execute((p1, p2, r) -> r.setValue( p1.getName() + " is older than " + p2.getName()) ));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Result result = new Result();
ksession.insert(result);
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
FactHandle markFH = ksession.insert(mark);
FactHandle edsonFH = ksession.insert(edson);
FactHandle marioFH = ksession.insert(mario);
ksession.fireAllRules();
assertEquals( "Mario is older than Mark", result.getValue() );
}
@Test
public void test3Patterns() {
Result result = new Result();
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<String> nameV = declarationOf( type( String.class ) );
Rule rule = rule( "myrule" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark")),
expr("exprB", personV, markV, (p1, p2) -> p1.getAge() > p2.getAge()),
expr("exprC", nameV, personV, (s, p) -> s.equals( p.getName() ))
)
.then(on(nameV)
.execute(s -> result.value = s));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( "Mario" );
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Mario", result.value);
}
@Test
public void testOr() {
Result result = new Result();
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Person> markV = declarationOf( type( Person.class ) );
Variable<String> nameV = declarationOf( type( String.class ) );
Rule rule = rule( "or" )
.view(
or(
expr("exprA", personV, p -> p.getName().equals("Mark")),
and(
expr("exprA", markV, p -> p.getName().equals("Mark")),
expr("exprB", personV, markV, (p1, p2) -> p1.getAge() > p2.getAge())
)
),
expr("exprC", nameV, personV, (s, p) -> s.equals( p.getName() ))
)
.then(on(nameV)
.execute(s -> result.value = s));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( "Mario" );
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Mario", result.value);
}
@Test
public void testNot() {
Result result = new Result();
Variable<Person> oldestV = declarationOf( type( Person.class ) );
Variable<Person> otherV = declarationOf( type( Person.class ) );
Rule rule = rule("not")
.view(
not(otherV, oldestV, (p1, p2) -> p1.getAge() > p2.getAge())
)
.then(on(oldestV)
.execute(p -> result.value = "Oldest person is " + p.getName()));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("Oldest person is Mario", result.value);
}
@Test
public void testAccumulate1() {
Result result = new Result();
Variable<Person> person = declarationOf( type( Person.class ) );
Variable<Integer> resultSum = declarationOf( type( Integer.class ) );
Rule rule = rule("accumulate")
.view(
accumulate(expr(person, p -> p.getName().startsWith("M")),
sum((Person p) -> p.getAge()).as(resultSum))
)
.then( on(resultSum).execute(sum -> result.value = "total = " + sum) );
// TODO: Remove this
final Object parsed = JavaParser.parseBlock("{" +
" Rule rule = rule(\"accumulate\")\n" +
" .view(\n" +
" accumulate(expr(person, p -> p.getName().startsWith(\"M\")),\n" +
" sum((Person p) -> p.getAge()).as(resultSum))\n" +
" )\n" +
" .then( on(resultSum).execute(sum -> result.value = \"total = \" + sum) );" +
"}" +
"");
System.out.println("\n\n\n\n\n\n\n");
System.out.println("parsed = " + parsed);
System.out.println("\n\n\n\n\n\n\n");
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("total = 77", result.value);
}
@Test
public void testAccumulate2() {
Result result = new Result();
Variable<Person> person = declarationOf( type( Person.class ) );
Variable<Integer> resultSum = declarationOf( type( Integer.class ) );
Variable<Double> resultAvg = declarationOf( type( Double.class ) );
Rule rule = rule("accumulate")
.view(
accumulate(expr(person, p -> p.getName().startsWith("M")),
sum(Person::getAge).as(resultSum),
avg(Person::getAge).as(resultAvg))
)
.then(
on(resultSum, resultAvg)
.execute((sum, avg) -> result.value = "total = " + sum + "; average = " + avg)
);
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 40));
ksession.fireAllRules();
assertEquals("total = 77; average = 38.5", result.value);
}
@Test
public void testGlobalInConsequence() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Global<Result> resultG = globalOf( type( Result.class ), "org.mypkg" );
Rule rule = rule( "org.mypkg", "global" )
.view(
expr("exprA", markV, p -> p.getName().equals("Mark"))
.indexedBy( String.class, ConstraintType.EQUAL, Person::getName, "Mark" )
.reactOn( "name" )
)
.then(on(markV, resultG)
.execute((p, r) -> r.setValue( p.getName() + " is " + p.getAge() ) ) );
Model model = new ModelImpl().addRule( rule ).addGlobal( resultG );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
Result result = new Result();
ksession.setGlobal( resultG.getName(), result );
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
ksession.insert(mark);
ksession.insert(edson);
ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mark is 37", result.value);
}
@Test
public void testGlobalInConstraint() {
Variable<Person> markV = declarationOf( type( Person.class ) );
Global<Result> resultG = globalOf( type( Result.class ), "org.mypkg" );
Global<String> nameG = globalOf( type( String.class ), "org.mypkg" );
Rule rule = rule( "org.mypkg", "global" )
.view(
expr("exprA", markV, nameG, (p, n) -> p.getName().equals(n))
.reactOn( "name" )
)
.then(on(markV, resultG)
.execute((p, r) -> r.setValue( p.getName() + " is " + p.getAge() ) ) );
Model model = new ModelImpl().addRule( rule ).addGlobal( nameG ).addGlobal( resultG );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.setGlobal( nameG.getName(), "Mark" );
Result result = new Result();
ksession.setGlobal( resultG.getName(), result );
Person mark = new Person("Mark", 37);
Person edson = new Person("Edson", 35);
Person mario = new Person("Mario", 40);
ksession.insert(mark);
ksession.insert(edson);
ksession.insert(mario);
ksession.fireAllRules();
assertEquals("Mark is 37", result.value);
}
@Test
public void testNotEmptyPredicate() {
Rule rule = rule("R")
.view(not(input(declarationOf(type(Person.class)))))
.then(execute((drools) -> drools.insert(new Result("ok")) ));
Model model = new ModelImpl().addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ReteDumper.checkRete(ksession, node -> !(node instanceof AlphaNode) );
Person mario = new Person("Mario", 40);
ksession.insert(mario);
ksession.fireAllRules();
assertTrue( ksession.getObjects(new ClassObjectFilter( Result.class ) ).isEmpty() );
}
@Test
public void testQuery() {
Variable<Person> personV = declarationOf( type( Person.class ), "$p" );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query1<Integer> query = query( "olderThan", ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Model model = new ModelImpl().addQuery( query );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
QueryResults results = ksession.getQueryResults( "olderThan", 40 );
assertEquals( 1, results.size() );
Person p = (Person) results.iterator().next().get( "$p" );
assertEquals( "Mario", p.getName() );
}
@Test
public void testQueryInRule() {
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query2<Person, Integer> query = query( "olderThan", personV, ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Rule rule = rule("R")
.view( query.call(personV, valueOf(40)) )
.then(on(personV)
.execute((drools, p) -> drools.insert(new Result(p.getName())) ));
Model model = new ModelImpl().addQuery( query ).addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
ksession.fireAllRules();
Collection<Result> results = (Collection<Result>) ksession.getObjects( new ClassObjectFilter( Result.class ) );
assertEquals( 1, results.size() );
assertEquals( "Mario", results.iterator().next().getValue() );
}
@Test
public void testQueryInRuleWithDeclaration() {
Variable<Person> personV = declarationOf( type( Person.class ) );
Variable<Integer> ageV = declarationOf( type( Integer.class ) );
Query2<Person, Integer> query = query( "olderThan", personV, ageV )
.view( expr("exprA", personV, ageV, (p, a) -> p.getAge() > a) );
Rule rule = rule("R")
.view(
expr( "exprB", personV, p -> p.getName().startsWith( "M" ) ),
query.call(personV, valueOf(40))
)
.then(on(personV)
.execute((drools, p) -> drools.insert(new Result(p.getName())) ));
Model model = new ModelImpl().addQuery( query ).addRule( rule );
KieBase kieBase = KieBaseBuilder.createKieBaseFromModel( model );
KieSession ksession = kieBase.newKieSession();
ksession.insert( new Person( "Mark", 39 ) );
ksession.insert( new Person( "Mario", 41 ) );
ksession.insert( new Person( "Edson", 41 ) );
ksession.fireAllRules();
Collection<Result> results = (Collection<Result>) ksession.getObjects( new ClassObjectFilter( Result.class ) );
assertEquals( 1, results.size() );
assertEquals( "Mario", results.iterator().next().getValue() );
}
}
|
Removed println in test (#1470)
|
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/FlowTest.java
|
Removed println in test (#1470)
|
|
Java
|
apache-2.0
|
e26991fead79123ecb46f90dd3f2f9d4fba7df3e
| 0
|
apache/ode,aaronanderson/ode,apache/ode,mproch/apache-ode,Subasinghe/ode,Subasinghe/ode,Subasinghe/ode,Subasinghe/ode,aaronanderson/ode,mproch/apache-ode,aaronanderson/ode,apache/ode,aaronanderson/ode,Subasinghe/ode,apache/ode,apache/ode
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.axis2;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.collections.map.MultiKeyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.deploy.DeploymentPoller;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.axis2.hooks.ODEMessageReceiver;
import org.apache.ode.axis2.service.DeploymentWebService;
import org.apache.ode.axis2.service.ManagementService;
import org.apache.ode.bpel.connector.BpelServerConnector;
import org.apache.ode.bpel.dao.BpelDAOConnectionFactory;
import org.apache.ode.bpel.engine.BpelServerImpl;
import org.apache.ode.bpel.scheduler.quartz.QuartzSchedulerImpl;
import org.apache.ode.daohib.DataSourceConnectionProvider;
import org.apache.ode.daohib.HibernateTransactionManagerLookup;
import org.apache.ode.daohib.SessionManager;
import org.apache.ode.daohib.bpel.BpelDAOConnectionFactoryImpl;
import org.apache.ode.utils.fs.TempFileManager;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.DialectFactory;
import org.objectweb.jotm.Jotm;
import org.opentools.minerva.MinervaPool;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import javax.wsdl.Definition;
import javax.xml.namespace.QName;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Server class called by our Axis hooks to handle all ODE lifecycle
* management.
*/
public class ODEServer {
private static final Log __log = LogFactory.getLog(ODEServer.class);
private static final Messages __msgs = Messages.getMessages(Messages.class);
private File _appRoot;
private BpelServerImpl _server;
private ODEConfigProperties _odeConfig;
private AxisConfiguration _axisConfig;
private DataSource _datasource;
private TransactionManager _txMgr;
private BpelDAOConnectionFactory _daoCF;
private ExecutorService _executorService;
private QuartzSchedulerImpl _scheduler;
private DeploymentPoller _poller;
private MultiKeyMap _services = new MultiKeyMap();
private MultiKeyMap _externalServices = new MultiKeyMap();
private BpelServerConnector _connector;
public void init(ServletConfig config, AxisConfiguration axisConf) throws ServletException {
_axisConfig = axisConf;
_appRoot = new File(config.getServletContext().getRealPath("/WEB-INF"));
TempFileManager.setWorkingDirectory(_appRoot);
__log.debug("Loading properties");
_odeConfig = new ODEConfigProperties(_appRoot);
_odeConfig.load();
__log.debug("Initializing transaction manager");
initTxMgr();
__log.debug("Creating data source.");
initDataSource();
__log.debug("Starting Hibernate.");
initHibernate();
__log.debug("Hibernate started.");
__log.debug("Initializing BPEL server.");
initBpelServer();
try {
_server.start();
} catch (Exception ex) {
String errmsg = __msgs.msgOdeBpelServerStartFailure();
__log.error(errmsg,ex);
throw new ServletException(errmsg, ex);
}
__log.debug("Initializing JCA adapter.");
initConnector();
new ManagementService().enableService(_axisConfig, _server, _appRoot.getAbsolutePath());
new DeploymentWebService().enableService(_axisConfig, _server, _poller, _appRoot.getAbsolutePath());
File deploymentDir = new File(_appRoot, "processes");
_poller = new DeploymentPoller(deploymentDir, this);
_poller.start();
__log.info(__msgs.msgPollingStarted(deploymentDir.getAbsolutePath()));
__log.info(__msgs.msgOdeStarted());
}
/**
* Shutdown the service engine. This performs cleanup before the BPE is
* terminated. Once this method has been called, init() must be called before
* the transformation engine can be started again with a call to start().
*
* @throws AxisFault if the engine is unable to shut down.
*/
public void shutDown() throws AxisFault {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
_poller.stop();
_poller = null;
try {
_server.stop();
} catch (Throwable ex) {
__log.fatal("Error stopping services.", ex);
}
__log.info("ODE stopped.");
try {
try {
__log.debug("shutting down quartz scheduler.");
_scheduler.shutdown();
} catch (Exception ex) {
__log.error("Scheduler couldn't be shutdown.", ex);
}
__log.debug("cleaning up temporary files.");
TempFileManager.cleanup();
__log.debug("shutting down transaction manager.");
_txMgr = null;
__log.info(__msgs.msgOdeShutdownCompleted());
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public ODEService createService(Definition def, QName serviceName, String portName) throws AxisFault {
if (_services.get(serviceName, portName) != null){
AxisService service = ((ODEService)_services.get(serviceName, portName)).getAxisService();
_axisConfig.removeService(service.getName());
}
AxisService axisService = ODEAxisService.createService(_axisConfig,
def, serviceName, portName);
ODEService odeService = new ODEService(axisService, def, serviceName, portName,
_server, _txMgr);
_services.put(serviceName, portName, odeService);
// Setting our new service on the receiver, the same receiver handles all
// operations so the first one should fit them all
AxisOperation firstOp = (AxisOperation)axisService.getOperations().next();
((ODEMessageReceiver)firstOp.getMessageReceiver()).setService(odeService);
((ODEMessageReceiver)firstOp.getMessageReceiver()).setExecutorService(_executorService);
// We're public!
_axisConfig.addService(axisService);
__log.debug("Created Axis2 service " + serviceName);
return odeService;
}
public ExternalService createExternalService(Definition def, QName serviceName, String portName) {
ExternalService extService = (ExternalService) _externalServices.get(serviceName);
if (extService != null)
return extService;
extService = new ExternalService(def, serviceName, portName, _executorService, _axisConfig);
_externalServices.put(serviceName, portName, extService);
__log.debug("Created external service " + serviceName);
return extService;
}
public void destroyService(QName serviceName) {
try {
_axisConfig.removeService(serviceName.getLocalPart());
} catch (AxisFault axisFault) {
__log.error("Couldn't destroy service " + serviceName);
}
_services.remove(serviceName);
}
public ODEService getService(QName serviceName, String portName) {
return (ODEService) _services.get(serviceName, portName);
}
public ODEService getService(QName serviceName, QName portTypeName) {
// TODO Normally this lookup should't exist as there could be more one than port
// TODO for a portType. See MessageExchangeContextImpl.
for (Object o : _services.values()) {
ODEService service = (ODEService) o;
if (service.respondsTo(serviceName, portTypeName)) return service;
}
return null;
}
public ExternalService getExternalService(QName serviceName, String portName) {
return (ExternalService) _externalServices.get(serviceName, portName);
}
public AxisInvoker createInvoker() {
return new AxisInvoker(_executorService);
}
private void initTxMgr() throws ServletException {
InitialContext ctx;
try {
ctx = new InitialContext();
} catch (NamingException e) {
throw new ServletException("Couldn't find any JNDI to lookup.", e);
}
try {
// First try
_txMgr = (TransactionManager) ctx.lookup("javax.transaction.TransactionManager");
} catch (NamingException e) {
try {
// Second try
_txMgr = (TransactionManager) ctx.lookup("javax.transaction.TransactionManager");
} catch (NamingException ex) {
__log.info("Couldn't find a transaction manager, using the default (JOTM).");
// Giving up: couldn't find a proper transaction manager, fallback to Jotm.
try {
Jotm jotm = new Jotm(true, false);
jotm.getTransactionManager().setTransactionTimeout(30);
_txMgr = jotm.getTransactionManager();
} catch (Exception e1) {
throw new ServletException("Couldn't initialize a proper transaction manager!", e);
}
}
} finally {
try {
ctx.close();
} catch (NamingException e) {
__log.error(e);
}
}
}
private void initDataSource() throws ServletException {
switch (_odeConfig.getDbMode()) {
case EXTERNAL:
initExternalDb();
break;
case EMBEDDED:
initEmbeddedDb();
break;
case INTERNAL:
initInternalDb();
break;
default:
break;
}
}
private void initConnector() throws ServletException {
int port = _odeConfig.getConnectorPort();
if (port == 0) {
__log.info("Skipping connector initialization.");
} else {
_connector = new BpelServerConnector();
_connector.setBpelServer(_server);
_connector.setPort(_odeConfig.getConnectorPort());
_connector.setId("jcaServer");
try {
_connector.start();
} catch (Exception e) {
__log.error("Failed to initialize JCA connector.",e);
}
}
}
private void initExternalDb() throws ServletException {
try {
_datasource = lookupInJndi(_odeConfig.getDbDataSource());
__log.info(__msgs.msgOdeUsingExternalDb(_odeConfig.getDbDataSource()));
} catch (Exception ex) {
String msg = __msgs.msgOdeInitExternalDbFailed(_odeConfig.getDbDataSource());
__log.error(msg,ex);
throw new ServletException(msg,ex);
}
}
private void initInternalDb() throws ServletException {
throw new ServletException("internalDb not supported!");
}
/**
* Initialize embedded (DERBY) database.
*/
private void initEmbeddedDb() throws ServletException {
__log.info("Using DataSource Derby");
String url = "jdbc:derby:" + _appRoot + "/" + _odeConfig.getDbEmbeddedName();
__log.debug("creating Minerva pool for " + url);
MinervaPool minervaPool = new MinervaPool();
minervaPool.setTransactionManager(_txMgr);
minervaPool.getConnectionFactory().setConnectionURL(url);
minervaPool.getConnectionFactory().setUserName("sa");
minervaPool.getConnectionFactory().setDriver(
org.apache.derby.jdbc.EmbeddedDriver.class.getName());
minervaPool.getPoolParams().maxSize = _odeConfig.getPoolMaxSize();
minervaPool.getPoolParams().minSize = _odeConfig.getPoolMinSize();
minervaPool.getPoolParams().blocking = false;
minervaPool.setType(MinervaPool.PoolType.MANAGED);
try {
minervaPool.start();
} catch (Exception ex) {
String errmsg = __msgs.msgOdeDbPoolStartupFailed(url);
__log.error(errmsg,ex);
throw new ServletException(errmsg,ex);
}
_datasource = minervaPool.createDataSource();
}
/**
* Initialize the Hibernate data store.
*
* @throws ServletException
*/
private void initHibernate() throws ServletException {
Properties properties = new Properties();
properties.put(Environment.CONNECTION_PROVIDER,
DataSourceConnectionProvider.class.getName());
properties.put(Environment.TRANSACTION_MANAGER_STRATEGY,
HibernateTransactionManagerLookup.class.getName());
// properties.put(Environment.SESSION_FACTORY_NAME, "jta");
try {
properties.put(Environment.DIALECT, guessDialect(_datasource));
} catch (Exception ex) {
String errmsg = __msgs.msgOdeInitHibernateDialectDetectFailed();
__log.error(errmsg,ex);
throw new ServletException(errmsg,ex);
}
File hibernatePropFile = new File(_appRoot, "conf" + File.separatorChar + "hibernate.properties");
if (hibernatePropFile.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(hibernatePropFile);
properties.load(new BufferedInputStream(fis));
} catch (IOException e) {
String errmsg = __msgs
.msgOdeInitHibernateErrorReadingHibernateProperties(hibernatePropFile);
__log.error(errmsg, e);
throw new ServletException(errmsg, e);
}
} else {
__log.warn(__msgs
.msgOdeInitHibernatePropertiesNotFound(hibernatePropFile));
}
SessionManager sm = new SessionManager(properties, _datasource, _txMgr);
_daoCF = new BpelDAOConnectionFactoryImpl(sm);
}
private void initBpelServer() {
if (__log.isDebugEnabled()) {
__log.debug("ODE initializing");
}
_server = new BpelServerImpl();
_server.setAutoActivate(true);
_executorService = Executors.newCachedThreadPool();
_scheduler = new QuartzSchedulerImpl();
_scheduler.setBpelServer(_server);
_scheduler.setExecutorService(_executorService, 20);
_scheduler.setTransactionManager(_txMgr);
_scheduler.setDataSource(_datasource);
_scheduler.init();
_server.setDaoConnectionFactory(_daoCF);
_server.setEndpointReferenceContext(new EndpointReferenceContextImpl(this));
_server.setMessageExchangeContext(new MessageExchangeContextImpl(this));
_server.setBindingContext(new BindingContextImpl(this));
_server.setScheduler(_scheduler);
_server.init();
}
@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
InitialContext ctx = null;
try {
ctx = new InitialContext();
return (T) ctx.lookup(objName);
} finally {
if (ctx != null)
try {
ctx.close();
} catch (Exception ex1) {
__log.error("Error closing JNDI connection.", ex1);
}
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
private String guessDialect(DataSource dataSource) throws Exception {
String dialect = null;
// Open a connection and use that connection to figure out database
// product name/version number in order to decide which Hibernate
// dialect to use.
Connection conn = dataSource.getConnection();
try {
DatabaseMetaData metaData = conn.getMetaData();
if (metaData != null) {
String dbProductName = metaData.getDatabaseProductName();
int dbMajorVer = metaData.getDatabaseMajorVersion();
__log.info("Using database " + dbProductName + " major version "
+ dbMajorVer);
DialectFactory.DatabaseDialectMapper mapper = HIBERNATE_DIALECTS.get(dbProductName);
if (mapper != null) {
dialect = mapper.getDialectClass(dbMajorVer);
} else {
Dialect hbDialect = DialectFactory.determineDialect(dbProductName, dbMajorVer);
if (hbDialect != null)
dialect = hbDialect.getClass().getName();
}
}
} finally {
conn.close();
}
if (dialect == null) {
__log
.info("Cannot determine hibernate dialect for this database: using the default one.");
dialect = DEFAULT_HIBERNATE_DIALECT;
}
return dialect;
}
public BpelServerImpl getBpelServer() {
return _server;
}
private static final String DEFAULT_HIBERNATE_DIALECT = "org.hibernate.dialect.DerbyDialect";
private static final HashMap<String, DialectFactory.VersionInsensitiveMapper> HIBERNATE_DIALECTS = new HashMap<String, DialectFactory.VersionInsensitiveMapper>();
static {
// Hibernate has a nice table that resolves the dialect from the database
// product name,
// but doesn't include all the drivers. So this is supplementary, and some
// day in the
// future they'll add more drivers and we can get rid of this.
// Drivers already recognized by Hibernate:
// HSQL Database Engine
// DB2/NT
// MySQL
// PostgreSQL
// Microsoft SQL Server Database, Microsoft SQL Server
// Sybase SQL Server
// Informix Dynamic Server
// Oracle 8 and Oracle >8
HIBERNATE_DIALECTS.put("Apache Derby",
new DialectFactory.VersionInsensitiveMapper(
"org.hibernate.dialect.DerbyDialect"));
}
/**
* An {@link javax.naming.spi.ObjectFactory} implementation that can be used to bind the
* JOTM {@link javax.transaction.TransactionManager} implementation in JNDI.
*/
private class JotmTransactionManagerFactory implements ObjectFactory {
public Object getObjectInstance(Object objref, Name name, Context ctx, Hashtable env) throws Exception {
Reference ref = (Reference) objref;
if (ref.getClassName().equals(TransactionManager.class.getName())) {
return _txMgr;
}
throw new RuntimeException("The reference class name \"" + ref.getClassName() + "\" is unknown.");
}
}
/**
* JNDI {@link ObjectFactory} implementation for Hibernate-based
* connection factory objects.
*/
private class HibernateDaoObjectFactory implements ObjectFactory {
public Object getObjectInstance(Object objref, Name name, Context ctx, Hashtable env) throws Exception {
Reference ref = (Reference) objref;
if (ref.getClassName().equals(BpelDAOConnectionFactory.class.getName())) {
return _daoCF;
}
throw new RuntimeException("The reference class name \"" + ref.getClassName() + "\" is unknown.");
}
}
}
|
axis2/src/main/java/org/apache/ode/axis2/ODEServer.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.axis2;
import com.fs.naming.mem.InMemoryContextFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.collections.map.MultiKeyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.deploy.DeploymentPoller;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.axis2.hooks.ODEMessageReceiver;
import org.apache.ode.axis2.service.DeploymentWebService;
import org.apache.ode.axis2.service.ManagementService;
import org.apache.ode.bpel.connector.BpelServerConnector;
import org.apache.ode.bpel.dao.BpelDAOConnectionFactory;
import org.apache.ode.bpel.engine.BpelServerImpl;
import org.apache.ode.bpel.scheduler.quartz.QuartzSchedulerImpl;
import org.apache.ode.daohib.DataSourceConnectionProvider;
import org.apache.ode.daohib.HibernateTransactionManagerLookup;
import org.apache.ode.daohib.SessionManager;
import org.apache.ode.daohib.bpel.BpelDAOConnectionFactoryImpl;
import org.apache.ode.utils.fs.TempFileManager;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.DialectFactory;
import org.objectweb.jotm.Jotm;
import org.opentools.minerva.MinervaPool;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import javax.wsdl.Definition;
import javax.xml.namespace.QName;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Server class called by our Axis hooks to handle all ODE lifecycle
* management.
*/
public class ODEServer {
private static final Log __log = LogFactory.getLog(ODEServer.class);
private static final Messages __msgs = Messages.getMessages(Messages.class);
private File _appRoot;
private BpelServerImpl _server;
private ODEConfigProperties _odeConfig;
private AxisConfiguration _axisConfig;
private DataSource _datasource;
private Jotm _jotm;
private BpelDAOConnectionFactory _daoCF;
private ExecutorService _executorService;
private QuartzSchedulerImpl _scheduler;
private DeploymentPoller _poller;
private MultiKeyMap _services = new MultiKeyMap();
private MultiKeyMap _externalServices = new MultiKeyMap();
private BpelServerConnector _connector;
// private HashMap<QName,ODEService> _services = new HashMap<QName,ODEService>();
// private HashMap<QName,ExternalService> _externalServices = new HashMap<QName,ExternalService>();
public void init(ServletConfig config, AxisConfiguration axisConf) throws ServletException {
_axisConfig = axisConf;
_appRoot = new File(config.getServletContext().getRealPath("/WEB-INF"));
TempFileManager.setWorkingDirectory(_appRoot);
__log.debug("Loading properties");
_odeConfig = new ODEConfigProperties(_appRoot);
_odeConfig.load();
__log.debug("Initializing transaction manager");
initTxMgr();
__log.debug("Creating data source.");
initDataSource();
__log.debug("Starting Hibernate.");
initHibernate();
__log.debug("Hibernate started.");
__log.debug("Initializing BPEL server.");
initBpelServer();
try {
_server.start();
} catch (Exception ex) {
String errmsg = __msgs.msgOdeBpelServerStartFailure();
__log.error(errmsg,ex);
throw new ServletException(errmsg, ex);
}
__log.debug("Initializing JCA adapter.");
initConnector();
new ManagementService().enableService(_axisConfig, _server, _appRoot.getAbsolutePath());
new DeploymentWebService().enableService(_axisConfig, _server, _poller, _appRoot.getAbsolutePath());
File deploymentDir = new File(_appRoot, "processes");
_poller = new DeploymentPoller(deploymentDir, this);
_poller.start();
__log.info(__msgs.msgPollingStarted(deploymentDir.getAbsolutePath()));
__log.info(__msgs.msgOdeStarted());
}
/**
* Shutdown the service engine. This performs cleanup before the BPE is
* terminated. Once this method has been called, init() must be called before
* the transformation engine can be started again with a call to start().
*
* @throws AxisFault if the engine is unable to shut down.
*/
public void shutDown() throws AxisFault {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
_poller.stop();
_poller = null;
try {
_server.stop();
} catch (Throwable ex) {
__log.fatal("Error stopping services.", ex);
}
__log.info("ODE stopped.");
try {
try {
__log.debug("shutting down quartz scheduler.");
_scheduler.shutdown();
} catch (Exception ex) {
__log.error("Scheduler couldn't be shutdown.", ex);
}
__log.debug("cleaning up temporary files.");
TempFileManager.cleanup();
__log.debug("shutting down transaction manager.");
_jotm.stop();
_jotm = null;
__log.info(__msgs.msgOdeShutdownCompleted());
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public ODEService createService(Definition def, QName serviceName, String portName) throws AxisFault {
if (_services.get(serviceName, portName) != null){
AxisService service = ((ODEService)_services.get(serviceName, portName)).getAxisService();
_axisConfig.removeService(service.getName());
}
AxisService axisService = ODEAxisService.createService(_axisConfig,
def, serviceName, portName);
ODEService odeService = new ODEService(axisService, def, serviceName, portName,
_server, _jotm.getTransactionManager());
_services.put(serviceName, portName, odeService);
// Setting our new service on the receiver, the same receiver handles all
// operations so the first one should fit them all
AxisOperation firstOp = (AxisOperation)axisService.getOperations().next();
((ODEMessageReceiver)firstOp.getMessageReceiver()).setService(odeService);
((ODEMessageReceiver)firstOp.getMessageReceiver()).setExecutorService(_executorService);
// We're public!
_axisConfig.addService(axisService);
__log.debug("Created Axis2 service " + serviceName);
return odeService;
}
public ExternalService createExternalService(Definition def, QName serviceName, String portName) {
ExternalService extService = (ExternalService) _externalServices.get(serviceName);
if (extService != null)
return extService;
extService = new ExternalService(def, serviceName, portName, _executorService, _axisConfig);
_externalServices.put(serviceName, portName, extService);
__log.debug("Created external service " + serviceName);
return extService;
}
public void destroyService(QName serviceName) {
try {
_axisConfig.removeService(serviceName.getLocalPart());
} catch (AxisFault axisFault) {
__log.error("Couldn't destroy service " + serviceName);
}
_services.remove(serviceName);
}
public ODEService getService(QName serviceName, String portName) {
return (ODEService) _services.get(serviceName, portName);
}
public ODEService getService(QName serviceName, QName portTypeName) {
// TODO Normally this lookup should't exist as there could be more one than port
// TODO for a portType. See MessageExchangeContextImpl.
for (Object o : _services.values()) {
ODEService service = (ODEService) o;
if (service.respondsTo(serviceName, portTypeName)) return service;
}
return null;
}
public ExternalService getExternalService(QName serviceName, String portName) {
return (ExternalService) _externalServices.get(serviceName, portName);
}
public AxisInvoker createInvoker() {
return new AxisInvoker(_executorService);
}
private void initTxMgr() throws ServletException {
try {
_jotm = new Jotm(true, false);
_jotm.getTransactionManager().setTransactionTimeout(30);
Reference txm = new Reference("javax.transaction.TransactionManager",
JotmTransactionManagerFactory.class.getName(), null);
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
InMemoryContextFactory.class.getName());
System.setProperty(Context.PROVIDER_URL, "ode");
InitialContext ctx = new InitialContext();
ctx.rebind("TransactionManager", txm);
ctx.close();
} catch (Exception ex) {
__log.error("Error creating initial JNDI context.",ex);
throw new ServletException("Failed to start JNDI!",ex);
}
}
private void initDataSource() throws ServletException {
switch (_odeConfig.getDbMode()) {
case EXTERNAL:
initExternalDb();
break;
case EMBEDDED:
initEmbeddedDb();
break;
case INTERNAL:
initInternalDb();
break;
default:
break;
}
}
private void initConnector() throws ServletException {
int port = _odeConfig.getConnectorPort();
if (port == 0) {
__log.info("Skipping connector initialization.");
} else {
_connector = new BpelServerConnector();
_connector.setBpelServer(_server);
_connector.setPort(_odeConfig.getConnectorPort());
_connector.setId("jcaServer");
try {
_connector.start();
} catch (Exception e) {
__log.error("Failed to initialize JCA connector.",e);
}
}
}
private void initExternalDb() throws ServletException {
try {
_datasource = lookupInJndi(_odeConfig.getDbDataSource());
__log.info(__msgs.msgOdeUsingExternalDb(_odeConfig.getDbDataSource()));
} catch (Exception ex) {
String msg = __msgs.msgOdeInitExternalDbFailed(_odeConfig.getDbDataSource());
__log.error(msg,ex);
throw new ServletException(msg,ex);
}
}
private void initInternalDb() throws ServletException {
throw new ServletException("internalDb not supported!");
}
/**
* Initialize embedded (DERBY) database.
*/
private void initEmbeddedDb() throws ServletException {
__log.info("Using DataSource Derby");
String url =
"jdbc:derby:" + _appRoot + "/" + _odeConfig.getDbEmbeddedName();
__log.debug("creating Minerva pool for " + url);
MinervaPool minervaPool = new MinervaPool();
minervaPool.setTransactionManager(_jotm.getTransactionManager());
minervaPool.getConnectionFactory().setConnectionURL(url);
minervaPool.getConnectionFactory().setUserName("sa");
minervaPool.getConnectionFactory().setDriver(
org.apache.derby.jdbc.EmbeddedDriver.class.getName());
minervaPool.getPoolParams().maxSize = _odeConfig.getPoolMaxSize();
minervaPool.getPoolParams().minSize = _odeConfig.getPoolMinSize();
minervaPool.getPoolParams().blocking = false;
minervaPool.setType(MinervaPool.PoolType.MANAGED);
try {
minervaPool.start();
} catch (Exception ex) {
String errmsg = __msgs.msgOdeDbPoolStartupFailed(url);
__log.error(errmsg,ex);
throw new ServletException(errmsg,ex);
}
_datasource = minervaPool.createDataSource();
}
/**
* Initialize the Hibernate data store.
*
* @throws ServletException
*/
private void initHibernate() throws ServletException {
Properties properties = new Properties();
properties.put(Environment.CONNECTION_PROVIDER,
DataSourceConnectionProvider.class.getName());
properties.put(Environment.TRANSACTION_MANAGER_STRATEGY,
HibernateTransactionManagerLookup.class.getName());
properties.put(Environment.SESSION_FACTORY_NAME, "jta");
try {
properties.put(Environment.DIALECT, guessDialect(_datasource));
} catch (Exception ex) {
String errmsg = __msgs.msgOdeInitHibernateDialectDetectFailed();
__log.error(errmsg,ex);
throw new ServletException(errmsg,ex);
}
File hibernatePropFile = new File(_appRoot, "conf" + File.separatorChar + "hibernate.properties");
if (hibernatePropFile.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(hibernatePropFile);
properties.load(new BufferedInputStream(fis));
} catch (IOException e) {
String errmsg = __msgs
.msgOdeInitHibernateErrorReadingHibernateProperties(hibernatePropFile);
__log.error(errmsg, e);
throw new ServletException(errmsg, e);
}
} else {
__log.warn(__msgs
.msgOdeInitHibernatePropertiesNotFound(hibernatePropFile));
}
SessionManager sm = new SessionManager(properties, _datasource, _jotm.getTransactionManager());
_daoCF = new BpelDAOConnectionFactoryImpl(sm);
Reference bpelSscfRef = new Reference(BpelDAOConnectionFactory.class.getName(),
HibernateDaoObjectFactory.class.getName(), null);
try {
InitialContext ctx = new InitialContext();
try {
if (_daoCF != null)
ctx.rebind("bpelSSCF", bpelSscfRef);
} finally {
ctx.close();
}
} catch (Exception ex) {
throw new ServletException("Couldn't bind connection factory!", ex);
}
}
private void initBpelServer() {
if (__log.isDebugEnabled()) {
__log.debug("ODE initializing");
}
_server = new BpelServerImpl();
_server.setAutoActivate(true);
_executorService = Executors.newCachedThreadPool();
_scheduler = new QuartzSchedulerImpl();
_scheduler.setBpelServer(_server);
_scheduler.setExecutorService(_executorService, 20);
_scheduler.setTransactionManager(_jotm.getTransactionManager());
_scheduler.setDataSource(_datasource);
_scheduler.init();
_server.setDaoConnectionFactory(_daoCF);
_server.setEndpointReferenceContext(new EndpointReferenceContextImpl(this));
_server.setMessageExchangeContext(new MessageExchangeContextImpl(this));
_server.setBindingContext(new BindingContextImpl(this));
_server.setScheduler(_scheduler);
_server.init();
}
@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
InitialContext ctx = null;
try {
ctx = new InitialContext();
return (T) ctx.lookup(objName);
} finally {
if (ctx != null)
try {
ctx.close();
} catch (Exception ex1) {
__log.error("Error closing JNDI connection.", ex1);
}
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
private String guessDialect(DataSource dataSource) throws Exception {
String dialect = null;
// Open a connection and use that connection to figure out database
// product name/version number in order to decide which Hibernate
// dialect to use.
Connection conn = dataSource.getConnection();
try {
DatabaseMetaData metaData = conn.getMetaData();
if (metaData != null) {
String dbProductName = metaData.getDatabaseProductName();
int dbMajorVer = metaData.getDatabaseMajorVersion();
__log.info("Using database " + dbProductName + " major version "
+ dbMajorVer);
DialectFactory.DatabaseDialectMapper mapper = HIBERNATE_DIALECTS.get(dbProductName);
if (mapper != null) {
dialect = mapper.getDialectClass(dbMajorVer);
} else {
Dialect hbDialect = DialectFactory.determineDialect(dbProductName, dbMajorVer);
if (hbDialect != null)
dialect = hbDialect.getClass().getName();
}
}
} finally {
conn.close();
}
if (dialect == null) {
__log
.info("Cannot determine hibernate dialect for this database: using the default one.");
dialect = DEFAULT_HIBERNATE_DIALECT;
}
return dialect;
}
public BpelServerImpl getBpelServer() {
return _server;
}
private static final String DEFAULT_HIBERNATE_DIALECT = "org.hibernate.dialect.DerbyDialect";
private static final HashMap<String, DialectFactory.VersionInsensitiveMapper> HIBERNATE_DIALECTS = new HashMap<String, DialectFactory.VersionInsensitiveMapper>();
static {
// Hibernate has a nice table that resolves the dialect from the database
// product name,
// but doesn't include all the drivers. So this is supplementary, and some
// day in the
// future they'll add more drivers and we can get rid of this.
// Drivers already recognized by Hibernate:
// HSQL Database Engine
// DB2/NT
// MySQL
// PostgreSQL
// Microsoft SQL Server Database, Microsoft SQL Server
// Sybase SQL Server
// Informix Dynamic Server
// Oracle 8 and Oracle >8
HIBERNATE_DIALECTS.put("Apache Derby",
new DialectFactory.VersionInsensitiveMapper(
"org.hibernate.dialect.DerbyDialect"));
}
/**
* An {@link javax.naming.spi.ObjectFactory} implementation that can be used to bind the
* JOTM {@link javax.transaction.TransactionManager} implementation in JNDI.
*/
private class JotmTransactionManagerFactory implements ObjectFactory {
public Object getObjectInstance(Object objref, Name name, Context ctx, Hashtable env) throws Exception {
Reference ref = (Reference) objref;
if (ref.getClassName().equals(TransactionManager.class.getName())) {
return _jotm.getTransactionManager();
}
throw new RuntimeException("The reference class name \"" + ref.getClassName() + "\" is unknown.");
}
}
/**
* JNDI {@link ObjectFactory} implementation for Hibernate-based
* connection factory objects.
*/
private class HibernateDaoObjectFactory implements ObjectFactory {
public Object getObjectInstance(Object objref, Name name, Context ctx, Hashtable env) throws Exception {
Reference ref = (Reference) objref;
if (ref.getClassName().equals(BpelDAOConnectionFactory.class.getName())) {
return _daoCF;
}
throw new RuntimeException("The reference class name \"" + ref.getClassName() + "\" is unknown.");
}
}
}
|
ODE-39 The JNDI usage has been cleaned up. There's still an issue with the transaction manager though, we'll have to use explicit factories to create the initial context so that JOTM doesn't get in the way. And as long as Geronimo won't have a Transaction Manager accessible through JNDI, that won't be possible... Maybe Spring could help though.
git-svn-id: aa171c635fe092da43bc3212e891e07172936fe5@441620 13f79535-47bb-0310-9956-ffa450edef68
|
axis2/src/main/java/org/apache/ode/axis2/ODEServer.java
|
ODE-39 The JNDI usage has been cleaned up. There's still an issue with the transaction manager though, we'll have to use explicit factories to create the initial context so that JOTM doesn't get in the way. And as long as Geronimo won't have a Transaction Manager accessible through JNDI, that won't be possible... Maybe Spring could help though.
|
|
Java
|
apache-2.0
|
b20732566e2c806b540d0ce566a48e209b2d7719
| 0
|
apache/pdfbox,apache/pdfbox
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.interactive.form;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.rendering.TestPDFToImage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* Test flatten different forms and compare with rendering.
*
* Some of the tests are currently disabled to not run within the CI environment
* as the test results need manual inspection. Enable as needed.
*
*/
@Execution(ExecutionMode.CONCURRENT)
class PDAcroFormFlattenTest
{
private static final File IN_DIR = new File("target/test-output/flatten/in");
private static final File OUT_DIR = new File("target/test-output/flatten/out");
@BeforeAll
static void setUp()
{
IN_DIR.mkdirs();
OUT_DIR.mkdirs();
}
@ParameterizedTest
@CsvSource({
// PDFBOX-142 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12742551/Testformular1.pdf,Testformular1.pdf",
// PDFBOX-563 Filled template.
// Disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/12425859/TestFax_56972.pdf,TestFax_56972.pdf",
// PDFBOX-2469 Empty template.
"https://issues.apache.org/jira/secure/attachment/12682897/FormI-9-English.pdf,FormI-9-English.pdf",
// PDFBOX-2469 Filled template.
// Disabled as there is a minimal difference which can not be seen visually, see PDFBOX-5133
// "https://issues.apache.org/jira/secure/attachment/12678455/testPDF_acroForm.pdf,testPDF_acroForm.pdf",
//PDFBOX-2586 Empty template.
"https://issues.apache.org/jira/secure/attachment/12689788/test.pdf,test-2586.pdf",
// PDFBOX-3083 Filled template rotated.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12770263/mypdf.pdf,mypdf.pdf",
// PDFBOX-3262 Hidden fields.
"https://issues.apache.org/jira/secure/attachment/12792007/hidden_fields.pdf,hidden_fields.pdf",
// PDFBOX-3396 Signed Document 1.
"https://issues.apache.org/jira/secure/attachment/12816014/Signed-Document-1.pdf,Signed-Document-1.pdf",
// PDFBOX-3396 Signed Document 2.
"https://issues.apache.org/jira/secure/attachment/12816016/Signed-Document-2.pdf,Signed-Document-2.pdf",
// PDFBOX-3396 Signed Document 3.
"https://issues.apache.org/jira/secure/attachment/12821307/Signed-Document-3.pdf,Signed-Document-3.pdf",
// PDFBOX-3396 Signed Document 4.
"https://issues.apache.org/jira/secure/attachment/12821308/Signed-Document-4.pdf,Signed-Document-4.pdf",
// PDFBOX-3587 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12840280/OpenOfficeForm_filled.pdf,OpenOfficeForm_filled.pdf",
// PDFBOX-4157 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12976553/PDFBOX-4157-filled.pdf,PDFBOX-4157-filled.pdf",
// PDFBOX-4172 Filled template.
// disabled as there is a minimal difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12976552/PDFBOX-4172-filled.pdf,PDFBOX-4172-filled.pdf",
// PDFBOX-4615 Filled template.
// disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/12976452/resetboundingbox-filled.pdf,PDFBOX-4615-filled.pdf",
// PDFBOX-4693: page is not rotated, but the appearance stream is.
"https://issues.apache.org/jira/secure/attachment/12986337/stenotypeTest-3_rotate_no_flatten.pdf,PDFBOX-4693-filled.pdf",
// PDFBOX-4788: non-widget annotations are not to be removed on a page that has no widget
// annotations.
"https://issues.apache.org/jira/secure/attachment/12994791/flatten.pdf,PDFBOX-4788.pdf",
// PDFBOX-4889: appearance streams with empty /BBox.
"https://issues.apache.org/jira/secure/attachment/13005793/f1040sb%20test.pdf,PDFBOX-4889.pdf",
// PDFBOX-4955: appearance streams with forms that are not used.
"https://issues.apache.org/jira/secure/attachment/13011410/PDFBOX-4955.pdf,PDFBOX-4955.pdf",
// PDFBOX-4958 text and button with image.
// disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/13012242/PDFBOX-4958.pdf,PDFBOX-4958-flattened.pdf"
})
void testFlatten(String sourceUrl, String targetFileName) throws IOException {
flattenAndCompare(sourceUrl, targetFileName);
}
@Test
void flattenSingleField() throws IOException
{
final File IN_DIR = new File("src/test/resources/org/apache/pdfbox/pdmodel/interactive/form");
final String NAME_OF_PDF = "MultilineFields.pdf";
PDDocument document = Loader.loadPDF(new File(IN_DIR, NAME_OF_PDF));
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
int numFieldsBefore = acroForm.getFields().size();
List<PDField> toBeFlattened = new ArrayList<>();
PDTextField field = (PDTextField) acroForm.getField("AlignLeft-Filled");
toBeFlattened.add(field);
acroForm.flatten(toBeFlattened,false);
assertEquals(numFieldsBefore, acroForm.getFields().size() + 1, "the number of form fields shall be reduced by one");
assertNull(acroForm.getField("AlignLeft-Filled"), "the flattened field shall no longer exist");
// Store for manual comparison if needed
// final File OUT_DIR = new File("target/test-output");
// File file = new File(OUT_DIR, "MultilineFields-SingleFieldFlattened.pdf");
// document.save(file);
}
@Test
void flattenTestPDFBOX5254() throws IOException
{
String sourceUrl = "https://issues.apache.org/jira/secure/attachment/13005793/f1040sb%20test.pdf";
String targetFileName = "PDFBOX-4889-5254.pdf";
generateSamples(sourceUrl, targetFileName);
File inputFile = new File(IN_DIR, targetFileName);
File outputFile = new File(OUT_DIR, targetFileName);
try (PDDocument testPdf = Loader.loadPDF(inputFile))
{
testPdf.getDocumentCatalog().getAcroForm().flatten();
testPdf.setAllSecurityToBeRemoved(true);
assertTrue(testPdf.getDocumentCatalog().getAcroForm().getFields().isEmpty());
testPdf.save(outputFile, CompressParameters.NO_COMPRESSION);
}
// compare rendering
if (!TestPDFToImage.doTestFile(outputFile, IN_DIR.getAbsolutePath(),
OUT_DIR.getAbsolutePath()))
{
fail("Rendering of " + outputFile
+ " failed or is not identical to expected rendering in " + IN_DIR
+ " directory");
}
else
{
// cleanup input and output directory for matching files.
removeAllRenditions(inputFile);
inputFile.delete();
outputFile.delete();
}
}
/*
* Flatten and compare with generated image samples.
*
* @throws IOException
*/
private static void flattenAndCompare(String sourceUrl, String targetFileName) throws IOException
{
generateSamples(sourceUrl,targetFileName);
File inputFile = new File(IN_DIR, targetFileName);
File outputFile = new File(OUT_DIR, targetFileName);
try (PDDocument testPdf = Loader.loadPDF(inputFile))
{
testPdf.getDocumentCatalog().getAcroForm().flatten();
testPdf.setAllSecurityToBeRemoved(true);
assertTrue(testPdf.getDocumentCatalog().getAcroForm().getFields().isEmpty());
testPdf.save(outputFile);
}
// compare rendering
if (!TestPDFToImage.doTestFile(outputFile, IN_DIR.getAbsolutePath(),
OUT_DIR.getAbsolutePath()))
{
fail("Rendering of " + outputFile + " failed or is not identical to expected rendering in " + IN_DIR + " directory");
}
else
{
// cleanup input and output directory for matching files.
removeAllRenditions(inputFile);
inputFile.delete();
outputFile.delete();
}
}
/*
* Generate the sample images to which the PDF will be compared after flatten.
*
* @throws IOException
*/
private static void generateSamples(String sourceUrl, String targetFile) throws IOException
{
getFromUrl(sourceUrl, targetFile);
File file = new File(IN_DIR,targetFile);
try (PDDocument document = Loader.loadPDF(file, (String) null))
{
String outputPrefix = IN_DIR.getAbsolutePath() + '/' + file.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
String fileName = outputPrefix + (i + 1) + ".png";
BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
ImageIO.write(image, "PNG", new File(fileName));
}
}
}
/*
* Get a PDF from URL and copy to file for processing.
*
* @throws IOException
*/
private static void getFromUrl(String sourceUrl, String targetFile) throws IOException
{
try (InputStream is = new URL(sourceUrl).openStream())
{
Files.copy(is, new File(IN_DIR, targetFile).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
/*
* Remove renditions for the PDF from the input directory.
* The output directory will have been cleaned by the TestPDFToImage utility.
*/
private static void removeAllRenditions(final File inputFile)
{
File[] testFiles = inputFile.getParentFile().listFiles(
(File dir, String name) ->
(name.startsWith(inputFile.getName()) && name.toLowerCase().endsWith(".png")));
Stream.of(testFiles).forEach(File::delete);
}
}
|
pdfbox/src/test/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroFormFlattenTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.interactive.form;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.rendering.TestPDFToImage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* Test flatten different forms and compare with rendering.
*
* Some of the tests are currently disabled to not run within the CI environment
* as the test results need manual inspection. Enable as needed.
*
*/
@Execution(ExecutionMode.CONCURRENT)
class PDAcroFormFlattenTest
{
private static final File IN_DIR = new File("target/test-output/flatten/in");
private static final File OUT_DIR = new File("target/test-output/flatten/out");
@BeforeAll
static void setUp()
{
IN_DIR.mkdirs();
OUT_DIR.mkdirs();
}
@ParameterizedTest
@CsvSource({
// PDFBOX-142 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12742551/Testformular1.pdf,Testformular1.pdf",
// PDFBOX-563 Filled template.
// Disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/12425859/TestFax_56972.pdf,TestFax_56972.pdf",
// PDFBOX-2469 Empty template.
"https://issues.apache.org/jira/secure/attachment/12682897/FormI-9-English.pdf,FormI-9-English.pdf",
// PDFBOX-2469 Filled template.
// Disabled as there is a minimal difference which can not be seen visually, see PDFBOX-5133
// "https://issues.apache.org/jira/secure/attachment/12678455/testPDF_acroForm.pdf,testPDF_acroForm.pdf",
//PDFBOX-2586 Empty template.
"https://issues.apache.org/jira/secure/attachment/12689788/test.pdf,test-2586.pdf",
// PDFBOX-3083 Filled template rotated.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12770263/mypdf.pdf,mypdf.pdf",
// PDFBOX-3262 Hidden fields.
"https://issues.apache.org/jira/secure/attachment/12792007/hidden_fields.pdf,hidden_fields.pdf",
// PDFBOX-3396 Signed Document 1.
"https://issues.apache.org/jira/secure/attachment/12816014/Signed-Document-1.pdf,Signed-Document-1.pdf",
// PDFBOX-3396 Signed Document 2.
"https://issues.apache.org/jira/secure/attachment/12816016/Signed-Document-2.pdf,Signed-Document-2.pdf",
// PDFBOX-3396 Signed Document 3.
"https://issues.apache.org/jira/secure/attachment/12821307/Signed-Document-3.pdf,Signed-Document-3.pdf",
// PDFBOX-3396 Signed Document 4.
"https://issues.apache.org/jira/secure/attachment/12821308/Signed-Document-4.pdf,Signed-Document-4.pdf",
// PDFBOX-3587 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12840280/OpenOfficeForm_filled.pdf,OpenOfficeForm_filled.pdf",
// PDFBOX-4157 Filled template.
// disabled as there is a small difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12976553/PDFBOX-4157-filled.pdf,PDFBOX-4157-filled.pdf",
// PDFBOX-4172 Filled template.
// disabled as there is a minimal difference which can not be seen visually
// "https://issues.apache.org/jira/secure/attachment/12976552/PDFBOX-4172-filled.pdf,PDFBOX-4172-filled.pdf",
// PDFBOX-4615 Filled template.
// disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/12976452/resetboundingbox-filled.pdf,PDFBOX-4615-filled.pdf",
// PDFBOX-4693: page is not rotated, but the appearance stream is.
"https://issues.apache.org/jira/secure/attachment/12986337/stenotypeTest-3_rotate_no_flatten.pdf,PDFBOX-4693-filled.pdf",
// PDFBOX-4788: non-widget annotations are not to be removed on a page that has no widget
// annotations.
"https://issues.apache.org/jira/secure/attachment/12994791/flatten.pdf,PDFBOX-4788.pdf",
// PDFBOX-4889: appearance streams with empty /BBox.
"https://issues.apache.org/jira/secure/attachment/13005793/f1040sb%20test.pdf,PDFBOX-4889.pdf",
// PDFBOX-4955: appearance streams with forms that are not used.
"https://issues.apache.org/jira/secure/attachment/13011410/PDFBOX-4955.pdf,PDFBOX-4955.pdf",
// PDFBOX-4958 text and button with image.
// disabled as there is a minimal difference which can not be seen visually on ci-builds
// "https://issues.apache.org/jira/secure/attachment/13012242/PDFBOX-4958.pdf,PDFBOX-4958-flattened.pdf"
})
void testFlatten(String sourceUrl, String targetFileName) throws IOException {
flattenAndCompare(sourceUrl, targetFileName);
}
@Test
void flattenSingleField() throws IOException
{
final File IN_DIR = new File("src/test/resources/org/apache/pdfbox/pdmodel/interactive/form");
final String NAME_OF_PDF = "MultilineFields.pdf";
PDDocument document = Loader.loadPDF(new File(IN_DIR, NAME_OF_PDF));
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
int numFieldsBefore = acroForm.getFields().size();
List<PDField> toBeFlattened = new ArrayList<>();
PDTextField field = (PDTextField) acroForm.getField("AlignLeft-Filled");
toBeFlattened.add(field);
acroForm.flatten(toBeFlattened,false);
assertEquals(numFieldsBefore, acroForm.getFields().size() + 1, "the number of form fields shall be reduced by one");
assertNull(acroForm.getField("AlignLeft-Filled"), "the flattened field shall no longer exist");
// Store for manual comparison if needed
// final File OUT_DIR = new File("target/test-output");
// File file = new File(OUT_DIR, "MultilineFields-SingleFieldFlattened.pdf");
// document.save(file);
}
/*
* Flatten and compare with generated image samples.
*
* @throws IOException
*/
private static void flattenAndCompare(String sourceUrl, String targetFileName) throws IOException
{
generateSamples(sourceUrl,targetFileName);
File inputFile = new File(IN_DIR, targetFileName);
File outputFile = new File(OUT_DIR, targetFileName);
try (PDDocument testPdf = Loader.loadPDF(inputFile))
{
testPdf.getDocumentCatalog().getAcroForm().flatten();
testPdf.setAllSecurityToBeRemoved(true);
assertTrue(testPdf.getDocumentCatalog().getAcroForm().getFields().isEmpty());
testPdf.save(outputFile);
}
// compare rendering
if (!TestPDFToImage.doTestFile(outputFile, IN_DIR.getAbsolutePath(),
OUT_DIR.getAbsolutePath()))
{
fail("Rendering of " + outputFile + " failed or is not identical to expected rendering in " + IN_DIR + " directory");
}
else
{
// cleanup input and output directory for matching files.
removeAllRenditions(inputFile);
inputFile.delete();
outputFile.delete();
}
}
/*
* Generate the sample images to which the PDF will be compared after flatten.
*
* @throws IOException
*/
private static void generateSamples(String sourceUrl, String targetFile) throws IOException
{
getFromUrl(sourceUrl, targetFile);
File file = new File(IN_DIR,targetFile);
try (PDDocument document = Loader.loadPDF(file, (String) null))
{
String outputPrefix = IN_DIR.getAbsolutePath() + '/' + file.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
String fileName = outputPrefix + (i + 1) + ".png";
BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
ImageIO.write(image, "PNG", new File(fileName));
}
}
}
/*
* Get a PDF from URL and copy to file for processing.
*
* @throws IOException
*/
private static void getFromUrl(String sourceUrl, String targetFile) throws IOException
{
try (InputStream is = new URL(sourceUrl).openStream())
{
Files.copy(is, new File(IN_DIR, targetFile).toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
/*
* Remove renditions for the PDF from the input directory.
* The output directory will have been cleaned by the TestPDFToImage utility.
*/
private static void removeAllRenditions(final File inputFile)
{
File[] testFiles = inputFile.getParentFile().listFiles(
(File dir, String name) ->
(name.startsWith(inputFile.getName()) && name.toLowerCase().endsWith(".png")));
Stream.of(testFiles).forEach(File::delete);
}
}
|
PDFBOX-5254: add test
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1892138 13f79535-47bb-0310-9956-ffa450edef68
|
pdfbox/src/test/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroFormFlattenTest.java
|
PDFBOX-5254: add test
|
|
Java
|
apache-2.0
|
a1ccddf8dd62c17e96891848de64ebda613df039
| 0
|
jtablesaw/tablesaw,jtablesaw/tablesaw,jtablesaw/tablesaw
|
package tech.tablesaw.api;
import com.google.common.base.Preconditions;
import tech.tablesaw.columns.Column;
import java.util.HashMap;
import java.util.Map;
public interface ColumnType {
Map<String, ColumnType> values = new HashMap<>();
// standard column types
ColumnType BOOLEAN = new StandardColumnType(Byte.MIN_VALUE, 1, "BOOLEAN", "Boolean");
ColumnType STRING = new StandardColumnType("", 4, "STRING", "String");
ColumnType NUMBER = new StandardColumnType(Double.NaN, 8, "NUMBER", "Number");
ColumnType LOCAL_DATE = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_DATE", "Date");
ColumnType LOCAL_DATE_TIME = new StandardColumnType(Long.MIN_VALUE, 8, "LOCAL_DATE_TIME","DateTime");
ColumnType LOCAL_TIME = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_TIME", "Time");
ColumnType SKIP = new StandardColumnType(null, 0, "SKIP", "Skipped");
static void register(ColumnType type) {
values.put(type.name(), type);
}
static ColumnType[] values() {
return values.values().toArray(new ColumnType[0]);
}
static ColumnType valueOf(String name) {
Preconditions.checkNotNull(name);
ColumnType result = values.get(name);
if (result == null) {
throw new IllegalArgumentException(name + " is not a registered column type.");
}
return result;
}
default Column create(String name) {
final String columnTypeName = this.name();
switch (columnTypeName) {
case "BOOLEAN": return BooleanColumn.create(name);
case "STRING": return StringColumn.create(name);
case "NUMBER": return DoubleColumn.create(name);
case "LOCAL_DATE": return DateColumn.create(name);
case "LOCAL_DATE_TIME": return DateTimeColumn.create(name);
case "LOCAL_TIME": return TimeColumn.create(name);
case "SKIP": throw new IllegalArgumentException("Cannot create column of type SKIP");
default:
throw new UnsupportedOperationException("Column type " + name() + " doesn't support column creation");
}
}
String name();
Comparable<?> getMissingValue();
int byteSize();
String getPrinterFriendlyName();
}
|
core/src/main/java/tech/tablesaw/api/ColumnType.java
|
package tech.tablesaw.api;
import com.google.common.base.Preconditions;
import tech.tablesaw.columns.Column;
import java.util.ArrayList;
import java.util.List;
public interface ColumnType {
List<ColumnType> values = new ArrayList<>();
// standard column types
ColumnType BOOLEAN = new StandardColumnType(Byte.MIN_VALUE, 1, "BOOLEAN", "Boolean");
ColumnType STRING = new StandardColumnType("", 4, "STRING", "String");
ColumnType NUMBER = new StandardColumnType(Double.NaN, 8, "NUMBER", "Number");
ColumnType LOCAL_DATE = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_DATE", "Date");
ColumnType LOCAL_DATE_TIME = new StandardColumnType(Long.MIN_VALUE, 8, "LOCAL_DATE_TIME","DateTime");
ColumnType LOCAL_TIME = new StandardColumnType(Integer.MIN_VALUE, 4, "LOCAL_TIME", "Time");
ColumnType SKIP = new StandardColumnType(null, 0, "SKIP", "Skipped");
static void register(ColumnType type) {
values.add(type);
}
static ColumnType[] values() {
return values.toArray(new ColumnType[0]);
}
static ColumnType valueOf(String name) {
Preconditions.checkNotNull(name);
for (ColumnType type : values) {
if (type.name().equals(name)) {
return type;
}
}
throw new IllegalArgumentException(name + " is not a registered column type.");
}
default Column create(String name) {
final String columnTypeName = this.name();
switch (columnTypeName) {
case "BOOLEAN": return BooleanColumn.create(name);
case "STRING": return StringColumn.create(name);
case "NUMBER": return DoubleColumn.create(name);
case "LOCAL_DATE": return DateColumn.create(name);
case "LOCAL_DATE_TIME": return DateTimeColumn.create(name);
case "LOCAL_TIME": return TimeColumn.create(name);
case "SKIP": throw new IllegalArgumentException("Cannot create column of type SKIP");
default:
throw new UnsupportedOperationException("Column type " + name() + " doesn't support column creation");
}
}
String name();
Comparable<?> getMissingValue();
int byteSize();
String getPrinterFriendlyName();
}
|
replace list-based ColumnType registry with Map version for easier name-based access
|
core/src/main/java/tech/tablesaw/api/ColumnType.java
|
replace list-based ColumnType registry with Map version for easier name-based access
|
|
Java
|
apache-2.0
|
6b78319d1b8ee6fa2831bc45ca360bcc12099764
| 0
|
ArcadiaConsulting/appstorestats
|
/**
* Copyright 2013 Arcadia Consulting C.B.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package es.arcadiaconsulting.appstoresstats.ios.io;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import es.arcadiaconsulting.appstoresstats.ios.model.Constants;
import es.arcadiaconsulting.appstoresstats.ios.model.UnitData;
public class DateHelper {
private static final Logger logger = LoggerFactory
.getLogger(DateHelper.class);
public static Date buildDateFromUTCString(String utc){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
return formatter.parse(utc);
} catch (ParseException e) {
logger.error("incorrect Date",e );
return null;
}
}
public static List<UnitData> getFullUnitData(Date deploymentDate,
Date queryDate, String sku,/** String propertiesFile,*/ String user,
String password, String vendorId) throws DateHelperException {
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
List<UnitData> unitDataList = new Vector<UnitData>();
// iterator for compare dates
GregorianCalendar dateIterator = new GregorianCalendar();
dateIterator.setTime(queryDate);
GregorianCalendar deploymentDateCalendar = new GregorianCalendar();
deploymentDateCalendar.setTime(deploymentDate);
// get last day checkable, must be 1 days before if today is the initial day
Date currentday= new Date(System.currentTimeMillis());
GregorianCalendar currentDayCalendar = new GregorianCalendar();
currentDayCalendar.setTime(currentday);
if( (currentDayCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==dateIterator.get(Calendar.DAY_OF_YEAR))){
dateIterator.add(Calendar.DATE, -1);
}
//check dates
if(deploymentDateCalendar.get(Calendar.YEAR)>dateIterator.get(Calendar.YEAR) ||
(deploymentDateCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && deploymentDateCalendar.get(Calendar.DAY_OF_YEAR)>dateIterator.get(Calendar.DAY_OF_YEAR))){
logger.error("Incorrect Dates, First date must be 2 days previous to final date");
throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date");
}
// if iterator is less or equal to deployment date we cant check units
if (dateIterator.before(deploymentDateCalendar)) {
logger.error("Incorrect date");
throw new DateHelperException(
"We cant get Results. There are not sales too. Wait some days");
}
//getting years query
int deploymentyear = deploymentDateCalendar.get(Calendar.YEAR);
int dateIteratorYear = dateIterator.get(Calendar.YEAR);
GregorianCalendar yearIterator = deploymentDateCalendar;
while(deploymentyear < dateIteratorYear){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(yearIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
deploymentyear = deploymentyear+1;
yearIterator.add(Calendar.YEAR, 1);
//if query is on first day of year return response
if(dateIterator.get(Calendar.MONTH)==1&&dateIterator.get(Calendar.DAY_OF_MONTH)==1)
return cleanUnitDataList(unitDataList);
}
//iterate for months (iterate to month)
GregorianCalendar monthIterator = (GregorianCalendar)dateIterator.clone();
if(monthIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)){
//si es el mismo mes la consulta hacemos la consulta dia a dia
GregorianCalendar dayIterator = deploymentDateCalendar;
while(dayIterator.get(Calendar.DAY_OF_YEAR)<=dateIterator.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(dayIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting day units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
dayIterator.add(Calendar.DATE, 1);
}
}else{
while(monthIterator.get(Calendar.MONTH)-1>-1){
monthIterator.add(Calendar.MONTH, -1);
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(monthIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
//if query is first day of month return unit data
// if(dateIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.getActualMaximum(Calendar.DAY_OF_MONTH))
// return unitDataList;
}
//iterate for weeks
//first do petiton for day to sunday
GregorianCalendar weekIterator = new GregorianCalendar(dateIterator.get(Calendar.YEAR),dateIterator.get(Calendar.MONTH),1);
//si cae en 1 el lunes y la fecha de consulta es superior al 7 que sera domingo se hara la consulta unicamente con la semana
if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY && dateIterator.get(Calendar.DAY_OF_MONTH)>=7){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(dateIterator.get(Calendar.DAY_OF_MONTH)==7)
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DATE, 7);
}else{
//si no coincide con la primera semana llegamos al domingo de la primera semana dia a dia
do{
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
//si es el mismo dia que el ultimo dia consultable se retorna
if(weekIterator.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR)&&
weekIterator.get(Calendar.MONTH)==dateIterator.get(Calendar.MONTH)&&
weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH))
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DATE, 1);
}while(weekIterator.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY);
}
//hacemos la consulta de semanas mientras el dia del iterador mas 6 sea menor o igual que la fecha de la query
//la consulta debe hacerse por domingos asi que hay que sumar los seis dias
while(weekIterator.get(Calendar.DAY_OF_MONTH)+7<=dateIterator.get(Calendar.DAY_OF_MONTH)){
weekIterator.add(Calendar.DAY_OF_MONTH, 7);
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting week sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(weekIterator.get(Calendar.DAY_OF_MONTH)+7==dateIterator.get(Calendar.DAY_OF_MONTH))
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DAY_OF_MONTH, 1);
}
//hacemos por ultimo la consulta hasta llegar al dia de la consulta
while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(weekIterator.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
weekIterator.add(Calendar.DATE, 1);
}
}
return cleanUnitDataList(unitDataList);
/** Redo to init for years
// getting day units until sunday or deployment day or first sunday
// without 1 week passed
while ((Calendar.SUNDAY != dateIterator.get(Calendar.DAY_OF_WEEK) || (Calendar.SUNDAY == dateIterator
.get(Calendar.DAY_OF_WEEK) && isFirstSunday(
deploymentDateCalendar, dateIterator)))) {
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
propertiesFile, user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(dateIterator), sku);
if (dayUnitData == null) {
logger.error("Error Getting day units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
dateIterator.add(Calendar.DATE, -1);
// if dateIterator is the same that deployment day return item
if(dateIterator.get(Calendar.YEAR)==deploymentDateCalendar.get(Calendar.YEAR)&&dateIterator.get(Calendar.DAY_OF_MONTH)==deploymentDateCalendar.get(Calendar.DAY_OF_MONTH)&&dateIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH))
return unitDataList;
}
//init week iteration
//if is first week is less than 7 (if is 7 we can do one week petition) we must do a petition for day to arrive to first month day
if(dateIterator.get(Calendar.DAY_OF_WEEK)<7){
}
while(){
}
*/
}
private static boolean isFirstSunday(Calendar deploymentDate,
Calendar sunday) {
int dayOfWeek = deploymentDate.get(Calendar.DAY_OF_WEEK);
Calendar dateIterator = deploymentDate;
dateIterator.add(Calendar.DATE, 8 - dayOfWeek);
if (dateIterator.get(Calendar.DAY_OF_WEEK_IN_MONTH) == sunday
.get(Calendar.DAY_OF_WEEK_IN_MONTH))
return true;
return false;
}
private static List<UnitData> cleanUnitDataList(List<UnitData> unitDataListIn){
List<UnitData> cleanedUnitDataList = new Vector<UnitData>();
for (Iterator iterator = unitDataListIn.iterator(); iterator
.hasNext();) {
UnitData unitData = (UnitData) iterator.next();
boolean countryIsAdded = false;
for (Iterator iterator2 = cleanedUnitDataList.iterator(); iterator2
.hasNext();) {
UnitData unitDataCleaned = (UnitData) iterator2.next();
if(unitData.getCountryCode().equals(unitDataCleaned.getCountryCode())){
countryIsAdded = true;
break;
}
}
if(!countryIsAdded){
UnitData newUnitData = new UnitData(unitData.countryCode, getAllCountryDataUnits(unitDataListIn,unitData.countryCode));
cleanedUnitDataList.add(newUnitData);
}
}
return cleanedUnitDataList;
}
private static int getAllCountryDataUnits(List<UnitData> unitData, String country ){
int units=0;
for (Iterator iterator = unitData.iterator(); iterator.hasNext();) {
UnitData unitData2 = (UnitData) iterator.next();
if(unitData2.getCountryCode().equals(country))
units = units + unitData2.getUnits();
}
return units;
}
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
public static final int USE_CASE_0 = 0;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
public static final int USE_CASE_1 = 1;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
public static final int USE_CASE_2 = 2;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
public static final int USE_CASE_3 = 3;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
public static final int USE_CASE_4 = 4;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
public static final int USE_CASE_5 = 5;
// consulta fecha inicio y fin menos de un mes
public static final int USE_CASE_6=6;
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
public static final int USE_CASE_7 = 7;
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
public static final int USE_CASE_8 = 8;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
public static final int USE_CASE_9 = 9;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
public static final int USE_CASE_10 = 10;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
public static final int USE_CASE_11 = 11;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
public static final int USE_CASE_12 = 12;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
public static final int USE_CASE_13 = 13;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
public static final int USE_CASE_14 = 14;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
public static final int USE_CASE_15 = 15;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
public static final int USE_CASE_16 = 16;
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
public static final int USE_CASE_17 = 17;
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
public static final int USE_CASE_18 = 18;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
public static final int USE_CASE_19 = 19;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
public static final int USE_CASE_20 = 20;
// consulta fecha inicio mas de un año, fecha fin menos de un mes
public static final int USE_CASE_21 = 21;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
public static final int USE_CASE_22 = 22;
public static int getDateUseCase(Date firstDate, Date secondDate){
GregorianCalendar firstDateCalendar = new GregorianCalendar();
firstDateCalendar.setTime(firstDate);
GregorianCalendar secondDateCalendar = new GregorianCalendar();
secondDateCalendar.setTime(secondDate);
Date currentDate = new Date(System.currentTimeMillis());
GregorianCalendar currentDateCalendar = new GregorianCalendar();
currentDateCalendar.setTime(currentDate);
GregorianCalendar oneMonth = (GregorianCalendar)currentDateCalendar.clone();
oneMonth.add(Calendar.MONTH, -1);
//GregorianCalendar threeMonth = (GregorianCalendar)currentDateCalendar.clone();
//threeMonth.add(Calendar.MONTH, -3);
GregorianCalendar sixMonth = (GregorianCalendar)currentDateCalendar.clone();
sixMonth.add(Calendar.MONTH, -6);
GregorianCalendar oneYear = (GregorianCalendar) currentDateCalendar.clone();
oneYear.add(Calendar.YEAR, -1);
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_0;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_1;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_2;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_3;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.after(oneMonth))
return USE_CASE_4;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.after(oneMonth))
return USE_CASE_5;
// consulta fecha inicio y fin menos de un mes
if(firstDateCalendar.after(oneMonth)&&secondDateCalendar.after(oneMonth))
return USE_CASE_6;
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_7;
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_8;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_9;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_10;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_11;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.after(oneMonth))
return USE_CASE_12;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_13;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_14;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_15;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.after(oneMonth))
return USE_CASE_16;
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.getMaximum(Calendar.DAY_OF_YEAR))
return USE_CASE_17;
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneYear))
return USE_CASE_18;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(sixMonth)&&secondDateCalendar.after(oneYear))
return USE_CASE_19;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)== Calendar.SUNDAY)
return USE_CASE_20;
// consulta fecha inicio mas de un año, fecha fin menos de un mes
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.after(oneMonth))
return USE_CASE_21;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!= Calendar.SUNDAY)
return USE_CASE_22;
return -1000;
}
public static List<UnitData> getUnitDataByDate(Date firstDate,
Date secondDate, String sku, String user,
String password, String vendorId) throws DateHelperException {
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
List<UnitData> unitDataList = new Vector<UnitData>();
GregorianCalendar firstDateCalendar = new GregorianCalendar();
firstDateCalendar.setTime(firstDate);
GregorianCalendar secondDateCalendar = new GregorianCalendar();
secondDateCalendar.setTime(secondDate);
//if seconddate is current delete one day
// get last day checkable, must be 1 days before if today is the initial day
Date currentday= new Date(System.currentTimeMillis());
GregorianCalendar currentDayCalendar = new GregorianCalendar();
currentDayCalendar.setTime(currentday);
if( (currentDayCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.get(Calendar.DAY_OF_YEAR))){
secondDateCalendar.add(Calendar.DATE, -1);
}
//check dates
if(firstDateCalendar.get(Calendar.YEAR)>secondDateCalendar.get(Calendar.YEAR) ||
(firstDateCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && firstDateCalendar.get(Calendar.DAY_OF_YEAR)>secondDateCalendar.get(Calendar.DAY_OF_YEAR))){
logger.error("Incorrect Dates, First date must be 2 days previous to final date");
throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date");
}
// if iterator is less or equal to deployment date we cant check units
if (secondDateCalendar.before(firstDateCalendar)) {
logger.error("Incorrect date");
throw new DateHelperException(
"We cant get Results. Incorrect dates. Wait some days");
}
//checkUseCase
int usecase = getDateUseCase(firstDateCalendar.getTime(),secondDateCalendar.getTime());
GregorianCalendar iteratorFirst = null;
GregorianCalendar iteratorSecond = null;
switch (usecase) {
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
case USE_CASE_0:
//
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
case USE_CASE_1:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorSecond = (GregorianCalendar)secondDateCalendar.clone();
while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorSecond.add(Calendar.DATE, 1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=iteratorSecond.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
case USE_CASE_2:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
case USE_CASE_3:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorSecond = (GregorianCalendar)secondDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorSecond.add(Calendar.DATE, 1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
case USE_CASE_4:
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
return cleanUnitDataList(unitDataList);
}else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
iteratorFirst.add(Calendar.DATE, 7);
break;
}
iteratorFirst.add(Calendar.DATE, 7);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.DATE, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
case USE_CASE_5:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
return cleanUnitDataList(unitDataList);
}else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
iteratorFirst.add(Calendar.DATE, 7);
break;
}
iteratorFirst.add(Calendar.DATE, 7);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.DATE, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio y fin menos de un mes
case USE_CASE_6:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
case USE_CASE_7:
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
case USE_CASE_8:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorFirst.set(Calendar.DAY_OF_MONTH, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
case USE_CASE_9:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
case USE_CASE_10:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
case USE_CASE_11:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
case USE_CASE_12:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
case USE_CASE_13:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
case USE_CASE_14:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
case USE_CASE_15:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
case USE_CASE_16:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorFirst.set(Calendar.DAY_OF_MONTH, 1);
return getFullUnitData(iteratorFirst.getTime(), secondDate, sku, user, password, vendorId);
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
case USE_CASE_17:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
case USE_CASE_18:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
case USE_CASE_19:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
case USE_CASE_20:
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin menos de un mes
case USE_CASE_21:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
case USE_CASE_22:
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
default:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
}
return cleanUnitDataList(unitDataList);
}
}
|
appstoresstats-ios/src/main/java/es/arcadiaconsulting/appstoresstats/ios/io/DateHelper.java
|
/**
* Copyright 2013 Arcadia Consulting C.B.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package es.arcadiaconsulting.appstoresstats.ios.io;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import es.arcadiaconsulting.appstoresstats.ios.model.Constants;
import es.arcadiaconsulting.appstoresstats.ios.model.UnitData;
public class DateHelper {
private static final Logger logger = LoggerFactory
.getLogger(DateHelper.class);
public static Date buildDateFromUTCString(String utc){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
return formatter.parse(utc);
} catch (ParseException e) {
logger.error("incorrect Date",e );
return null;
}
}
public static List<UnitData> getFullUnitData(Date deploymentDate,
Date queryDate, String sku,/** String propertiesFile,*/ String user,
String password, String vendorId) throws DateHelperException {
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
List<UnitData> unitDataList = new Vector<UnitData>();
// iterator for compare dates
GregorianCalendar dateIterator = new GregorianCalendar();
dateIterator.setTime(queryDate);
GregorianCalendar deploymentDateCalendar = new GregorianCalendar();
deploymentDateCalendar.setTime(deploymentDate);
// get last day checkable, must be 1 days before if today is the initial day
Date currentday= new Date(System.currentTimeMillis());
GregorianCalendar currentDayCalendar = new GregorianCalendar();
currentDayCalendar.setTime(currentday);
if( (currentDayCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==dateIterator.get(Calendar.DAY_OF_YEAR))){
dateIterator.add(Calendar.DATE, -1);
}
//check dates
if(deploymentDateCalendar.get(Calendar.YEAR)>dateIterator.get(Calendar.YEAR) ||
(deploymentDateCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && deploymentDateCalendar.get(Calendar.DAY_OF_YEAR)>dateIterator.get(Calendar.DAY_OF_YEAR))){
logger.error("Incorrect Dates, First date must be 2 days previous to final date");
throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date");
}
// if iterator is less or equal to deployment date we cant check units
if (dateIterator.before(deploymentDateCalendar)) {
logger.error("Incorrect date");
throw new DateHelperException(
"We cant get Results. There are not sales too. Wait some days");
}
//getting years query
int deploymentyear = deploymentDateCalendar.get(Calendar.YEAR);
int dateIteratorYear = dateIterator.get(Calendar.YEAR);
GregorianCalendar yearIterator = deploymentDateCalendar;
while(deploymentyear < dateIteratorYear){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(yearIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
deploymentyear = deploymentyear+1;
yearIterator.add(Calendar.YEAR, 1);
//if query is on first day of year return response
if(dateIterator.get(Calendar.MONTH)==1&&dateIterator.get(Calendar.DAY_OF_MONTH)==1)
return cleanUnitDataList(unitDataList);
}
//iterate for months (iterate to month)
GregorianCalendar monthIterator = (GregorianCalendar)dateIterator.clone();
if(monthIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)){
//si es el mismo mes la consulta hacemos la consulta dia a dia
GregorianCalendar dayIterator = deploymentDateCalendar;
while(dayIterator.get(Calendar.DAY_OF_YEAR)<=dateIterator.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(dayIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting day units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
dayIterator.add(Calendar.DATE, 1);
}
}else{
while(monthIterator.get(Calendar.MONTH)-1>-1){
monthIterator.add(Calendar.MONTH, -1);
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(monthIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
//if query is first day of month return unit data
// if(dateIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.getActualMaximum(Calendar.DAY_OF_MONTH))
// return unitDataList;
}
//iterate for weeks
//first do petiton for day to sunday
GregorianCalendar weekIterator = new GregorianCalendar(dateIterator.get(Calendar.YEAR),dateIterator.get(Calendar.MONTH),1);
//si cae en 1 el lunes y la fecha de consulta es superior al 7 que sera domingo se hara la consulta unicamente con la semana
if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY && dateIterator.get(Calendar.DAY_OF_MONTH)>=7){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(dateIterator.get(Calendar.DAY_OF_MONTH)==7)
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DATE, 7);
}else{
//si no coincide con la primera semana llegamos al domingo de la primera semana dia a dia
do{
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
//si es el mismo dia que el ultimo dia consultable se retorna
if(weekIterator.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR)&&
weekIterator.get(Calendar.MONTH)==dateIterator.get(Calendar.MONTH)&&
weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH))
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DATE, 1);
}while(weekIterator.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY);
}
//hacemos la consulta de semanas mientras el dia del iterador mas 6 sea menor o igual que la fecha de la query
//la consulta debe hacerse por domingos asi que hay que sumar los seis dias
while(weekIterator.get(Calendar.DAY_OF_MONTH)+7<=dateIterator.get(Calendar.DAY_OF_MONTH)){
weekIterator.add(Calendar.DAY_OF_MONTH, 7);
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting week sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(weekIterator.get(Calendar.DAY_OF_MONTH)+7==dateIterator.get(Calendar.DAY_OF_MONTH))
return cleanUnitDataList(unitDataList);
weekIterator.add(Calendar.DAY_OF_MONTH, 1);
}
//hacemos por ultimo la consulta hasta llegar al dia de la consulta
while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(weekIterator.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(weekIterator.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
weekIterator.add(Calendar.DATE, 1);
}
}
return cleanUnitDataList(unitDataList);
/** Redo to init for years
// getting day units until sunday or deployment day or first sunday
// without 1 week passed
while ((Calendar.SUNDAY != dateIterator.get(Calendar.DAY_OF_WEEK) || (Calendar.SUNDAY == dateIterator
.get(Calendar.DAY_OF_WEEK) && isFirstSunday(
deploymentDateCalendar, dateIterator)))) {
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
propertiesFile, user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(dateIterator), sku);
if (dayUnitData == null) {
logger.error("Error Getting day units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
dateIterator.add(Calendar.DATE, -1);
// if dateIterator is the same that deployment day return item
if(dateIterator.get(Calendar.YEAR)==deploymentDateCalendar.get(Calendar.YEAR)&&dateIterator.get(Calendar.DAY_OF_MONTH)==deploymentDateCalendar.get(Calendar.DAY_OF_MONTH)&&dateIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH))
return unitDataList;
}
//init week iteration
//if is first week is less than 7 (if is 7 we can do one week petition) we must do a petition for day to arrive to first month day
if(dateIterator.get(Calendar.DAY_OF_WEEK)<7){
}
while(){
}
*/
}
private static boolean isFirstSunday(Calendar deploymentDate,
Calendar sunday) {
int dayOfWeek = deploymentDate.get(Calendar.DAY_OF_WEEK);
Calendar dateIterator = deploymentDate;
dateIterator.add(Calendar.DATE, 8 - dayOfWeek);
if (dateIterator.get(Calendar.DAY_OF_WEEK_IN_MONTH) == sunday
.get(Calendar.DAY_OF_WEEK_IN_MONTH))
return true;
return false;
}
private static List<UnitData> cleanUnitDataList(List<UnitData> unitDataListIn){
List<UnitData> cleanedUnitDataList = new Vector<UnitData>();
for (Iterator iterator = unitDataListIn.iterator(); iterator
.hasNext();) {
UnitData unitData = (UnitData) iterator.next();
boolean countryIsAdded = false;
for (Iterator iterator2 = cleanedUnitDataList.iterator(); iterator2
.hasNext();) {
UnitData unitDataCleaned = (UnitData) iterator2.next();
if(unitData.getCountryCode().equals(unitDataCleaned.getCountryCode())){
countryIsAdded = true;
break;
}
}
if(!countryIsAdded){
UnitData newUnitData = new UnitData(unitData.countryCode, getAllCountryDataUnits(unitDataListIn,unitData.countryCode));
cleanedUnitDataList.add(newUnitData);
}
}
return cleanedUnitDataList;
}
private static int getAllCountryDataUnits(List<UnitData> unitData, String country ){
int units=0;
for (Iterator iterator = unitData.iterator(); iterator.hasNext();) {
UnitData unitData2 = (UnitData) iterator.next();
if(unitData2.getCountryCode().equals(country))
units = units + unitData2.getUnits();
}
return units;
}
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
public static final int USE_CASE_0 = 0;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
public static final int USE_CASE_1 = 1;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
public static final int USE_CASE_2 = 2;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
public static final int USE_CASE_3 = 3;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
public static final int USE_CASE_4 = 4;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
public static final int USE_CASE_5 = 5;
// consulta fecha inicio y fin menos de un mes
public static final int USE_CASE_6=6;
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
public static final int USE_CASE_7 = 7;
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
public static final int USE_CASE_8 = 8;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
public static final int USE_CASE_9 = 9;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
public static final int USE_CASE_10 = 10;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
public static final int USE_CASE_11 = 11;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
public static final int USE_CASE_12 = 12;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
public static final int USE_CASE_13 = 13;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
public static final int USE_CASE_14 = 14;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
public static final int USE_CASE_15 = 15;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
public static final int USE_CASE_16 = 16;
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
public static final int USE_CASE_17 = 17;
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
public static final int USE_CASE_18 = 18;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
public static final int USE_CASE_19 = 19;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
public static final int USE_CASE_20 = 20;
// consulta fecha inicio mas de un año, fecha fin menos de un mes
public static final int USE_CASE_21 = 21;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
public static final int USE_CASE_22 = 22;
public static int getDateUseCase(Date firstDate, Date secondDate){
GregorianCalendar firstDateCalendar = new GregorianCalendar();
firstDateCalendar.setTime(firstDate);
GregorianCalendar secondDateCalendar = new GregorianCalendar();
secondDateCalendar.setTime(secondDate);
Date currentDate = new Date(System.currentTimeMillis());
GregorianCalendar currentDateCalendar = new GregorianCalendar();
currentDateCalendar.setTime(currentDate);
GregorianCalendar oneMonth = (GregorianCalendar)currentDateCalendar.clone();
oneMonth.add(Calendar.MONTH, -1);
//GregorianCalendar threeMonth = (GregorianCalendar)currentDateCalendar.clone();
//threeMonth.add(Calendar.MONTH, -3);
GregorianCalendar sixMonth = (GregorianCalendar)currentDateCalendar.clone();
sixMonth.add(Calendar.MONTH, -6);
GregorianCalendar oneYear = (GregorianCalendar) currentDateCalendar.clone();
oneYear.add(Calendar.YEAR, -1);
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_0;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_1;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_2;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_3;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY
&&secondDateCalendar.after(oneMonth))
return USE_CASE_4;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY
&&secondDateCalendar.after(oneMonth))
return USE_CASE_5;
// consulta fecha inicio y fin menos de un mes
if(firstDateCalendar.after(oneMonth)&&secondDateCalendar.after(oneMonth))
return USE_CASE_6;
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_7;
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_8;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_9;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_10;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_11;
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1
&&secondDateCalendar.after(oneMonth))
return USE_CASE_12;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH))
return USE_CASE_13;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
return USE_CASE_14;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY)
return USE_CASE_15;
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1
&&secondDateCalendar.after(oneMonth))
return USE_CASE_16;
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.getMaximum(Calendar.DAY_OF_YEAR))
return USE_CASE_17;
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneYear))
return USE_CASE_18;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(sixMonth)&&secondDateCalendar.after(oneYear))
return USE_CASE_19;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)== Calendar.SUNDAY)
return USE_CASE_20;
// consulta fecha inicio mas de un año, fecha fin menos de un mes
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.after(oneMonth))
return USE_CASE_21;
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!= Calendar.SUNDAY)
return USE_CASE_22;
return -1000;
}
public static List<UnitData> getUnitDataByDate(Date firstDate,
Date secondDate, String sku, String user,
String password, String vendorId) throws DateHelperException {
SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
List<UnitData> unitDataList = new Vector<UnitData>();
GregorianCalendar firstDateCalendar = new GregorianCalendar();
firstDateCalendar.setTime(firstDate);
GregorianCalendar secondDateCalendar = new GregorianCalendar();
secondDateCalendar.setTime(secondDate);
//if seconddate is current delete one day
// get last day checkable, must be 1 days before if today is the initial day
Date currentday= new Date(System.currentTimeMillis());
GregorianCalendar currentDayCalendar = new GregorianCalendar();
currentDayCalendar.setTime(currentday);
if( (currentDayCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.get(Calendar.DAY_OF_YEAR))){
secondDateCalendar.add(Calendar.DATE, -1);
}
//check dates
if(firstDateCalendar.get(Calendar.YEAR)>secondDateCalendar.get(Calendar.YEAR) ||
(firstDateCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && firstDateCalendar.get(Calendar.DAY_OF_YEAR)>secondDateCalendar.get(Calendar.DAY_OF_YEAR))){
logger.error("Incorrect Dates, First date must be 2 days previous to final date");
throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date");
}
// if iterator is less or equal to deployment date we cant check units
if (secondDateCalendar.before(firstDateCalendar)) {
logger.error("Incorrect date");
throw new DateHelperException(
"We cant get Results. Incorrect dates. Wait some days");
}
//checkUseCase
int usecase = getDateUseCase(firstDateCalendar.getTime(),secondDateCalendar.getTime());
GregorianCalendar iteratorFirst = null;
GregorianCalendar iteratorSecond = null;
switch (usecase) {
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo
case USE_CASE_0:
//
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==secondDateCalendar.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo
case USE_CASE_1:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorSecond = (GregorianCalendar)secondDateCalendar.clone();
while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorSecond.add(Calendar.DATE, 1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=iteratorSecond.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==iteratorSecond.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo
case USE_CASE_2:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==secondDateCalendar.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo
case USE_CASE_3:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorSecond = (GregorianCalendar)secondDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorSecond.add(Calendar.DATE, 1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==iteratorSecond.get(Calendar.DAY_OF_YEAR))
return cleanUnitDataList(unitDataList);
iteratorFirst.add(Calendar.DATE, 7);
}
break;
// consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes
case USE_CASE_4:
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
return cleanUnitDataList(unitDataList);
}else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
iteratorFirst.add(Calendar.DATE, 7);
break;
}
iteratorFirst.add(Calendar.DATE, 7);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.DATE, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes
case USE_CASE_5:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){
iteratorFirst.add(Calendar.DATE, -1);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting week units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+6==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
return cleanUnitDataList(unitDataList);
}else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
iteratorFirst.add(Calendar.DATE, 7);
break;
}
iteratorFirst.add(Calendar.DATE, 7);
}
while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime()));
return cleanUnitDataList(unitDataList);
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.DATE, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio y fin menos de un mes
case USE_CASE_6:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
case USE_CASE_7:
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes
case USE_CASE_8:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorFirst.set(Calendar.DAY_OF_MONTH, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
case USE_CASE_9:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo
case USE_CASE_10:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo
case USE_CASE_11:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes
case USE_CASE_12:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes
case USE_CASE_13:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo
case USE_CASE_14:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo
case USE_CASE_15:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes
case USE_CASE_16:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar)firstDateCalendar.clone();
iteratorFirst.set(Calendar.DAY_OF_MONTH, 1);
return getFullUnitData(iteratorFirst.getTime(), secondDate, sku, user, password, vendorId);
// consulta fecha inicio mas de un año, fecha fin ultimo dia del año
case USE_CASE_17:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin anterior a seis meses
case USE_CASE_18:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 6 y 12 meses
case USE_CASE_19:
logger.warn("We can get sales with this dates, we get the aproximated possible sale");
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo
case USE_CASE_20:
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
// consulta fecha inicio mas de un año, fecha fin menos de un mes
case USE_CASE_21:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
// consulta fecha inicio mas de un año, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo
case USE_CASE_22:
iteratorFirst = (GregorianCalendar) firstDateCalendar.clone();
while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting year units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.YEAR, 1);
}
iteratorFirst.set(Calendar.DAY_OF_YEAR, 1);
while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){
List<UnitData> dayUnitData = Autoingestion.getUnitsByDate(
/**propertiesFile,*/ user, password, vendorId,
Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY,
Constants.REPORT_SUBTYPE_SUMMARY_NAME,
sdf.format(iteratorFirst.getTime()), sku);
if (dayUnitData == null) {
logger.error("Error Getting month units");
throw new DateHelperException(
"Problem getting day sales. Please see log for more information");
}
unitDataList.addAll(dayUnitData);
iteratorFirst.add(Calendar.MONTH, 1);
}
return cleanUnitDataList(unitDataList);
default:
return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId);
}
return cleanUnitDataList(unitDataList);
}
}
|
change week incrementor
|
appstoresstats-ios/src/main/java/es/arcadiaconsulting/appstoresstats/ios/io/DateHelper.java
|
change week incrementor
|
|
Java
|
apache-2.0
|
4df900a4a513a94ebf29c2818c9491e815deaeda
| 0
|
cibuddy/cibuddy,cibuddy/cibuddy
|
/*
* Copyright (C) 2012 Mirko Jahn <mirkojahn@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cibuddy.jenkins;
import com.cibuddy.core.build.server.IProjectState;
import com.cibuddy.core.build.server.IServer;
import de.kalpatec.pojosr.framework.launch.ClasspathScanner;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistry;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistryFactory;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import org.apache.felix.fileinstall.ArtifactInstaller;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
/**
*
* @author Mirko Jahn <mirkojahn@gmail.com>
*/
public class TestServiceExposure {
PojoServiceRegistry registry;
File jenkinsConfigFile = new File("src/test/resources/com/cibuddy/jenkins/jenkins-ci-public.jenkins");
@Before
public void before() throws Exception {
Map config = new HashMap();
config.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner().scanForBundles());
ServiceLoader<PojoServiceRegistryFactory> loader = ServiceLoader.load(PojoServiceRegistryFactory.class);
registry = loader.iterator().next().newPojoServiceRegistry(config);
// make sure this bundle is started by manually loading the activator
// (we're not yet a bundle to be picked up automatically)
Activator activator = new Activator();
activator.start(registry.getBundleContext());
}
@Test
public void test() throws Exception{
Assert.assertNotNull("BundleContext is not set.", Activator.getBundleContext());
ServiceReference sr = registry.getServiceReference(ArtifactInstaller.class.getName());
Assert.assertNotNull("No service registered, although expected to be "
+ "there for the file based travis server configuration.",sr);
ArtifactInstaller ai = (ArtifactInstaller)registry.getService(sr);
Assert.assertTrue("File does not exist! Check path and setup!", jenkinsConfigFile.exists());
if(ai instanceof ServerConfigurationListener){
// check if the ArtifactInstaller could handle a configuration file
boolean canHandle = ai.canHandle(jenkinsConfigFile);
Assert.assertTrue("The file failed the verification and appears to be not valid.", canHandle);
// ensure that there are no IServer's exposed first
if(registry.getServiceReference(IServer.class.getName()) != null){
Assert.fail("Found a ServiceReference prior to registration. This should not happen.");
}
// now check exposure of an IServer
ai.install(jenkinsConfigFile);
ServiceReference sr2 = registry.getServiceReference(IServer.class.getName());
if(sr2 == null){
Assert.fail("NO IServer service found when expected! Check registration...");
}
IServer server = (IServer)registry.getService(sr2);
Assert.assertNotNull("Server object of IServer service couldn't be retrieved", server);
// do a very very simple server configuration comparison
Assert.assertEquals("The server alias is not identical to the one set in the configuration file.", "org.apache", server.getBuildServerAlias());
Assert.assertEquals("The server type is not identical to the one expected.", IServer.TYPE_JENKINS_SERVER, server.getBuildServerType());
Assert.assertEquals("The server URL is not identical to the one set in the configuration file.",new URI("https://builds.apache.org/"),server.getBuildServerURL());
Assert.assertNotNull("The server version is not as expected!",server.getBuildServerVersion());
Assert.assertTrue("Version string doesn't contain a dot as expected. Might have changed though...", server.getBuildServerVersion().contains("."));
//Assert.assertEquals("The server version is not as expected! (they might have upgraded ;-))","1.480",server.getBuildServerVersion());
Assert.assertEquals("The server source is not as expected!",jenkinsConfigFile.toURI().toURL().getFile(),server.getBuildServerSource());
// this might fail at any point... do it just because of curiosity
// FIXME: only test this with a specific variable set and not with a network look-up!!!
// IProjectState ibp = server.getProjectState("Karaf");
// Assert.assertNotNull("No such project found on server - do we have internet access???",ibp);
// Assert.assertNotNull("No build status available, but should be.",ibp.getBuildStatus());
// Assert.assertNotNull("No build status received.",ibp.getProjectColor());
} else {
Assert.fail("Expected only one service exposed coming from this bundle.");
}
}
}
|
servers/jenkins/src/test/java/com/cibuddy/jenkins/TestServiceExposure.java
|
/*
* Copyright (C) 2012 Mirko Jahn <mirkojahn@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cibuddy.jenkins;
import com.cibuddy.core.build.server.IProjectState;
import com.cibuddy.core.build.server.IServer;
import de.kalpatec.pojosr.framework.launch.ClasspathScanner;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistry;
import de.kalpatec.pojosr.framework.launch.PojoServiceRegistryFactory;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import org.apache.felix.fileinstall.ArtifactInstaller;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
/**
*
* @author Mirko Jahn <mirkojahn@gmail.com>
*/
public class TestServiceExposure {
PojoServiceRegistry registry;
File jenkinsConfigFile = new File("src/test/resources/com/cibuddy/jenkins/jenkins-ci-public.jenkins");
@Before
public void before() throws Exception {
Map config = new HashMap();
config.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner().scanForBundles());
ServiceLoader<PojoServiceRegistryFactory> loader = ServiceLoader.load(PojoServiceRegistryFactory.class);
registry = loader.iterator().next().newPojoServiceRegistry(config);
// make sure this bundle is started by manually loading the activator
// (we're not yet a bundle to be picked up automatically)
Activator activator = new Activator();
activator.start(registry.getBundleContext());
}
@Test
public void test() throws Exception{
Assert.assertNotNull("BundleContext is not set.", Activator.getBundleContext());
ServiceReference sr = registry.getServiceReference(ArtifactInstaller.class.getName());
Assert.assertNotNull("No service registered, although expected to be "
+ "there for the file based travis server configuration.",sr);
ArtifactInstaller ai = (ArtifactInstaller)registry.getService(sr);
Assert.assertTrue("File does not exist! Check path and setup!", jenkinsConfigFile.exists());
if(ai instanceof ServerConfigurationListener){
// check if the ArtifactInstaller could handle a configuration file
boolean canHandle = ai.canHandle(jenkinsConfigFile);
Assert.assertTrue("The file failed the verification and appears to be not valid.", canHandle);
// ensure that there are no IServer's exposed first
if(registry.getServiceReference(IServer.class.getName()) != null){
Assert.fail("Found a ServiceReference prior to registration. This should not happen.");
}
// now check exposure of an IServer
ai.install(jenkinsConfigFile);
ServiceReference sr2 = registry.getServiceReference(IServer.class.getName());
if(sr2 == null){
Assert.fail("NO IServer service found when expected! Check registration...");
}
IServer server = (IServer)registry.getService(sr2);
Assert.assertNotNull("Server object of IServer service couldn't be retrieved", server);
// do a very very simple server configuration comparison
Assert.assertEquals("The server alias is not identical to the one set in the configuration file.", "org.apache", server.getBuildServerAlias());
Assert.assertEquals("The server type is not identical to the one expected.", IServer.TYPE_JENKINS_SERVER, server.getBuildServerType());
Assert.assertEquals("The server URL is not identical to the one set in the configuration file.",new URI("https://builds.apache.org/"),server.getBuildServerURL());
Assert.assertNotNull("The server version is not as expected!",server.getBuildServerVersion());
Assert.assertTrue("Version string doesn't contain a dot as expected. Might have changed though...", server.getBuildServerVersion().contains("."));
//Assert.assertEquals("The server version is not as expected! (they might have upgraded ;-))","1.480",server.getBuildServerVersion());
Assert.assertEquals("The server source is not as expected!",jenkinsConfigFile.toURI().toURL().getFile(),server.getBuildServerSource());
// this might fail at any point... do it just because of curiosity
// FIXME: only test this with a specific variable set!!!
IProjectState ibp = server.getProjectState("Karaf");
Assert.assertNotNull("No such project found on server - do we have internet access???",ibp);
Assert.assertNotNull("No build status available, but should be.",ibp.getBuildStatus());
Assert.assertNotNull("No build status received.",ibp.getProjectColor());
} else {
Assert.fail("Expected only one service exposed coming from this bundle.");
}
}
}
|
removed network dependency on test execution
|
servers/jenkins/src/test/java/com/cibuddy/jenkins/TestServiceExposure.java
|
removed network dependency on test execution
|
|
Java
|
apache-2.0
|
03f5b09af51af0e77594b4d414ace306867c4f0c
| 0
|
OpenHFT/Chronicle-Core
|
/*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.core.io;
import sun.misc.Cleaner;
import sun.nio.ch.DirectBuffer;
import sun.reflect.Reflection;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Created by peter on 26/08/15.
* A collection of IO utility tools
*/
public enum IOTools {
;
public static boolean shallowDeleteDirWithFiles(String directory) {
File dir = new File(directory);
File[] entries = dir.listFiles();
if(entries==null)return false;
Stream.of(entries).filter(File::isDirectory).forEach(f -> {
throw new AssertionError("Contains directory " + f);
});
Stream.of(entries).forEach(File::delete);
return dir.delete();
}
/**
* This method first looks for the file in the classpath. If this is not found it
* appends the suffix .gz and looks again in the classpath to see if it is present.
* If it is still not found it looks for the file on the file system. If it not found
* it appends the suffix .gz and looks again on the file system.
* If it still not found a FileNotFoundException is thrown.
*
* @param name Name of the file
* @return A byte[] containing the contents of the file
* @throws IOException FileNotFoundException thrown if file is not found
*/
public static byte[] readFile(String name) throws IOException {
ClassLoader classLoader;
try {
classLoader = Reflection.getCallerClass().getClassLoader();
} catch (Throwable e) {
classLoader = Thread.currentThread().getContextClassLoader();
}
InputStream is = classLoader.getResourceAsStream(name);
if (is == null)
is = classLoader.getResourceAsStream(name + ".gz");
if (is == null)
try {
is = new FileInputStream(name);
} catch (FileNotFoundException e) {
try {
is = new GZIPInputStream(new FileInputStream(name + ".gz"));
} catch (FileNotFoundException e1) {
throw e;
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(512, is.available()));
byte[] bytes = new byte[1024];
for (int len; (len = is.read(bytes)) > 0; )
out.write(bytes, 0, len);
return out.toByteArray();
}
public static void writeFile(String filename, byte[] bytes) throws IOException {
OutputStream out = new FileOutputStream(filename);
if (filename.endsWith(".gz"))
out = new GZIPOutputStream(out);
out.write(bytes);
out.close();
}
public static String tempName(String filename) {
int ext = filename.lastIndexOf('.');
if (ext > 0 && ext > filename.length() - 5) {
return filename.substring(0, ext) + System.nanoTime() + filename.substring(ext);
}
return filename + System.nanoTime();
}
public static void clean(ByteBuffer bb) {
if (bb instanceof DirectBuffer) {
Cleaner cl = ((DirectBuffer) bb).cleaner();
if (cl != null)
cl.clean();
}
}
}
|
src/main/java/net/openhft/chronicle/core/io/IOTools.java
|
/*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.core.io;
import sun.misc.Cleaner;
import sun.nio.ch.DirectBuffer;
import sun.reflect.Reflection;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Created by peter on 26/08/15.
* A collection of IO utility tools
*/
public enum IOTools {
;
public static boolean shallowDeleteDirWithFiles(String directory) {
File dir = new File(directory);
File[] entries = dir.listFiles();
Stream.of(entries).filter(File::isDirectory).forEach(f -> {
throw new AssertionError("Contains directory " + f);
});
Stream.of(entries).forEach(File::delete);
return dir.delete();
}
/**
* This method first looks for the file in the classpath. If this is not found it
* appends the suffix .gz and looks again in the classpath to see if it is present.
* If it is still not found it looks for the file on the file system. If it not found
* it appends the suffix .gz and looks again on the file system.
* If it still not found a FileNotFoundException is thrown.
*
* @param name Name of the file
* @return A byte[] containing the contents of the file
* @throws IOException FileNotFoundException thrown if file is not found
*/
public static byte[] readFile(String name) throws IOException {
ClassLoader classLoader;
try {
classLoader = Reflection.getCallerClass().getClassLoader();
} catch (Throwable e) {
classLoader = Thread.currentThread().getContextClassLoader();
}
InputStream is = classLoader.getResourceAsStream(name);
if (is == null)
is = classLoader.getResourceAsStream(name + ".gz");
if (is == null)
try {
is = new FileInputStream(name);
} catch (FileNotFoundException e) {
try {
is = new GZIPInputStream(new FileInputStream(name + ".gz"));
} catch (FileNotFoundException e1) {
throw e;
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(512, is.available()));
byte[] bytes = new byte[1024];
for (int len; (len = is.read(bytes)) > 0; )
out.write(bytes, 0, len);
return out.toByteArray();
}
public static void writeFile(String filename, byte[] bytes) throws IOException {
OutputStream out = new FileOutputStream(filename);
if (filename.endsWith(".gz"))
out = new GZIPOutputStream(out);
out.write(bytes);
out.close();
}
public static String tempName(String filename) {
int ext = filename.lastIndexOf('.');
if (ext > 0 && ext > filename.length() - 5) {
return filename.substring(0, ext) + System.nanoTime() + filename.substring(ext);
}
return filename + System.nanoTime();
}
public static void clean(ByteBuffer bb) {
if (bb instanceof DirectBuffer) {
Cleaner cl = ((DirectBuffer) bb).cleaner();
if (cl != null)
cl.clean();
}
}
}
|
Fix bug in IOTools.
|
src/main/java/net/openhft/chronicle/core/io/IOTools.java
|
Fix bug in IOTools.
|
|
Java
|
apache-2.0
|
67960f38f1cf5543a80c7f604e6964cbc315db5e
| 0
|
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.util.Pair;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.util.StringUtils;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.activities.CommCareHomeActivity;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns;
import org.commcare.dalvik.services.CommCareSessionService;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.jr.extensions.IntentCallout;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.FormSaveCallback;
import org.odk.collect.android.listeners.WidgetChangedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity.ProgressBarMode;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.Base64Wrapper;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.GeoUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.views.ResizingImageView;
import org.odk.collect.android.widgets.DateTimeWidget;
import org.odk.collect.android.widgets.IntentWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.TimeWidget;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
/**
* FormEntryActivity is responsible for displaying questions, animating transitions between
* questions, and allowing the user to enter data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormEntryActivity extends FragmentActivity implements AnimationListener, FormLoaderListener,
FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener,
WidgetChangedListener {
private static final String t = "FormEntryActivity";
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int INTENT_CALLOUT = 10;
public static final int HIERARCHY_ACTIVITY_FIRST_START = 11;
public static final int SIGNATURE_CAPTURE = 12;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
public static final String KEY_INSTANCEDESTINATION = "instancedestination";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
public static final String KEY_FORM_CONTENT_URI = "form_content_uri";
public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri";
public static final String KEY_AES_STORAGE_KEY = "key_aes_storage";
public static final String KEY_HEADER_STRING = "form_header";
public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management";
public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled";
public static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved";
/**
* Intent extra flag to track if this form is an archive. Used to trigger
* return logic when this activity exits to the home screen, such as
* whether to redirect to archive view or sync the form.
*/
public static final String IS_ARCHIVED_FORM = "is-archive-form";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private String mFormPath;
// Path to a particular form instance
public static String mInstancePath;
private String mInstanceDestination;
private GestureDetector mGestureDetector;
private SecretKeySpec symetricKey = null;
public static FormController mFormController;
private Animation mInAnimation;
private Animation mOutAnimation;
private ViewGroup mViewPane;
private View mCurrentView;
private AlertDialog mRepeatDialog;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
private boolean mIncompleteEnabled = true;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private Uri formProviderContentURI = FormsColumns.CONTENT_URI;
private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI;
private static String mHeaderString;
// Was the form saved? Used to set activity return code.
public boolean hasSaved = false;
private BroadcastReceiver mNoGPSReceiver;
// marked true if we are in the process of saving a form because the user
// database & key session are expiring. Being set causes savingComplete to
// broadcast a form saving intent.
private boolean savingFormOnKeySessionExpiration = false;
enum AnimationType {
LEFT, RIGHT, FADE
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
@SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// CommCareSessionService will call this.formSaveCallback when the
// key session is closing down and we need to save any intermediate
// results before they become un-saveable.
CommCareApplication._().getSession().registerFormSaveCallback(this);
} catch (SessionUnavailableException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Couldn't register form save callback because session doesn't exist");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment");
if(fragmentClass != null) {
final FragmentManager fm = this.getSupportFragmentManager();
//Add breadcrumb bar
Fragment bar = (Fragment) fm.findFragmentByTag(TITLE_FRAGMENT_TAG);
// If the state holder is null, create a new one for this activity
if (bar == null) {
try {
bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance();
//the bar will set this up for us again if we need.
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit();
} catch(Exception e) {
Log.w("odk-collect", "couldn't instantiate fragment: " + fragmentClass);
}
}
}
}
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
return;
}
setupUI();
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(
getApplicationContext()));
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) {
formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) {
instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) {
mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION);
}
if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) {
mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED);
}
if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED);
}
if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) {
String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(savedInstanceState.containsKey(KEY_HEADER_STRING)) {
mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING);
}
if(savedInstanceState.containsKey(KEY_HAS_SAVED)) {
hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = this.getLastCustomNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
refreshCurrentView();
return;
}
boolean readOnly = false;
// Not a restart from a screen orientation change (or other).
mFormController = null;
mInstancePath = null;
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if(intent.hasExtra(KEY_FORM_CONTENT_URI)) {
this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) {
this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCEDESTINATION)) {
this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION);
} else {
mInstanceDestination = Collect.INSTANCES_PATH;
}
if(intent.hasExtra(KEY_AES_STORAGE_KEY)) {
String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(intent.hasExtra(KEY_HEADER_STRING)) {
this.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING);
}
if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) {
this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true);
}
if(intent.hasExtra(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED);
}
if(mHeaderString != null) {
setTitle(mHeaderString);
} else {
setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form));
}
//csims@dimagi.com - Jan 24, 2012
//Since these are parceled across the content resolver, there's no guarantee of reference equality.
//We need to manually check value equality on the type
final String contentType = getContentResolver().getType(uri);
Uri formUri = null;
switch (contentType) {
case InstanceColumns.CONTENT_ITEM_TYPE:
final Cursor instanceCursor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
instanceCursor = new CursorLoader(this, uri, null, null, null, null).loadInBackground();
} else {
instanceCursor = this.managedQuery(uri, null, null, null, null);
}
if (instanceCursor.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
mInstancePath =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
final String jrFormId =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
//If this form is both already completed
if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) {
if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) {
readOnly = true;
}
}
final String[] selectionArgs = {
jrFormId
};
final String selection = FormsColumns.JR_FORM_ID + " like ?";
final Cursor formCursor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
formCursor = new CursorLoader(this, formProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
formCursor = managedQuery(formProviderContentURI, null, selection, selectionArgs, null);
}
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath =
formCursor.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID)));
} else if (formCursor.getCount() < 1) {
CommCareHomeActivity.createErrorDialog(this, "Parent form does not exist", EXIT);
return;
} else if (formCursor.getCount() > 1) {
CommCareHomeActivity.createErrorDialog(this, "More than one possible parent form", EXIT);
return;
}
}
break;
case FormsColumns.CONTENT_ITEM_TYPE:
final Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, uri, null, null, null, null).loadInBackground();
} else {
c = this.managedQuery(uri, null, null, null, null);
}
if (c.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = uri;
}
break;
default:
Log.e(t, "unrecognized URI");
CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT);
return;
}
if(formUri == null) {
Log.e(t, "unrecognized URI");
CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(this, symetricKey, readOnly);
mFormLoaderTask.execute(formUri);
showDialog(PROGRESS_DIALOG);
}
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
/*
* EventLog accepts only proper Strings as input, but prior to this version,
* Android would try to send SpannedStrings to it, thus crashing the app.
* This makes sure the title is actually a String.
* This fixes bug 174626.
*/
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2
&& item.getTitleCondensed() != null) {
if (BuildConfig.DEBUG) {
Log.v(t, "Selected item is: " + item);
}
item.setTitleCondensed(item.getTitleCondensed().toString());
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public void formSaveCallback() {
// note that we have started saving the form
savingFormOnKeySessionExpiration = true;
// start saving form, which will call the key session logout completion
// function when it finishes.
saveDataToDisk(EXIT, false, null, true);
}
/**
* Setup BroadcastReceiver for asking user if they want to enable gps
*/
private void registerFormEntryReceivers() {
// See if this form needs GPS to be turned on
mNoGPSReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.removeStickyBroadcast(intent);
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Set<String> providers = GeoUtils.evaluateProviders(manager);
if (providers.isEmpty()) {
DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == DialogInterface.BUTTON_POSITIVE) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
};
GeoUtils.showNoGpsDialog(FormEntryActivity.this, onChangeListener);
}
}
};
registerReceiver(mNoGPSReceiver,
new IntentFilter(GeoUtils.ACTION_CHECK_GPS_ENABLED));
}
/**
* Setup Activity's UI
*/
private void setupUI() {
setContentView(R.layout.screen_form_entry);
setNavBarVisibility();
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"done".equals(v.getTag())) {
FormEntryActivity.this.showNextView();
} else {
triggerUserFormComplete();
}
}
});
prevButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"quit".equals(v.getTag())) {
FormEntryActivity.this.showPreviousView();
} else {
FormEntryActivity.this.triggerUserQuitInput();
}
}
});
mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane);
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this);
}
public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment";
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString());
outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString());
outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination);
outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled);
outState.putBoolean(KEY_HAS_SAVED, hasSaved);
outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod);
if(symetricKey != null) {
try {
outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded()));
} catch (ClassNotFoundException e) {
// we can't really get here anyway, since we couldn't have decoded the string to begin with
throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key");
}
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
if(requestCode == HIERARCHY_ACTIVITY_FIRST_START) {
//they pressed 'back' on the first heirarchy screen. we should assume they want to
//back out of form entry all together
finishReturnInstance(false);
} else if(requestCode == INTENT_CALLOUT){
processIntentResponse(intent, true);
}
// request was canceled, so do nothing
return;
}
ContentValues values;
Uri imageURI;
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case INTENT_CALLOUT:
processIntentResponse(intent);
break;
case IMAGE_CAPTURE:
case SIGNATURE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// The intent is empty, but we know we saved the image to the temp file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String s = mInstanceFolder + "/" + System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath());
}
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, nf.getName());
values.put(Images.Media.DISPLAY_NAME, nf.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, nf.getAbsolutePath());
imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// get gp of chosen file
String sourceImagePath = null;
Uri selectedImage = intent.getData();
sourceImagePath = FileUtils.getPath(this, selectedImage);
// Copy file to sdcard
String mInstanceFolder1 =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String destImagePath = mInstanceFolder1 + "/" + System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
imageURI =
getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
} else {
Log.e(t, "NO IMAGE EXISTS at: " + source.getAbsolutePath());
}
refreshCurrentView();
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content provider
// then the widget copies the file and makes a new entry in the content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so refresh
refreshCurrentView(false);
break;
}
}
private void processIntentResponse(Intent response){
processIntentResponse(response, false);
}
private void processIntentResponse(Intent response, boolean cancelled) {
// keep track of whether we should auto advance
boolean advance = false;
boolean quick = false;
//We need to go grab our intent callout object to process the results here
IntentWidget bestMatch = null;
//Ugh, copied from the odkview mostly, that's stupid
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
//Figure out if we have a pending intent widget
if (q instanceof IntentWidget) {
if(((IntentWidget) q).isWaitingForBinaryData() || bestMatch == null) {
bestMatch = (IntentWidget)q;
}
}
}
if(bestMatch != null) {
//Set our instance destination for binary data if needed
String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
//get the original intent callout
IntentCallout ic = bestMatch.getIntentCallout();
quick = "quick".equals(ic.getAppearance());
//And process it
advance = ic.processResponse(response, (ODKView)mCurrentView, mFormController.getInstance(), new File(destination));
ic.setCancelled(cancelled);
}
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// auto advance if we got a good result and are in quick mode
if(advance && quick){
showNextView();
}
}
public void updateFormRelevencies(){
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
if(!(mCurrentView instanceof ODKView)){
throw new RuntimeException("Tried to update form relevency not on compound view");
}
ODKView oldODKV = (ODKView)mCurrentView;
FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts();
Set<FormEntryPrompt> used = new HashSet<FormEntryPrompt>();
ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets();
ArrayList<Integer> removeList = new ArrayList<Integer>();
for(int i=0;i<oldWidgets.size();i++){
QuestionWidget oldWidget = oldWidgets.get(i);
boolean stillRelevent = false;
for(FormEntryPrompt prompt : newValidPrompts) {
if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) {
stillRelevent = true;
used.add(prompt);
}
}
if(!stillRelevent){
removeList.add(Integer.valueOf(i));
}
}
// remove "atomically" to not mess up iterations
oldODKV.removeQuestionsFromIndex(removeList);
//Now go through add add any new prompts that we need
for(int i = 0 ; i < newValidPrompts.length; ++i) {
FormEntryPrompt prompt = newValidPrompts[i];
if(used.contains(prompt)) {
//nothing to do here
continue;
}
oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i);
}
}
private static class NavigationDetails {
public int totalQuestions = 0;
public int completedQuestions = 0;
public boolean relevantBeforeCurrentScreen = false;
public boolean isFirstScreen = false;
public int answeredOnScreen = 0;
public int requiredOnScreen = 0;
public int relevantAfterCurrentScreen = 0;
public FormIndex currentScreenExit = null;
}
private NavigationDetails calculateNavigationStatus() {
NavigationDetails details = new NavigationDetails();
FormIndex userFormIndex = mFormController.getFormIndex();
FormIndex currentFormIndex = FormIndex.createBeginningOfFormIndex();
mFormController.expandRepeats(currentFormIndex);
int event = mFormController.getEvent(currentFormIndex);
try {
// keep track of whether there is a question that exists before the
// current screen
boolean onCurrentScreen = false;
while (event != FormEntryController.EVENT_END_OF_FORM) {
int comparison = currentFormIndex.compareTo(userFormIndex);
if (comparison == 0) {
onCurrentScreen = true;
details.currentScreenExit = mFormController.getNextFormIndex(currentFormIndex, true);
}
if (onCurrentScreen && currentFormIndex.equals(details.currentScreenExit)) {
onCurrentScreen = false;
}
// Figure out if there are any events before this screen (either
// new repeat or relevant questions are valid)
if (event == FormEntryController.EVENT_QUESTION
|| event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// Figure out whether we're on the last screen
if (!details.relevantBeforeCurrentScreen && !details.isFirstScreen) {
// We got to the current screen without finding a
// relevant question,
// I guess we're on the first one.
if (onCurrentScreen
&& !details.relevantBeforeCurrentScreen) {
details.isFirstScreen = true;
} else {
// We're using the built in steps (and they take
// relevancy into account)
// so if there are prompts they have to be relevant
details.relevantBeforeCurrentScreen = true;
}
}
}
if (event == FormEntryController.EVENT_QUESTION) {
FormEntryPrompt[] prompts = mFormController.getQuestionPrompts(currentFormIndex);
if (!onCurrentScreen && details.currentScreenExit != null) {
details.relevantAfterCurrentScreen += prompts.length;
}
details.totalQuestions += prompts.length;
// Current questions are complete only if they're answered.
// Past questions are always complete.
// Future questions are never complete.
if (onCurrentScreen) {
for (FormEntryPrompt prompt : prompts) {
if (this.mCurrentView instanceof ODKView) {
ODKView odkv = (ODKView) this.mCurrentView;
prompt = getOnScreenPrompt(prompt, odkv);
}
boolean isAnswered = prompt.getAnswerValue() != null
|| prompt.getDataType() == Constants.DATATYPE_NULL;
if (prompt.isRequired()) {
details.requiredOnScreen++;
if (isAnswered) {
details.answeredOnScreen++;
}
}
if (isAnswered) {
details.completedQuestions++;
}
}
} else if (comparison < 0) {
// For previous questions, consider all "complete"
details.completedQuestions += prompts.length;
// TODO: This doesn't properly capture state to
// determine whether we will end up out of the form if
// we hit back!
// Need to test _until_ we get a question that is
// relevant, then we can skip the relevancy tests
}
}
else if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// If we've already passed the current screen, this repeat
// junction is coming up in the future and we will need to
// know
// about it
if (!onCurrentScreen && details.currentScreenExit != null) {
details.totalQuestions++;
details.relevantAfterCurrentScreen++;
} else {
// Otherwise we already passed it and it no longer
// affects the count
}
}
currentFormIndex = mFormController.getNextFormIndex(currentFormIndex, FormController.STEP_INTO_GROUP, false);
event = mFormController.getEvent(currentFormIndex);
}
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
// Set form back to correct state
mFormController.jumpToIndex(userFormIndex);
return details;
}
/**
* Update progress bar's max and value, and the various buttons and navigation cues
* associated with navigation
*
* @param view ODKView to update
*/
public void updateNavigationCues(View view) {
updateFloatingLabels(view);
ProgressBarMode mode = PreferencesActivity.getProgressBarMode(this);
setNavBarVisibility();
if(mode == ProgressBarMode.None) { return; }
NavigationDetails details = calculateNavigationStatus();
if(mode == ProgressBarMode.ProgressOnly && view instanceof ODKView) {
((ODKView)view).updateProgressBar(details.completedQuestions, details.totalQuestions);
return;
}
ProgressBar progressBar = (ProgressBar)this.findViewById(R.id.nav_prog_bar);
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
if(!details.relevantBeforeCurrentScreen) {
prevButton.setImageResource(R.drawable.icon_close_darkwarm);
prevButton.setTag("quit");
} else {
prevButton.setImageResource(R.drawable.icon_chevron_left_brand);
prevButton.setTag("back");
}
//Apparently in Android 2.3 setting the drawable resource for the progress bar
//causes it to lose it bounds. It's a bit cheaper to keep them around than it
//is to invalidate the view, though.
Rect bounds = progressBar.getProgressDrawable().getBounds(); //Save the drawable bound
Log.i("Questions","Total questions: " + details.totalQuestions + " | Completed questions: " + details.completedQuestions);
progressBar.getProgressDrawable().setBounds(bounds); //Set the bounds to the saved value
progressBar.setMax(details.totalQuestions);
if(details.relevantAfterCurrentScreen == 0 && (details.requiredOnScreen == details.answeredOnScreen || details.requiredOnScreen < 1)) {
nextButton.setImageResource(R.drawable.icon_chevron_right_attnpos);
//TODO: _really_? This doesn't seem right
nextButton.setTag("done");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_full));
Log.i("Questions","Form complete");
// if we get here, it means we don't have any more relevant questions after this one, so we mark it as complete
progressBar.setProgress(details.totalQuestions); // completely fills the progressbar
} else {
nextButton.setImageResource(R.drawable.icon_chevron_right_brand);
//TODO: _really_? This doesn't seem right
nextButton.setTag("next");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_modern));
progressBar.setProgress(details.completedQuestions);
}
//We should probably be doing this based on the widgets, maybe, not the model? Hard to call.
updateBadgeInfo(details.requiredOnScreen, details.answeredOnScreen);
}
private void setNavBarVisibility() {
//Make sure the nav bar visibility is set
int navBarVisibility = PreferencesActivity.getProgressBarMode(this).useNavigationBar() ? View.VISIBLE : View.GONE;
View nav = this.findViewById(R.id.nav_pane);
if(nav.getVisibility() != navBarVisibility) {
nav.setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge_border_drawer).setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge).setVisibility(navBarVisibility);
}
}
enum FloatingLabel {
good ("floating-good", R.drawable.label_floating_good, R.color.cc_attention_positive_text),
caution ("floating-caution", R.drawable.label_floating_caution, R.color.cc_light_warm_accent_color),
bad ("floating-bad", R.drawable.label_floating_bad, R.color.cc_attention_negative_color);
String label;
int resourceId;
int colorId;
FloatingLabel(String label, int resourceId, int colorId) {
this.label = label;
this.resourceId = resourceId;
this.colorId = colorId;
}
public String getAppearance() { return label;}
public int getBackgroundDrawable() { return resourceId; }
public int getColorId() { return colorId; }
};
private void updateFloatingLabels(View currentView) {
//TODO: this should actually be set up to scale per screen size.
ArrayList<Pair<String, FloatingLabel>> smallLabels = new ArrayList<Pair<String, FloatingLabel>>();
ArrayList<Pair<String, FloatingLabel>> largeLabels = new ArrayList<Pair<String, FloatingLabel>>();
FloatingLabel[] labelTypes = FloatingLabel.values();
if(currentView instanceof ODKView) {
for(QuestionWidget widget : ((ODKView)currentView).getWidgets()) {
String hint = widget.getPrompt().getAppearanceHint();
if(hint == null) { continue; }
for(FloatingLabel type : labelTypes) {
if(type.getAppearance().equals(hint)) {
String widgetText = widget.getPrompt().getQuestionText();
if(widgetText != null && widgetText.length() < 15) {
smallLabels.add(new Pair(widgetText, type));
} else {
largeLabels.add(new Pair(widgetText, type));
}
}
}
}
}
final ViewGroup parent = (ViewGroup)this.findViewById(R.id.form_entry_label_layout);
parent.removeAllViews();
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
int minHeight = 7 * pixels;
//Ok, now go ahead and add all of the small labels
for(int i = 0 ; i < smallLabels.size(); i = i + 2 ) {
if(i + 1 < smallLabels.size()) {
LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(lpp);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
TextView left = (TextView)View.inflate(this, R.layout.component_floating_label, null);
left.setLayoutParams(lp);
left.setText(smallLabels.get(i).first + "; " + smallLabels.get(i + 1).first);
left.setBackgroundResource(smallLabels.get(i).second.resourceId);
left.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
left.setTextColor(smallLabels.get(i).second.colorId);
left.setMinimumHeight(minHeight);
layout.addView(left);
parent.addView(layout);
} else {
largeLabels.add(smallLabels.get(i));
}
}
for(int i = 0 ; i < largeLabels.size(); ++i ) {
final TextView view = (TextView)View.inflate(this, R.layout.component_floating_label, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
view.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
view.setText(largeLabels.get(i).first);
view.setBackgroundResource(largeLabels.get(i).second.resourceId);
view.setTextColor(largeLabels.get(i).second.colorId);
view.setMinimumHeight(minHeight);
parent.addView(view);
}
}
private void updateBadgeInfo(int requiredOnScreen, int answeredOnScreen) {
View badgeBorder = this.findViewById(R.id.nav_badge_border_drawer);
TextView badge = (TextView)this.findViewById(R.id.nav_badge);
//If we don't need this stuff, just bail
if(requiredOnScreen <= 1) {
//Hide all badge related items
badgeBorder.setVisibility(View.INVISIBLE);
badge.setVisibility(View.INVISIBLE);
return;
}
//Otherwise, update badge stuff
badgeBorder.setVisibility(View.VISIBLE);
badge.setVisibility(View.VISIBLE);
if(requiredOnScreen - answeredOnScreen == 0) {
//Unicode checkmark
badge.setText("\u2713");
badge.setBackgroundResource(R.drawable.badge_background_complete);
} else {
badge.setBackgroundResource(R.drawable.badge_background);
badge.setText(String.valueOf(requiredOnScreen - answeredOnScreen));
}
}
/**
* Takes in a form entry prompt that is obtained generically and if there
* is already one on screen (which, for isntance, may have cached some of its data)
* returns the object in use currently.
*
* @param prompt
* @return
*/
private FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt, ODKView view) {
FormIndex index = prompt.getIndex();
for(QuestionWidget widget : view.getWidgets()) {
if(widget.getFormId().equals(index)) {
return widget.getPrompt();
}
}
return prompt;
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
refreshCurrentView(true);
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView(boolean animateLastView) {
if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); }
int event = mFormController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not field-lists,
// repeat events, and indexes in field-lists that is not the containing group.
while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList())
|| event == FormEntryController.EVENT_REPEAT
|| (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) {
event = mFormController.stepToPreviousEvent();
}
//If we're at the beginning of form event, but don't show the screen for that, we need
//to get the next valid screen
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
this.showNextView(true);
} else {
View current = createView(event);
showView(current, AnimationType.FADE, animateLastView);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.removeItem(MENU_PREFERENCES);
if(mIncompleteEnabled) {
menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon(
android.R.drawable.ic_menu_save);
}
menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1) ? false
: true);
menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_LANGUAGES:
createLanguageDialog();
return true;
case MENU_SAVE:
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false);
return true;
case MENU_HIERARCHY_VIEW:
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
case android.R.id.home:
triggerUserQuitInput();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @return true If the current index of the form controller contains questions
*/
private boolean currentPromptIsQuestion() {
return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController
.getEvent() == FormEntryController.EVENT_GROUP);
}
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
return saveAnswersForCurrentScreen(evaluateConstraints, true, false);
}
/**
* Attempt to save the answer(s) in the current screen to into the data model.
*
* @param evaluateConstraints
* @param failOnRequired Whether or not the constraint evaluation
* should return false if the question is only
* required. (this is helpful for incomplete
* saves)
* @param headless running in a process that can't display graphics
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints,
boolean failOnRequired,
boolean headless) {
// only try to save if the current event is a question or a field-list
// group
boolean success = true;
if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION)
|| ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) &&
mFormController.indexIsInFieldList())) {
if (mCurrentView instanceof ODKView) {
HashMap<FormIndex, IAnswerData> answers =
((ODKView)mCurrentView).getAnswers();
// Sort the answers so if there are multiple errors, we can
// bring focus to the first one
List<FormIndex> indexKeys = new ArrayList<FormIndex>();
indexKeys.addAll(answers.keySet());
Collections.sort(indexKeys, new Comparator<FormIndex>() {
@Override
public int compare(FormIndex arg0, FormIndex arg1) {
return arg0.compareTo(arg1);
}
});
for (FormIndex index : indexKeys) {
// Within a group, you can only save for question events
if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus = saveAnswer(answers.get(index),
index, evaluateConstraints);
if (evaluateConstraints &&
((saveStatus != FormEntryController.ANSWER_OK) &&
(failOnRequired ||
saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) {
if (!headless) {
createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success);
}
success = false;
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
} else {
String viewType;
if (mCurrentView == null || mCurrentView.getClass() == null) {
viewType = "null";
} else {
viewType = mCurrentView.getClass().toString();
}
Log.w(t, "Unknown view type rendered while current event was question or group! View type: " + viewType);
}
}
return success;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
qw.clearAnswer();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer));
menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt));
}
/*
* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// We don't have the right view here, so we store the View's ID as the
// item ID and loop through the possible views to find the one the user
// clicked on.
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
createClearDialog(qw);
}
}
return super.onContextItemSelected(item);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onRetainCustomNonConfigurationInstance()
*
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainCustomNonConfigurationInstance() {
// if a form is loading, pass the loader task
if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (mFormController != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
private String getHeaderString() {
if(mHeaderString != null) {
//Localization?
return mHeaderString;
} else {
return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle();
}
}
/**
* Creates a view given the View type and an event
*
* @param event
* @return newly created View
*/
private View createView(int event) {
boolean isGroup = false;
setTitle(getHeaderString());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View.inflate(this, R.layout.form_entry_start, null);
setTitle(getHeaderString());
((TextView) startView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.enter_data_description, mFormController.getFormTitle()));
((CheckBox) startView.findViewById(R.id.screen_form_entry_start_cbx_dismiss)).setText(StringUtils.getStringSpannableRobust(this, R.string.form_entry_start_hide));
((TextView) startView.findViewById(R.id.screen_form_entry_advance_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.advance));
((TextView) startView.findViewById(R.id.screen_form_entry_backup_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.backup));
Drawable image = null;
String[] projection = {
FormsColumns.FORM_MEDIA_PATH
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String[] selectionArgs = {
mFormPath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, formProviderContentURI, projection, selection, selectionArgs, null).loadInBackground();
} else {
c = managedQuery(formProviderContentURI, projection, selection, selectionArgs, null);
}
String mediaDir = null;
if (c.getCount() < 1) {
CommCareActivity.createErrorDialog(this, "Form doesn't exist", EXIT);
return new View(this);
} else {
c.moveToFirst();
mediaDir = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + "/form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image = getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
((ImageView) startView.findViewById(R.id.form_start_bling))
.setImageDrawable(image);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.save_enter_data_description,
mFormController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
instanceComplete.setText(StringUtils.getStringSpannableRobust(this, R.string.mark_finished));
//If incomplete is not enabled, make sure this box is checked.
instanceComplete.setChecked(!mIncompleteEnabled || isInstanceComplete(true));
if(mFormController.isFormReadOnly() || !mIncompleteEnabled) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);
//TODO: Figure this out based on the content provider or some part of the context
saveAs.setVisibility(View.GONE);
endView.findViewById(R.id.save_form_as).setVisibility(View.GONE);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] {
returnFilter
});
String saveName = getDefaultFormTitle();
saveAs.setText(saveName);
// Create 'save' button
Button button = (Button) endView.findViewById(R.id.save_exit_button);
if(mFormController.isFormReadOnly()) {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.exit));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
finishReturnInstance();
}
});
} else {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.quit_entry));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this, StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.save_as_error),
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT,
instanceComplete.isChecked(),
saveAs.getText().toString(),
false);
}
}
});
}
return endView;
case FormEntryController.EVENT_GROUP:
isGroup = true;
case FormEntryController.EVENT_QUESTION:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
odkv =
new ODKView(this, mFormController.getQuestionPrompts(),
mFormController.getGroupsForCurrentIndex(),
mFormController.getWidgetFactory(), this, isGroup);
Log.i(t, "created view for group");
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
// this is badness to avoid a crash.
// really a next view should increment the formcontroller, create the view
// if the view is null, then keep the current view and pop an error.
return new View(this);
}
// Makes a "clear answer" menu pop up on long-click of
// select-one/select-multiple questions
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly() &&
!mFormController.isFormReadOnly() &&
(qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE ||
qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) {
registerForContextMenu(qw);
}
}
updateNavigationCues(odkv);
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
return null;
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
*/
@SuppressLint("NewApi")
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
//We need to ignore this even if it's processed by the action
//bar (if one exists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View customView = getActionBar().getCustomView();
if(customView != null) {
if(customView.dispatchTouchEvent(mv)) {
return true;
}
}
}
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are: a question, an ask
* repeat dialog, or the submit screen. Also saves answers to the data model after checking
* constraints.
*/
private void showNextView() { showNextView(false); }
private void showNextView(boolean resuming) {
if(!resuming && mFormController.getEvent() == FormEntryController.EVENT_BEGINNING_OF_FORM) {
//See if we should stop displaying the start screen
CheckBox stopShowingIntroScreen = (CheckBox)mCurrentView.findViewById(R.id.screen_form_entry_start_cbx_dismiss);
//Not sure why it would, but maybe timing issues?
if(stopShowingIntroScreen != null) {
if(stopShowingIntroScreen.isChecked()) {
//set it!
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putBoolean(PreferencesActivity.KEY_SHOW_START_SCREEN, false).commit();
}
}
}
if (currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
return;
}
}
if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
try{
group_skip: do {
event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
View next = createView(event);
if(!resuming) {
showView(next, AnimationType.RIGHT);
} else {
showView(next, AnimationType.FADE, false);
}
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break group_skip;
case FormEntryController.EVENT_GROUP:
//We only hit this event if we're at the _opening_ of a field
//list, so it seems totally fine to do it this way, technically
//though this should test whether the index is the field list
//host.
if (mFormController.indexIsInFieldList()
&& mFormController.getQuestionPrompts().length != 0) {
View nextGroupView = createView(event);
if(!resuming) {
showView(nextGroupView, AnimationType.RIGHT);
} else {
showView(nextGroupView, AnimationType.FADE, false);
}
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT:
Log.i(t, "repeat: " + mFormController.getFormIndex().getReference());
// skip repeats
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ mFormController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}catch(XPathTypeMismatchException e){
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
} else {
mBeenSwiped = false;
}
}
/**
* Determines what should be displayed between a question, or the start screen and displays the
* appropriate view. Also saves answers to the data model without checking constraints.
*/
private void showPreviousView() {
// The answer is saved on a back swipe, but question constraints are ignored.
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
FormIndex startIndex = mFormController.getFormIndex();
FormIndex lastValidIndex = startIndex;
if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = mFormController.stepToPreviousEvent();
//Step backwards until we either find a question, the beginning of the form,
//or a field list with valid questions inside
while (event != FormEntryController.EVENT_BEGINNING_OF_FORM
&& event != FormEntryController.EVENT_QUESTION
&& !(event == FormEntryController.EVENT_GROUP
&& mFormController.indexIsInFieldList() && mFormController
.getQuestionPrompts().length != 0)) {
event = mFormController.stepToPreviousEvent();
lastValidIndex = mFormController.getFormIndex();
}
//check if we're at the beginning and not doing the whole "First screen" thing
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
//If so, we can't go all the way back here, so we've gotta hit the last index that was valid
mFormController.jumpToIndex(lastValidIndex);
//Did we jump at all? (not sure how we could have, but there might be a mismatch)
if(lastValidIndex.equals(startIndex)) {
//If not, don't even bother changing the view.
//NOTE: This needs to be the same as the
//exit condition below, in case either changes
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
return;
}
//We might have walked all the way back still, which isn't great,
//so keep moving forward again until we find it
if(lastValidIndex.isBeginningOfFormIndex()) {
//there must be a repeat between where we started and the beginning of hte form, walk back up to it
this.showNextView(true);
return;
}
}
View next = createView(event);
showView(next, AnimationType.LEFT);
} else {
//NOTE: this needs to match the exist condition above
//when there is no start screen
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
}
}
/**
* Displays the View specified by the parameter 'next', animating both the current view and next
* appropriately given the AnimationType. Also updates the progress bar.
*/
public void showView(View next, AnimationType from) { showView(next, from, true); }
public void showView(View next, AnimationType from, boolean animateLastView) {
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
if (mCurrentView != null) {
if(animateLastView) {
mCurrentView.startAnimation(mOutAnimation);
}
mViewPane.removeView(mCurrentView);
}
mInAnimation.setAnimationListener(this);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mCurrentView = next;
mViewPane.addView(mCurrentView, lp);
mCurrentView.startAnimation(mInAnimation);
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
FrameLayout header = (FrameLayout)mCurrentView.findViewById(R.id.form_entry_header);
TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label));
header.setVisibility(View.GONE);
groupLabel.setVisibility(View.GONE);
String groupLabelText = ((ODKView) mCurrentView).getGroupLabel();
if(!"".equals(groupLabelText)) {
groupLabel.setText(groupLabelText);
header.setVisibility(View.VISIBLE);
groupLabel.setVisibility(View.VISIBLE);
}
} else {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0);
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog() and
* onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 (cupcake). We do use
* managed dialogs for our static loading ProgressDialog. The main issue we noticed and are
* waiting to see fixed is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) {
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
if (constraintText == null) {
constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error);
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error);
break;
}
boolean displayed = false;
//We need to see if question in violation is on the screen, so we can show this cleanly.
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
if(index.equals(q.getFormId())) {
q.notifyInvalid(constraintText, requestFocus);
displayed = true;
break;
}
}
if(!displayed) {
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
mBeenSwiped = false;
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a repeat of the
* current group.
*/
private void createRepeatDialog() {
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme);
View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null);
mRepeatDialog = new AlertDialog.Builder(wrapper).create();
final AlertDialog theDialog = mRepeatDialog;
mRepeatDialog.setView(view);
mRepeatDialog.setIcon(android.R.drawable.ic_dialog_info);
boolean hasNavBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
//this is super gross...
NavigationDetails details = null;
if(hasNavBar) {
details = calculateNavigationStatus();
}
final boolean backExitsForm = hasNavBar && !details.relevantBeforeCurrentScreen;
final boolean nextExitsForm = hasNavBar && details.relevantAfterCurrentScreen == 0;
Button back = (Button)view.findViewById(R.id.component_repeat_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(backExitsForm) {
FormEntryActivity.this.triggerUserQuitInput();
} else {
theDialog.dismiss();
FormEntryActivity.this.refreshCurrentView(false);
}
}
});
Button newButton = (Button)view.findViewById(R.id.component_repeat_new);
newButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
try {
mFormController.newRepeat();
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT);
return;
}
showNextView();
}
});
Button skip = (Button)view.findViewById(R.id.component_repeat_skip);
skip.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
if(!nextExitsForm) {
showNextView();
} else {
triggerUserFormComplete();
}
}
});
back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back));
//Load up our icons
Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit);
exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight());
Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done);
doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight());
if (mFormController.getLastRepeatCount() > 0) {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits));
}
} else {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits));
}
}
mRepeatDialog.setCancelable(false);
mRepeatDialog.show();
if(nextExitsForm) {
skip.setCompoundDrawables(null, doneIcon, null, null);
}
if(backExitsForm) {
back.setCompoundDrawables(null, exitIcon, null, null);
}
mBeenSwiped = false;
}
/**
* Saves form data to disk.
*
* @param exit If set, will exit program after save.
* @param complete Has the user marked the instances as complete?
* @param updatedSaveName Set name of the instance's content provider, if
* non-null
* @param headless Disables GUI warnings and lets answers that
* violate constraints be saved.
* @return Did the data save successfully?
*/
private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) {
if (!formHasLoaded()) {
return;
}
// save current answer; if headless, don't evaluate the constraints
// before doing so.
if (headless &&
(!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) {
return;
} else if (!headless &&
!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) {
Toast.makeText(this,
StringUtils.getStringSpannableRobust(this, R.string.data_saved_error),
Toast.LENGTH_SHORT).show();
return;
}
// If a save task is already running, just let it do its thing
if ((mSaveToDiskTask != null) &&
(mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) {
return;
}
mSaveToDiskTask =
new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless);
mSaveToDiskTask.setFormSavedListener(this);
mSaveToDiskTask.execute();
if (!headless) {
showDialog(SAVING_DIALOG);
}
}
/**
* Create a dialog with options to save and exit, save, or quit without saving
*/
private void createQuitDialog() {
final String[] items = mIncompleteEnabled ?
new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} :
new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)};
mAlertDialog =
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle()))
.setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setItems(items, new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
if(items.length == 1) {
discardChangesAndExit();
} else {
saveDataToDisk(EXIT, isInstanceComplete(false), null, false);
}
break;
case 1: // discard changes and exit
discardChangesAndExit();
break;
case 2:// do nothing
break;
}
}
}).create();
mAlertDialog.getListView().setSelector(R.drawable.selector);
mAlertDialog.show();
}
private void discardChangesAndExit() {
String selection =
InstanceColumns.INSTANCE_FILE_PATH + " like '"
+ mInstancePath + "'";
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, null, null).loadInBackground();
} else {
c = FormEntryActivity.this.managedQuery(instanceProviderContentURI, null, selection, null, null);
}
// if it's not already saved, erase everything
if (c.getCount() < 1) {
int images = 0;
int audio = 0;
int video = 0;
// delete media first
String instanceFolder =
mInstancePath.substring(0,
mInstancePath.lastIndexOf("/") + 1);
Log.i(t, "attempting to delete: " + instanceFolder);
String where =
Images.Media.DATA + " like '" + instanceFolder + "%'";
String[] projection = {
Images.ImageColumns._ID
};
// images
Cursor imageCursor = null;
try {
imageCursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
images =
getContentResolver()
.delete(
Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
// audio
Cursor audioCursor = null;
try {
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
String id =
audioCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
audio =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
// video
Cursor videoCursor = null;
try {
videoCursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
String id =
videoCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
video =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
finishReturnInstance(false);
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener);
mAlertDialog.setButton2(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for the form.
*/
private void createLanguageDialog() {
final String[] languages = mFormController.getLanguages();
int selected = -1;
if (languages != null) {
String language = mFormController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog =
new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// Update the language in the content provider when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE, languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = {
mFormPath
};
int updated =
getContentResolver().update(formProviderContentURI, values,
selection, selectArgs);
Log.i(t, "Updated language to: " + languages[whichButton] + " in "
+ updated + " rows");
mFormController.setLanguage(languages[whichButton]);
dialog.dismiss();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(StringUtils.getStringRobust(this, R.string.change_language))
.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create();
mAlertDialog.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
mFormLoaderTask.cancel(true);
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.loading_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
mSaveToDiskTask.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.saving_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel), savingButtonListener);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
if(mRepeatDialog != null && mRepeatDialog.isShowing()) {
mRepeatDialog.dismiss();
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
dismissDialogs();
if (mCurrentView != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (mNoGPSReceiver != null) {
unregisterReceiver(mNoGPSReceiver);
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
registerFormEntryReceivers();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (mFormController != null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
dismissDialog(PROGRESS_DIALOG);
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
//csims@dimagi.com - 22/08/2012 - For release only, fix immediately.
//There is a _horribly obnoxious_ bug in TimePickers that messes up how they work
//on screen rotation. We need to re-do any setAnswers that we perform on them after
//onResume.
try {
if(mCurrentView instanceof ODKView) {
ODKView ov = ((ODKView) mCurrentView);
if(ov.getWidgets() != null) {
for(QuestionWidget qw : ov.getWidgets()) {
if(qw instanceof DateTimeWidget) {
((DateTimeWidget)qw).setAnswer();
} else if(qw instanceof TimeWidget) {
((TimeWidget)qw).setAnswer();
}
}
}
}
} catch(Exception e) {
//if this fails, we _really_ don't want to mess anything up. this is a last minute
//fix
}
}
/**
* Call when the user provides input that they want to quit the form
*/
private void triggerUserQuitInput() {
//If we're just reviewing a read only form, don't worry about saving
//or what not, just quit
if(mFormController.isFormReadOnly()) {
//It's possible we just want to "finish" here, but
//I don't really wanna break any c compatibility
finishReturnInstance(false);
} else {
createQuitDialog();
}
}
/**
* Get the default title for ODK's "Form title" field
*
* @return
*/
private String getDefaultFormTitle() {
String saveName = mFormController.getFormTitle();
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
instance = new CursorLoader(this, instanceUri, null, null, null, null).loadInBackground();
} else {
instance = managedQuery(instanceUri, null, null, null, null);
}
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName =
instance.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
}
return saveName;
}
/**
* Call when the user is ready to save and return the current form as complete
*/
private void triggerUserFormComplete() {
saveDataToDisk(EXIT, true, getDefaultFormTitle(), false);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
triggerUserQuitInput();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
mFormLoaderTask.cancel(true);
mFormLoaderTask.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(false);
}
}
super.onDestroy();
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationEnd(android.view.animation.Animation)
*/
@Override
public void onAnimationEnd(Animation arg0) {
mBeenSwiped = false;
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationRepeat(android.view.animation.Animation)
*/
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationStart(android.view.animation.Animation)
*/
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingComplete(org.odk.collect.android.logic.FormController)
*
* loadingComplete() is called by FormLoaderTask once it has finished loading a form.
*/
@SuppressLint("NewApi")
@Override
public void loadingComplete(FormController fc) {
dismissDialog(PROGRESS_DIALOG);
mFormController = fc;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
// Newer menus may have already built the menu, before all data was ready
invalidateOptionsMenu();
}
Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced();
if(mLocalizer != null){
String mLocale = mLocalizer.getLocale();
if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){
fc.setLanguage(mLocale);
}
else{
Logger.log("formloader", "The current locale is not set");
}
} else{
Logger.log("formloader", "Could not get the localizer");
}
// Set saved answer path
if (mInstancePath == null) {
// Create new answer folder.
String time =
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
.format(Calendar.getInstance().getTime());
String file =
mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.'));
String path = mInstanceDestination + "/" + file + "_" + time;
if (FileUtils.createFolder(path)) {
mInstancePath = path + "/" + file + "_" + time + ".xml";
}
} else {
// we've just loaded a saved form, so start in the hierarchy view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START);
return; // so we don't show the intro screen before jumping to the hierarchy
}
//mFormController.setLanguage(mFormController.getLanguage());
/* here was code that loaded cached language preferences fin the
* collect code. we've overridden that to use our language
* from the shared preferences
*/
refreshCurrentView();
updateNavigationCues(this.mCurrentView);
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingError(java.lang.String)
*
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
CommCareActivity.createErrorDialog(this, errorMsg, EXIT);
} else {
CommCareActivity.createErrorDialog(this, StringUtils.getStringRobust(this, R.string.parse_error), EXIT);
}
}
/**
* {@inheritDoc}
*
* Display save status notification and exit or continue on in the form.
* If form entry is being saved because key session is expiring then
* continue closing the session/logging out.
*
* @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean)
*/
@Override
public void savingComplete(int saveStatus, boolean headless) {
if (!headless) {
dismissDialog(SAVING_DIALOG);
}
// Did we just save a form because the key session
// (CommCareSessionService) is ending?
if (savingFormOnKeySessionExpiration) {
savingFormOnKeySessionExpiration = false;
// Notify the key session that the form state has been saved (or at
// least attempted to be saved) so CommCareSessionService can
// continue closing down key pool and user database.
try {
CommCareApplication._().getSession().closeSession(true);
} catch (SessionUnavailableException sue) {
// form saving took too long, so we logged out already.
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Saving current form took too long, " +
"so data was (probably) discarded and the session closed. " +
"Save exit code: " + saveStatus);
}
} else {
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints Should form contraints be checked when saving answer?
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) {
try {
if (evaluateConstraints) {
return mFormController.answerQuestion(index, answer);
} else {
mFormController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
} catch(XPathException e) {
//this is where runtime exceptions get triggered after the form has loaded
CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT);
//We're exiting anyway
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has already been
* 'marked completed'. A form can be 'unmarked' complete and then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
complete =
sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
c = this.managedQuery(instanceProviderContentURI, null, selection, selectionArgs, null);
}
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
private void finishReturnInstance() {
finishReturnInstance(true);
}
/**
* Returns the instance that was just filled out to the calling activity,
* if requested.
*
* @param reportSaved was a form saved? Delegates the result code of the
* activity
*/
private void finishReturnInstance(boolean reportSaved) {
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
c = managedQuery(instanceProviderContentURI, null, selection, selectionArgs, null);
}
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id);
Intent formReturnIntent = new Intent();
formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly());
if(reportSaved || hasSaved) {
setResult(RESULT_OK, formReturnIntent.setData(instance));
} else {
setResult(RESULT_CANCELED, formReturnIntent.setData(instance));
}
}
}
try {
CommCareApplication._().getSession().unregisterFormSaveCallback();
} catch (SessionUnavailableException sue) {
// looks like the session expired
}
this.dismissDialogs();
finish();
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown(MotionEvent e) {
return false;
}
/*
* Looks for user swipes. If the user has swiped, move to the appropriate screen.
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) {
mBeenSwiped = true;
if (velocityX > 0) {
showPreviousView();
} else {
int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true));
boolean navBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
if(!navBar || (navBar && event != FormEntryController.EVENT_END_OF_FORM)) {
showNextView();
}
}
return true;
}
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long pressed.
// We don't wnat that, so cancel it.
mCurrentView.cancelLongPress();
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.AdvanceToNextListener#advance()
*/
@Override
public void advance() {
next();
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.WidgetChangedListener#widgetEntryChanged()
*/
@Override
public void widgetEntryChanged() {
updateFormRelevencies();
updateNavigationCues(this.mCurrentView);
}
/**
* Has form loading (via FormLoaderTask) completed?
*/
private boolean formHasLoaded() {
return mFormController != null;
}
}
|
app/src/org/odk/collect/android/activities/FormEntryActivity.java
|
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.activities;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.util.Pair;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.android.util.StringUtils;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.activities.CommCareHomeActivity;
import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI;
import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns;
import org.commcare.dalvik.services.CommCareSessionService;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.jr.extensions.IntentCallout;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.FormSaveCallback;
import org.odk.collect.android.listeners.WidgetChangedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity.ProgressBarMode;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.Base64Wrapper;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.GeoUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.views.ResizingImageView;
import org.odk.collect.android.widgets.DateTimeWidget;
import org.odk.collect.android.widgets.IntentWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.TimeWidget;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
/**
* FormEntryActivity is responsible for displaying questions, animating transitions between
* questions, and allowing the user to enter data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormEntryActivity extends FragmentActivity implements AnimationListener, FormLoaderListener,
FormSavedListener, FormSaveCallback, AdvanceToNextListener, OnGestureListener,
WidgetChangedListener {
private static final String t = "FormEntryActivity";
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int INTENT_CALLOUT = 10;
public static final int HIERARCHY_ACTIVITY_FIRST_START = 11;
public static final int SIGNATURE_CAPTURE = 12;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
public static final String KEY_INSTANCEDESTINATION = "instancedestination";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
public static final String KEY_FORM_CONTENT_URI = "form_content_uri";
public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri";
public static final String KEY_AES_STORAGE_KEY = "key_aes_storage";
public static final String KEY_HEADER_STRING = "form_header";
public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management";
public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled";
public static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved";
/**
* Intent extra flag to track if this form is an archive. Used to trigger
* return logic when this activity exits to the home screen, such as
* whether to redirect to archive view or sync the form.
*/
public static final String IS_ARCHIVED_FORM = "is-archive-form";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
private String mFormPath;
// Path to a particular form instance
public static String mInstancePath;
private String mInstanceDestination;
private GestureDetector mGestureDetector;
private SecretKeySpec symetricKey = null;
public static FormController mFormController;
private Animation mInAnimation;
private Animation mOutAnimation;
private ViewGroup mViewPane;
private View mCurrentView;
private AlertDialog mRepeatDialog;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
private boolean mIncompleteEnabled = true;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private Uri formProviderContentURI = FormsColumns.CONTENT_URI;
private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI;
private static String mHeaderString;
// Was the form saved? Used to set activity return code.
public boolean hasSaved = false;
private BroadcastReceiver mNoGPSReceiver;
// marked true if we are in the process of saving a form because the user
// database & key session are expiring. Being set causes savingComplete to
// broadcast a form saving intent.
private boolean savingFormOnKeySessionExpiration = false;
enum AnimationType {
LEFT, RIGHT, FADE
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
@Override
@SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// CommCareSessionService will call this.formSaveCallback when the
// key session is closing down and we need to save any intermediate
// results before they become un-saveable.
CommCareApplication._().getSession().registerFormSaveCallback(this);
} catch (SessionUnavailableException e) {
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Couldn't register form save callback because session doesn't exist");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
final String fragmentClass = this.getIntent().getStringExtra("odk_title_fragment");
if(fragmentClass != null) {
final FragmentManager fm = this.getSupportFragmentManager();
//Add breadcrumb bar
Fragment bar = (Fragment) fm.findFragmentByTag(TITLE_FRAGMENT_TAG);
// If the state holder is null, create a new one for this activity
if (bar == null) {
try {
bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance();
//the bar will set this up for us again if we need.
getActionBar().setDisplayShowCustomEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit();
} catch(Exception e) {
Log.w("odk-collect", "couldn't instantiate fragment: " + fragmentClass);
}
}
}
}
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
return;
}
setupUI();
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(
getApplicationContext()));
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) {
formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) {
instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI));
}
if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) {
mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION);
}
if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) {
mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED);
}
if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED);
}
if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) {
String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(savedInstanceState.containsKey(KEY_HEADER_STRING)) {
mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING);
}
if(savedInstanceState.containsKey(KEY_HAS_SAVED)) {
hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = this.getLastCustomNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
refreshCurrentView();
return;
}
boolean readOnly = false;
// Not a restart from a screen orientation change (or other).
mFormController = null;
mInstancePath = null;
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if(intent.hasExtra(KEY_FORM_CONTENT_URI)) {
this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) {
this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI));
}
if(intent.hasExtra(KEY_INSTANCEDESTINATION)) {
this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION);
} else {
mInstanceDestination = Collect.INSTANCES_PATH;
}
if(intent.hasExtra(KEY_AES_STORAGE_KEY)) {
String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY);
try {
byte[] storageKey = new Base64Wrapper().decode(base64Key);
symetricKey = new SecretKeySpec(storageKey, "AES");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Base64 encoding not available on this platform");
}
}
if(intent.hasExtra(KEY_HEADER_STRING)) {
this.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING);
}
if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) {
this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true);
}
if(intent.hasExtra(KEY_RESIZING_ENABLED)) {
ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED);
}
if(mHeaderString != null) {
setTitle(mHeaderString);
} else {
setTitle(StringUtils.getStringRobust(this, R.string.app_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form));
}
//csims@dimagi.com - Jan 24, 2012
//Since these are parceled across the content resolver, there's no guarantee of reference equality.
//We need to manually check value equality on the type
final String contentType = getContentResolver().getType(uri);
Uri formUri = null;
switch (contentType) {
case InstanceColumns.CONTENT_ITEM_TYPE:
final Cursor instanceCursor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
instanceCursor = new CursorLoader(this, uri, null, null, null, null).loadInBackground();
} else {
instanceCursor = this.managedQuery(uri, null, null, null, null);
}
if (instanceCursor.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
mInstancePath =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
final String jrFormId =
instanceCursor.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
//If this form is both already completed
if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) {
if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) {
readOnly = true;
}
}
final String[] selectionArgs = {
jrFormId
};
final String selection = FormsColumns.JR_FORM_ID + " like ?";
final Cursor formCursor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
formCursor = new CursorLoader(this, formProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
formCursor = managedQuery(formProviderContentURI, null, selection, selectionArgs, null);
}
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath =
formCursor.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID)));
} else if (formCursor.getCount() < 1) {
CommCareHomeActivity.createErrorDialog(this, "Parent form does not exist", EXIT);
return;
} else if (formCursor.getCount() > 1) {
CommCareHomeActivity.createErrorDialog(this, "More than one possible parent form", EXIT);
return;
}
}
break;
case FormsColumns.CONTENT_ITEM_TYPE:
final Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, uri, null, null, null, null).loadInBackground();
} else {
c = this.managedQuery(uri, null, null, null, null);
}
if (c.getCount() != 1) {
CommCareHomeActivity.createErrorDialog(this, "Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
formUri = uri;
}
break;
default:
Log.e(t, "unrecognized URI");
CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT);
return;
}
if(formUri == null) {
Log.e(t, "unrecognized URI");
CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(this, symetricKey, readOnly);
mFormLoaderTask.execute(formUri);
showDialog(PROGRESS_DIALOG);
}
}
}
@Override
public void formSaveCallback() {
// note that we have started saving the form
savingFormOnKeySessionExpiration = true;
// start saving form, which will call the key session logout completion
// function when it finishes.
saveDataToDisk(EXIT, false, null, true);
}
/**
* Setup BroadcastReceiver for asking user if they want to enable gps
*/
private void registerFormEntryReceivers() {
// See if this form needs GPS to be turned on
mNoGPSReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.removeStickyBroadcast(intent);
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Set<String> providers = GeoUtils.evaluateProviders(manager);
if (providers.isEmpty()) {
DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == DialogInterface.BUTTON_POSITIVE) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
};
GeoUtils.showNoGpsDialog(FormEntryActivity.this, onChangeListener);
}
}
};
registerReceiver(mNoGPSReceiver,
new IntentFilter(GeoUtils.ACTION_CHECK_GPS_ENABLED));
}
/**
* Setup Activity's UI
*/
private void setupUI() {
setContentView(R.layout.screen_form_entry);
setNavBarVisibility();
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
nextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"done".equals(v.getTag())) {
FormEntryActivity.this.showNextView();
} else {
triggerUserFormComplete();
}
}
});
prevButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!"quit".equals(v.getTag())) {
FormEntryActivity.this.showPreviousView();
} else {
FormEntryActivity.this.triggerUserQuitInput();
}
}
});
mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane);
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this);
}
public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment";
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString());
outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString());
outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination);
outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled);
outState.putBoolean(KEY_HAS_SAVED, hasSaved);
outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod);
if(symetricKey != null) {
try {
outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded()));
} catch (ClassNotFoundException e) {
// we can't really get here anyway, since we couldn't have decoded the string to begin with
throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key");
}
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_CANCELED) {
if(requestCode == HIERARCHY_ACTIVITY_FIRST_START) {
//they pressed 'back' on the first heirarchy screen. we should assume they want to
//back out of form entry all together
finishReturnInstance(false);
} else if(requestCode == INTENT_CALLOUT){
processIntentResponse(intent, true);
}
// request was canceled, so do nothing
return;
}
ContentValues values;
Uri imageURI;
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case INTENT_CALLOUT:
processIntentResponse(intent);
break;
case IMAGE_CAPTURE:
case SIGNATURE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// The intent is empty, but we know we saved the image to the temp file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String s = mInstanceFolder + "/" + System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath());
}
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, nf.getName());
values.put(Images.Media.DISPLAY_NAME, nf.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, nf.getAbsolutePath());
imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move it there before
* inserting it into the content provider. Once the android image capture bug gets
* fixed, (read, we move on from Android 1.6) we want to handle images the audio and
* video
*/
// get gp of chosen file
String sourceImagePath = null;
Uri selectedImage = intent.getData();
sourceImagePath = FileUtils.getPath(this, selectedImage);
// Copy file to sdcard
String mInstanceFolder1 =
mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
String destImagePath = mInstanceFolder1 + "/" + System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
imageURI =
getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
((ODKView) mCurrentView).setBinaryData(imageURI);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
} else {
Log.e(t, "NO IMAGE EXISTS at: " + source.getAbsolutePath());
}
refreshCurrentView();
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content provider
// then the widget copies the file and makes a new entry in the content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
refreshCurrentView();
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so refresh
refreshCurrentView(false);
break;
}
}
private void processIntentResponse(Intent response){
processIntentResponse(response, false);
}
private void processIntentResponse(Intent response, boolean cancelled) {
// keep track of whether we should auto advance
boolean advance = false;
boolean quick = false;
//We need to go grab our intent callout object to process the results here
IntentWidget bestMatch = null;
//Ugh, copied from the odkview mostly, that's stupid
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
//Figure out if we have a pending intent widget
if (q instanceof IntentWidget) {
if(((IntentWidget) q).isWaitingForBinaryData() || bestMatch == null) {
bestMatch = (IntentWidget)q;
}
}
}
if(bestMatch != null) {
//Set our instance destination for binary data if needed
String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1);
//get the original intent callout
IntentCallout ic = bestMatch.getIntentCallout();
quick = "quick".equals(ic.getAppearance());
//And process it
advance = ic.processResponse(response, (ODKView)mCurrentView, mFormController.getInstance(), new File(destination));
ic.setCancelled(cancelled);
}
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// auto advance if we got a good result and are in quick mode
if(advance && quick){
showNextView();
}
}
public void updateFormRelevencies(){
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
if(!(mCurrentView instanceof ODKView)){
throw new RuntimeException("Tried to update form relevency not on compound view");
}
ODKView oldODKV = (ODKView)mCurrentView;
FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts();
Set<FormEntryPrompt> used = new HashSet<FormEntryPrompt>();
ArrayList<QuestionWidget> oldWidgets = oldODKV.getWidgets();
ArrayList<Integer> removeList = new ArrayList<Integer>();
for(int i=0;i<oldWidgets.size();i++){
QuestionWidget oldWidget = oldWidgets.get(i);
boolean stillRelevent = false;
for(FormEntryPrompt prompt : newValidPrompts) {
if(prompt.getIndex().equals(oldWidget.getPrompt().getIndex())) {
stillRelevent = true;
used.add(prompt);
}
}
if(!stillRelevent){
removeList.add(Integer.valueOf(i));
}
}
// remove "atomically" to not mess up iterations
oldODKV.removeQuestionsFromIndex(removeList);
//Now go through add add any new prompts that we need
for(int i = 0 ; i < newValidPrompts.length; ++i) {
FormEntryPrompt prompt = newValidPrompts[i];
if(used.contains(prompt)) {
//nothing to do here
continue;
}
oldODKV.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i);
}
}
private static class NavigationDetails {
public int totalQuestions = 0;
public int completedQuestions = 0;
public boolean relevantBeforeCurrentScreen = false;
public boolean isFirstScreen = false;
public int answeredOnScreen = 0;
public int requiredOnScreen = 0;
public int relevantAfterCurrentScreen = 0;
public FormIndex currentScreenExit = null;
}
private NavigationDetails calculateNavigationStatus() {
NavigationDetails details = new NavigationDetails();
FormIndex userFormIndex = mFormController.getFormIndex();
FormIndex currentFormIndex = FormIndex.createBeginningOfFormIndex();
mFormController.expandRepeats(currentFormIndex);
int event = mFormController.getEvent(currentFormIndex);
try {
// keep track of whether there is a question that exists before the
// current screen
boolean onCurrentScreen = false;
while (event != FormEntryController.EVENT_END_OF_FORM) {
int comparison = currentFormIndex.compareTo(userFormIndex);
if (comparison == 0) {
onCurrentScreen = true;
details.currentScreenExit = mFormController.getNextFormIndex(currentFormIndex, true);
}
if (onCurrentScreen && currentFormIndex.equals(details.currentScreenExit)) {
onCurrentScreen = false;
}
// Figure out if there are any events before this screen (either
// new repeat or relevant questions are valid)
if (event == FormEntryController.EVENT_QUESTION
|| event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// Figure out whether we're on the last screen
if (!details.relevantBeforeCurrentScreen && !details.isFirstScreen) {
// We got to the current screen without finding a
// relevant question,
// I guess we're on the first one.
if (onCurrentScreen
&& !details.relevantBeforeCurrentScreen) {
details.isFirstScreen = true;
} else {
// We're using the built in steps (and they take
// relevancy into account)
// so if there are prompts they have to be relevant
details.relevantBeforeCurrentScreen = true;
}
}
}
if (event == FormEntryController.EVENT_QUESTION) {
FormEntryPrompt[] prompts = mFormController.getQuestionPrompts(currentFormIndex);
if (!onCurrentScreen && details.currentScreenExit != null) {
details.relevantAfterCurrentScreen += prompts.length;
}
details.totalQuestions += prompts.length;
// Current questions are complete only if they're answered.
// Past questions are always complete.
// Future questions are never complete.
if (onCurrentScreen) {
for (FormEntryPrompt prompt : prompts) {
if (this.mCurrentView instanceof ODKView) {
ODKView odkv = (ODKView) this.mCurrentView;
prompt = getOnScreenPrompt(prompt, odkv);
}
boolean isAnswered = prompt.getAnswerValue() != null
|| prompt.getDataType() == Constants.DATATYPE_NULL;
if (prompt.isRequired()) {
details.requiredOnScreen++;
if (isAnswered) {
details.answeredOnScreen++;
}
}
if (isAnswered) {
details.completedQuestions++;
}
}
} else if (comparison < 0) {
// For previous questions, consider all "complete"
details.completedQuestions += prompts.length;
// TODO: This doesn't properly capture state to
// determine whether we will end up out of the form if
// we hit back!
// Need to test _until_ we get a question that is
// relevant, then we can skip the relevancy tests
}
}
else if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// If we've already passed the current screen, this repeat
// junction is coming up in the future and we will need to
// know
// about it
if (!onCurrentScreen && details.currentScreenExit != null) {
details.totalQuestions++;
details.relevantAfterCurrentScreen++;
} else {
// Otherwise we already passed it and it no longer
// affects the count
}
}
currentFormIndex = mFormController.getNextFormIndex(currentFormIndex, FormController.STEP_INTO_GROUP, false);
event = mFormController.getEvent(currentFormIndex);
}
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
// Set form back to correct state
mFormController.jumpToIndex(userFormIndex);
return details;
}
/**
* Update progress bar's max and value, and the various buttons and navigation cues
* associated with navigation
*
* @param view ODKView to update
*/
public void updateNavigationCues(View view) {
updateFloatingLabels(view);
ProgressBarMode mode = PreferencesActivity.getProgressBarMode(this);
setNavBarVisibility();
if(mode == ProgressBarMode.None) { return; }
NavigationDetails details = calculateNavigationStatus();
if(mode == ProgressBarMode.ProgressOnly && view instanceof ODKView) {
((ODKView)view).updateProgressBar(details.completedQuestions, details.totalQuestions);
return;
}
ProgressBar progressBar = (ProgressBar)this.findViewById(R.id.nav_prog_bar);
ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next);
ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev);
if(!details.relevantBeforeCurrentScreen) {
prevButton.setImageResource(R.drawable.icon_close_darkwarm);
prevButton.setTag("quit");
} else {
prevButton.setImageResource(R.drawable.icon_chevron_left_brand);
prevButton.setTag("back");
}
//Apparently in Android 2.3 setting the drawable resource for the progress bar
//causes it to lose it bounds. It's a bit cheaper to keep them around than it
//is to invalidate the view, though.
Rect bounds = progressBar.getProgressDrawable().getBounds(); //Save the drawable bound
Log.i("Questions","Total questions: " + details.totalQuestions + " | Completed questions: " + details.completedQuestions);
progressBar.getProgressDrawable().setBounds(bounds); //Set the bounds to the saved value
progressBar.setMax(details.totalQuestions);
if(details.relevantAfterCurrentScreen == 0 && (details.requiredOnScreen == details.answeredOnScreen || details.requiredOnScreen < 1)) {
nextButton.setImageResource(R.drawable.icon_chevron_right_attnpos);
//TODO: _really_? This doesn't seem right
nextButton.setTag("done");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_full));
Log.i("Questions","Form complete");
// if we get here, it means we don't have any more relevant questions after this one, so we mark it as complete
progressBar.setProgress(details.totalQuestions); // completely fills the progressbar
} else {
nextButton.setImageResource(R.drawable.icon_chevron_right_brand);
//TODO: _really_? This doesn't seem right
nextButton.setTag("next");
progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.progressbar_modern));
progressBar.setProgress(details.completedQuestions);
}
//We should probably be doing this based on the widgets, maybe, not the model? Hard to call.
updateBadgeInfo(details.requiredOnScreen, details.answeredOnScreen);
}
private void setNavBarVisibility() {
//Make sure the nav bar visibility is set
int navBarVisibility = PreferencesActivity.getProgressBarMode(this).useNavigationBar() ? View.VISIBLE : View.GONE;
View nav = this.findViewById(R.id.nav_pane);
if(nav.getVisibility() != navBarVisibility) {
nav.setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge_border_drawer).setVisibility(navBarVisibility);
this.findViewById(R.id.nav_badge).setVisibility(navBarVisibility);
}
}
enum FloatingLabel {
good ("floating-good", R.drawable.label_floating_good, R.color.cc_attention_positive_text),
caution ("floating-caution", R.drawable.label_floating_caution, R.color.cc_light_warm_accent_color),
bad ("floating-bad", R.drawable.label_floating_bad, R.color.cc_attention_negative_color);
String label;
int resourceId;
int colorId;
FloatingLabel(String label, int resourceId, int colorId) {
this.label = label;
this.resourceId = resourceId;
this.colorId = colorId;
}
public String getAppearance() { return label;}
public int getBackgroundDrawable() { return resourceId; }
public int getColorId() { return colorId; }
};
private void updateFloatingLabels(View currentView) {
//TODO: this should actually be set up to scale per screen size.
ArrayList<Pair<String, FloatingLabel>> smallLabels = new ArrayList<Pair<String, FloatingLabel>>();
ArrayList<Pair<String, FloatingLabel>> largeLabels = new ArrayList<Pair<String, FloatingLabel>>();
FloatingLabel[] labelTypes = FloatingLabel.values();
if(currentView instanceof ODKView) {
for(QuestionWidget widget : ((ODKView)currentView).getWidgets()) {
String hint = widget.getPrompt().getAppearanceHint();
if(hint == null) { continue; }
for(FloatingLabel type : labelTypes) {
if(type.getAppearance().equals(hint)) {
String widgetText = widget.getPrompt().getQuestionText();
if(widgetText != null && widgetText.length() < 15) {
smallLabels.add(new Pair(widgetText, type));
} else {
largeLabels.add(new Pair(widgetText, type));
}
}
}
}
}
final ViewGroup parent = (ViewGroup)this.findViewById(R.id.form_entry_label_layout);
parent.removeAllViews();
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
int minHeight = 7 * pixels;
//Ok, now go ahead and add all of the small labels
for(int i = 0 ; i < smallLabels.size(); i = i + 2 ) {
if(i + 1 < smallLabels.size()) {
LinearLayout.LayoutParams lpp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(lpp);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
TextView left = (TextView)View.inflate(this, R.layout.component_floating_label, null);
left.setLayoutParams(lp);
left.setText(smallLabels.get(i).first + "; " + smallLabels.get(i + 1).first);
left.setBackgroundResource(smallLabels.get(i).second.resourceId);
left.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
left.setTextColor(smallLabels.get(i).second.colorId);
left.setMinimumHeight(minHeight);
layout.addView(left);
parent.addView(layout);
} else {
largeLabels.add(smallLabels.get(i));
}
}
for(int i = 0 ; i < largeLabels.size(); ++i ) {
final TextView view = (TextView)View.inflate(this, R.layout.component_floating_label, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
view.setPadding(pixels, 2 * pixels, pixels, 2 * pixels);
view.setText(largeLabels.get(i).first);
view.setBackgroundResource(largeLabels.get(i).second.resourceId);
view.setTextColor(largeLabels.get(i).second.colorId);
view.setMinimumHeight(minHeight);
parent.addView(view);
}
}
private void updateBadgeInfo(int requiredOnScreen, int answeredOnScreen) {
View badgeBorder = this.findViewById(R.id.nav_badge_border_drawer);
TextView badge = (TextView)this.findViewById(R.id.nav_badge);
//If we don't need this stuff, just bail
if(requiredOnScreen <= 1) {
//Hide all badge related items
badgeBorder.setVisibility(View.INVISIBLE);
badge.setVisibility(View.INVISIBLE);
return;
}
//Otherwise, update badge stuff
badgeBorder.setVisibility(View.VISIBLE);
badge.setVisibility(View.VISIBLE);
if(requiredOnScreen - answeredOnScreen == 0) {
//Unicode checkmark
badge.setText("\u2713");
badge.setBackgroundResource(R.drawable.badge_background_complete);
} else {
badge.setBackgroundResource(R.drawable.badge_background);
badge.setText(String.valueOf(requiredOnScreen - answeredOnScreen));
}
}
/**
* Takes in a form entry prompt that is obtained generically and if there
* is already one on screen (which, for isntance, may have cached some of its data)
* returns the object in use currently.
*
* @param prompt
* @return
*/
private FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt, ODKView view) {
FormIndex index = prompt.getIndex();
for(QuestionWidget widget : view.getWidgets()) {
if(widget.getFormId().equals(index)) {
return widget.getPrompt();
}
}
return prompt;
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
refreshCurrentView(true);
}
/**
* Refreshes the current view. the controller and the displayed view can get out of sync due to
* dialogs and restarts caused by screen orientation changes, so they're resynchronized here.
*/
public void refreshCurrentView(boolean animateLastView) {
if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); }
int event = mFormController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not field-lists,
// repeat events, and indexes in field-lists that is not the containing group.
while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT
|| (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList())
|| event == FormEntryController.EVENT_REPEAT
|| (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) {
event = mFormController.stepToPreviousEvent();
}
//If we're at the beginning of form event, but don't show the screen for that, we need
//to get the next valid screen
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
this.showNextView(true);
} else {
View current = createView(event);
showView(current, AnimationType.FADE, animateLastView);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.removeItem(MENU_PREFERENCES);
if(mIncompleteEnabled) {
menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon(
android.R.drawable.ic_menu_save);
}
menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1) ? false
: true);
menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_LANGUAGES:
createLanguageDialog();
return true;
case MENU_SAVE:
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null, false);
return true;
case MENU_HIERARCHY_VIEW:
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
case android.R.id.home:
triggerUserQuitInput();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @return true If the current index of the form controller contains questions
*/
private boolean currentPromptIsQuestion() {
return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController
.getEvent() == FormEntryController.EVENT_GROUP);
}
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
return saveAnswersForCurrentScreen(evaluateConstraints, true, false);
}
/**
* Attempt to save the answer(s) in the current screen to into the data model.
*
* @param evaluateConstraints
* @param failOnRequired Whether or not the constraint evaluation
* should return false if the question is only
* required. (this is helpful for incomplete
* saves)
* @param headless running in a process that can't display graphics
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints,
boolean failOnRequired,
boolean headless) {
// only try to save if the current event is a question or a field-list
// group
boolean success = true;
if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION)
|| ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) &&
mFormController.indexIsInFieldList())) {
if (mCurrentView instanceof ODKView) {
HashMap<FormIndex, IAnswerData> answers =
((ODKView)mCurrentView).getAnswers();
// Sort the answers so if there are multiple errors, we can
// bring focus to the first one
List<FormIndex> indexKeys = new ArrayList<FormIndex>();
indexKeys.addAll(answers.keySet());
Collections.sort(indexKeys, new Comparator<FormIndex>() {
@Override
public int compare(FormIndex arg0, FormIndex arg1) {
return arg0.compareTo(arg1);
}
});
for (FormIndex index : indexKeys) {
// Within a group, you can only save for question events
if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) {
int saveStatus = saveAnswer(answers.get(index),
index, evaluateConstraints);
if (evaluateConstraints &&
((saveStatus != FormEntryController.ANSWER_OK) &&
(failOnRequired ||
saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) {
if (!headless) {
createConstraintToast(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success);
}
success = false;
}
} else {
Log.w(t,
"Attempted to save an index referencing something other than a question: "
+ index.getReference());
}
}
} else {
String viewType;
if (mCurrentView == null || mCurrentView.getClass() == null) {
viewType = "null";
} else {
viewType = mCurrentView.getClass().toString();
}
Log.w(t, "Unknown view type rendered while current event was question or group! View type: " + viewType);
}
}
return success;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
qw.clearAnswer();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer));
menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt));
}
/*
* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
// We don't have the right view here, so we store the View's ID as the
// item ID and loop through the possible views to find the one the user
// clicked on.
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
createClearDialog(qw);
}
}
return super.onContextItemSelected(item);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onRetainCustomNonConfigurationInstance()
*
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainCustomNonConfigurationInstance() {
// if a form is loading, pass the loader task
if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (mFormController != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
private String getHeaderString() {
if(mHeaderString != null) {
//Localization?
return mHeaderString;
} else {
return StringUtils.getStringRobust(this, R.string.app_name) + " > " + mFormController.getFormTitle();
}
}
/**
* Creates a view given the View type and an event
*
* @param event
* @return newly created View
*/
private View createView(int event) {
boolean isGroup = false;
setTitle(getHeaderString());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View.inflate(this, R.layout.form_entry_start, null);
setTitle(getHeaderString());
((TextView) startView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.enter_data_description, mFormController.getFormTitle()));
((CheckBox) startView.findViewById(R.id.screen_form_entry_start_cbx_dismiss)).setText(StringUtils.getStringSpannableRobust(this, R.string.form_entry_start_hide));
((TextView) startView.findViewById(R.id.screen_form_entry_advance_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.advance));
((TextView) startView.findViewById(R.id.screen_form_entry_backup_text)).setText(StringUtils.getStringSpannableRobust(this, R.string.backup));
Drawable image = null;
String[] projection = {
FormsColumns.FORM_MEDIA_PATH
};
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String[] selectionArgs = {
mFormPath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, formProviderContentURI, projection, selection, selectionArgs, null).loadInBackground();
} else {
c = managedQuery(formProviderContentURI, projection, selection, selectionArgs, null);
}
String mediaDir = null;
if (c.getCount() < 1) {
CommCareActivity.createErrorDialog(this, "Form doesn't exist", EXIT);
return new View(this);
} else {
c.moveToFirst();
mediaDir = c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH));
}
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + "/form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image = getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
((ImageView) startView.findViewById(R.id.form_start_bling))
.setImageDrawable(image);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description)).setText(StringUtils.getStringSpannableRobust(this, R.string.save_enter_data_description,
mFormController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
instanceComplete.setText(StringUtils.getStringSpannableRobust(this, R.string.mark_finished));
//If incomplete is not enabled, make sure this box is checked.
instanceComplete.setChecked(!mIncompleteEnabled || isInstanceComplete(true));
if(mFormController.isFormReadOnly() || !mIncompleteEnabled) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);
//TODO: Figure this out based on the content provider or some part of the context
saveAs.setVisibility(View.GONE);
endView.findViewById(R.id.save_form_as).setVisibility(View.GONE);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] {
returnFilter
});
String saveName = getDefaultFormTitle();
saveAs.setText(saveName);
// Create 'save' button
Button button = (Button) endView.findViewById(R.id.save_exit_button);
if(mFormController.isFormReadOnly()) {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.exit));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
finishReturnInstance();
}
});
} else {
button.setText(StringUtils.getStringSpannableRobust(this, R.string.quit_entry));
button.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this, StringUtils.getStringSpannableRobust(FormEntryActivity.this, R.string.save_as_error),
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT,
instanceComplete.isChecked(),
saveAs.getText().toString(),
false);
}
}
});
}
return endView;
case FormEntryController.EVENT_GROUP:
isGroup = true;
case FormEntryController.EVENT_QUESTION:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
odkv =
new ODKView(this, mFormController.getQuestionPrompts(),
mFormController.getGroupsForCurrentIndex(),
mFormController.getWidgetFactory(), this, isGroup);
Log.i(t, "created view for group");
} catch (RuntimeException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
// this is badness to avoid a crash.
// really a next view should increment the formcontroller, create the view
// if the view is null, then keep the current view and pop an error.
return new View(this);
}
// Makes a "clear answer" menu pop up on long-click of
// select-one/select-multiple questions
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly() &&
!mFormController.isFormReadOnly() &&
(qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE ||
qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) {
registerForContextMenu(qw);
}
}
updateNavigationCues(odkv);
return odkv;
default:
Log.e(t, "Attempted to create a view that does not exist.");
return null;
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
*/
@SuppressLint("NewApi")
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
//We need to ignore this even if it's processed by the action
//bar (if one exists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View customView = getActionBar().getCustomView();
if(customView != null) {
if(customView.dispatchTouchEvent(mv)) {
return true;
}
}
}
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are: a question, an ask
* repeat dialog, or the submit screen. Also saves answers to the data model after checking
* constraints.
*/
private void showNextView() { showNextView(false); }
private void showNextView(boolean resuming) {
if(!resuming && mFormController.getEvent() == FormEntryController.EVENT_BEGINNING_OF_FORM) {
//See if we should stop displaying the start screen
CheckBox stopShowingIntroScreen = (CheckBox)mCurrentView.findViewById(R.id.screen_form_entry_start_cbx_dismiss);
//Not sure why it would, but maybe timing issues?
if(stopShowingIntroScreen != null) {
if(stopShowingIntroScreen.isChecked()) {
//set it!
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putBoolean(PreferencesActivity.KEY_SHOW_START_SCREEN, false).commit();
}
}
}
if (currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
return;
}
}
if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) {
int event;
try{
group_skip: do {
event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
View next = createView(event);
if(!resuming) {
showView(next, AnimationType.RIGHT);
} else {
showView(next, AnimationType.FADE, false);
}
break group_skip;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break group_skip;
case FormEntryController.EVENT_GROUP:
//We only hit this event if we're at the _opening_ of a field
//list, so it seems totally fine to do it this way, technically
//though this should test whether the index is the field list
//host.
if (mFormController.indexIsInFieldList()
&& mFormController.getQuestionPrompts().length != 0) {
View nextGroupView = createView(event);
if(!resuming) {
showView(nextGroupView, AnimationType.RIGHT);
} else {
showView(nextGroupView, AnimationType.FADE, false);
}
break group_skip;
}
// otherwise it's not a field-list group, so just skip it
break;
case FormEntryController.EVENT_REPEAT:
Log.i(t, "repeat: " + mFormController.getFormIndex().getReference());
// skip repeats
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ mFormController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
}catch(XPathTypeMismatchException e){
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT);
}
} else {
mBeenSwiped = false;
}
}
/**
* Determines what should be displayed between a question, or the start screen and displays the
* appropriate view. Also saves answers to the data model without checking constraints.
*/
private void showPreviousView() {
// The answer is saved on a back swipe, but question constraints are ignored.
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
FormIndex startIndex = mFormController.getFormIndex();
FormIndex lastValidIndex = startIndex;
if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = mFormController.stepToPreviousEvent();
//Step backwards until we either find a question, the beginning of the form,
//or a field list with valid questions inside
while (event != FormEntryController.EVENT_BEGINNING_OF_FORM
&& event != FormEntryController.EVENT_QUESTION
&& !(event == FormEntryController.EVENT_GROUP
&& mFormController.indexIsInFieldList() && mFormController
.getQuestionPrompts().length != 0)) {
event = mFormController.stepToPreviousEvent();
lastValidIndex = mFormController.getFormIndex();
}
//check if we're at the beginning and not doing the whole "First screen" thing
if(event == FormEntryController.EVENT_BEGINNING_OF_FORM && !PreferencesActivity.showFirstScreen(this)) {
//If so, we can't go all the way back here, so we've gotta hit the last index that was valid
mFormController.jumpToIndex(lastValidIndex);
//Did we jump at all? (not sure how we could have, but there might be a mismatch)
if(lastValidIndex.equals(startIndex)) {
//If not, don't even bother changing the view.
//NOTE: This needs to be the same as the
//exit condition below, in case either changes
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
return;
}
//We might have walked all the way back still, which isn't great,
//so keep moving forward again until we find it
if(lastValidIndex.isBeginningOfFormIndex()) {
//there must be a repeat between where we started and the beginning of hte form, walk back up to it
this.showNextView(true);
return;
}
}
View next = createView(event);
showView(next, AnimationType.LEFT);
} else {
//NOTE: this needs to match the exist condition above
//when there is no start screen
mBeenSwiped = false;
FormEntryActivity.this.triggerUserQuitInput();
}
}
/**
* Displays the View specified by the parameter 'next', animating both the current view and next
* appropriately given the AnimationType. Also updates the progress bar.
*/
public void showView(View next, AnimationType from) { showView(next, from, true); }
public void showView(View next, AnimationType from, boolean animateLastView) {
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
if (mCurrentView != null) {
if(animateLastView) {
mCurrentView.startAnimation(mOutAnimation);
}
mViewPane.removeView(mCurrentView);
}
mInAnimation.setAnimationListener(this);
RelativeLayout.LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mCurrentView = next;
mViewPane.addView(mCurrentView, lp);
mCurrentView.startAnimation(mInAnimation);
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
FrameLayout header = (FrameLayout)mCurrentView.findViewById(R.id.form_entry_header);
TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label));
header.setVisibility(View.GONE);
groupLabel.setVisibility(View.GONE);
String groupLabelText = ((ODKView) mCurrentView).getGroupLabel();
if(!"".equals(groupLabelText)) {
groupLabel.setText(groupLabelText);
header.setVisibility(View.VISIBLE);
groupLabel.setVisibility(View.VISIBLE);
}
} else {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0);
}
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog() and
* onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 (cupcake). We do use
* managed dialogs for our static loading ProgressDialog. The main issue we noticed and are
* waiting to see fixed is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) {
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
if (constraintText == null) {
constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error);
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error);
break;
}
boolean displayed = false;
//We need to see if question in violation is on the screen, so we can show this cleanly.
for(QuestionWidget q : ((ODKView)mCurrentView).getWidgets()) {
if(index.equals(q.getFormId())) {
q.notifyInvalid(constraintText, requestFocus);
displayed = true;
break;
}
}
if(!displayed) {
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
mBeenSwiped = false;
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a repeat of the
* current group.
*/
private void createRepeatDialog() {
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme);
View view = LayoutInflater.from(wrapper).inflate(R.layout.component_repeat_new_dialog, null);
mRepeatDialog = new AlertDialog.Builder(wrapper).create();
final AlertDialog theDialog = mRepeatDialog;
mRepeatDialog.setView(view);
mRepeatDialog.setIcon(android.R.drawable.ic_dialog_info);
boolean hasNavBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
//this is super gross...
NavigationDetails details = null;
if(hasNavBar) {
details = calculateNavigationStatus();
}
final boolean backExitsForm = hasNavBar && !details.relevantBeforeCurrentScreen;
final boolean nextExitsForm = hasNavBar && details.relevantAfterCurrentScreen == 0;
Button back = (Button)view.findViewById(R.id.component_repeat_back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(backExitsForm) {
FormEntryActivity.this.triggerUserQuitInput();
} else {
theDialog.dismiss();
FormEntryActivity.this.refreshCurrentView(false);
}
}
});
Button newButton = (Button)view.findViewById(R.id.component_repeat_new);
newButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
try {
mFormController.newRepeat();
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT);
return;
}
showNextView();
}
});
Button skip = (Button)view.findViewById(R.id.component_repeat_skip);
skip.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
theDialog.dismiss();
if(!nextExitsForm) {
showNextView();
} else {
triggerUserFormComplete();
}
}
});
back.setText(StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back));
//Load up our icons
Drawable exitIcon = getResources().getDrawable(R.drawable.icon_exit);
exitIcon.setBounds(0, 0, exitIcon.getIntrinsicWidth(), exitIcon.getIntrinsicHeight());
Drawable doneIcon = getResources().getDrawable(R.drawable.icon_done);
doneIcon.setBounds(0, 0, doneIcon.getIntrinsicWidth(), doneIcon.getIntrinsicHeight());
if (mFormController.getLastRepeatCount() > 0) {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.leaving_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.add_another));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits));
}
} else {
mRepeatDialog.setTitle(StringUtils.getStringRobust(this, R.string.entering_repeat_ask));
mRepeatDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.add_repeat,
mFormController.getLastGroupText()));
newButton.setText(StringUtils.getStringSpannableRobust(this, R.string.entering_repeat));
if(!nextExitsForm) {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no));
} else {
skip.setText(StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits));
}
}
mRepeatDialog.setCancelable(false);
mRepeatDialog.show();
if(nextExitsForm) {
skip.setCompoundDrawables(null, doneIcon, null, null);
}
if(backExitsForm) {
back.setCompoundDrawables(null, exitIcon, null, null);
}
mBeenSwiped = false;
}
/**
* Saves form data to disk.
*
* @param exit If set, will exit program after save.
* @param complete Has the user marked the instances as complete?
* @param updatedSaveName Set name of the instance's content provider, if
* non-null
* @param headless Disables GUI warnings and lets answers that
* violate constraints be saved.
* @return Did the data save successfully?
*/
private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) {
if (!formHasLoaded()) {
return;
}
// save current answer; if headless, don't evaluate the constraints
// before doing so.
if (headless &&
(!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) {
return;
} else if (!headless &&
!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) {
Toast.makeText(this,
StringUtils.getStringSpannableRobust(this, R.string.data_saved_error),
Toast.LENGTH_SHORT).show();
return;
}
// If a save task is already running, just let it do its thing
if ((mSaveToDiskTask != null) &&
(mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) {
return;
}
mSaveToDiskTask =
new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless);
mSaveToDiskTask.setFormSavedListener(this);
mSaveToDiskTask.execute();
if (!headless) {
showDialog(SAVING_DIALOG);
}
}
/**
* Create a dialog with options to save and exit, save, or quit without saving
*/
private void createQuitDialog() {
final String[] items = mIncompleteEnabled ?
new String[] {StringUtils.getStringRobust(this, R.string.keep_changes), StringUtils.getStringRobust(this, R.string.do_not_save)} :
new String[] {StringUtils.getStringRobust(this, R.string.do_not_save)};
mAlertDialog =
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(StringUtils.getStringRobust(this, R.string.quit_application, mFormController.getFormTitle()))
.setNeutralButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_exit),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setItems(items, new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
if(items.length == 1) {
discardChangesAndExit();
} else {
saveDataToDisk(EXIT, isInstanceComplete(false), null, false);
}
break;
case 1: // discard changes and exit
discardChangesAndExit();
break;
case 2:// do nothing
break;
}
}
}).create();
mAlertDialog.getListView().setSelector(R.drawable.selector);
mAlertDialog.show();
}
private void discardChangesAndExit() {
String selection =
InstanceColumns.INSTANCE_FILE_PATH + " like '"
+ mInstancePath + "'";
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, null, null).loadInBackground();
} else {
c = FormEntryActivity.this.managedQuery(instanceProviderContentURI, null, selection, null, null);
}
// if it's not already saved, erase everything
if (c.getCount() < 1) {
int images = 0;
int audio = 0;
int video = 0;
// delete media first
String instanceFolder =
mInstancePath.substring(0,
mInstancePath.lastIndexOf("/") + 1);
Log.i(t, "attempting to delete: " + instanceFolder);
String where =
Images.Media.DATA + " like '" + instanceFolder + "%'";
String[] projection = {
Images.ImageColumns._ID
};
// images
Cursor imageCursor = null;
try {
imageCursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
images =
getContentResolver()
.delete(
Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
// audio
Cursor audioCursor = null;
try {
audioCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
String id =
audioCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
audio =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
// video
Cursor videoCursor = null;
try {
videoCursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, where, null, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
String id =
videoCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
Log.i(
t,
"attempting to delete: "
+ Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
video =
getContentResolver()
.delete(
Uri.withAppendedPath(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id), null, null);
}
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
finishReturnInstance(false);
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(StringUtils.getStringRobust(this, R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener);
mAlertDialog.setButton2(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for the form.
*/
private void createLanguageDialog() {
final String[] languages = mFormController.getLanguages();
int selected = -1;
if (languages != null) {
String language = mFormController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog =
new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// Update the language in the content provider when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE, languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = {
mFormPath
};
int updated =
getContentResolver().update(formProviderContentURI, values,
selection, selectArgs);
Log.i(t, "Updated language to: " + languages[whichButton] + " in "
+ updated + " rows");
mFormController.setLanguage(languages[whichButton]);
dialog.dismiss();
if (currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(StringUtils.getStringRobust(this, R.string.change_language))
.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.do_not_change),
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create();
mAlertDialog.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
mFormLoaderTask.cancel(true);
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.loading_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener =
new DialogInterface.OnClickListener() {
/*
* (non-Javadoc)
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
mSaveToDiskTask.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(StringUtils.getStringRobust(this, R.string.saving_form));
mProgressDialog.setMessage(StringUtils.getStringSpannableRobust(this, R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel), savingButtonListener);
mProgressDialog.setButton(StringUtils.getStringSpannableRobust(this, R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
if(mRepeatDialog != null && mRepeatDialog.isShowing()) {
mRepeatDialog.dismiss();
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
dismissDialogs();
if (mCurrentView != null && currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (mNoGPSReceiver != null) {
unregisterReceiver(mNoGPSReceiver);
}
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
registerFormEntryReceivers();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (mFormController != null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
dismissDialog(PROGRESS_DIALOG);
refreshCurrentView();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
if (mErrorMessage != null && (mAlertDialog != null && !mAlertDialog.isShowing())) {
CommCareActivity.createErrorDialog(this, mErrorMessage, EXIT);
return;
}
//csims@dimagi.com - 22/08/2012 - For release only, fix immediately.
//There is a _horribly obnoxious_ bug in TimePickers that messes up how they work
//on screen rotation. We need to re-do any setAnswers that we perform on them after
//onResume.
try {
if(mCurrentView instanceof ODKView) {
ODKView ov = ((ODKView) mCurrentView);
if(ov.getWidgets() != null) {
for(QuestionWidget qw : ov.getWidgets()) {
if(qw instanceof DateTimeWidget) {
((DateTimeWidget)qw).setAnswer();
} else if(qw instanceof TimeWidget) {
((TimeWidget)qw).setAnswer();
}
}
}
}
} catch(Exception e) {
//if this fails, we _really_ don't want to mess anything up. this is a last minute
//fix
}
}
/**
* Call when the user provides input that they want to quit the form
*/
private void triggerUserQuitInput() {
//If we're just reviewing a read only form, don't worry about saving
//or what not, just quit
if(mFormController.isFormReadOnly()) {
//It's possible we just want to "finish" here, but
//I don't really wanna break any c compatibility
finishReturnInstance(false);
} else {
createQuitDialog();
}
}
/**
* Get the default title for ODK's "Form title" field
*
* @return
*/
private String getDefaultFormTitle() {
String saveName = mFormController.getFormTitle();
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
instance = new CursorLoader(this, instanceUri, null, null, null, null).loadInBackground();
} else {
instance = managedQuery(instanceUri, null, null, null, null);
}
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName =
instance.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
}
return saveName;
}
/**
* Call when the user is ready to save and return the current form as complete
*/
private void triggerUserFormComplete() {
saveDataToDisk(EXIT, true, getDefaultFormTitle(), false);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
triggerUserQuitInput();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/*
* (non-Javadoc)
* @see android.support.v4.app.FragmentActivity#onDestroy()
*/
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
mFormLoaderTask.cancel(true);
mFormLoaderTask.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(false);
}
}
super.onDestroy();
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationEnd(android.view.animation.Animation)
*/
@Override
public void onAnimationEnd(Animation arg0) {
mBeenSwiped = false;
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationRepeat(android.view.animation.Animation)
*/
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see android.view.animation.Animation.AnimationListener#onAnimationStart(android.view.animation.Animation)
*/
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingComplete(org.odk.collect.android.logic.FormController)
*
* loadingComplete() is called by FormLoaderTask once it has finished loading a form.
*/
@SuppressLint("NewApi")
@Override
public void loadingComplete(FormController fc) {
dismissDialog(PROGRESS_DIALOG);
mFormController = fc;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
// Newer menus may have already built the menu, before all data was ready
invalidateOptionsMenu();
}
Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced();
if(mLocalizer != null){
String mLocale = mLocalizer.getLocale();
if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){
fc.setLanguage(mLocale);
}
else{
Logger.log("formloader", "The current locale is not set");
}
} else{
Logger.log("formloader", "Could not get the localizer");
}
// Set saved answer path
if (mInstancePath == null) {
// Create new answer folder.
String time =
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
.format(Calendar.getInstance().getTime());
String file =
mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.'));
String path = mInstanceDestination + "/" + file + "_" + time;
if (FileUtils.createFolder(path)) {
mInstancePath = path + "/" + file + "_" + time + ".xml";
}
} else {
// we've just loaded a saved form, so start in the hierarchy view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START);
return; // so we don't show the intro screen before jumping to the hierarchy
}
//mFormController.setLanguage(mFormController.getLanguage());
/* here was code that loaded cached language preferences fin the
* collect code. we've overridden that to use our language
* from the shared preferences
*/
refreshCurrentView();
updateNavigationCues(this.mCurrentView);
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.FormLoaderListener#loadingError(java.lang.String)
*
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
CommCareActivity.createErrorDialog(this, errorMsg, EXIT);
} else {
CommCareActivity.createErrorDialog(this, StringUtils.getStringRobust(this, R.string.parse_error), EXIT);
}
}
/**
* {@inheritDoc}
*
* Display save status notification and exit or continue on in the form.
* If form entry is being saved because key session is expiring then
* continue closing the session/logging out.
*
* @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean)
*/
@Override
public void savingComplete(int saveStatus, boolean headless) {
if (!headless) {
dismissDialog(SAVING_DIALOG);
}
// Did we just save a form because the key session
// (CommCareSessionService) is ending?
if (savingFormOnKeySessionExpiration) {
savingFormOnKeySessionExpiration = false;
// Notify the key session that the form state has been saved (or at
// least attempted to be saved) so CommCareSessionService can
// continue closing down key pool and user database.
try {
CommCareApplication._().getSession().closeSession(true);
} catch (SessionUnavailableException sue) {
// form saving took too long, so we logged out already.
Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW,
"Saving current form took too long, " +
"so data was (probably) discarded and the session closed. " +
"Save exit code: " + saveStatus);
}
} else {
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show();
hasSaved = true;
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints Should form contraints be checked when saving answer?
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) {
try {
if (evaluateConstraints) {
return mFormController.answerQuestion(index, answer);
} else {
mFormController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
} catch(XPathException e) {
//this is where runtime exceptions get triggered after the form has loaded
CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT);
//We're exiting anyway
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has already been
* 'marked completed'. A form can be 'unmarked' complete and then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
complete =
sharedPreferences.getBoolean(PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
c = this.managedQuery(instanceProviderContentURI, null, selection, selectionArgs, null);
}
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
private void finishReturnInstance() {
finishReturnInstance(true);
}
/**
* Returns the instance that was just filled out to the calling activity,
* if requested.
*
* @param reportSaved was a form saved? Delegates the result code of the
* activity
*/
private void finishReturnInstance(boolean reportSaved) {
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = {
mInstancePath
};
Cursor c;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
c = new CursorLoader(this, instanceProviderContentURI, null, selection, selectionArgs, null).loadInBackground();
} else {
c = managedQuery(instanceProviderContentURI, null, selection, selectionArgs, null);
}
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id);
Intent formReturnIntent = new Intent();
formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly());
if(reportSaved || hasSaved) {
setResult(RESULT_OK, formReturnIntent.setData(instance));
} else {
setResult(RESULT_CANCELED, formReturnIntent.setData(instance));
}
}
}
try {
CommCareApplication._().getSession().unregisterFormSaveCallback();
} catch (SessionUnavailableException sue) {
// looks like the session expired
}
this.dismissDialogs();
finish();
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent)
*/
@Override
public boolean onDown(MotionEvent e) {
return false;
}
/*
* Looks for user swipes. If the user has swiped, move to the appropriate screen.
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (CommCareActivity.isHorizontalSwipe(this, e1, e2)) {
mBeenSwiped = true;
if (velocityX > 0) {
showPreviousView();
} else {
int event = mFormController.getEvent(mFormController.getNextFormIndex(mFormController.getFormIndex(), true));
boolean navBar = PreferencesActivity.getProgressBarMode(this).useNavigationBar();
if(!navBar || (navBar && event != FormEntryController.EVENT_END_OF_FORM)) {
showNextView();
}
}
return true;
}
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long pressed.
// We don't wnat that, so cancel it.
mCurrentView.cancelLongPress();
return false;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent)
*/
@Override
public void onShowPress(MotionEvent e) {
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent)
*/
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.AdvanceToNextListener#advance()
*/
@Override
public void advance() {
next();
}
/*
* (non-Javadoc)
* @see org.odk.collect.android.listeners.WidgetChangedListener#widgetEntryChanged()
*/
@Override
public void widgetEntryChanged() {
updateFormRelevencies();
updateNavigationCues(this.mCurrentView);
}
/**
* Has form loading (via FormLoaderTask) completed?
*/
private boolean formHasLoaded() {
return mFormController != null;
}
}
|
Fix for bug 174626, in which long presses to remove answers would crash
the app.
|
app/src/org/odk/collect/android/activities/FormEntryActivity.java
|
Fix for bug 174626, in which long presses to remove answers would crash the app.
|
|
Java
|
apache-2.0
|
d0611d2fc766f25048aacd8ed954304a569f2f60
| 0
|
JNOSQL/artemis
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.document;
import org.jnosql.artemis.CDIJUnitRunner;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.IdNotFoundException;
import org.jnosql.artemis.model.Job;
import org.jnosql.artemis.model.Person;
import org.jnosql.artemis.reflection.ClassRepresentations;
import org.jnosql.diana.api.NonUniqueResultException;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCollectionManager;
import org.jnosql.diana.api.document.DocumentCondition;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(CDIJUnitRunner.class)
public class DefaultDocumentTemplateTest {
private Person person = Person.builder().
withAge().
withPhones(Arrays.asList("234", "432")).
withName("Name")
.withId(19)
.withIgnore().build();
private Document[] documents = new Document[]{
Document.of("age", 10),
Document.of("phones", Arrays.asList("234", "432")),
Document.of("name", "Name"),
Document.of("id", 19L),
};
@Inject
private DocumentEntityConverter converter;
@Inject
private ClassRepresentations classRepresentations;
@Inject
private Converters converters;
private DocumentCollectionManager managerMock;
private DefaultDocumentTemplate subject;
private ArgumentCaptor<DocumentEntity> captor;
private DocumentEventPersistManager documentEventPersistManager;
@SuppressWarnings("unchecked")
@Before
public void setUp() {
managerMock = Mockito.mock(DocumentCollectionManager.class);
documentEventPersistManager = Mockito.mock(DocumentEventPersistManager.class);
captor = ArgumentCaptor.forClass(DocumentEntity.class);
Instance<DocumentCollectionManager> instance = Mockito.mock(Instance.class);
when(instance.get()).thenReturn(managerMock);
DefaultDocumentWorkflow workflow = new DefaultDocumentWorkflow(documentEventPersistManager, converter);
this.subject = new DefaultDocumentTemplate(converter, instance, workflow,
documentEventPersistManager, classRepresentations, converters);
}
@Test
public void shouldSave() {
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock
.insert(any(DocumentEntity.class)))
.thenReturn(document);
subject.insert(this.person);
verify(managerMock).insert(captor.capture());
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldSaveTTL() {
Duration twoHours = Duration.ofHours(2L);
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock.insert(any(DocumentEntity.class),
Mockito.eq(twoHours)))
.thenReturn(document);
subject.insert(this.person, twoHours);
verify(managerMock).insert(captor.capture(), Mockito.eq(twoHours));
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldUpdate() {
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock
.update(any(DocumentEntity.class)))
.thenReturn(document);
subject.update(this.person);
verify(managerMock).update(captor.capture());
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldInsertEntitiesTTL() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Duration duration = Duration.ofHours(2);
Mockito.when(managerMock
.insert(any(DocumentEntity.class), Mockito.eq(duration)))
.thenReturn(documentEntity);
subject.insert(Arrays.asList(person, person), duration);
verify(managerMock, times(2)).insert(any(DocumentEntity.class), any(Duration.class));
}
@Test
public void shouldInsertEntities() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.insert(any(DocumentEntity.class)))
.thenReturn(documentEntity);
subject.insert(Arrays.asList(person, person));
verify(managerMock, times(2)).insert(any(DocumentEntity.class));
}
@Test
public void shouldUpdateEntities() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.update(any(DocumentEntity.class)))
.thenReturn(documentEntity);
subject.update(Arrays.asList(person, person));
verify(managerMock, times(2)).update(any(DocumentEntity.class));
}
@Test
public void shouldDelete() {
DocumentDeleteQuery query = delete().from("delete").build();
subject.delete(query);
verify(managerMock).delete(query);
}
@Test
public void shouldSelect() {
DocumentQuery query = select().from("delete").build();
subject.select(query);
verify(managerMock).select(query);
}
@Test
public void shouldReturnSingleResult() {
DocumentEntity columnEntity = DocumentEntity.of("Person");
columnEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(singletonList(columnEntity));
DocumentQuery query = select().from("person").build();
Optional<Person> result = subject.singleResult(query);
assertTrue(result.isPresent());
}
@Test
public void shouldReturnSingleResultIsEmpty() {
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(emptyList());
DocumentQuery query = select().from("person").build();
Optional<Person> result = subject.singleResult(query);
assertFalse(result.isPresent());
}
@Test(expected = NonUniqueResultException.class)
public void shouldReturnErrorWhenThereMoreThanASingleResult() {
DocumentEntity columnEntity = DocumentEntity.of("Person");
columnEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(Arrays.asList(columnEntity, columnEntity));
DocumentQuery query = select().from("person").build();
subject.singleResult(query);
}
@Test(expected = NullPointerException.class)
public void shouldReturnErrorWhenFindIdHasIdNull() {
subject.find(Person.class, null);
}
@Test(expected = NullPointerException.class)
public void shouldReturnErrorWhenFindIdHasClassNull() {
subject.find(null, "10");
}
@Test(expected = IdNotFoundException.class)
public void shouldReturnErrorWhenThereIsNotIdInFind() {
subject.find(Job.class, "10");
}
@Test
public void shouldReturnFind() {
subject.find(Person.class, "10");
ArgumentCaptor<DocumentQuery> queryCaptor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(managerMock).select(queryCaptor.capture());
DocumentQuery query = queryCaptor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(DocumentCondition.eq(Document.of("_id", 10L)), condition);
}
@Test
public void shouldDeleteEntity() {
subject.delete(Person.class, "10");
ArgumentCaptor<DocumentDeleteQuery> queryCaptor = ArgumentCaptor.forClass(DocumentDeleteQuery.class);
verify(managerMock).delete(queryCaptor.capture());
DocumentDeleteQuery query = queryCaptor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(DocumentCondition.eq(Document.of("_id", 10L)), condition);
}
}
|
artemis-document/src/test/java/org/jnosql/artemis/document/DefaultDocumentTemplateTest.java
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.document;
import org.jnosql.artemis.CDIJUnitRunner;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.IdNotFoundException;
import org.jnosql.artemis.model.Job;
import org.jnosql.artemis.model.Person;
import org.jnosql.artemis.reflection.ClassRepresentations;
import org.jnosql.diana.api.NonUniqueResultException;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentCollectionManager;
import org.jnosql.diana.api.document.DocumentCondition;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.time.Duration;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(CDIJUnitRunner.class)
public class DefaultDocumentTemplateTest {
private Person person = Person.builder().
withAge().
withPhones(Arrays.asList("234", "432")).
withName("Name")
.withId(19)
.withIgnore().build();
private Document[] documents = new Document[]{
Document.of("age", 10),
Document.of("phones", Arrays.asList("234", "432")),
Document.of("name", "Name"),
Document.of("id", 19L),
};
@Inject
private DocumentEntityConverter converter;
@Inject
private ClassRepresentations classRepresentations;
@Inject
private Converters converters;
private DocumentCollectionManager managerMock;
private DefaultDocumentTemplate subject;
private ArgumentCaptor<DocumentEntity> captor;
private DocumentEventPersistManager documentEventPersistManager;
@SuppressWarnings("unchecked")
@Before
public void setUp() {
managerMock = Mockito.mock(DocumentCollectionManager.class);
documentEventPersistManager = Mockito.mock(DocumentEventPersistManager.class);
captor = ArgumentCaptor.forClass(DocumentEntity.class);
Instance<DocumentCollectionManager> instance = Mockito.mock(Instance.class);
when(instance.get()).thenReturn(managerMock);
DefaultDocumentWorkflow workflow = new DefaultDocumentWorkflow(documentEventPersistManager, converter);
this.subject = new DefaultDocumentTemplate(converter, instance, workflow,
documentEventPersistManager, classRepresentations, converters);
}
@Test
public void shouldSave() {
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock
.insert(any(DocumentEntity.class)))
.thenReturn(document);
subject.insert(this.person);
verify(managerMock).insert(captor.capture());
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldSaveTTL() {
Duration twoHours = Duration.ofHours(2L);
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock.insert(any(DocumentEntity.class),
Mockito.eq(twoHours)))
.thenReturn(document);
subject.insert(this.person, twoHours);
verify(managerMock).insert(captor.capture(), Mockito.eq(twoHours));
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldUpdate() {
DocumentEntity document = DocumentEntity.of("Person");
document.addAll(Stream.of(documents).collect(Collectors.toList()));
when(managerMock
.update(any(DocumentEntity.class)))
.thenReturn(document);
subject.update(this.person);
verify(managerMock).update(captor.capture());
verify(documentEventPersistManager).firePostEntity(any(Person.class));
verify(documentEventPersistManager).firePreEntity(any(Person.class));
verify(documentEventPersistManager).firePreDocument(any(DocumentEntity.class));
verify(documentEventPersistManager).firePostDocument(any(DocumentEntity.class));
DocumentEntity value = captor.getValue();
assertEquals("Person", value.getName());
assertEquals(4, value.getDocuments().size());
}
@Test
public void shouldInsertEntitiesTTL() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Duration duration = Duration.ofHours(2);
Mockito.when(managerMock
.insert(any(DocumentEntity.class), Mockito.eq(duration)))
.thenReturn(documentEntity);
subject.insert(Arrays.asList(person, person), duration);
verify(managerMock, times(2)).insert(any(DocumentEntity.class), any(Duration.class));
}
@Test
public void shouldInsertEntities() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.insert(any(DocumentEntity.class)))
.thenReturn(documentEntity);
subject.insert(Arrays.asList(person, person));
verify(managerMock, times(2)).insert(any(DocumentEntity.class));
}
@Test
public void shouldUpdateEntities() {
DocumentEntity documentEntity = DocumentEntity.of("Person");
documentEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.update(any(DocumentEntity.class)))
.thenReturn(documentEntity);
subject.update(Arrays.asList(person, person));
verify(managerMock, times(2)).update(any(DocumentEntity.class));
}
@Test
public void shouldDelete() {
DocumentDeleteQuery query = delete().from("delete").build();
subject.delete(query);
verify(managerMock).delete(query);
}
@Test
public void shouldSelect() {
DocumentQuery query = select().from("delete").build();
subject.select(query);
verify(managerMock).select(query);
}
@Test
public void shouldReturnSingleResult() {
DocumentEntity columnEntity = DocumentEntity.of("Person");
columnEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(singletonList(columnEntity));
DocumentQuery query = select().from("person").build();
Optional<Person> result = subject.singleResult(query);
assertTrue(result.isPresent());
}
@Test
public void shouldReturnSingleResultIsEmpty() {
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(emptyList());
DocumentQuery query = select().from("person").build();
Optional<Person> result = subject.singleResult(query);
assertFalse(result.isPresent());
}
@Test(expected = NonUniqueResultException.class)
public void shouldReturnErrorWhenThereMoreThanASingleResult() {
DocumentEntity columnEntity = DocumentEntity.of("Person");
columnEntity.addAll(Stream.of(documents).collect(Collectors.toList()));
Mockito.when(managerMock
.select(any(DocumentQuery.class)))
.thenReturn(Arrays.asList(columnEntity, columnEntity));
DocumentQuery query = select().from("person").build();
subject.singleResult(query);
}
@Test(expected = NullPointerException.class)
public void shouldReturnErrorWhenFindIdHasIdNull() {
subject.find(Person.class, null);
}
@Test(expected = NullPointerException.class)
public void shouldReturnErrorWhenFindIdHasClassNull() {
subject.find(null, "10");
}
@Test(expected = IdNotFoundException.class)
public void shouldReturnErrorWhenThereIsNotIdInFind() {
subject.find(Job.class, "10");
}
@Test
public void shouldReturnFind() {
subject.find(Person.class, "10");
ArgumentCaptor<DocumentQuery> queryCaptor = ArgumentCaptor.forClass(DocumentQuery.class);
verify(managerMock).select(queryCaptor.capture());
DocumentQuery query = queryCaptor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(DocumentCondition.eq(Document.of("_id", "10")), condition);
}
@Test
public void shouldDeleteEntity() {
subject.delete(Person.class, "10");
ArgumentCaptor<DocumentDeleteQuery> queryCaptor = ArgumentCaptor.forClass(DocumentDeleteQuery.class);
verify(managerMock).delete(queryCaptor.capture());
DocumentDeleteQuery query = queryCaptor.getValue();
DocumentCondition condition = query.getCondition().get();
assertEquals("Person", query.getDocumentCollection());
assertEquals(DocumentCondition.eq(Document.of("_id", "10")), condition);
}
}
|
fixes tests
|
artemis-document/src/test/java/org/jnosql/artemis/document/DefaultDocumentTemplateTest.java
|
fixes tests
|
|
Java
|
apache-2.0
|
d03c773ded5f54519596e526b7d2e79543e425ff
| 0
|
stinsonga/libgdx,libgdx/libgdx,libgdx/libgdx,Zomby2D/libgdx,libgdx/libgdx,bladecoder/libgdx,bladecoder/libgdx,cypherdare/libgdx,tommyettinger/libgdx,tommyettinger/libgdx,Zomby2D/libgdx,stinsonga/libgdx,stinsonga/libgdx,tommyettinger/libgdx,libgdx/libgdx,NathanSweet/libgdx,bladecoder/libgdx,NathanSweet/libgdx,cypherdare/libgdx,tommyettinger/libgdx,stinsonga/libgdx,NathanSweet/libgdx,cypherdare/libgdx,cypherdare/libgdx,cypherdare/libgdx,NathanSweet/libgdx,bladecoder/libgdx,libgdx/libgdx,tommyettinger/libgdx,Zomby2D/libgdx,stinsonga/libgdx,bladecoder/libgdx,NathanSweet/libgdx,Zomby2D/libgdx,Zomby2D/libgdx
|
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
import java.io.*;
import java.math.BigInteger;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import com.badlogic.gdx.backends.gwt.preloader.AssetFilter.AssetType;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.StreamUtils;
import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.ConfigurationProperty;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
/** Copies assets from the path specified in the modules gdx.assetpath configuration property to the war/ folder and generates the
* assets.txt file. The type of a file is determined by an {@link AssetFilter}, which is either created by instantiating the class
* specified in the gdx.assetfilterclass property, or falling back to the {@link DefaultAssetFilter}.
* @author mzechner */
public class PreloaderBundleGenerator extends Generator {
private class Asset {
String filePathOrig;
FileWrapper file;
AssetType type;
public Asset(String filePathOrig, FileWrapper file, AssetType type) {
this.filePathOrig = filePathOrig;
this.file = file;
this.type = type;
}
}
@Override
public String generate (TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
System.out.println(new File(".").getAbsolutePath());
String assetPath = getAssetPath(context);
String assetOutputPath = getAssetOutputPath(context);
if ( assetOutputPath == null ){
assetOutputPath = "war/";
}
AssetFilter assetFilter = getAssetFilter(context);
FileWrapper source = new FileWrapper(assetPath);
if (!source.exists()) {
source = new FileWrapper("../" + assetPath);
if (!source.exists())
throw new RuntimeException("assets path '" + assetPath
+ "' does not exist. Check your gdx.assetpath property in your GWT project's module gwt.xml file");
}
if (!source.isDirectory())
throw new RuntimeException("assets path '" + assetPath
+ "' is not a directory. Check your gdx.assetpath property in your GWT project's module gwt.xml file");
System.out.println("Copying resources from " + assetPath + " to " + assetOutputPath );
System.out.println(source.file.getAbsolutePath());
FileWrapper target = new FileWrapper("assets/"); // this should always be the war/ directory of the GWT project.
System.out.println(target.file.getAbsolutePath());
if (!target.file.getAbsolutePath().replace("\\", "/").endsWith(assetOutputPath + "assets")) {
target = new FileWrapper(assetOutputPath + "assets/");
}
if (target.exists()) {
if (!target.deleteDirectory()) throw new RuntimeException("Couldn't clean target path '" + target + "'");
}
ArrayList<Asset> assets = new ArrayList<Asset>();
copyDirectory(source, target, assetFilter, assets);
// Now collect classpath files and copy to assets
List<String> classpathFiles = getClasspathFiles(context);
for (String classpathFile : classpathFiles) {
if (assetFilter.accept(classpathFile, false)) {
try {
InputStream is = context.getClass().getClassLoader().getResourceAsStream(classpathFile);
byte[] bytes = StreamUtils.copyStreamToByteArray(is);
is.close();
FileWrapper origFile = target.child(classpathFile);
FileWrapper destFile = target.child(fileNameWithMd5(origFile, bytes));
destFile.writeBytes(bytes, false);
assets.add(new Asset(origFile.path(), destFile, assetFilter.getType(destFile.path())));
} catch (IOException e) {
e.printStackTrace();
}
}
}
HashMap<String, ArrayList<Asset>> bundles = new HashMap<String, ArrayList<Asset>>();
for (Asset asset : assets) {
String bundleName = assetFilter.getBundleName(asset.file.path());
if (bundleName == null) {
bundleName = "assets";
}
ArrayList<Asset> bundleAssets = bundles.get(bundleName);
if (bundleAssets == null) {
bundleAssets = new ArrayList<Asset>();
bundles.put(bundleName, bundleAssets);
}
bundleAssets.add(asset);
}
// Write the tokens for Preloader.preload()
for (Entry<String, ArrayList<Asset>> bundle : bundles.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Asset asset : bundle.getValue()) {
String pathOrig = asset.filePathOrig.replace('\\', '/').replace(assetOutputPath, "").replaceFirst("assets/", "");
if (pathOrig.startsWith("/")) pathOrig = pathOrig.substring(1);
String pathMd5 = asset.file.path().replace('\\', '/').replace(assetOutputPath, "").replaceFirst("assets/", "");
if (pathMd5.startsWith("/")) pathMd5 = pathMd5.substring(1);
sb.append(asset.type.code);
sb.append(":");
sb.append(pathOrig);
sb.append(":");
sb.append(pathMd5);
sb.append(":");
sb.append(asset.file.isDirectory() ? 0 : asset.file.length());
sb.append(":");
String mimetype = URLConnection.guessContentTypeFromName(asset.file.name());
sb.append(mimetype == null ? "application/unknown" : mimetype);
sb.append(":");
sb.append(asset.file.isDirectory() || assetFilter.preload(pathOrig) ? '1' : '0');
sb.append("\n");
}
target.child(bundle.getKey() + ".txt").writeString(sb.toString(), false);
}
return createDummyClass(logger, context);
}
private void copyFile(FileWrapper source, String filePathOrig, FileWrapper dest, AssetFilter filter, ArrayList<Asset> assets) {
if (!filter.accept(filePathOrig, false)) return;
try {
assets.add(new Asset(filePathOrig, dest, filter.getType(dest.path())));
dest.write(source.read(), false);
} catch (Exception ex) {
throw new GdxRuntimeException("Error copying source file: " + source + "\n" //
+ "To destination: " + dest, ex);
}
}
private void copyDirectory(FileWrapper sourceDir, FileWrapper destDir, AssetFilter filter, ArrayList<Asset> assets) {
if (!filter.accept(destDir.path(), true)) return;
assets.add(new Asset(destDir.path(), destDir, AssetType.Directory));
destDir.mkdirs();
FileWrapper[] files = sourceDir.list();
for (int i = 0, n = files.length; i < n; i++) {
FileWrapper srcFile = files[i];
if (srcFile.isDirectory()) {
FileWrapper destFile = destDir.child(srcFile.name());
copyDirectory(srcFile, destFile, filter, assets);
} else {
FileWrapper destFile = destDir.child(fileNameWithMd5(srcFile, srcFile.readBytes()));
copyFile(srcFile, destDir.child(srcFile.name()).path(), destFile, filter, assets);
}
}
}
private AssetFilter getAssetFilter (GeneratorContext context) {
ConfigurationProperty assetFilterClassProperty = null;
try {
assetFilterClassProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetfilterclass");
} catch (BadPropertyValueException e) {
return new DefaultAssetFilter();
}
if (assetFilterClassProperty.getValues().size() == 0) {
return new DefaultAssetFilter();
}
String assetFilterClass = assetFilterClassProperty.getValues().get(0);
if (assetFilterClass == null) return new DefaultAssetFilter();
try {
return (AssetFilter)Class.forName(assetFilterClass).newInstance();
} catch (Exception e) {
throw new RuntimeException("Couldn't instantiate custom AssetFilter '" + assetFilterClass
+ "', make sure the class is public and has a public default constructor", e);
}
}
private String getAssetPath (GeneratorContext context) {
ConfigurationProperty assetPathProperty = null;
try {
assetPathProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetpath");
} catch (BadPropertyValueException e) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
}
if (assetPathProperty.getValues().size() == 0) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
}
String paths = assetPathProperty.getValues().get(0);
if(paths == null) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
} else {
ArrayList<String> existingPaths = new ArrayList<String>();
String[] tokens = paths.split(",");
for(String token: tokens) {
System.out.println(token);
if(new FileWrapper(token).exists() || new FileWrapper("../" + token).exists()) {
return token;
}
}
throw new RuntimeException(
"No valid gdx.assetpath defined. Fix <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> in your GWT projects gwt.xml file");
}
}
private String getAssetOutputPath (GeneratorContext context) {
ConfigurationProperty assetPathProperty = null;
try {
assetPathProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetoutputpath");
} catch (BadPropertyValueException e) {
return null;
}
if (assetPathProperty.getValues().size() == 0) {
return null;
}
String paths = assetPathProperty.getValues().get(0);
if(paths == null) {
return null;
} else {
ArrayList<String> existingPaths = new ArrayList<String>();
String[] tokens = paths.split(",");
String path = null;
for(String token: tokens) {
if (new FileWrapper(token).exists() || new FileWrapper(token).mkdirs()) {
path = token;
}
}
if (path != null && !path.endsWith("/")){
path += "/";
}
return path;
}
}
private List<String> getClasspathFiles(GeneratorContext context) {
List<String> classpathFiles = new ArrayList<String>();
try {
ConfigurationProperty prop = context.getPropertyOracle().getConfigurationProperty("gdx.files.classpath");
for (String value : prop.getValues()) {
classpathFiles.add(value);
}
} catch (BadPropertyValueException e) {
// Ignore
}
return classpathFiles;
}
private String createDummyClass (TreeLogger logger, GeneratorContext context) {
String packageName = "com.badlogic.gdx.backends.gwt.preloader";
String className = "PreloaderBundleImpl";
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
composer.addImplementedInterface(packageName + ".PreloaderBundle");
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter == null) {
return packageName + "." + className;
}
SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
sourceWriter.commit(logger);
return packageName + "." + className;
}
private static String fileNameWithMd5(FileWrapper fw, byte[] bytes) {
String md5;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
md5 = String.format("%032x", new BigInteger(1, digest.digest()));
} catch (NoSuchAlgorithmException e) {
// Fallback
md5 = String.valueOf(System.currentTimeMillis());
}
String nameWithMd5 = fw.nameWithoutExtension() + "-" + md5;
String extension = fw.extension();
if (!extension.isEmpty() || fw.name().endsWith(".")) {
nameWithMd5 = nameWithMd5 + "." + extension;
}
return nameWithMd5;
}
}
|
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/preloader/PreloaderBundleGenerator.java
|
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
import java.io.*;
import java.math.BigInteger;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import com.badlogic.gdx.backends.gwt.preloader.AssetFilter.AssetType;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.ConfigurationProperty;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import org.apache.commons.io.IOUtils;
/** Copies assets from the path specified in the modules gdx.assetpath configuration property to the war/ folder and generates the
* assets.txt file. The type of a file is determined by an {@link AssetFilter}, which is either created by instantiating the class
* specified in the gdx.assetfilterclass property, or falling back to the {@link DefaultAssetFilter}.
* @author mzechner */
public class PreloaderBundleGenerator extends Generator {
private class Asset {
String filePathOrig;
FileWrapper file;
AssetType type;
public Asset(String filePathOrig, FileWrapper file, AssetType type) {
this.filePathOrig = filePathOrig;
this.file = file;
this.type = type;
}
}
@Override
public String generate (TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
System.out.println(new File(".").getAbsolutePath());
String assetPath = getAssetPath(context);
String assetOutputPath = getAssetOutputPath(context);
if ( assetOutputPath == null ){
assetOutputPath = "war/";
}
AssetFilter assetFilter = getAssetFilter(context);
FileWrapper source = new FileWrapper(assetPath);
if (!source.exists()) {
source = new FileWrapper("../" + assetPath);
if (!source.exists())
throw new RuntimeException("assets path '" + assetPath
+ "' does not exist. Check your gdx.assetpath property in your GWT project's module gwt.xml file");
}
if (!source.isDirectory())
throw new RuntimeException("assets path '" + assetPath
+ "' is not a directory. Check your gdx.assetpath property in your GWT project's module gwt.xml file");
System.out.println("Copying resources from " + assetPath + " to " + assetOutputPath );
System.out.println(source.file.getAbsolutePath());
FileWrapper target = new FileWrapper("assets/"); // this should always be the war/ directory of the GWT project.
System.out.println(target.file.getAbsolutePath());
if (!target.file.getAbsolutePath().replace("\\", "/").endsWith(assetOutputPath + "assets")) {
target = new FileWrapper(assetOutputPath + "assets/");
}
if (target.exists()) {
if (!target.deleteDirectory()) throw new RuntimeException("Couldn't clean target path '" + target + "'");
}
ArrayList<Asset> assets = new ArrayList<Asset>();
copyDirectory(source, target, assetFilter, assets);
// Now collect classpath files and copy to assets
List<String> classpathFiles = getClasspathFiles(context);
for (String classpathFile : classpathFiles) {
if (assetFilter.accept(classpathFile, false)) {
try {
InputStream is = context.getClass().getClassLoader().getResourceAsStream(classpathFile);
byte[] bytes = IOUtils.toByteArray(is);
is.close();
FileWrapper origFile = target.child(classpathFile);
FileWrapper destFile = target.child(fileNameWithMd5(origFile, bytes));
destFile.writeBytes(bytes, false);
assets.add(new Asset(origFile.path(), destFile, assetFilter.getType(destFile.path())));
} catch (IOException e) {
e.printStackTrace();
}
}
}
HashMap<String, ArrayList<Asset>> bundles = new HashMap<String, ArrayList<Asset>>();
for (Asset asset : assets) {
String bundleName = assetFilter.getBundleName(asset.file.path());
if (bundleName == null) {
bundleName = "assets";
}
ArrayList<Asset> bundleAssets = bundles.get(bundleName);
if (bundleAssets == null) {
bundleAssets = new ArrayList<Asset>();
bundles.put(bundleName, bundleAssets);
}
bundleAssets.add(asset);
}
// Write the tokens for Preloader.preload()
for (Entry<String, ArrayList<Asset>> bundle : bundles.entrySet()) {
StringBuilder sb = new StringBuilder();
for (Asset asset : bundle.getValue()) {
String pathOrig = asset.filePathOrig.replace('\\', '/').replace(assetOutputPath, "").replaceFirst("assets/", "");
if (pathOrig.startsWith("/")) pathOrig = pathOrig.substring(1);
String pathMd5 = asset.file.path().replace('\\', '/').replace(assetOutputPath, "").replaceFirst("assets/", "");
if (pathMd5.startsWith("/")) pathMd5 = pathMd5.substring(1);
sb.append(asset.type.code);
sb.append(":");
sb.append(pathOrig);
sb.append(":");
sb.append(pathMd5);
sb.append(":");
sb.append(asset.file.isDirectory() ? 0 : asset.file.length());
sb.append(":");
String mimetype = URLConnection.guessContentTypeFromName(asset.file.name());
sb.append(mimetype == null ? "application/unknown" : mimetype);
sb.append(":");
sb.append(asset.file.isDirectory() || assetFilter.preload(pathOrig) ? '1' : '0');
sb.append("\n");
}
target.child(bundle.getKey() + ".txt").writeString(sb.toString(), false);
}
return createDummyClass(logger, context);
}
private void copyFile(FileWrapper source, String filePathOrig, FileWrapper dest, AssetFilter filter, ArrayList<Asset> assets) {
if (!filter.accept(filePathOrig, false)) return;
try {
assets.add(new Asset(filePathOrig, dest, filter.getType(dest.path())));
dest.write(source.read(), false);
} catch (Exception ex) {
throw new GdxRuntimeException("Error copying source file: " + source + "\n" //
+ "To destination: " + dest, ex);
}
}
private void copyDirectory(FileWrapper sourceDir, FileWrapper destDir, AssetFilter filter, ArrayList<Asset> assets) {
if (!filter.accept(destDir.path(), true)) return;
assets.add(new Asset(destDir.path(), destDir, AssetType.Directory));
destDir.mkdirs();
FileWrapper[] files = sourceDir.list();
for (int i = 0, n = files.length; i < n; i++) {
FileWrapper srcFile = files[i];
if (srcFile.isDirectory()) {
FileWrapper destFile = destDir.child(srcFile.name());
copyDirectory(srcFile, destFile, filter, assets);
} else {
FileWrapper destFile = destDir.child(fileNameWithMd5(srcFile, srcFile.readBytes()));
copyFile(srcFile, destDir.child(srcFile.name()).path(), destFile, filter, assets);
}
}
}
private AssetFilter getAssetFilter (GeneratorContext context) {
ConfigurationProperty assetFilterClassProperty = null;
try {
assetFilterClassProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetfilterclass");
} catch (BadPropertyValueException e) {
return new DefaultAssetFilter();
}
if (assetFilterClassProperty.getValues().size() == 0) {
return new DefaultAssetFilter();
}
String assetFilterClass = assetFilterClassProperty.getValues().get(0);
if (assetFilterClass == null) return new DefaultAssetFilter();
try {
return (AssetFilter)Class.forName(assetFilterClass).newInstance();
} catch (Exception e) {
throw new RuntimeException("Couldn't instantiate custom AssetFilter '" + assetFilterClass
+ "', make sure the class is public and has a public default constructor", e);
}
}
private String getAssetPath (GeneratorContext context) {
ConfigurationProperty assetPathProperty = null;
try {
assetPathProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetpath");
} catch (BadPropertyValueException e) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
}
if (assetPathProperty.getValues().size() == 0) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
}
String paths = assetPathProperty.getValues().get(0);
if(paths == null) {
throw new RuntimeException(
"No gdx.assetpath defined. Add <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> to your GWT projects gwt.xml file");
} else {
ArrayList<String> existingPaths = new ArrayList<String>();
String[] tokens = paths.split(",");
for(String token: tokens) {
System.out.println(token);
if(new FileWrapper(token).exists() || new FileWrapper("../" + token).exists()) {
return token;
}
}
throw new RuntimeException(
"No valid gdx.assetpath defined. Fix <set-configuration-property name=\"gdx.assetpath\" value=\"relative/path/to/assets/\"/> in your GWT projects gwt.xml file");
}
}
private String getAssetOutputPath (GeneratorContext context) {
ConfigurationProperty assetPathProperty = null;
try {
assetPathProperty = context.getPropertyOracle().getConfigurationProperty("gdx.assetoutputpath");
} catch (BadPropertyValueException e) {
return null;
}
if (assetPathProperty.getValues().size() == 0) {
return null;
}
String paths = assetPathProperty.getValues().get(0);
if(paths == null) {
return null;
} else {
ArrayList<String> existingPaths = new ArrayList<String>();
String[] tokens = paths.split(",");
String path = null;
for(String token: tokens) {
if (new FileWrapper(token).exists() || new FileWrapper(token).mkdirs()) {
path = token;
}
}
if (path != null && !path.endsWith("/")){
path += "/";
}
return path;
}
}
private List<String> getClasspathFiles(GeneratorContext context) {
List<String> classpathFiles = new ArrayList<String>();
try {
ConfigurationProperty prop = context.getPropertyOracle().getConfigurationProperty("gdx.files.classpath");
for (String value : prop.getValues()) {
classpathFiles.add(value);
}
} catch (BadPropertyValueException e) {
// Ignore
}
return classpathFiles;
}
private String createDummyClass (TreeLogger logger, GeneratorContext context) {
String packageName = "com.badlogic.gdx.backends.gwt.preloader";
String className = "PreloaderBundleImpl";
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
composer.addImplementedInterface(packageName + ".PreloaderBundle");
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter == null) {
return packageName + "." + className;
}
SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
sourceWriter.commit(logger);
return packageName + "." + className;
}
private static String fileNameWithMd5(FileWrapper fw, byte[] bytes) {
String md5;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
md5 = String.format("%032x", new BigInteger(1, digest.digest()));
} catch (NoSuchAlgorithmException e) {
// Fallback
md5 = String.valueOf(System.currentTimeMillis());
}
String nameWithMd5 = fw.nameWithoutExtension() + "-" + md5;
String extension = fw.extension();
if (!extension.isEmpty() || fw.name().endsWith(".")) {
nameWithMd5 = nameWithMd5 + "." + extension;
}
return nameWithMd5;
}
}
|
GWT PreloaderBundleGenerator don't use Apache Commons to calculate MD5 hash, relates to #4314 (#6173)
|
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/preloader/PreloaderBundleGenerator.java
|
GWT PreloaderBundleGenerator don't use Apache Commons to calculate MD5 hash, relates to #4314 (#6173)
|
|
Java
|
apache-2.0
|
a6c8ccbc99a9fc83cc5ddfcfd65f9c3c4d4e920c
| 0
|
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.facet.range;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleDocValuesField;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.facet.DrillDownQuery;
import org.apache.lucene.facet.DrillSideways;
import org.apache.lucene.facet.DrillSideways.DrillSidewaysResult;
import org.apache.lucene.facet.FacetField;
import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.Facets;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsConfig;
import org.apache.lucene.facet.LabelAndValue;
import org.apache.lucene.facet.MultiFacets;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.queries.function.valuesource.DoubleFieldSource;
import org.apache.lucene.queries.function.valuesource.FloatFieldSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
public class TestRangeFacetCounts extends FacetTestCase {
public void testBasicLong() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
field.setLongValue(l);
w.addDocument(doc);
}
// Also add Long.MAX_VALUE
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, true));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=22 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (1)\n",
result.toString());
r.close();
d.close();
}
public void testUselessRange() {
expectThrows(IllegalArgumentException.class, () -> {
new LongRange("useless", 7, true, 6, true);
});
expectThrows(IllegalArgumentException.class, () -> {
new LongRange("useless", 7, true, 7, false);
});
expectThrows(IllegalArgumentException.class, () -> {
new DoubleRange("useless", 7.0, true, 6.0, true);
});
expectThrows(IllegalArgumentException.class, () -> {
new DoubleRange("useless", 7.0, true, 7.0, false);
});
}
public void testLongMinMax() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
field.setLongValue(Long.MIN_VALUE);
w.addDocument(doc);
field.setLongValue(0);
w.addDocument(doc);
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("min", Long.MIN_VALUE, true, Long.MIN_VALUE, true),
new LongRange("max", Long.MAX_VALUE, true, Long.MAX_VALUE, true),
new LongRange("all0", Long.MIN_VALUE, true, Long.MAX_VALUE, true),
new LongRange("all1", Long.MIN_VALUE, false, Long.MAX_VALUE, true),
new LongRange("all2", Long.MIN_VALUE, true, Long.MAX_VALUE, false),
new LongRange("all3", Long.MIN_VALUE, false, Long.MAX_VALUE, false));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=3 childCount=6\n min (1)\n max (1)\n all0 (3)\n all1 (2)\n all2 (2)\n all3 (1)\n",
result.toString());
r.close();
d.close();
}
public void testOverlappedEndStart() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
field.setLongValue(l);
w.addDocument(doc);
}
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("0-10", 0L, true, 10L, true),
new LongRange("10-20", 10L, true, 20L, true),
new LongRange("20-30", 20L, true, 30L, true),
new LongRange("30-40", 30L, true, 40L, true));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=41 childCount=4\n 0-10 (11)\n 10-20 (11)\n 20-30 (11)\n 30-40 (11)\n",
result.toString());
r.close();
d.close();
}
/** Tests single request that mixes Range and non-Range
* faceting, with DrillSideways and taxonomy. */
public void testMixedRangeAndNonRangeTaxonomy() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Directory td = newDirectory();
DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
FacetsConfig config = new FacetsConfig();
for (long l = 0; l < 100; l++) {
Document doc = new Document();
// For computing range facet counts:
doc.add(new NumericDocValuesField("field", l));
// For drill down by numeric range:
doc.add(new LongPoint("field", l));
if ((l&3) == 0) {
doc.add(new FacetField("dim", "a"));
} else {
doc.add(new FacetField("dim", "b"));
}
w.addDocument(config.build(tw, doc));
}
final IndexReader r = w.getReader();
final TaxonomyReader tr = new DirectoryTaxonomyReader(tw);
IndexSearcher s = newSearcher(r, false);
if (VERBOSE) {
System.out.println("TEST: searcher=" + s);
}
DrillSideways ds = new DrillSideways(s, config, tr) {
@Override
protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
FacetsCollector dimFC = drillDowns;
FacetsCollector fieldFC = drillDowns;
if (drillSideways != null) {
for(int i=0;i<drillSideways.length;i++) {
String dim = drillSidewaysDims[i];
if (dim.equals("field")) {
fieldFC = drillSideways[i];
} else {
dimFC = drillSideways[i];
}
}
}
Map<String,Facets> byDim = new HashMap<>();
byDim.put("field",
new LongRangeFacetCounts("field", fieldFC,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false)));
byDim.put("dim", getTaxonomyFacetCounts(taxoReader, config, dimFC));
return new MultiFacets(byDim, null);
}
@Override
protected boolean scoreSubDocsAtOnce() {
return random().nextBoolean();
}
};
// First search, no drill downs:
DrillDownQuery ddq = new DrillDownQuery(config);
DrillSidewaysResult dsr = ds.search(null, ddq, 10);
assertEquals(100, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=100 childCount=2\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
// Second search, drill down on dim=b:
ddq = new DrillDownQuery(config);
ddq.add("dim", "b");
dsr = ds.search(null, ddq, 10);
assertEquals(75, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=100 childCount=2\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=16 childCount=5\n less than 10 (7)\n less than or equal to 10 (8)\n over 90 (7)\n 90 or above (8)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
// Third search, drill down on "less than or equal to 10":
ddq = new DrillDownQuery(config);
ddq.add("field", LongPoint.newRangeQuery("field", 0L, 10L));
dsr = ds.search(null, ddq, 10);
assertEquals(11, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=11 childCount=2\n b (8)\n a (3)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(tw, tr, td, r, d);
}
public void testBasicDouble() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
DoubleDocValuesField field = new DoubleDocValuesField("field", 0.0);
doc.add(field);
for(long l=0;l<100;l++) {
field.setDoubleValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new DoubleRangeFacetCounts("field", fc,
new DoubleRange("less than 10", 0.0, true, 10.0, false),
new DoubleRange("less than or equal to 10", 0.0, true, 10.0, true),
new DoubleRange("over 90", 90.0, false, 100.0, false),
new DoubleRange("90 or above", 90.0, true, 100.0, false),
new DoubleRange("over 1000", 1000.0, false, Double.POSITIVE_INFINITY, false));
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
public void testBasicFloat() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
FloatDocValuesField field = new FloatDocValuesField("field", 0.0f);
doc.add(field);
for(long l=0;l<100;l++) {
field.setFloatValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new DoubleRangeFacetCounts("field", new FloatFieldSource("field"), fc,
new DoubleRange("less than 10", 0.0f, true, 10.0f, false),
new DoubleRange("less than or equal to 10", 0.0f, true, 10.0f, true),
new DoubleRange("over 90", 90.0f, false, 100.0f, false),
new DoubleRange("90 or above", 90.0f, true, 100.0f, false),
new DoubleRange("over 1000", 1000.0f, false, Double.POSITIVE_INFINITY, false));
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
public void testRandomLongs() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs);
}
long[] values = new long[numDocs];
long minValue = Long.MAX_VALUE;
long maxValue = Long.MIN_VALUE;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
long v = random().nextLong();
values[i] = v;
doc.add(new NumericDocValuesField("field", v));
doc.add(new LongPoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 100);
LongRange[] ranges = new LongRange[numRange];
int[] expectedCounts = new int[numRange];
long minAcceptedValue = Long.MAX_VALUE;
long maxAcceptedValue = Long.MIN_VALUE;
for(int rangeID=0;rangeID<numRange;rangeID++) {
long min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
LongRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextLong();
}
long max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
LongRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextLong();
}
if (min > max) {
long x = min;
min = max;
max = x;
}
boolean minIncl;
boolean maxIncl;
// NOTE: max - min >= 0 is here to handle the common overflow case!
if (max - min >= 0 && max - min < 2) {
// If max == min or max == min+1, we always do inclusive, else we might pass an empty range and hit exc from LongRange's ctor:
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
ranges[rangeID] = new LongRange("r" + rangeID, min, minIncl, max, maxIncl);
if (VERBOSE) {
System.out.println(" range " + rangeID + ": " + ranges[rangeID]);
}
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchQuery;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchQuery = LongPoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchQuery = LongPoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchQuery = null;
}
ValueSource vs = new LongFieldSource("field");
Facets facets = new LongRangeFacetCounts("field", vs, sfc, fastMatchQuery, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
LongRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
ddq.add("field", LongPoint.newRangeQuery("field", range.min, range.max));
} else {
ddq.add("field", range.getQuery(fastMatchQuery, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
public void testRandomFloats() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
float[] values = new float[numDocs];
float minValue = Float.POSITIVE_INFINITY;
float maxValue = Float.NEGATIVE_INFINITY;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
float v = random().nextFloat();
values[i] = v;
doc.add(new FloatDocValuesField("field", v));
doc.add(new FloatPoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 5);
DoubleRange[] ranges = new DoubleRange[numRange];
int[] expectedCounts = new int[numRange];
float minAcceptedValue = Float.POSITIVE_INFINITY;
float maxAcceptedValue = Float.NEGATIVE_INFINITY;
boolean[] rangeMinIncl = new boolean[numRange];
boolean[] rangeMaxIncl = new boolean[numRange];
if (VERBOSE) {
System.out.println("TEST: " + numRange + " ranges");
}
for(int rangeID=0;rangeID<numRange;rangeID++) {
double min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextDouble();
}
double max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextDouble();
}
if (min > max) {
double x = min;
min = max;
max = x;
}
// Must truncate to float precision so that the
// drill-down counts (which use NRQ.newFloatRange)
// are correct:
min = (float) min;
max = (float) max;
boolean minIncl;
boolean maxIncl;
if (min == max) {
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
rangeMinIncl[rangeID] = minIncl;
rangeMaxIncl[rangeID] = maxIncl;
ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
if (VERBOSE) {
System.out.println("TEST: range " + rangeID + ": " + ranges[rangeID]);
}
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (VERBOSE) {
System.out.println("TEST: check doc=" + i + " val=" + values[i] + " accept=" + accept);
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchQuery;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchQuery = FloatPoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchQuery = FloatPoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchQuery = null;
}
ValueSource vs = new FloatFieldSource("field");
Facets facets = new DoubleRangeFacetCounts("field", vs, sfc, fastMatchQuery, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println("TEST: verify range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
DoubleRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
// We must do the nextUp/down in float space, here, because the nextUp that DoubleRange did in double space, when cast back to float,
// in fact does nothing!
float minFloat = (float) range.min;
if (rangeMinIncl[rangeID] == false) {
minFloat = Math.nextUp(minFloat);
}
float maxFloat = (float) range.max;
if (rangeMaxIncl[rangeID] == false) {
maxFloat = Math.nextAfter(maxFloat, Float.NEGATIVE_INFINITY);
}
ddq.add("field", FloatPoint.newRangeQuery("field", minFloat, maxFloat));
} else {
ddq.add("field", range.getQuery(fastMatchQuery, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
public void testRandomDoubles() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
double[] values = new double[numDocs];
double minValue = Double.POSITIVE_INFINITY;
double maxValue = Double.NEGATIVE_INFINITY;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
double v = random().nextDouble();
values[i] = v;
doc.add(new DoubleDocValuesField("field", v));
doc.add(new DoublePoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 5);
DoubleRange[] ranges = new DoubleRange[numRange];
int[] expectedCounts = new int[numRange];
double minAcceptedValue = Double.POSITIVE_INFINITY;
double maxAcceptedValue = Double.NEGATIVE_INFINITY;
for(int rangeID=0;rangeID<numRange;rangeID++) {
double min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextDouble();
}
double max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextDouble();
}
if (min > max) {
double x = min;
min = max;
max = x;
}
boolean minIncl;
boolean maxIncl;
if (min == max) {
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchFilter;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchFilter = DoublePoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchFilter = DoublePoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchFilter = null;
}
ValueSource vs = new DoubleFieldSource("field");
Facets facets = new DoubleRangeFacetCounts("field", vs, sfc, fastMatchFilter, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
DoubleRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
ddq.add("field", DoublePoint.newRangeQuery("field", range.min, range.max));
} else {
ddq.add("field", range.getQuery(fastMatchFilter, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
// LUCENE-5178
public void testMissingValues() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
if (l % 5 == 0) {
// Every 5th doc is missing the value:
w.addDocument(new Document());
continue;
}
field.setLongValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false));
assertEquals("dim=field path=[] value=16 childCount=5\n less than 10 (8)\n less than or equal to 10 (8)\n over 90 (8)\n 90 or above (8)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
private static class UsedQuery extends Query {
private final AtomicBoolean used;
private final Query in;
UsedQuery(Query in, AtomicBoolean used) {
this.in = in;
this.used = used;
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj) == false) {
return false;
}
UsedQuery that = (UsedQuery) obj;
return in.equals(that.in);
}
@Override
public int hashCode() {
return 31 * super.hashCode() + in.hashCode();
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query inRewritten = in.rewrite(reader);
if (in != inRewritten) {
return new UsedQuery(inRewritten, used);
}
return super.rewrite(reader);
}
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
final Weight in = this.in.createWeight(searcher, needsScores);
return new Weight(in.getQuery()) {
@Override
public void extractTerms(Set<Term> terms) {
in.extractTerms(terms);
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
return in.explain(context, doc);
}
@Override
public float getValueForNormalization() throws IOException {
return in.getValueForNormalization();
}
@Override
public void normalize(float norm, float topLevelBoost) {
in.normalize(norm, topLevelBoost);
}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
used.set(true);
return in.scorer(context);
}
};
}
@Override
public String toString(String field) {
return "UsedQuery(" + in + ")";
}
}
public void testCustomDoublesValueSource() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
writer.addDocument(doc);
writer.addDocument(doc);
writer.addDocument(doc);
// Test wants 3 docs in one segment:
writer.forceMerge(1);
final ValueSource vs = new ValueSource() {
@SuppressWarnings("rawtypes")
@Override
public FunctionValues getValues(Map ignored, LeafReaderContext ignored2) {
return new DoubleDocValues(null) {
@Override
public double doubleVal(int doc) {
return doc+1;
}
};
}
@Override
public boolean equals(Object o) {
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String description() {
throw new UnsupportedOperationException();
}
};
FacetsConfig config = new FacetsConfig();
FacetsCollector fc = new FacetsCollector();
IndexReader r = writer.getReader();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
final DoubleRange[] ranges = new DoubleRange[] {
new DoubleRange("< 1", 0.0, true, 1.0, false),
new DoubleRange("< 2", 0.0, true, 2.0, false),
new DoubleRange("< 5", 0.0, true, 5.0, false),
new DoubleRange("< 10", 0.0, true, 10.0, false),
new DoubleRange("< 20", 0.0, true, 20.0, false),
new DoubleRange("< 50", 0.0, true, 50.0, false)};
final Query fastMatchFilter;
final AtomicBoolean filterWasUsed = new AtomicBoolean();
if (random().nextBoolean()) {
// Sort of silly:
final Query in = new MatchAllDocsQuery();
fastMatchFilter = new UsedQuery(in, filterWasUsed);
} else {
fastMatchFilter = null;
}
if (VERBOSE) {
System.out.println("TEST: fastMatchFilter=" + fastMatchFilter);
}
Facets facets = new DoubleRangeFacetCounts("field", vs, fc, fastMatchFilter, ranges);
assertEquals("dim=field path=[] value=3 childCount=6\n < 1 (0)\n < 2 (1)\n < 5 (3)\n < 10 (3)\n < 20 (3)\n < 50 (3)\n", facets.getTopChildren(10, "field").toString());
assertTrue(fastMatchFilter == null || filterWasUsed.get());
DrillDownQuery ddq = new DrillDownQuery(config);
ddq.add("field", ranges[1].getQuery(fastMatchFilter, vs));
// Test simple drill-down:
assertEquals(1, s.search(ddq, 10).totalHits);
// Test drill-sideways after drill-down
DrillSideways ds = new DrillSideways(s, config, (TaxonomyReader) null) {
@Override
protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
assert drillSideways.length == 1;
return new DoubleRangeFacetCounts("field", vs, drillSideways[0], fastMatchFilter, ranges);
}
@Override
protected boolean scoreSubDocsAtOnce() {
return random().nextBoolean();
}
};
DrillSidewaysResult dsr = ds.search(ddq, 10);
assertEquals(1, dsr.hits.totalHits);
assertEquals("dim=field path=[] value=3 childCount=6\n < 1 (0)\n < 2 (1)\n < 5 (3)\n < 10 (3)\n < 20 (3)\n < 50 (3)\n",
dsr.facets.getTopChildren(10, "field").toString());
writer.close();
IOUtils.close(r, dir);
}
}
|
lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.facet.range;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleDocValuesField;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.facet.DrillDownQuery;
import org.apache.lucene.facet.DrillSideways;
import org.apache.lucene.facet.DrillSideways.DrillSidewaysResult;
import org.apache.lucene.facet.FacetField;
import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.facet.FacetTestCase;
import org.apache.lucene.facet.Facets;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsConfig;
import org.apache.lucene.facet.LabelAndValue;
import org.apache.lucene.facet.MultiFacets;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.queries.function.valuesource.DoubleFieldSource;
import org.apache.lucene.queries.function.valuesource.FloatFieldSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.TestUtil;
public class TestRangeFacetCounts extends FacetTestCase {
public void testBasicLong() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
field.setLongValue(l);
w.addDocument(doc);
}
// Also add Long.MAX_VALUE
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, true));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=22 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (1)\n",
result.toString());
r.close();
d.close();
}
public void testUselessRange() {
expectThrows(IllegalArgumentException.class, () -> {
new LongRange("useless", 7, true, 6, true);
});
expectThrows(IllegalArgumentException.class, () -> {
new LongRange("useless", 7, true, 7, false);
});
expectThrows(IllegalArgumentException.class, () -> {
new DoubleRange("useless", 7.0, true, 6.0, true);
});
expectThrows(IllegalArgumentException.class, () -> {
new DoubleRange("useless", 7.0, true, 7.0, false);
});
}
public void testLongMinMax() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
field.setLongValue(Long.MIN_VALUE);
w.addDocument(doc);
field.setLongValue(0);
w.addDocument(doc);
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("min", Long.MIN_VALUE, true, Long.MIN_VALUE, true),
new LongRange("max", Long.MAX_VALUE, true, Long.MAX_VALUE, true),
new LongRange("all0", Long.MIN_VALUE, true, Long.MAX_VALUE, true),
new LongRange("all1", Long.MIN_VALUE, false, Long.MAX_VALUE, true),
new LongRange("all2", Long.MIN_VALUE, true, Long.MAX_VALUE, false),
new LongRange("all3", Long.MIN_VALUE, false, Long.MAX_VALUE, false));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=3 childCount=6\n min (1)\n max (1)\n all0 (3)\n all1 (2)\n all2 (2)\n all3 (1)\n",
result.toString());
r.close();
d.close();
}
public void testOverlappedEndStart() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
field.setLongValue(l);
w.addDocument(doc);
}
field.setLongValue(Long.MAX_VALUE);
w.addDocument(doc);
IndexReader r = w.getReader();
w.close();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("0-10", 0L, true, 10L, true),
new LongRange("10-20", 10L, true, 20L, true),
new LongRange("20-30", 20L, true, 30L, true),
new LongRange("30-40", 30L, true, 40L, true));
FacetResult result = facets.getTopChildren(10, "field");
assertEquals("dim=field path=[] value=41 childCount=4\n 0-10 (11)\n 10-20 (11)\n 20-30 (11)\n 30-40 (11)\n",
result.toString());
r.close();
d.close();
}
/** Tests single request that mixes Range and non-Range
* faceting, with DrillSideways and taxonomy. */
public void testMixedRangeAndNonRangeTaxonomy() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Directory td = newDirectory();
DirectoryTaxonomyWriter tw = new DirectoryTaxonomyWriter(td, IndexWriterConfig.OpenMode.CREATE);
FacetsConfig config = new FacetsConfig();
for (long l = 0; l < 100; l++) {
Document doc = new Document();
// For computing range facet counts:
doc.add(new NumericDocValuesField("field", l));
// For drill down by numeric range:
doc.add(new LongPoint("field", l));
if ((l&3) == 0) {
doc.add(new FacetField("dim", "a"));
} else {
doc.add(new FacetField("dim", "b"));
}
w.addDocument(config.build(tw, doc));
}
final IndexReader r = w.getReader();
final TaxonomyReader tr = new DirectoryTaxonomyReader(tw);
IndexSearcher s = newSearcher(r, false);
if (VERBOSE) {
System.out.println("TEST: searcher=" + s);
}
DrillSideways ds = new DrillSideways(s, config, tr) {
@Override
protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
FacetsCollector dimFC = drillDowns;
FacetsCollector fieldFC = drillDowns;
if (drillSideways != null) {
for(int i=0;i<drillSideways.length;i++) {
String dim = drillSidewaysDims[i];
if (dim.equals("field")) {
fieldFC = drillSideways[i];
} else {
dimFC = drillSideways[i];
}
}
}
Map<String,Facets> byDim = new HashMap<>();
byDim.put("field",
new LongRangeFacetCounts("field", fieldFC,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false)));
byDim.put("dim", getTaxonomyFacetCounts(taxoReader, config, dimFC));
return new MultiFacets(byDim, null);
}
@Override
protected boolean scoreSubDocsAtOnce() {
return random().nextBoolean();
}
};
// First search, no drill downs:
DrillDownQuery ddq = new DrillDownQuery(config);
DrillSidewaysResult dsr = ds.search(null, ddq, 10);
assertEquals(100, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=100 childCount=2\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
// Second search, drill down on dim=b:
ddq = new DrillDownQuery(config);
ddq.add("dim", "b");
dsr = ds.search(null, ddq, 10);
assertEquals(75, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=100 childCount=2\n b (75)\n a (25)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=16 childCount=5\n less than 10 (7)\n less than or equal to 10 (8)\n over 90 (7)\n 90 or above (8)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
// Third search, drill down on "less than or equal to 10":
ddq = new DrillDownQuery(config);
ddq.add("field", LongPoint.newRangeQuery("field", 0L, 10L));
dsr = ds.search(null, ddq, 10);
assertEquals(11, dsr.hits.totalHits);
assertEquals("dim=dim path=[] value=11 childCount=2\n b (8)\n a (3)\n", dsr.facets.getTopChildren(10, "dim").toString());
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
dsr.facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(tw, tr, td, r, d);
}
public void testBasicDouble() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
DoubleDocValuesField field = new DoubleDocValuesField("field", 0.0);
doc.add(field);
for(long l=0;l<100;l++) {
field.setDoubleValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new DoubleRangeFacetCounts("field", fc,
new DoubleRange("less than 10", 0.0, true, 10.0, false),
new DoubleRange("less than or equal to 10", 0.0, true, 10.0, true),
new DoubleRange("over 90", 90.0, false, 100.0, false),
new DoubleRange("90 or above", 90.0, true, 100.0, false),
new DoubleRange("over 1000", 1000.0, false, Double.POSITIVE_INFINITY, false));
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
public void testBasicFloat() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
FloatDocValuesField field = new FloatDocValuesField("field", 0.0f);
doc.add(field);
for(long l=0;l<100;l++) {
field.setFloatValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new DoubleRangeFacetCounts("field", new FloatFieldSource("field"), fc,
new DoubleRange("less than 10", 0.0f, true, 10.0f, false),
new DoubleRange("less than or equal to 10", 0.0f, true, 10.0f, true),
new DoubleRange("over 90", 90.0f, false, 100.0f, false),
new DoubleRange("90 or above", 90.0f, true, 100.0f, false),
new DoubleRange("over 1000", 1000.0f, false, Double.POSITIVE_INFINITY, false));
assertEquals("dim=field path=[] value=21 childCount=5\n less than 10 (10)\n less than or equal to 10 (11)\n over 90 (9)\n 90 or above (10)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
public void testRandomLongs() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs);
}
long[] values = new long[numDocs];
long minValue = Long.MAX_VALUE;
long maxValue = Long.MIN_VALUE;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
long v = random().nextLong();
values[i] = v;
doc.add(new NumericDocValuesField("field", v));
doc.add(new LongPoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 100);
LongRange[] ranges = new LongRange[numRange];
int[] expectedCounts = new int[numRange];
long minAcceptedValue = Long.MAX_VALUE;
long maxAcceptedValue = Long.MIN_VALUE;
for(int rangeID=0;rangeID<numRange;rangeID++) {
long min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
LongRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextLong();
}
long max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
LongRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextLong();
}
if (min > max) {
long x = min;
min = max;
max = x;
}
boolean minIncl;
boolean maxIncl;
// NOTE: max - min >= 0 is here to handle the common overflow case!
if (max - min >= 0 && max - min < 2) {
// If max == min or max == min+1, we always do inclusive, else we might pass an empty range and hit exc from LongRange's ctor:
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
ranges[rangeID] = new LongRange("r" + rangeID, min, minIncl, max, maxIncl);
if (VERBOSE) {
System.out.println(" range " + rangeID + ": " + ranges[rangeID]);
}
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchQuery;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchQuery = LongPoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchQuery = LongPoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchQuery = null;
}
ValueSource vs = new LongFieldSource("field");
Facets facets = new LongRangeFacetCounts("field", vs, sfc, fastMatchQuery, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
LongRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
ddq.add("field", LongPoint.newRangeQuery("field", range.min, range.max));
} else {
ddq.add("field", range.getQuery(fastMatchQuery, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
public void testRandomFloats() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
float[] values = new float[numDocs];
float minValue = Float.POSITIVE_INFINITY;
float maxValue = Float.NEGATIVE_INFINITY;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
float v = random().nextFloat();
values[i] = v;
doc.add(new FloatDocValuesField("field", v));
doc.add(new FloatPoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 5);
DoubleRange[] ranges = new DoubleRange[numRange];
int[] expectedCounts = new int[numRange];
float minAcceptedValue = Float.POSITIVE_INFINITY;
float maxAcceptedValue = Float.NEGATIVE_INFINITY;
if (VERBOSE) {
System.out.println("TEST: " + numRange + " ranges");
}
for(int rangeID=0;rangeID<numRange;rangeID++) {
double min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextDouble();
}
double max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextDouble();
}
if (min > max) {
double x = min;
min = max;
max = x;
}
// Must truncate to float precision so that the
// drill-down counts (which use NRQ.newFloatRange)
// are correct:
min = (float) min;
max = (float) max;
boolean minIncl;
boolean maxIncl;
if (min == max) {
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
if (VERBOSE) {
System.out.println("TEST: range " + rangeID + ": " + ranges[rangeID]);
}
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (VERBOSE) {
System.out.println("TEST: check doc=" + i + " val=" + values[i] + " accept=" + accept);
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchQuery;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchQuery = FloatPoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchQuery = FloatPoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchQuery = null;
}
ValueSource vs = new FloatFieldSource("field");
Facets facets = new DoubleRangeFacetCounts("field", vs, sfc, fastMatchQuery, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println("TEST: verify range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
DoubleRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
ddq.add("field", FloatPoint.newRangeQuery("field", (float) range.min, (float) range.max));
} else {
ddq.add("field", range.getQuery(fastMatchQuery, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
public void testRandomDoubles() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), dir);
int numDocs = atLeast(1000);
double[] values = new double[numDocs];
double minValue = Double.POSITIVE_INFINITY;
double maxValue = Double.NEGATIVE_INFINITY;
for(int i=0;i<numDocs;i++) {
Document doc = new Document();
double v = random().nextDouble();
values[i] = v;
doc.add(new DoubleDocValuesField("field", v));
doc.add(new DoublePoint("field", v));
w.addDocument(doc);
minValue = Math.min(minValue, v);
maxValue = Math.max(maxValue, v);
}
IndexReader r = w.getReader();
IndexSearcher s = newSearcher(r, false);
FacetsConfig config = new FacetsConfig();
int numIters = atLeast(10);
for(int iter=0;iter<numIters;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
int numRange = TestUtil.nextInt(random(), 1, 5);
DoubleRange[] ranges = new DoubleRange[numRange];
int[] expectedCounts = new int[numRange];
double minAcceptedValue = Double.POSITIVE_INFINITY;
double maxAcceptedValue = Double.NEGATIVE_INFINITY;
for(int rangeID=0;rangeID<numRange;rangeID++) {
double min;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
min = prevRange.min;
} else {
min = prevRange.max;
}
} else {
min = random().nextDouble();
}
double max;
if (rangeID > 0 && random().nextInt(10) == 7) {
// Use an existing boundary:
DoubleRange prevRange = ranges[random().nextInt(rangeID)];
if (random().nextBoolean()) {
max = prevRange.min;
} else {
max = prevRange.max;
}
} else {
max = random().nextDouble();
}
if (min > max) {
double x = min;
min = max;
max = x;
}
boolean minIncl;
boolean maxIncl;
if (min == max) {
minIncl = true;
maxIncl = true;
} else {
minIncl = random().nextBoolean();
maxIncl = random().nextBoolean();
}
ranges[rangeID] = new DoubleRange("r" + rangeID, min, minIncl, max, maxIncl);
// Do "slow but hopefully correct" computation of
// expected count:
for(int i=0;i<numDocs;i++) {
boolean accept = true;
if (minIncl) {
accept &= values[i] >= min;
} else {
accept &= values[i] > min;
}
if (maxIncl) {
accept &= values[i] <= max;
} else {
accept &= values[i] < max;
}
if (accept) {
expectedCounts[rangeID]++;
minAcceptedValue = Math.min(minAcceptedValue, values[i]);
maxAcceptedValue = Math.max(maxAcceptedValue, values[i]);
}
}
}
FacetsCollector sfc = new FacetsCollector();
s.search(new MatchAllDocsQuery(), sfc);
Query fastMatchFilter;
if (random().nextBoolean()) {
if (random().nextBoolean()) {
fastMatchFilter = DoublePoint.newRangeQuery("field", minValue, maxValue);
} else {
fastMatchFilter = DoublePoint.newRangeQuery("field", minAcceptedValue, maxAcceptedValue);
}
} else {
fastMatchFilter = null;
}
ValueSource vs = new DoubleFieldSource("field");
Facets facets = new DoubleRangeFacetCounts("field", vs, sfc, fastMatchFilter, ranges);
FacetResult result = facets.getTopChildren(10, "field");
assertEquals(numRange, result.labelValues.length);
for(int rangeID=0;rangeID<numRange;rangeID++) {
if (VERBOSE) {
System.out.println(" range " + rangeID + " expectedCount=" + expectedCounts[rangeID]);
}
LabelAndValue subNode = result.labelValues[rangeID];
assertEquals("r" + rangeID, subNode.label);
assertEquals(expectedCounts[rangeID], subNode.value.intValue());
DoubleRange range = ranges[rangeID];
// Test drill-down:
DrillDownQuery ddq = new DrillDownQuery(config);
if (random().nextBoolean()) {
ddq.add("field", DoublePoint.newRangeQuery("field", range.min, range.max));
} else {
ddq.add("field", range.getQuery(fastMatchFilter, vs));
}
assertEquals(expectedCounts[rangeID], s.search(ddq, 10).totalHits);
}
}
w.close();
IOUtils.close(r, dir);
}
// LUCENE-5178
public void testMissingValues() throws Exception {
Directory d = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d);
Document doc = new Document();
NumericDocValuesField field = new NumericDocValuesField("field", 0L);
doc.add(field);
for(long l=0;l<100;l++) {
if (l % 5 == 0) {
// Every 5th doc is missing the value:
w.addDocument(new Document());
continue;
}
field.setLongValue(l);
w.addDocument(doc);
}
IndexReader r = w.getReader();
FacetsCollector fc = new FacetsCollector();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
Facets facets = new LongRangeFacetCounts("field", fc,
new LongRange("less than 10", 0L, true, 10L, false),
new LongRange("less than or equal to 10", 0L, true, 10L, true),
new LongRange("over 90", 90L, false, 100L, false),
new LongRange("90 or above", 90L, true, 100L, false),
new LongRange("over 1000", 1000L, false, Long.MAX_VALUE, false));
assertEquals("dim=field path=[] value=16 childCount=5\n less than 10 (8)\n less than or equal to 10 (8)\n over 90 (8)\n 90 or above (8)\n over 1000 (0)\n",
facets.getTopChildren(10, "field").toString());
w.close();
IOUtils.close(r, d);
}
private static class UsedQuery extends Query {
private final AtomicBoolean used;
private final Query in;
UsedQuery(Query in, AtomicBoolean used) {
this.in = in;
this.used = used;
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj) == false) {
return false;
}
UsedQuery that = (UsedQuery) obj;
return in.equals(that.in);
}
@Override
public int hashCode() {
return 31 * super.hashCode() + in.hashCode();
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
final Query inRewritten = in.rewrite(reader);
if (in != inRewritten) {
return new UsedQuery(inRewritten, used);
}
return super.rewrite(reader);
}
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
final Weight in = this.in.createWeight(searcher, needsScores);
return new Weight(in.getQuery()) {
@Override
public void extractTerms(Set<Term> terms) {
in.extractTerms(terms);
}
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
return in.explain(context, doc);
}
@Override
public float getValueForNormalization() throws IOException {
return in.getValueForNormalization();
}
@Override
public void normalize(float norm, float topLevelBoost) {
in.normalize(norm, topLevelBoost);
}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
used.set(true);
return in.scorer(context);
}
};
}
@Override
public String toString(String field) {
return "UsedQuery(" + in + ")";
}
}
public void testCustomDoublesValueSource() throws Exception {
Directory dir = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
Document doc = new Document();
writer.addDocument(doc);
writer.addDocument(doc);
writer.addDocument(doc);
// Test wants 3 docs in one segment:
writer.forceMerge(1);
final ValueSource vs = new ValueSource() {
@SuppressWarnings("rawtypes")
@Override
public FunctionValues getValues(Map ignored, LeafReaderContext ignored2) {
return new DoubleDocValues(null) {
@Override
public double doubleVal(int doc) {
return doc+1;
}
};
}
@Override
public boolean equals(Object o) {
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String description() {
throw new UnsupportedOperationException();
}
};
FacetsConfig config = new FacetsConfig();
FacetsCollector fc = new FacetsCollector();
IndexReader r = writer.getReader();
IndexSearcher s = newSearcher(r);
s.search(new MatchAllDocsQuery(), fc);
final DoubleRange[] ranges = new DoubleRange[] {
new DoubleRange("< 1", 0.0, true, 1.0, false),
new DoubleRange("< 2", 0.0, true, 2.0, false),
new DoubleRange("< 5", 0.0, true, 5.0, false),
new DoubleRange("< 10", 0.0, true, 10.0, false),
new DoubleRange("< 20", 0.0, true, 20.0, false),
new DoubleRange("< 50", 0.0, true, 50.0, false)};
final Query fastMatchFilter;
final AtomicBoolean filterWasUsed = new AtomicBoolean();
if (random().nextBoolean()) {
// Sort of silly:
final Query in = new MatchAllDocsQuery();
fastMatchFilter = new UsedQuery(in, filterWasUsed);
} else {
fastMatchFilter = null;
}
if (VERBOSE) {
System.out.println("TEST: fastMatchFilter=" + fastMatchFilter);
}
Facets facets = new DoubleRangeFacetCounts("field", vs, fc, fastMatchFilter, ranges);
assertEquals("dim=field path=[] value=3 childCount=6\n < 1 (0)\n < 2 (1)\n < 5 (3)\n < 10 (3)\n < 20 (3)\n < 50 (3)\n", facets.getTopChildren(10, "field").toString());
assertTrue(fastMatchFilter == null || filterWasUsed.get());
DrillDownQuery ddq = new DrillDownQuery(config);
ddq.add("field", ranges[1].getQuery(fastMatchFilter, vs));
// Test simple drill-down:
assertEquals(1, s.search(ddq, 10).totalHits);
// Test drill-sideways after drill-down
DrillSideways ds = new DrillSideways(s, config, (TaxonomyReader) null) {
@Override
protected Facets buildFacetsResult(FacetsCollector drillDowns, FacetsCollector[] drillSideways, String[] drillSidewaysDims) throws IOException {
assert drillSideways.length == 1;
return new DoubleRangeFacetCounts("field", vs, drillSideways[0], fastMatchFilter, ranges);
}
@Override
protected boolean scoreSubDocsAtOnce() {
return random().nextBoolean();
}
};
DrillSidewaysResult dsr = ds.search(ddq, 10);
assertEquals(1, dsr.hits.totalHits);
assertEquals("dim=field path=[] value=3 childCount=6\n < 1 (0)\n < 2 (1)\n < 5 (3)\n < 10 (3)\n < 20 (3)\n < 50 (3)\n",
dsr.facets.getTopChildren(10, "field").toString());
writer.close();
IOUtils.close(r, dir);
}
}
|
fix random float test to do the +/- 1 ulp in float space
|
lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java
|
fix random float test to do the +/- 1 ulp in float space
|
|
Java
|
bsd-2-clause
|
1d19356cb9f2d8e9b72a129e5719cca45d89821f
| 0
|
jenkinsci/p4-plugin,jenkinsci/p4-plugin,jenkinsci/p4-plugin
|
package org.jenkinsci.plugins.p4.changes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import org.jenkinsci.plugins.p4.client.ConnectionHelper;
import org.jenkinsci.plugins.p4.email.P4UserProperty;
import org.kohsuke.stapler.export.Exported;
import com.perforce.p4java.core.ChangelistStatus;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.IFix;
import com.perforce.p4java.core.file.FileAction;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.impl.generic.core.Label;
import hudson.model.User;
import hudson.scm.ChangeLogSet;
import hudson.tasks.Mailer.UserProperty;
public class P4ChangeEntry extends ChangeLogSet.Entry {
private static Logger logger = Logger.getLogger(P4ChangeEntry.class.getName());
private int FILE_COUNT_LIMIT = 50;
private P4Revision id;
private User author;
private Date date = new Date();
private String clientId = "";
private String msg = "";
private Collection<String> affectedPaths;
private boolean shelved;
private boolean fileLimit = false;
public List<IFileSpec> files;
public List<IFix> jobs;
public P4ChangeEntry(P4ChangeSet parent) {
super();
setParent(parent);
files = new ArrayList<IFileSpec>();
jobs = new ArrayList<IFix>();
affectedPaths = new ArrayList<String>();
}
public P4ChangeEntry() {
}
public void setChange(ConnectionHelper p4, IChangelistSummary changelist) throws Exception {
// set id
int changeId = changelist.getId();
id = new P4Revision(changeId);
// set author
String user = changelist.getUsername();
author = User.get(user);
// set email property on user
String email = p4.getEmail(user);
if (email != null && !email.isEmpty()) {
P4UserProperty p4prop = new P4UserProperty(email);
author.addProperty(p4prop);
logger.fine("Setting email for user: " + user + ":" + email);
// Set default email for Jenkins user if not defined
UserProperty prop = author.getProperty(UserProperty.class);
if( prop == null || prop.getAddress() == null || prop.getAddress().isEmpty()) {
prop = new UserProperty(email);
author.addProperty(prop);
logger.fine("Setting default user: " + user + ":" + email);
}
}
// set date of change
date = changelist.getDate();
// set client id
clientId = changelist.getClientId();
// set display message
msg = changelist.getDescription();
// set list of file revisions in change
if (changelist.getStatus() == ChangelistStatus.PENDING) {
files = p4.getShelvedFiles(changeId);
shelved = true;
} else {
files = p4.getChangeFiles(changeId, FILE_COUNT_LIMIT + 1);
shelved = false;
}
if (files.size() > FILE_COUNT_LIMIT) {
fileLimit = true;
files = files.subList(0, FILE_COUNT_LIMIT);
}
// set list of affected paths
affectedPaths = new ArrayList<String>();
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
// set list of jobs in change
this.jobs = p4.getJobs(changeId);
}
public void setLabel(ConnectionHelper p4, String labelId) throws Exception {
Label label = (Label) p4.getLabel(labelId);
// set id
id = new P4Revision(labelId);
// set author
String user = label.getOwnerName();
user = (user != null && !user.isEmpty()) ? user : "unknown";
author = User.get(user);
// set date of change
date = label.getLastAccess();
// set client id
clientId = labelId;
// set display message
msg = label.getDescription();
// set list of file revisions in change
files = p4.getLabelFiles(labelId, FILE_COUNT_LIMIT + 1);
if (files.size() > FILE_COUNT_LIMIT) {
fileLimit = true;
files = files.subList(0, FILE_COUNT_LIMIT);
}
// set list of affected paths
affectedPaths = new ArrayList<String>();
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
}
@Exported
public String getChangeNumber() {
return id.toString();
}
@Exported
public String getChangeTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
public P4Revision getId() {
return id;
}
public void setId(P4Revision value) {
id = value;
}
@Override
public User getAuthor() {
// JENKINS-31169
if (author == null) {
return User.getUnknown();
}
return author;
}
public void setAuthor(String value) {
author = User.get(value);
}
public Date getDate() {
return date;
}
public void setDate(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = sdf.parse(value);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setClientId(String value) {
clientId = value;
}
public String getClientId() {
return clientId;
}
@Override
public String getMsg() {
return msg;
}
public void setMsg(String value) {
msg = value;
}
@Override
public Collection<String> getAffectedPaths() {
// JENKINS-31306
if (affectedPaths.size() < 1 && files != null && files.size() > 0) {
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
}
return affectedPaths;
}
public boolean isFileLimit() {
return fileLimit;
}
public List<IFileSpec> getFiles() {
return files;
}
public String getAction(IFileSpec file) {
FileAction action = file.getAction();
String s = action.name();
return s.replace("/", "_");
}
public void setShelved(boolean value) {
shelved = value;
}
public boolean isShelved() {
return shelved;
}
public boolean isLabel() {
return id.isLabel();
}
public List<IFix> getJobs() {
return jobs;
}
public String getJobStatus(IFix job) {
String status = job.getStatus();
return status;
}
public int getMaxLimit() {
return FILE_COUNT_LIMIT;
}
}
|
src/main/java/org/jenkinsci/plugins/p4/changes/P4ChangeEntry.java
|
package org.jenkinsci.plugins.p4.changes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import org.jenkinsci.plugins.p4.client.ConnectionHelper;
import org.jenkinsci.plugins.p4.email.P4UserProperty;
import org.kohsuke.stapler.export.Exported;
import com.perforce.p4java.core.ChangelistStatus;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.IFix;
import com.perforce.p4java.core.file.FileAction;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.impl.generic.core.Label;
import hudson.model.User;
import hudson.scm.ChangeLogSet;
public class P4ChangeEntry extends ChangeLogSet.Entry {
private static Logger logger = Logger.getLogger(P4ChangeEntry.class.getName());
private int FILE_COUNT_LIMIT = 50;
private P4Revision id;
private User author;
private Date date = new Date();
private String clientId = "";
private String msg = "";
private Collection<String> affectedPaths;
private boolean shelved;
private boolean fileLimit = false;
public List<IFileSpec> files;
public List<IFix> jobs;
public P4ChangeEntry(P4ChangeSet parent) {
super();
setParent(parent);
files = new ArrayList<IFileSpec>();
jobs = new ArrayList<IFix>();
affectedPaths = new ArrayList<String>();
}
public P4ChangeEntry() {
}
public void setChange(ConnectionHelper p4, IChangelistSummary changelist) throws Exception {
// set id
int changeId = changelist.getId();
id = new P4Revision(changeId);
// set author
String user = changelist.getUsername();
author = User.get(user);
// set email property on user
String email = p4.getEmail(user);
if (email != null && !email.isEmpty()) {
P4UserProperty p4prop = new P4UserProperty(email);
author.addProperty(p4prop);
logger.fine("Setting email for user: " + user + ":" + email);
}
// set date of change
date = changelist.getDate();
// set client id
clientId = changelist.getClientId();
// set display message
msg = changelist.getDescription();
// set list of file revisions in change
if (changelist.getStatus() == ChangelistStatus.PENDING) {
files = p4.getShelvedFiles(changeId);
shelved = true;
} else {
files = p4.getChangeFiles(changeId, FILE_COUNT_LIMIT + 1);
shelved = false;
}
if (files.size() > FILE_COUNT_LIMIT) {
fileLimit = true;
files = files.subList(0, FILE_COUNT_LIMIT);
}
// set list of affected paths
affectedPaths = new ArrayList<String>();
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
// set list of jobs in change
this.jobs = p4.getJobs(changeId);
}
public void setLabel(ConnectionHelper p4, String labelId) throws Exception {
Label label = (Label) p4.getLabel(labelId);
// set id
id = new P4Revision(labelId);
// set author
String user = label.getOwnerName();
user = (user != null && !user.isEmpty()) ? user : "unknown";
author = User.get(user);
// set date of change
date = label.getLastAccess();
// set client id
clientId = labelId;
// set display message
msg = label.getDescription();
// set list of file revisions in change
files = p4.getLabelFiles(labelId, FILE_COUNT_LIMIT + 1);
if (files.size() > FILE_COUNT_LIMIT) {
fileLimit = true;
files = files.subList(0, FILE_COUNT_LIMIT);
}
// set list of affected paths
affectedPaths = new ArrayList<String>();
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
}
@Exported
public String getChangeNumber() {
return id.toString();
}
@Exported
public String getChangeTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
public P4Revision getId() {
return id;
}
public void setId(P4Revision value) {
id = value;
}
@Override
public User getAuthor() {
// JENKINS-31169
if (author == null) {
return User.getUnknown();
}
return author;
}
public void setAuthor(String value) {
author = User.get(value);
}
public Date getDate() {
return date;
}
public void setDate(String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = sdf.parse(value);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setClientId(String value) {
clientId = value;
}
public String getClientId() {
return clientId;
}
@Override
public String getMsg() {
return msg;
}
public void setMsg(String value) {
msg = value;
}
@Override
public Collection<String> getAffectedPaths() {
// JENKINS-31306
if (affectedPaths.size() < 1 && files != null && files.size() > 0) {
for (IFileSpec item : files) {
affectedPaths.add(item.getDepotPathString());
}
}
return affectedPaths;
}
public boolean isFileLimit() {
return fileLimit;
}
public List<IFileSpec> getFiles() {
return files;
}
public String getAction(IFileSpec file) {
FileAction action = file.getAction();
String s = action.name();
return s.replace("/", "_");
}
public void setShelved(boolean value) {
shelved = value;
}
public boolean isShelved() {
return shelved;
}
public boolean isLabel() {
return id.isLabel();
}
public List<IFix> getJobs() {
return jobs;
}
public String getJobStatus(IFix job) {
String status = job.getStatus();
return status;
}
public int getMaxLimit() {
return FILE_COUNT_LIMIT;
}
}
|
Add Perforce email address if Jenkins User is undefined.
Other email plugins use P4UserProperty, but for if UserProperty is
undefined update this one too.
JENKINS-32879
|
src/main/java/org/jenkinsci/plugins/p4/changes/P4ChangeEntry.java
|
Add Perforce email address if Jenkins User is undefined.
|
|
Java
|
bsd-3-clause
|
2bb5cc6a6917580441ff8b544a01d765ab2442a3
| 0
|
naixx/threetenbp,naixx/threetenbp,pepyakin/threetenbp,pepyakin/threetenbp,jnehlmeier/threetenbp,ThreeTen/threetenbp,ThreeTen/threetenbp,jnehlmeier/threetenbp
|
/*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time;
import java.io.Serializable;
import java.util.TimeZone;
/**
* A clock providing access to the current instant, date and time using a time-zone.
* <p>
* Instances of this class are used to find the current instant, which can be
* interpreted using the stored time-zone to find the current date and time.
* As such, a clock can be used instead of {@link System#currentTimeMillis()}
* and {@link TimeZone#getDefault()}.
* <p>
* The primary purpose of this abstraction is to allow alternate clocks to be
* plugged in as and when required. Applications use an object to obtain the
* current time rather than a static method. This can simplify testing.
* <p>
* Applications should <i>avoid</i> using the static methods on this class.
* Instead, they should pass a {@code Clock} into any method that requires it.
* A dependency injection framework is one way to achieve this:
* <pre>
* public class MyBean {
* private Clock clock; // dependency inject
* ...
* public void process(LocalDate eventDate) {
* if (eventDate.isBefore(LocalDate.now(clock)) {
* ...
* }
* }
* }
* </pre>
* This approach allows an alternate clock, such as {@link #fixed} to be used during testing.
* <p>
* The {@code system} factory method provides clocks based on the best available system clock,
* such as {@code System.currentTimeMillis}.
*
* <h4>Implementation notes</h4>
* This abstract class must be implemented with care to ensure other classes in
* the framework operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* <p>
* The principal methods are defined to allow the throwing of an exception.
* In normal use, no exceptions will be thrown, however one possible implementation would be to
* obtain the time from a central time server across the network. Obviously, in this case the
* lookup could fail, and so the method is permitted to throw an exception.
* <p>
* The returned instants from {@code Clock} work on a time-scale that ignores leap seconds.
* If the implementation wraps a source that provides leap second information, then a mechanism
* should be used to "smooth" the leap second, such as UTC-SLS.
* <p>
* Subclass implementations should implement {@code Serializable} wherever possible.
* They should also be immutable and thread-safe, implementing {@code equals()},
* {@code hashCode()} and {@code toString()} based on their state.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public abstract class Clock {
/**
* Gets a clock that obtains the current instant using the best available system clock,
* converting to date and time using the UTC time-zone.
* <p>
* This clock, rather than the {@link #systemDefaultZone() default zone clock}, should
* be used when you need the current instant without the date or time.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Conversion from instant to date or time uses the {@link ZoneId#UTC UTC time-zone}.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @return a clock that uses the best available system clock in the UTC zone, not null
*/
public static Clock systemUTC() {
return new SystemClock(ZoneId.UTC);
}
/**
* Gets a clock that obtains the current date and time using best available system clock.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Conversion from instant to date or time uses the specified time-zone.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param zone the time-zone to use to convert the instant to date-time, not null
* @return a clock that uses the best available system clock in the specified zone, not null
*/
public static Clock system(ZoneId zone) {
MathUtils.checkNotNull(zone, "ZoneId must not be null");
return new SystemClock(zone);
}
/**
* Gets a clock using the default time-zone and the best available system clock.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Using this method hard codes a dependency to the default time-zone into your application.
* It is recommended to avoid this and use a specific time-zone whenever possible.
* The {@link #systemUTC() UTC clock} should be used when you need the current instant
* without the date or time.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @return a clock that uses the best available system clock in the default zone, not null
* @see ZoneId#systemDefault()
*/
public static Clock systemDefaultZone() {
return new SystemClock(ZoneId.systemDefault());
}
//-----------------------------------------------------------------------
/**
* Gets a clock that always returns the same instant in the UTC time-zone.
* <p>
* This clock simply returns the specified instant.
* As such, it is not a clock in the conventional sense.
* The main use case for this is in testing, where the fixed clock ensures tests
* are not dependent on the current clock.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param fixedInstant the instant to use as the clock, not null
* @return a clock that always returns the same instant, not null
*/
public static Clock fixedUTC(Instant fixedInstant) {
MathUtils.checkNotNull(fixedInstant, "Instant must not be null");
return new FixedClock(fixedInstant, ZoneId.UTC);
}
/**
* Gets a clock that always returns the same instant.
* <p>
* This clock simply returns the specified instant.
* As such, it is not a clock in the conventional sense.
* The main use case for this is in testing, where the fixed clock ensures tests
* are not dependent on the current clock.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param fixedInstant the instant to use as the clock, not null
* @param zone the time-zone to use to convert the instant to date-time, not null
* @return a clock that always returns the same instant, not null
*/
public static Clock fixed(Instant fixedInstant, ZoneId zone) {
MathUtils.checkNotNull(fixedInstant, "Instant must not be null");
MathUtils.checkNotNull(zone, "ZoneId must not be null");
return new FixedClock(fixedInstant, zone);
}
//-------------------------------------------------------------------------
/**
* Gets a clock that is offset from the instant returned by the specified base clock.
* <p>
* This clock wraps another clock, returning instants that are offset by the specified duration.
* The main use case for this is to simulate running in the future or in the past.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}
* providing that the base clock is.
*
* @param offset the duration by which this time-source is offset from the system millisecond clock
* @return a {@code TimeSource} that is offset from the system millisecond clock, not null
*/
public static Clock offset(Clock baseClock, Duration offset) {
MathUtils.checkNotNull(baseClock, "Clock must not be null");
MathUtils.checkNotNull(offset, "Duration must not be null");
if (offset.equals(Duration.ZERO)) {
return baseClock;
}
return new OffsetClock(baseClock, offset);
}
//-----------------------------------------------------------------------
/**
* Constructor accessible by subclasses.
*/
protected Clock() {
}
//-----------------------------------------------------------------------
/**
* Gets the time-zone being used to create dates and times.
* <p>
* A clock will typically obtain the current instant and then convert that
* to a date or time using a time-zone. This method returns the time-zone used.
*
* @return the time-zone being used to interpret instants, not null
*/
public abstract ZoneId getZone();
/**
* Returns a copy of this clock with a different time-zone.
* <p>
* A clock will typically obtain the current instant and then convert that
* to a date or time using a time-zone. This method returns a new clock that
* uses a different time-zone.
*
* @param zone the time-zone to change to, not null
* @return the new clock with the altered time-zone, not null
*/
public abstract Clock withZone(ZoneId zone);
//-------------------------------------------------------------------------
/**
* Gets the current millisecond instant of the clock.
* <p>
* This returns the millisecond-based instant, measured from 1970-01-01T00:00 UTC.
* This is equivalent to the definition of {@link System#currentTimeMillis()}.
* <p>
* Most applications should avoid this method and use {@link Instant} to represent
* an instant on the time-line rather than a raw millisecond value.
* This method is provided to allow the use of the clock in high performance use cases
* where the creation of an object would be unacceptable.
* <p>
* The default implementation calls {@link #instant}.
*
* @return the current millisecond instant from this clock, measured from
* the Java epoch of 1970-01-01T00:00 UTC, not null
* @throws CalendricalException if the instant cannot be obtained, not thrown by most implementations
*/
public long millis() {
return instant().toEpochMilli();
}
//-----------------------------------------------------------------------
/**
* Gets the current instant of the clock.
* <p>
* This returns an instant representing the current instant as defined by the clock.
* <p>
* The default implementation calls {@link #millis}.
*
* @return the current instant from this clock, not null
* @throws CalendricalException if the instant cannot be obtained, not thrown by most implementations
*/
public abstract Instant instant();
//-----------------------------------------------------------------------
// methods below here offer opportunity for performance gains
// need ZoneRules.getOffset(long epSecs)
/**
* Gets today's date.
* <p>
* This returns today's date based on the current instant and time-zone.
*
* @return the current date, not null
* @throws CalendricalException if the date cannot be obtained, not thrown by most implementations
*/
public LocalDate today() {
return LocalDate.now(this);
// long epSecs = MathUtils.floorDiv(millis(), 1000);
// long offsetSecs = getZone().getRules().getOffset(epSecs);
// long localSecs = MathUtils.safeAdd(epSecs, offsetSecs);
// long epDay = MathUtils.floorDiv(localSecs, MathUtils.SECONDS_PER_DAY);
// return LocalDate.ofEpochDay(epDay);
}
// /**
// * Gets yesterday's date.
// * <p>
// * This returns yesterday's date from the clock.
// * This is calculated relative to {@code today()}.
// *
// * @return the date yesterday, not null
// * @throws CalendricalException if the date cannot be created
// */
// public LocalDate yesterday() {
// return today().minusDays(1);
// }
//
// /**
// * Gets tomorrow's date.
// * <p>
// * This returns tomorrow's date from the clock.
// * This is calculated relative to {@code today()}.
// *
// * @return the date tomorrow, not null
// * @throws CalendricalException if the date cannot be created
// */
// public LocalDate tomorrow() {
// return today().plusDays(1);
// }
//-----------------------------------------------------------------------
/**
* Gets the current time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current time from the clock.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The local time can only be calculated from an instant if the time-zone is known.
* As such, the local time is derived by default from {@code offsetTime()}.
*
* @return the current time, not null
* @throws CalendricalException if the time cannot be obtained, not thrown by most implementations
*/
public LocalTime localTime() {
return LocalTime.now(this);
}
// /**
// * Gets the current time with a resolution of seconds.
// * <p>
// * This returns the current time from the clock rounded to the second.
// * This is achieved by setting the nanosecond part to be zero.
// *
// * @return the current time to the nearest second, not null
// * @throws CalendricalException if the time cannot be created
// */
// public LocalTime timeToSecond() {
// return time().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current time with a resolution of minutes.
// * <p>
// * This returns the current time from the clock rounded to the minute.
// * This is achieved by setting the second and nanosecond parts to be zero.
// *
// * @return the current time to the nearest minute, not null
// * @throws CalendricalException if the time cannot be created
// */
// public LocalTime timeToMinute() {
// return time().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current date-time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current date-time from the clock.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The local date-time can only be calculated from an instant if the time-zone is known.
* As such, the local date-time is derived by default from {@code offsetDateTime()}.
*
* @return the current date-time, not null
* @throws CalendricalException if the date-time cannot be obtained, not thrown by most implementations
*/
public LocalDateTime localDateTime() {
return LocalDateTime.now(this);
}
// /**
// * Gets the current date-time with a resolution of seconds.
// * <p>
// * This returns the current date-time from the clock rounded to the second.
// * This is achieved by setting the nanosecond part to be zero.
// *
// * @return the current date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public LocalDateTime dateTimeToSecond() {
// return dateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current date-time with a resolution of minutes.
// * <p>
// * This returns the current date-time from the clock rounded to the minute.
// * This is achieved by setting the second and nanosecond parts to be zero.
// *
// * @return the current date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public LocalDateTime dateTimeToMinute() {
// return dateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//
// //-----------------------------------------------------------------------
// /**
// * Gets the current offset date.
// * <p>
// * This returns the current offset date from the clock with the correct offset from {@link #getZone()}.
// * <p>
// * The offset date is derived by default from {@code instant()} and {@code getZone()}.
// *
// * @return the current offset date, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDate offsetDate() {
// return OffsetDate.now(this);
// }
//
// //-----------------------------------------------------------------------
// /**
// * Gets the current offset time with maximum resolution of up to nanoseconds.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The result is not filtered, and so will have whatever resolution the clock has.
// * For example, the {@link #system system clock} has up to millisecond resolution.
// * <p>
// * The offset time is derived by default from {@code instant()} and {@code getZone()}.
// *
// * @return the current offset time, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTime() {
// return OffsetTime.now(this);
// }
//
// /**
// * Gets the current offset time with a resolution of seconds.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current offset time to the nearest second, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTimeToSecond() {
// return offsetTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current offset time with a resolution of minutes.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current offset time to the nearest minute, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTimeToMinute() {
// return offsetTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current offset date-time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The offset date-time is derived by default from {@code instant()} and {@code getZone()}.
*
* @return the current offset date-time, not null
* @throws CalendricalException if the date-time cannot be obtained, not thrown by most implementations
*/
public OffsetDateTime offsetDateTime() {
return OffsetDateTime.now(this);
}
// /**
// * Gets the current offset date-time with a resolution of seconds.
// * <p>
// * This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current offset date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDateTime offsetDateTimeToSecond() {
// return offsetDateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current offset date-time with a resolution of minutes.
// * <p>
// * This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current offset date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDateTime offsetDateTimeToMinute() {
// return offsetDateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current zoned date-time.
* <p>
* This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The zoned date-time is derived by default from {@code instant()} and {@code getZone()}.
*
* @return the current zoned date-time, not null
* @throws CalendricalException if the date-time cannot be obtained, not thrown by most implementations
*/
public ZonedDateTime zonedDateTime() {
return ZonedDateTime.now(this);
}
// /**
// * Gets the current zoned date-time with a resolution of seconds.
// * <p>
// * This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current zoned date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public ZonedDateTime zonedDateTimeToSecond() {
// return zonedDateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current zoned date-time with a resolution of minutes.
// * <p>
// * This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current zoned date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public ZonedDateTime zonedDateTimeToMinute() {
// return zonedDateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Implementation of a clock that always returns the latest time from
* {@link System#currentTimeMillis()}.
*/
static final class SystemClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final ZoneId zone;
SystemClock(ZoneId zone) {
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(this.zone)) { // intentional NPE
return this;
}
return new SystemClock(zone);
}
@Override
public long millis() {
return System.currentTimeMillis();
}
@Override
public Instant instant() {
return Instant.ofEpochMilli(millis());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SystemClock) {
return zone.equals(((SystemClock) obj).zone);
}
return false;
}
@Override
public int hashCode() {
return zone.hashCode() + 1;
}
@Override
public String toString() {
return "SystemClock[" + zone + "]";
}
}
//-----------------------------------------------------------------------
/**
* Implementation of a clock that always returns the same instant.
* This is typically used for testing.
*/
static final class FixedClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final Instant instant;
private final ZoneId zone;
FixedClock(Instant fixedInstant, ZoneId zone) {
this.instant = fixedInstant;
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(this.zone)) { // intentional NPE
return this;
}
return new FixedClock(instant, zone);
}
@Override
public Instant instant() {
return instant;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FixedClock) {
FixedClock other = (FixedClock) obj;
return instant.equals(other.instant) && zone.equals(other.zone);
}
return false;
}
@Override
public int hashCode() {
return instant.hashCode() ^ zone.hashCode();
}
@Override
public String toString() {
return "FixedClock[" + instant + "," + zone + "]";
}
}
//-----------------------------------------------------------------------
/**
* Implementation of a clock that adds an offset to an underlying clock.
*/
static final class OffsetClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final Clock baseClock;
private final Duration offset;
OffsetClock(Clock baseClock, Duration offset) {
this.baseClock = baseClock;
this.offset = offset;
}
@Override
public ZoneId getZone() {
return baseClock.getZone();
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(baseClock.getZone())) { // intentional NPE
return this;
}
return new OffsetClock(baseClock.withZone(zone), offset);
}
@Override
public long millis() {
return MathUtils.safeAdd(baseClock.millis(), offset.toMillisLong());
}
@Override
public Instant instant() {
return baseClock.instant().plus(offset);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof OffsetClock) {
OffsetClock other = (OffsetClock) obj;
return baseClock.equals(other.baseClock) && offset.equals(other.offset);
}
return false;
}
@Override
public int hashCode() {
return baseClock.hashCode() ^ offset.hashCode();
}
@Override
public String toString() {
return "OffsetClock[" + baseClock + "," + offset + "]";
}
}
}
|
src/main/java/javax/time/Clock.java
|
/*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time;
import java.io.Serializable;
import java.util.TimeZone;
/**
* A clock providing access to the current instant, date and time using a time-zone.
* <p>
* Instances of this class are used to find the current instant, which can be
* interpreted using the stored time-zone to find the current date and time.
* As such, a clock can be used instead of {@link System#currentTimeMillis()}
* and {@link TimeZone#getDefault()}.
* <p>
* The primary purpose of this abstraction is to allow alternate clocks to be
* plugged in as and when required. Applications use an object to obtain the
* current time rather than a static method. This can simplify testing.
* <p>
* Applications should <i>avoid</i> using the static methods on this class.
* Instead, they should pass a {@code Clock} into any method that requires it.
* A dependency injection framework is one way to achieve this:
* <pre>
* public class MyBean {
* private Clock clock; // dependency inject
* ...
* public void process(LocalDate eventDate) {
* if (eventDate.isBefore(LocalDate.now(clock)) {
* ...
* }
* }
* }
* </pre>
* This approach allows an alternate clock, such as {@link #fixed} to be used during testing.
* <p>
* The {@code system} factory method provides clocks based on the best available system clock,
* such as {@code System.currentTimeMillis}.
*
* <h4>Implementation notes</h4>
* This abstract class must be implemented with care to ensure other classes in
* the framework operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* <p>
* The principal methods are defined to allow the throwing of an exception.
* In normal use, no exceptions will be thrown, however one possible implementation would be to
* obtain the time from a central time server across the network. Obviously, in this case the
* lookup could fail, and so the method is permitted to throw an exception.
* <p>
* The returned instants from {@code Clock} work on a time-scale that ignores leap seconds.
* If the implementation wraps a source that provides leap second information, then a mechanism
* should be used to "smooth" the leap second, such as UTC-SLS.
* <p>
* Subclass implementations should implement {@code Serializable} wherever possible.
* They should also be immutable and thread-safe, implementing {@code equals()},
* {@code hashCode()} and {@code toString()} based on their state.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public abstract class Clock {
/**
* Gets a clock that obtains the current instant using the best available system clock,
* converting to date and time using the UTC time-zone.
* <p>
* This clock, rather than the {@link #systemDefaultZone() default zone clock}, should
* be used when you need the current instant without the date or time.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Conversion from instant to date or time uses the {@link ZoneId#UTC UTC time-zone}.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @return a clock that uses the best available system clock in the UTC zone, not null
*/
public static Clock systemUTC() {
return new SystemClock(ZoneId.UTC);
}
/**
* Gets a clock that obtains the current date and time using best available system clock.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Conversion from instant to date or time uses the specified time-zone.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param zone the time-zone to use to convert the instant to date-time, not null
* @return a clock that uses the best available system clock in the specified zone, not null
*/
public static Clock system(ZoneId zone) {
MathUtils.checkNotNull(zone, "ZoneId must not be null");
return new SystemClock(zone);
}
/**
* Gets a clock using the default time-zone and the best available system clock.
* <p>
* The clock is based on the best available system clock from the JDK.
* This may use {@link System#currentTimeMillis()}, or a higher resolution clock if
* one is available.
* <p>
* Using this method hard codes a dependency to the default time-zone into your application.
* It is recommended to avoid this and use a specific time-zone whenever possible.
* The {@link #systemUTC() UTC clock} should be used when you need the current instant
* without the date or time.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @return a clock that uses the best available system clock in the default zone, not null
* @see ZoneId#systemDefault()
*/
public static Clock systemDefaultZone() {
return new SystemClock(ZoneId.systemDefault());
}
//-----------------------------------------------------------------------
/**
* Gets a clock that always returns the same instant in the UTC time-zone.
* <p>
* This clock simply returns the specified instant.
* As such, it is not a clock in the conventional sense.
* The main use case for this is in testing, where the fixed clock ensures tests
* are not dependent on the current clock.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param fixedInstant the instant to use as the clock, not null
* @return a clock that always returns the same instant, not null
*/
public static Clock fixedUTC(Instant fixedInstant) {
MathUtils.checkNotNull(fixedInstant, "Instant must not be null");
return new FixedClock(fixedInstant, ZoneId.UTC);
}
/**
* Gets a clock that always returns the same instant.
* <p>
* This clock simply returns the specified instant.
* As such, it is not a clock in the conventional sense.
* The main use case for this is in testing, where the fixed clock ensures tests
* are not dependent on the current clock.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param fixedInstant the instant to use as the clock, not null
* @param zone the time-zone to use to convert the instant to date-time, not null
* @return a clock that always returns the same instant, not null
*/
public static Clock fixed(Instant fixedInstant, ZoneId zone) {
MathUtils.checkNotNull(fixedInstant, "Instant must not be null");
MathUtils.checkNotNull(zone, "ZoneId must not be null");
return new FixedClock(fixedInstant, zone);
}
//-------------------------------------------------------------------------
/**
* Gets a clock that is offset from the instant returned by the specified base clock.
* <p>
* This clock wraps another clock, returning instants that are offset by the specified duration.
* The main use case for this is to simulate running in the future or in the past.
* <p>
* The returned implementation is immutable, thread-safe and {@code Serializable}.
*
* @param offset the duration by which this time-source is offset from the system millisecond clock
* @return a {@code TimeSource} that is offset from the system millisecond clock, not null
*/
public static Clock offset(Clock baseClock, Duration offset) {
MathUtils.checkNotNull(baseClock, "Clock must not be null");
MathUtils.checkNotNull(offset, "Duration must not be null");
if (offset.equals(Duration.ZERO)) {
return baseClock;
}
return new OffsetClock(baseClock, offset);
}
//-----------------------------------------------------------------------
/**
* Constructor accessible by subclasses.
*/
protected Clock() {
}
//-----------------------------------------------------------------------
/**
* Gets the time-zone being used to create dates and times.
* <p>
* A clock will typically obtain the current instant and then convert that
* to a date or time using a time-zone. This method returns the time-zone used.
*
* @return the time-zone being used to interpret instants, not null
*/
public abstract ZoneId getZone();
/**
* Returns a copy of this clock with a different time-zone.
* <p>
* A clock will typically obtain the current instant and then convert that
* to a date or time using a time-zone. This method returns a new clock that
* uses a different time-zone.
*
* @param zone the time-zone to change to, not null
* @return the new clock with the altered time-zone, not null
*/
public abstract Clock withZone(ZoneId zone);
//-------------------------------------------------------------------------
/**
* Gets the current millisecond instant of the clock.
* <p>
* This returns the millisecond-based instant, measured from 1970-01-01T00:00 UTC.
* This is equivalent to the definition of {@link System#currentTimeMillis()}.
* <p>
* Most applications should avoid this method and use {@link Instant} to represent
* an instant on the time-line rather than a raw millisecond value.
* This method is provided to allow the use of the clock in high performance use cases
* where the creation of an object would be unacceptable.
* <p>
* The default implementation calls {@link #instant}.
*
* @return the current millisecond instant from this clock, measured from
* the Java epoch of 1970-01-01T00:00 UTC, not null
* @throws RuntimeException if the instant cannot be obtained, not thrown by most implementations
*/
public long millis() {
return instant().toEpochMilli();
}
//-----------------------------------------------------------------------
/**
* Gets the current instant of the clock.
* <p>
* This returns an instant representing the current instant as defined by the clock.
* <p>
* The default implementation calls {@link #millis}.
*
* @return the current instant from this clock, not null
* @throws RuntimeException if the instant cannot be obtained, not thrown by most implementations
*/
public abstract Instant instant();
//-----------------------------------------------------------------------
// methods below here offer opportunity for performance gains
// need ZoneRules.getOffset(long epSecs)
/**
* Gets today's date.
* <p>
* This returns today's date based on the current instant and time-zone.
*
* @return the current date, not null
* @throws RuntimeException if the date cannot be obtained, not thrown by most implementations
*/
public LocalDate today() {
return LocalDate.now(this);
// long epSecs = MathUtils.floorDiv(millis(), 1000);
// long offsetSecs = getZone().getRules().getOffset(epSecs);
// long localSecs = MathUtils.safeAdd(epSecs, offsetSecs);
// long epDay = MathUtils.floorDiv(localSecs, MathUtils.SECONDS_PER_DAY);
// return LocalDate.ofEpochDay(epDay);
}
// /**
// * Gets yesterday's date.
// * <p>
// * This returns yesterday's date from the clock.
// * This is calculated relative to {@code today()}.
// *
// * @return the date yesterday, not null
// * @throws CalendricalException if the date cannot be created
// */
// public LocalDate yesterday() {
// return today().minusDays(1);
// }
//
// /**
// * Gets tomorrow's date.
// * <p>
// * This returns tomorrow's date from the clock.
// * This is calculated relative to {@code today()}.
// *
// * @return the date tomorrow, not null
// * @throws CalendricalException if the date cannot be created
// */
// public LocalDate tomorrow() {
// return today().plusDays(1);
// }
//-----------------------------------------------------------------------
/**
* Gets the current time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current time from the clock.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The local time can only be calculated from an instant if the time-zone is known.
* As such, the local time is derived by default from {@code offsetTime()}.
*
* @return the current time, not null
* @throws CalendricalException if the time cannot be created
*/
public LocalTime localTime() {
return LocalTime.now(this);
}
// /**
// * Gets the current time with a resolution of seconds.
// * <p>
// * This returns the current time from the clock rounded to the second.
// * This is achieved by setting the nanosecond part to be zero.
// *
// * @return the current time to the nearest second, not null
// * @throws CalendricalException if the time cannot be created
// */
// public LocalTime timeToSecond() {
// return time().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current time with a resolution of minutes.
// * <p>
// * This returns the current time from the clock rounded to the minute.
// * This is achieved by setting the second and nanosecond parts to be zero.
// *
// * @return the current time to the nearest minute, not null
// * @throws CalendricalException if the time cannot be created
// */
// public LocalTime timeToMinute() {
// return time().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current date-time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current date-time from the clock.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The local date-time can only be calculated from an instant if the time-zone is known.
* As such, the local date-time is derived by default from {@code offsetDateTime()}.
*
* @return the current date-time, not null
* @throws CalendricalException if the date-time cannot be created
*/
public LocalDateTime localDateTime() {
return LocalDateTime.now(this);
}
// /**
// * Gets the current date-time with a resolution of seconds.
// * <p>
// * This returns the current date-time from the clock rounded to the second.
// * This is achieved by setting the nanosecond part to be zero.
// *
// * @return the current date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public LocalDateTime dateTimeToSecond() {
// return dateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current date-time with a resolution of minutes.
// * <p>
// * This returns the current date-time from the clock rounded to the minute.
// * This is achieved by setting the second and nanosecond parts to be zero.
// *
// * @return the current date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public LocalDateTime dateTimeToMinute() {
// return dateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//
// //-----------------------------------------------------------------------
// /**
// * Gets the current offset date.
// * <p>
// * This returns the current offset date from the clock with the correct offset from {@link #getZone()}.
// * <p>
// * The offset date is derived by default from {@code instant()} and {@code getZone()}.
// *
// * @return the current offset date, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDate offsetDate() {
// return OffsetDate.now(this);
// }
//
// //-----------------------------------------------------------------------
// /**
// * Gets the current offset time with maximum resolution of up to nanoseconds.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The result is not filtered, and so will have whatever resolution the clock has.
// * For example, the {@link #system system clock} has up to millisecond resolution.
// * <p>
// * The offset time is derived by default from {@code instant()} and {@code getZone()}.
// *
// * @return the current offset time, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTime() {
// return OffsetTime.now(this);
// }
//
// /**
// * Gets the current offset time with a resolution of seconds.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current offset time to the nearest second, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTimeToSecond() {
// return offsetTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current offset time with a resolution of minutes.
// * <p>
// * This returns the current offset time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current offset time to the nearest minute, not null
// * @throws CalendricalException if the time cannot be created
// */
// public OffsetTime offsetTimeToMinute() {
// return offsetTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current offset date-time with maximum resolution of up to nanoseconds.
* <p>
* This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The offset date-time is derived by default from {@code instant()} and {@code getZone()}.
*
* @return the current offset date-time, not null
* @throws CalendricalException if the date-time cannot be created
*/
public OffsetDateTime offsetDateTime() {
return OffsetDateTime.now(this);
}
// /**
// * Gets the current offset date-time with a resolution of seconds.
// * <p>
// * This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current offset date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDateTime offsetDateTimeToSecond() {
// return offsetDateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current offset date-time with a resolution of minutes.
// * <p>
// * This returns the current offset date-time from the clock with the correct offset from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current offset date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public OffsetDateTime offsetDateTimeToMinute() {
// return offsetDateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Gets the current zoned date-time.
* <p>
* This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
* The result is not filtered, and so will have whatever resolution the clock has.
* For example, the {@link #system system clock} has up to millisecond resolution.
* <p>
* The zoned date-time is derived by default from {@code instant()} and {@code getZone()}.
*
* @return the current zoned date-time, not null
* @throws CalendricalException if the date-time cannot be created
*/
public ZonedDateTime zonedDateTime() {
return ZonedDateTime.now(this);
}
// /**
// * Gets the current zoned date-time with a resolution of seconds.
// * <p>
// * This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
// * The time is rounded to the second by setting the nanosecond part to be zero.
// *
// * @return the current zoned date-time to the nearest second, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public ZonedDateTime zonedDateTimeToSecond() {
// return zonedDateTime().withNanoOfSecond(0);
// }
//
// /**
// * Gets the current zoned date-time with a resolution of minutes.
// * <p>
// * This returns the current zoned date-time from the clock with the zone from {@link #getZone()}.
// * The time is rounded to the second by setting the second and nanosecond parts to be zero.
// *
// * @return the current zoned date-time to the nearest minute, not null
// * @throws CalendricalException if the date-time cannot be created
// */
// public ZonedDateTime zonedDateTimeToMinute() {
// return zonedDateTime().withSecondOfMinute(0).withNanoOfSecond(0);
// }
//-----------------------------------------------------------------------
/**
* Implementation of a clock that always returns the latest time from
* {@link System#currentTimeMillis()}.
*/
static final class SystemClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final ZoneId zone;
SystemClock(ZoneId zone) {
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(this.zone)) { // intentional NPE
return this;
}
return new SystemClock(zone);
}
@Override
public long millis() {
return System.currentTimeMillis();
}
@Override
public Instant instant() {
return Instant.ofEpochMilli(millis());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SystemClock) {
return zone.equals(((SystemClock) obj).zone);
}
return false;
}
@Override
public int hashCode() {
return zone.hashCode() + 1;
}
@Override
public String toString() {
return "SystemClock[" + zone + "]";
}
}
//-----------------------------------------------------------------------
/**
* Implementation of a clock that always returns the same instant.
* This is typically used for testing.
*/
static final class FixedClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final Instant instant;
private final ZoneId zone;
FixedClock(Instant fixedInstant, ZoneId zone) {
this.instant = fixedInstant;
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(this.zone)) { // intentional NPE
return this;
}
return new FixedClock(instant, zone);
}
@Override
public Instant instant() {
return instant;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FixedClock) {
FixedClock other = (FixedClock) obj;
return instant.equals(other.instant) && zone.equals(other.zone);
}
return false;
}
@Override
public int hashCode() {
return instant.hashCode() ^ zone.hashCode();
}
@Override
public String toString() {
return "FixedClock[" + instant + "," + zone + "]";
}
}
//-----------------------------------------------------------------------
/**
* Implementation of a clock that adds an offset to an underlying clock.
*/
static final class OffsetClock extends Clock implements Serializable {
private static final long serialVersionUID = 1L;
private final Clock baseClock;
private final Duration offset;
OffsetClock(Clock baseClock, Duration offset) {
this.baseClock = baseClock;
this.offset = offset;
}
@Override
public ZoneId getZone() {
return baseClock.getZone();
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(baseClock.getZone())) { // intentional NPE
return this;
}
return new OffsetClock(baseClock.withZone(zone), offset);
}
@Override
public long millis() {
return MathUtils.safeAdd(baseClock.millis(), offset.toMillisLong());
}
@Override
public Instant instant() {
return baseClock.instant().plus(offset);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof OffsetClock) {
OffsetClock other = (OffsetClock) obj;
return baseClock.equals(other.baseClock) && offset.equals(other.offset);
}
return false;
}
@Override
public int hashCode() {
return baseClock.hashCode() ^ offset.hashCode();
}
@Override
public String toString() {
return "OffsetClock[" + baseClock + "," + offset + "]";
}
}
}
|
Javadoc
|
src/main/java/javax/time/Clock.java
|
Javadoc
|
|
Java
|
bsd-3-clause
|
9505ff7293f53321da48068f00461e6c421979e7
| 0
|
ConnCollege/cas,ConnCollege/cas,ConnCollege/cas
|
/*
* Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas.services.web.support;
import java.util.HashMap;
import java.util.Map;
import org.jasig.cas.services.Attribute;
import org.jasig.cas.services.MapBackedAttributeRepository;
import junit.framework.TestCase;
/**
*
* @author Scott Battaglia
* @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $
* @since 3.1
*
*/
public class AttributePropertyEditorTests extends TestCase {
private MapBackedAttributeRepository attributeRepository;
private AttributePropertyEditor editor;
private Attribute attr = new Attribute("test", "test");
protected void setUp() throws Exception {
this.attributeRepository = new MapBackedAttributeRepository();
final Map<String, Attribute> attributes = new HashMap<String, Attribute>();
attributes.put("test", this.attr);
this.attributeRepository.setAttributesMap(attributes);
this.editor = new AttributePropertyEditor(this.attributeRepository);
}
public void testAttributeNotExists() {
this.editor.setAsText("test2");
assertNull(this.editor.getValue());
}
public void testAttributeExists() {
this.editor.setAsText("test");
assertEquals(this.attr, this.editor.getValue());
}
}
|
cas-server-core/src/test/java/org/jasig/cas/services/web/support/AttributePropertyEditorTests.java
|
/*
* Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas.services.web.support;
import java.util.HashMap;
import java.util.Map;
import org.jasig.cas.services.Attribute;
import org.jasig.cas.services.MapBackedAttributeRepository;
import junit.framework.TestCase;
/**
*
* @author Scott Battaglia
* @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $
* @since 3.1
*
*/
public class AttributePropertyEditorTests extends TestCase {
private MapBackedAttributeRepository attributeRepository;
private AttributePropertyEditor editor;
private Attribute attr = new Attribute("test", "test");
protected void setUp() throws Exception {
this.attributeRepository = new MapBackedAttributeRepository();
final Map<String, Attribute> attributes = new HashMap<String, Attribute>();
attributes.put("test", this.attr);
this.attributeRepository.setAttributes(attributes);
this.editor = new AttributePropertyEditor(this.attributeRepository);
}
public void testAttributeNotExists() {
this.editor.setAsText("test2");
assertNull(this.editor.getValue());
}
public void testAttributeExists() {
this.editor.setAsText("test");
assertEquals(this.attr, this.editor.getValue());
}
}
|
changed setAttributes name to fix problem with Spring
|
cas-server-core/src/test/java/org/jasig/cas/services/web/support/AttributePropertyEditorTests.java
|
changed setAttributes name to fix problem with Spring
|
|
Java
|
apache-2.0
|
4738c7f94bccf9185d4e4549333d26a974cd865d
| 0
|
eivindveg/HotSUploader
|
src/main/java/ninja/eivind/hotsreplayuploader/repositories/JsonStoreFileRepository.java
|
// Copyright 2015 Eivind Vegsundvåg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ninja.eivind.hotsreplayuploader.repositories;
import com.fasterxml.jackson.databind.ObjectMapper;
import ninja.eivind.hotsreplayuploader.files.AccountDirectoryWatcher;
import ninja.eivind.hotsreplayuploader.models.ReplayFile;
import ninja.eivind.hotsreplayuploader.models.UploadStatus;
import ninja.eivind.hotsreplayuploader.utils.FileUtils;
import ninja.eivind.hotsreplayuploader.utils.StormHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JsonStoreFileRepository implements FileRepository {
private static final Logger LOG = LoggerFactory.getLogger(JsonStoreFileRepository.class);
private StormHandler stormHandler;
@Inject
private ObjectMapper mapper;
@Inject
private AccountDirectoryWatcher accountDirectoryWatcher;
@Inject
private ProviderRepository providerRepository;
@Inject
public JsonStoreFileRepository(StormHandler stormHandler) {
this.stormHandler = stormHandler;
cleanup();
}
@Override
public void deleteReplay(final ReplayFile replayFile) {
File file = replayFile.getFile();
if (file.delete()) {
LOG.info("ReplayFile " + file + " successfully deleted.");
if (stormHandler.getPropertiesFile(file).delete()) {
LOG.info("Property file for " + file + " successfully deleted.");
} else {
LOG.error("Could not delete property file for " + file);
}
} else {
LOG.error("ReplayFile " + file + " could not be deleted.");
}
}
private void cleanup() {
List<File> accounts = stormHandler.getApplicationAccountDirectories();
accounts.stream()
.flatMap(folder -> {
File[] children = folder.listFiles();
return Arrays.asList(children != null ? children : new File[0]).stream();
}).map(stormHandler::getReplayFile)
.filter(file -> !file.exists())
.map(stormHandler::getPropertiesFile)
.forEach((file) -> {
if (file.delete()) {
LOG.info("Deleted property file" + file + " for non-existing replay file.");
}
});
}
@Override
public void updateReplay(final ReplayFile file) {
File propertiesFile = stormHandler.getPropertiesFile(file.getFile());
String data;
try {
data = mapper.writeValueAsString(file.getUploadStatuses());
FileUtils.writeStringToFile(propertiesFile, data);
LOG.info("Property file for " + file + " updated.");
} catch (IOException e) {
throw new RuntimeException("Could not update property file for replay " + file, e);
}
}
@Override
public List<ReplayFile> getAll() {
return accountDirectoryWatcher.getAllFiles()
.map(ReplayFile::fromDirectory)
.flatMap(List::stream)
.map(replay -> {
File propertiesFile = stormHandler.getPropertiesFile(replay.getFile());
try {
if (propertiesFile.exists()) {
String properties = FileUtils.readFileToString(propertiesFile);
replay.addStatuses(Arrays.asList(mapper.readValue(properties, UploadStatus[].class)));
if (replay.hasExceptions()) {
replay.getFailedProperty().set(true);
}
} else {
replay.addStatuses(providerRepository.getAll().stream()
.map(UploadStatus::new)
.collect(Collectors.toList()));
FileUtils.writeStringToFile(propertiesFile, mapper.writeValueAsString(replay.getUploadStatuses()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return replay;
})
.collect(Collectors.toList());
}
}
|
remove jsonstorefilerepository
|
src/main/java/ninja/eivind/hotsreplayuploader/repositories/JsonStoreFileRepository.java
|
remove jsonstorefilerepository
|
||
Java
|
bsd-3-clause
|
c06e71ece71d6f406b0ca74f51edb0f41b6d9567
| 0
|
muloem/xins,muloem/xins,muloem/xins
|
src/java-client-framework/org/xins/client/UnexpectedErrorCodeException.java
|
/*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.client;
import org.xins.common.service.TargetDescriptor;
/**
* Exception that indicates an error code was received from the server-side
* that is not expected at the client-side.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.2.0
*/
public class UnexpectedErrorCodeException
extends UnsuccessfulXINSCallException {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>UnexpectedErrorCodeException</code>.
*
* @param request
* the original request, cannot be <code>null</code>.
*
* @param target
* descriptor for the target that was attempted to be called, cannot be
* <code>null</code>.
*
* @param duration
* the call duration in milliseconds, must be >= 0.
*
* @param resultData
* the result data, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null
* || target == null
* || duration < 0
* || resultData == null
* || resultData.{@link XINSCallResult#getErrorCode() getErrorCode()} == null</code>.
*/
UnexpectedErrorCodeException(XINSCallRequest request,
TargetDescriptor target,
long duration,
XINSCallResultData resultData)
throws IllegalArgumentException {
super(request, target, duration, resultData, null);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
}
|
Replaced by UnacceptableErrorCodeXINSCallException.
|
src/java-client-framework/org/xins/client/UnexpectedErrorCodeException.java
|
Replaced by UnacceptableErrorCodeXINSCallException.
|
||
Java
|
mit
|
d9256c459dcea7ae551a49bdefa75805864f3766
| 0
|
ihiroky/niotty
|
package net.ihiroky.niotty.nio;
import net.ihiroky.niotty.DefaultTransportFuture;
import net.ihiroky.niotty.EventLoop;
import net.ihiroky.niotty.FailedTransportFuture;
import net.ihiroky.niotty.SucceededTransportFuture;
import net.ihiroky.niotty.TransportFuture;
import net.ihiroky.niotty.buffer.BufferSink;
import net.ihiroky.niotty.event.TransportState;
import net.ihiroky.niotty.event.TransportStateEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
/**
* Created on 13/01/17, 16:13
*
* @author Hiroki Itoh
*/
public class NioClientSocketTransport extends NioSocketTransport<ConnectSelector> {
private SocketChannel clientChannel_;
private NioClientSocketConfig config_;
private NioClientSocketProcessor processor_;
private volatile NioChildChannelTransport childTransport_;
public NioClientSocketTransport(NioClientSocketConfig config, NioClientSocketProcessor processor) {
try {
SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
config.applySocketOptions(clientChannel);
this.clientChannel_ = clientChannel;
this.config_ = config;
this.processor_ = processor;
} catch (Exception e) {
throw new RuntimeException("failed to open client socket channel.", e);
}
}
@Override
public TransportFuture bind(SocketAddress local) {
try {
clientChannel_.bind(local);
getTransportListener().onBind(this, local);
return new SucceededTransportFuture(this);
} catch (IOException ioe) {
return new FailedTransportFuture(this, ioe);
}
}
@Override
public TransportFuture connect(SocketAddress remote) {
try {
if (clientChannel_.connect(remote)) {
return new SucceededTransportFuture(this);
}
DefaultTransportFuture future = new DefaultTransportFuture(this);
processor_.getConnectSelectorPool().register(
clientChannel_, SelectionKey.OP_CONNECT, new TransportFutureAttachment<>(this, future));
return future;
} catch (IOException ioe) {
return new FailedTransportFuture(this, ioe);
}
}
@Override
public TransportFuture close() {
if (getEventLoop() == null) {
closeSelectableChannel();
return new SucceededTransportFuture(this);
}
// SelectionKey of NioClientSocketTransport is already cancelled here.
if (childTransport_ != null) {
return childTransport_.closeSelectableChannelLater();
}
return new SucceededTransportFuture(this);
}
@Override
public TransportFuture join(InetAddress group, NetworkInterface networkInterface, InetAddress source) {
throw new UnsupportedOperationException("join");
}
@Override
public void write(final Object message) {
NioChildChannelTransport transport = childTransport_;
if (transport == null) {
throw new IllegalStateException("not connected.");
}
transport.write(message);
}
@Override
public void write(Object message, SocketAddress remote) {
throw new UnsupportedOperationException("write");
}
@Override
public InetSocketAddress localAddress() {
try {
return (InetSocketAddress) clientChannel_.getLocalAddress();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public InetSocketAddress remoteAddress() {
try {
return (InetSocketAddress) clientChannel_.getRemoteAddress();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public boolean isOpen() {
return clientChannel_.isOpen();
}
void registerLater(SelectableChannel channel, int ops, DefaultTransportFuture future) throws IOException {
NioChildChannelTransport child =
new NioChildChannelTransport(config_, processor_.getName(),
processor_.getWriteBufferSize(), processor_.isUseDirectBuffer());
this.childTransport_ = child;
InetSocketAddress remoteAddress = (InetSocketAddress) clientChannel_.getRemoteAddress();
getTransportListener().onConnect(this, remoteAddress);
future.done();
processor_.getMessageIOSelectorPool().register(channel, ops, child);
child.loadEventLater(new TransportStateEvent(child, TransportState.CONNECTED, remoteAddress));
}
@Override
protected void writeDirect(final BufferSink buffer) {
getEventLoop().offerTask(new EventLoop.Task<ConnectSelector>() {
@Override
public boolean execute(ConnectSelector eventLoop) throws Exception {
childTransport_.writeBufferSink(buffer);
return true;
}
});
}
}
|
src/main/java/net/ihiroky/niotty/nio/NioClientSocketTransport.java
|
package net.ihiroky.niotty.nio;
import net.ihiroky.niotty.DefaultTransportFuture;
import net.ihiroky.niotty.EventLoop;
import net.ihiroky.niotty.FailedTransportFuture;
import net.ihiroky.niotty.SucceededTransportFuture;
import net.ihiroky.niotty.TransportFuture;
import net.ihiroky.niotty.buffer.BufferSink;
import net.ihiroky.niotty.event.TransportState;
import net.ihiroky.niotty.event.TransportStateEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
/**
* Created on 13/01/17, 16:13
*
* @author Hiroki Itoh
*/
public class NioClientSocketTransport extends NioSocketTransport<ConnectSelector> {
private SocketChannel clientChannel_;
private NioClientSocketConfig config_;
private NioClientSocketProcessor processor_;
private volatile NioChildChannelTransport childTransport_;
public NioClientSocketTransport(NioClientSocketConfig config, NioClientSocketProcessor processor) {
try {
SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
config.applySocketOptions(clientChannel);
this.clientChannel_ = clientChannel;
this.config_ = config;
this.processor_ = processor;
} catch (Exception e) {
throw new RuntimeException("failed to open client socket channel.", e);
}
}
@Override
public TransportFuture bind(SocketAddress local) {
try {
clientChannel_.bind(local);
getTransportListener().onBind(this, local);
return new SucceededTransportFuture(this);
} catch (IOException ioe) {
return new FailedTransportFuture(this, ioe);
}
}
@Override
public TransportFuture connect(SocketAddress remote) {
try {
if (clientChannel_.connect(remote)) {
return new SucceededTransportFuture(this);
}
DefaultTransportFuture future = new DefaultTransportFuture(this);
processor_.getConnectSelectorPool().register(
clientChannel_, SelectionKey.OP_CONNECT, new TransportFutureAttachment<>(this, future));
return future;
} catch (IOException ioe) {
return new FailedTransportFuture(this, ioe);
}
}
@Override
public TransportFuture close() {
if (getEventLoop() == null) {
closeSelectableChannel();
return new SucceededTransportFuture(this);
}
// SelectionKey of NioClientSocketTransport is already cancelled here.
if (childTransport_ != null) {
return childTransport_.closeSelectableChannelLater();
}
return new SucceededTransportFuture(this);
}
@Override
public TransportFuture join(InetAddress group, NetworkInterface networkInterface, InetAddress source) {
throw new UnsupportedOperationException("join");
}
@Override
public void write(final Object message) {
NioChildChannelTransport transport = childTransport_;
if (transport == null) {
throw new IllegalStateException("not connected.");
}
transport.write(message);
}
@Override
public void write(Object message, SocketAddress remote) {
throw new UnsupportedOperationException("write");
}
@Override
public InetSocketAddress localAddress() {
try {
return (InetSocketAddress) clientChannel_.getLocalAddress();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public InetSocketAddress remoteAddress() {
try {
return (InetSocketAddress) clientChannel_.getRemoteAddress();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public boolean isOpen() {
return clientChannel_.isOpen();
}
void registerLater(SelectableChannel channel, int ops, DefaultTransportFuture future) {
NioChildChannelTransport child =
new NioChildChannelTransport(config_, processor_.getName(),
processor_.getWriteBufferSize(), processor_.isUseDirectBuffer());
this.childTransport_ = child;
InetSocketAddress remoteAddress;
try {
remoteAddress = (InetSocketAddress) clientChannel_.getRemoteAddress();
getTransportListener().onConnect(this, remoteAddress);
future.done();
} catch (IOException e) {
future.setThrowable(e);
return;
}
processor_.getMessageIOSelectorPool().register(channel, ops, child);
child.loadEventLater(new TransportStateEvent(child, TransportState.CONNECTED, remoteAddress));
}
@Override
protected void writeDirect(final BufferSink buffer) {
getEventLoop().offerTask(new EventLoop.Task<ConnectSelector>() {
@Override
public boolean execute(ConnectSelector eventLoop) throws Exception {
childTransport_.writeBufferSink(buffer);
return true;
}
});
}
}
|
Fix timing on setting exception to future
IOException is thrown by NioChildSocketTransport because the IOException
is handled in ConnectSelector
|
src/main/java/net/ihiroky/niotty/nio/NioClientSocketTransport.java
|
Fix timing on setting exception to future
|
|
Java
|
mit
|
48926e4d9d42b63ff54f2b08efa0dc86c36c598a
| 0
|
pstorch/bahnhoefe.gpx,RailwayStations/RSAPI,RailwayStations/RSAPI,RailwayStations/RSAPI
|
package org.railwaystations.api.resources;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.auth.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.InputStreamEntity;
import org.eclipse.jetty.util.URIUtil;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.railwaystations.api.PhotoImporter;
import org.railwaystations.api.StationsRepository;
import org.railwaystations.api.auth.AuthUser;
import org.railwaystations.api.auth.UploadTokenAuthenticator;
import org.railwaystations.api.auth.UploadTokenCredentials;
import org.railwaystations.api.db.CountryDao;
import org.railwaystations.api.db.PhotoDao;
import org.railwaystations.api.db.InboxDao;
import org.railwaystations.api.db.UserDao;
import org.railwaystations.api.model.*;
import org.railwaystations.api.monitoring.Monitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.security.RolesAllowed;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.net.URLDecoder;
import java.util.List;
import java.util.Optional;
@Path("/")
public class InboxResource {
private static final Logger LOG = LoggerFactory.getLogger(InboxResource.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final long MAX_SIZE = 20_000_000L;
private static final String IMAGE_PNG = "image/png";
private static final String IMAGE_JPEG = "image/jpeg";
private final StationsRepository repository;
private final File inboxDir;
private final File photoDir;
private final Monitor monitor;
private final UploadTokenAuthenticator authenticator;
private final InboxDao inboxDao;
private final UserDao userDao;
private final CountryDao countryDao;
private final PhotoDao photoDao;
private final String inboxBaseUrl;
private final File inboxToProcessDir;
private final File inboxProcessedDir;
public InboxResource(final StationsRepository repository, final String inboxDir,
final String inboxToProcessDir, final String inboxProcessedDir, final String photoDir,
final Monitor monitor, final UploadTokenAuthenticator authenticator,
final InboxDao inboxDao, final UserDao userDao, final CountryDao countryDao,
final PhotoDao photoDao, final String inboxBaseUrl) {
this.repository = repository;
this.inboxDir = new File(inboxDir);
this.inboxToProcessDir = new File(inboxToProcessDir);
this.inboxProcessedDir = new File(inboxProcessedDir);
this.photoDir = new File(photoDir);
this.monitor = monitor;
this.authenticator = authenticator;
this.inboxDao = inboxDao;
this.userDao = userDao;
this.countryDao = countryDao;
this.photoDao = photoDao;
this.inboxBaseUrl = inboxBaseUrl;
}
/**
* Not part of the "official" API.
* Supports upload of photos via the website.
*/
@POST
@Path("photoUpload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String post(@HeaderParam("User-Agent") final String userAgent,
@FormDataParam("email") final String email,
@FormDataParam("uploadToken") final String uploadToken,
@FormDataParam("stationId") final String stationId,
@FormDataParam("countryCode") final String countryCode,
@FormDataParam("stationTitle") final String stationTitle,
@FormDataParam("latitude") final Double latitude,
@FormDataParam("longitude") final Double longitude,
@FormDataParam("comment") final String comment,
@FormDataParam("file") final InputStream file,
@FormDataParam("file") final FormDataContentDisposition fd,
@HeaderParam("Referer") final String referer) throws JsonProcessingException {
LOG.info("MultipartFormData: email={}, station={}, country={}, file={}", email, stationId, countryCode, fd.getFileName());
try {
final Optional<AuthUser> authUser = authenticator.authenticate(new UploadTokenCredentials(email, uploadToken));
if (!authUser.isPresent()) {
final InboxResponse response = consumeBodyAndReturn(file, new InboxResponse(InboxResponse.InboxResponseState.UNAUTHORIZED));
return createIFrameAnswer(response, referer);
}
final String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fd.getFileName());
final InboxResponse response = uploadPhoto(userAgent, file, StringUtils.trimToNull(stationId), StringUtils.trimToNull(countryCode), contentType, stationTitle, latitude, longitude, comment, authUser.get());
return createIFrameAnswer(response, referer);
} catch (final Exception e) {
LOG.error("FormUpload error", e);
return createIFrameAnswer(new InboxResponse(InboxResponse.InboxResponseState.ERROR), referer);
}
}
@POST
@Path("photoUpload")
@Consumes({IMAGE_PNG, IMAGE_JPEG})
@Produces(MediaType.APPLICATION_JSON)
public Response post(final InputStream body,
@HeaderParam("User-Agent") final String userAgent,
@HeaderParam("Station-Id") final String stationId,
@HeaderParam("Country") final String country,
@HeaderParam("Content-Type") final String contentType,
@HeaderParam("Station-Title") final String encStationTitle,
@HeaderParam("Latitude") final Double latitude,
@HeaderParam("Longitude") final Double longitude,
@HeaderParam("Comment") final String encComment,
@Auth final AuthUser user) throws UnsupportedEncodingException {
final String stationTitle = encStationTitle != null ? URLDecoder.decode(encStationTitle, "UTF-8") : null;
final String comment = encComment != null ? URLDecoder.decode(encComment, "UTF-8") : null;
LOG.info("Nickname: {}; Email: {}; Country: {}; Station-Id: {}; Coords: {},{}; Title: {}; Content-Type: {}",
user.getName(), user.getUser().getEmail(), country, stationId, latitude, longitude, stationTitle, contentType);
final InboxResponse inboxResponse = uploadPhoto(userAgent, body, StringUtils.trimToNull(stationId), StringUtils.trimToNull(country), contentType, stationTitle, latitude, longitude, comment, user);
return Response.status(inboxResponse.getState().getResponseStatus()).entity(inboxResponse).build();
}
@POST
@Path("reportProblem")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public InboxResponse reportProblem(@HeaderParam("User-Agent") final String userAgent,
@NotNull() final ProblemReport problemReport,
@Auth final AuthUser user) {
LOG.info("New problem report: Nickname: {}; Country: {}; Station-Id: {}",
user.getName(), problemReport.getCountryCode(), problemReport.getStationId());
final Station station = repository.findByCountryAndId(problemReport.getCountryCode(), problemReport.getStationId());
if (station == null) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Station not found");
}
if (StringUtils.isBlank(problemReport.getComment())) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Comment is mandatory");
}
if (problemReport.getType() == null) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Problem type is mandatory");
}
final InboxEntry inboxEntry = new InboxEntry(problemReport.getCountryCode(), problemReport.getStationId(),
null, null, user.getUser().getId(), null, problemReport.getComment(),
problemReport.getType());
monitor.sendMessage(String.format("New problem report for %s - %s:%s%n%s: %s%nby %s%nvia %s",
station.getTitle(), station.getKey().getCountry(), station.getKey().getId(), problemReport.getType(),
StringUtils.trimToEmpty(problemReport.getComment()), user.getName(), userAgent));
return new InboxResponse(InboxResponse.InboxResponseState.REVIEW, inboxDao.insert(inboxEntry));
}
@GET
@Path("publicInbox")
@Produces(MediaType.APPLICATION_JSON)
public List<PublicInboxEntry> publicInbox() {
return inboxDao.findPublicInboxEntries();
}
@POST
@Path("userInbox")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<InboxStateQuery> userInbox(@Auth final AuthUser user, @NotNull final List<InboxStateQuery> queries) {
LOG.info("Query uploadStatus for Nickname: {}", user.getName());
for (final InboxStateQuery query : queries) {
query.setState(InboxStateQuery.InboxState.UNKNOWN);
if (query.getId() != null) {
final InboxEntry inboxEntry = inboxDao.findById(query.getId());
if (inboxEntry != null && inboxEntry.getPhotographerId() == user.getUser().getId()) {
query.setRejectedReason(inboxEntry.getRejectReason());
query.setCountryCode(inboxEntry.getCountryCode());
query.setStationId(inboxEntry.getStationId());
query.setCoordinates(inboxEntry.getCoordinates());
query.setFilename(inboxEntry.getFilename());
query.setInboxUrl(getInboxUrl(inboxEntry.getFilename(), isProcessed(inboxEntry.getFilename())));
if (inboxEntry.isDone()) {
if (inboxEntry.getRejectReason() == null) {
query.setState(InboxStateQuery.InboxState.ACCEPTED);
} else {
query.setState(InboxStateQuery.InboxState.REJECTED);
}
} else {
if (hasConflict(inboxEntry.getId(),
repository.findByCountryAndId(query.getCountryCode(), query.getStationId()))
|| hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates())) {
query.setState(InboxStateQuery.InboxState.CONFLICT);
} else {
query.setState(InboxStateQuery.InboxState.REVIEW);
}
}
}
}
}
return queries;
}
@GET
@RolesAllowed("ADMIN")
@Path("adminInbox")
@Produces(MediaType.APPLICATION_JSON)
public List<InboxEntry> adminInbox(@Auth final AuthUser user) {
final List<InboxEntry> pendingInboxEntries = inboxDao.findPendingInboxEntries();
for (final InboxEntry inboxEntry : pendingInboxEntries) {
final String filename = inboxEntry.getFilename();
inboxEntry.isProcessed(isProcessed(filename));
if (!inboxEntry.isProblemReport()) {
inboxEntry.setInboxUrl(getInboxUrl(filename, inboxEntry.isProcessed()));
}
if (!inboxEntry.getCoordinates().hasNullCoords()) {
inboxEntry.setConflict(hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates()));
}
}
return pendingInboxEntries;
}
private String getInboxUrl(final String filename, final boolean processed) {
return inboxBaseUrl + (processed ? "/processed/" : "/") + filename;
}
private boolean isProcessed(final String filename) {
return filename != null && new File(inboxProcessedDir, filename).exists();
}
@POST
@RolesAllowed("ADMIN")
@Path("adminInbox")
@Consumes(MediaType.APPLICATION_JSON)
public Response adminInbox(@Auth final AuthUser user, final InboxEntry command) {
final InboxEntry inboxEntry = inboxDao.findById(command.getId());
if (inboxEntry == null || inboxEntry.isDone()) {
throw new WebApplicationException("No pending inbox entry found", Response.Status.BAD_REQUEST);
}
switch (command.getCommand()) {
case REJECT :
rejectInboxEntry(inboxEntry, command.getRejectReason());
break;
case IMPORT :
importUpload(inboxEntry, command);
break;
case DEACTIVATE_STATION:
deactivateStation(inboxEntry);
break;
case DELETE_STATION:
deleteStation(inboxEntry);
break;
case DELETE_PHOTO:
deletePhoto(inboxEntry);
break;
case MARK_SOLVED:
markProblemReportSolved(inboxEntry);
break;
default:
throw new WebApplicationException("Unexpected command value: " + command.getCommand(), Response.Status.BAD_REQUEST);
}
return Response.ok().build();
}
@GET
@RolesAllowed("ADMIN")
@Path("adminInboxCount")
@Produces(MediaType.APPLICATION_JSON)
public InboxCountResponse adminInboxCount(@Auth final AuthUser user) {
return new InboxCountResponse(inboxDao.countPendingInboxEntries());
}
private void deactivateStation(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
repository.deactivate(station);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} station {} deactivated", inboxEntry.getId(), station.getKey());
}
private void deleteStation(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
photoDao.delete(station.getKey());
repository.delete(station);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} station {} deleted", inboxEntry.getId(), station.getKey());
}
private void deletePhoto(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
photoDao.delete(station.getKey());
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} photo of station {} deleted", inboxEntry.getId(), station.getKey());
}
private void markProblemReportSolved(final InboxEntry inboxEntry) {
assertStationExists(inboxEntry);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} accepted", inboxEntry.getId());
}
private Station assertStationExists(final InboxEntry inboxEntry) {
final Station station = repository.findByCountryAndId(inboxEntry.getCountryCode(), inboxEntry.getStationId());
if (station == null) {
throw new WebApplicationException("Station not found", Response.Status.BAD_REQUEST);
}
return station;
}
private void importUpload(final InboxEntry inboxEntry, final InboxEntry command) {
final File originalFile = getUploadFile(inboxEntry.getFilename());
final File processedFile = new File(inboxProcessedDir, inboxEntry.getFilename());
final File fileToImport = processedFile.exists() ? processedFile : originalFile;
LOG.info("Importing upload {}, {}", inboxEntry.getId(), fileToImport);
boolean updateStationKey = false;
Station station = repository.findByCountryAndId(inboxEntry.getCountryCode(), inboxEntry.getStationId());
if (station == null) {
station = repository.findByCountryAndId(command.getCountryCode(), command.getStationId());
updateStationKey = true;
}
if (station == null) {
if (!command.createStation()
|| StringUtils.isNotBlank(inboxEntry.getCountryCode())
|| StringUtils.isNotBlank(inboxEntry.getStationId())) {
throw new WebApplicationException("Station not found", Response.Status.BAD_REQUEST);
}
// create station
final Optional<Country> country = countryDao.findById(StringUtils.lowerCase(command.getCountryCode()));
if (!country.isPresent()) {
throw new WebApplicationException("Country not found", Response.Status.BAD_REQUEST);
}
if (StringUtils.isBlank(command.getStationId())) {
throw new WebApplicationException("Station ID can't be empty", Response.Status.BAD_REQUEST);
}
if (hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates()) && !command.ignoreConflict()) {
throw new WebApplicationException("There is a conflict with a nearby station", Response.Status.BAD_REQUEST);
}
station = new Station(new Station.Key(command.getCountryCode(), command.getStationId()), inboxEntry.getTitle(), inboxEntry.getCoordinates(), command.getDS100(), null, command.isActive());
repository.insert(station);
}
if (station.hasPhoto() && !command.ignoreConflict()) {
throw new WebApplicationException("Station already has a photo", Response.Status.BAD_REQUEST);
}
if (hasConflict(inboxEntry.getId(), station) && !command.ignoreConflict()) {
throw new WebApplicationException("There is a conflict with another upload", Response.Status.BAD_REQUEST);
}
final Optional<User> user = userDao.findById(inboxEntry.getPhotographerId());
final Optional<Country> country = countryDao.findById(StringUtils.lowerCase(station.getKey().getCountry()));
if (!country.isPresent()) {
throw new WebApplicationException("Country not found", Response.Status.BAD_REQUEST);
}
try {
final File countryDir = new File(photoDir, station.getKey().getCountry());
final Photo photo = PhotoImporter.createPhoto(station.getKey().getCountry(), country, station.getKey().getId(), user.get(), inboxEntry.getExtension());
if (station.hasPhoto()) {
photoDao.update(photo);
FileUtils.deleteQuietly(new File(countryDir, station.getKey().getId() + "." + inboxEntry.getExtension()));
} else {
photoDao.insert(photo);
}
if (processedFile.exists()) {
PhotoImporter.moveFile(processedFile, countryDir, station.getKey().getId(), inboxEntry.getExtension());
} else {
PhotoImporter.copyFile(originalFile, countryDir, station.getKey().getId(), inboxEntry.getExtension());
}
FileUtils.moveFileToDirectory(originalFile, new File(inboxDir, "done"), true);
if (updateStationKey) {
inboxDao.done(inboxEntry.getId(), command.getCountryCode(), command.getStationId());
} else {
inboxDao.done(inboxEntry.getId());
}
LOG.info("Upload {} accepted: {}", inboxEntry.getId(), fileToImport);
} catch (final Exception e) {
LOG.error("Error importing upload {} photo {}", inboxEntry.getId(), fileToImport);
throw new WebApplicationException("Error moving file: " + e.getMessage());
}
}
private void rejectInboxEntry(final InboxEntry inboxEntry, final String rejectReason) {
inboxDao.reject(inboxEntry.getId(), rejectReason);
if (inboxEntry.isProblemReport()) {
LOG.info("Rejecting problem report {}, {}", inboxEntry.getId(), rejectReason);
return;
}
final File file = getUploadFile(inboxEntry.getFilename());
LOG.info("Rejecting upload {}, {}, {}", inboxEntry.getId(), rejectReason, file);
try {
final File rejectDir = new File(inboxDir, "rejected");
FileUtils.moveFileToDirectory(file, rejectDir, true);
FileUtils.deleteQuietly(new File(inboxToProcessDir, inboxEntry.getFilename()));
FileUtils.deleteQuietly(new File(inboxProcessedDir, inboxEntry.getFilename()));
} catch (final IOException e) {
LOG.warn("Unable to move rejected file {}", file, e);
}
}
private InboxResponse uploadPhoto(final String userAgent, final InputStream body, final String stationId,
final String country, final String contentType, final String stationTitle,
final Double latitude, final Double longitude, final String comment,
final AuthUser user) {
final Station station = repository.findByCountryAndId(country, stationId);
Coordinates coordinates = null;
if (station == null) {
LOG.warn("Station not found");
if (StringUtils.isBlank(stationTitle) || latitude == null || longitude == null) {
LOG.warn("Not enough data for missing station: title={}, latitude={}, longitude={}", stationTitle, latitude, longitude);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Not enough data: either 'country' and 'stationId' or 'title', 'latitude' and 'longitude' have to be provided"));
}
if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180) {
LOG.warn("Lat/Lon out of range: latitude={}, longitude={}", latitude, longitude);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.LAT_LON_OUT_OF_RANGE, "'latitude' and/or 'longitude' out of range"));
}
coordinates = new Coordinates(latitude, longitude);
}
final String extension = mimeToExtension(contentType);
if (extension == null) {
LOG.warn("Unknown contentType '{}'", contentType);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.UNSUPPORTED_CONTENT_TYPE, "unsupported content type (only jpg and png are supported)"));
}
final boolean conflict = hasConflict(null, station) || hasConflict(null, coordinates);
File file = null;
final String inboxUrl;
final Integer id;
try {
if (station != null) {
// existing station
id = inboxDao.insert(new InboxEntry(station.getKey().getCountry(), station.getKey().getId(), stationTitle,
coordinates, user.getUser().getId(), extension, comment, null));
} else {
// missing station
id = inboxDao.insert(new InboxEntry(null, null, stationTitle,
coordinates, user.getUser().getId(), extension, comment, null));
}
file = getUploadFile(InboxEntry.getFilename(id, extension));
LOG.info("Writing photo to {}", file);
// write the file to the inbox directory
FileUtils.forceMkdir(inboxDir);
final long bytesRead = IOUtils.copyLarge(body, new FileOutputStream(file), 0L, MAX_SIZE);
if (bytesRead == MAX_SIZE) {
FileUtils.deleteQuietly(file);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.PHOTO_TOO_LARGE, "Photo too large, max " + MAX_SIZE + " bytes allowed"));
}
// additionally write the file to the input directory for Vsion.AI
FileUtils.copyFileToDirectory(file, inboxToProcessDir, true);
String duplicateInfo = "";
if (conflict) {
duplicateInfo = " (possible duplicate!)";
}
inboxUrl = inboxBaseUrl + "/" + URIUtil.encodePath(file.getName());
if (station != null) {
monitor.sendMessage(String.format("New photo upload for %s - %s:%s%n%s%n%s%s%nby %s%nvia %s",
station.getTitle(), station.getKey().getCountry(), station.getKey().getId(),
StringUtils.trimToEmpty(comment), inboxUrl, duplicateInfo, user.getName(), userAgent));
} else {
monitor.sendMessage(String.format("Photo upload for missing station %s at http://www.openstreetmap.org/?mlat=%s&mlon=%s&zoom=18&layers=M%n%s%n%s%s%nby %s%nvia %s",
stationTitle, latitude, longitude,
StringUtils.trimToEmpty(comment), inboxUrl, duplicateInfo, user.getName(), userAgent));
}
} catch (final IOException e) {
LOG.error("Error copying the uploaded file to {}", file, e);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.ERROR));
}
return new InboxResponse(conflict ? InboxResponse.InboxResponseState.CONFLICT : InboxResponse.InboxResponseState.REVIEW, id, file.getName(), inboxUrl);
}
private File getUploadFile(final String filename) {
return new File(inboxDir, filename);
}
private String createIFrameAnswer(final InboxResponse response, final String referer) throws JsonProcessingException {
return "<script language=\"javascript\" type=\"text/javascript\">" +
" window.top.window.postMessage('" + MAPPER.writeValueAsString(response) + "', '" + referer + "');" +
"</script>";
}
private boolean hasConflict(final Integer id, final Station station) {
if (station == null) {
return false;
}
if (station.hasPhoto()) {
return true;
}
return inboxDao.countPendingInboxEntriesForStation(id, station.getKey().getCountry(), station.getKey().getId()) > 0;
}
private boolean hasConflict(final Integer id, final Coordinates coordinates) {
if (coordinates == null || coordinates.hasNullCoords()) {
return false;
}
return inboxDao.countPendingInboxEntriesForNearbyCoordinates(id, coordinates) > 0 || repository.countNearbyCoordinates(coordinates) > 0;
}
private InboxResponse consumeBodyAndReturn(final InputStream body, final InboxResponse response) {
if (body != null) {
final InputStreamEntity inputStreamEntity = new InputStreamEntity(body);
try {
inputStreamEntity.writeTo(new NullOutputStream());
} catch (final IOException e) {
LOG.warn("Unable to consume body", e);
}
}
return response;
}
private String mimeToExtension(final String contentType) {
switch (contentType) {
case IMAGE_PNG:
return "png";
case IMAGE_JPEG:
return "jpg";
default:
return null;
}
}
private static class InboxCountResponse {
private final int pendingInboxEntries;
public InboxCountResponse(final int pendingInboxEntries) {
this.pendingInboxEntries = pendingInboxEntries;
}
public int getPendingInboxEntries() {
return pendingInboxEntries;
}
}
}
|
src/main/java/org/railwaystations/api/resources/InboxResource.java
|
package org.railwaystations.api.resources;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.auth.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.InputStreamEntity;
import org.eclipse.jetty.util.URIUtil;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.railwaystations.api.PhotoImporter;
import org.railwaystations.api.StationsRepository;
import org.railwaystations.api.auth.AuthUser;
import org.railwaystations.api.auth.UploadTokenAuthenticator;
import org.railwaystations.api.auth.UploadTokenCredentials;
import org.railwaystations.api.db.CountryDao;
import org.railwaystations.api.db.PhotoDao;
import org.railwaystations.api.db.InboxDao;
import org.railwaystations.api.db.UserDao;
import org.railwaystations.api.model.*;
import org.railwaystations.api.monitoring.Monitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.security.RolesAllowed;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.net.URLDecoder;
import java.util.List;
import java.util.Optional;
@Path("/")
public class InboxResource {
private static final Logger LOG = LoggerFactory.getLogger(InboxResource.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final long MAX_SIZE = 20_000_000L;
private static final String IMAGE_PNG = "image/png";
private static final String IMAGE_JPEG = "image/jpeg";
private final StationsRepository repository;
private final File inboxDir;
private final File photoDir;
private final Monitor monitor;
private final UploadTokenAuthenticator authenticator;
private final InboxDao inboxDao;
private final UserDao userDao;
private final CountryDao countryDao;
private final PhotoDao photoDao;
private final String inboxBaseUrl;
private final File inboxToProcessDir;
private final File inboxProcessedDir;
public InboxResource(final StationsRepository repository, final String inboxDir,
final String inboxToProcessDir, final String inboxProcessedDir, final String photoDir,
final Monitor monitor, final UploadTokenAuthenticator authenticator,
final InboxDao inboxDao, final UserDao userDao, final CountryDao countryDao,
final PhotoDao photoDao, final String inboxBaseUrl) {
this.repository = repository;
this.inboxDir = new File(inboxDir);
this.inboxToProcessDir = new File(inboxToProcessDir);
this.inboxProcessedDir = new File(inboxProcessedDir);
this.photoDir = new File(photoDir);
this.monitor = monitor;
this.authenticator = authenticator;
this.inboxDao = inboxDao;
this.userDao = userDao;
this.countryDao = countryDao;
this.photoDao = photoDao;
this.inboxBaseUrl = inboxBaseUrl;
}
/**
* Not part of the "official" API.
* Supports upload of photos via the website.
*/
@POST
@Path("photoUpload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String post(@HeaderParam("User-Agent") final String userAgent,
@FormDataParam("email") final String email,
@FormDataParam("uploadToken") final String uploadToken,
@FormDataParam("stationId") final String stationId,
@FormDataParam("countryCode") final String countryCode,
@FormDataParam("stationTitle") final String stationTitle,
@FormDataParam("latitude") final Double latitude,
@FormDataParam("longitude") final Double longitude,
@FormDataParam("comment") final String comment,
@FormDataParam("file") final InputStream file,
@FormDataParam("file") final FormDataContentDisposition fd,
@HeaderParam("Referer") final String referer) throws JsonProcessingException {
LOG.info("MultipartFormData: email={}, station={}, country={}, file={}", email, stationId, countryCode, fd.getFileName());
try {
final Optional<AuthUser> authUser = authenticator.authenticate(new UploadTokenCredentials(email, uploadToken));
if (!authUser.isPresent()) {
final InboxResponse response = consumeBodyAndReturn(file, new InboxResponse(InboxResponse.InboxResponseState.UNAUTHORIZED));
return createIFrameAnswer(response, referer);
}
final String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fd.getFileName());
final InboxResponse response = uploadPhoto(userAgent, file, StringUtils.trimToNull(stationId), StringUtils.trimToNull(countryCode), contentType, stationTitle, latitude, longitude, comment, authUser.get());
return createIFrameAnswer(response, referer);
} catch (final Exception e) {
LOG.error("FormUpload error", e);
return createIFrameAnswer(new InboxResponse(InboxResponse.InboxResponseState.ERROR), referer);
}
}
@POST
@Path("photoUpload")
@Consumes({IMAGE_PNG, IMAGE_JPEG})
@Produces(MediaType.APPLICATION_JSON)
public Response post(final InputStream body,
@HeaderParam("User-Agent") final String userAgent,
@HeaderParam("Station-Id") final String stationId,
@HeaderParam("Country") final String country,
@HeaderParam("Content-Type") final String contentType,
@HeaderParam("Station-Title") final String encStationTitle,
@HeaderParam("Latitude") final Double latitude,
@HeaderParam("Longitude") final Double longitude,
@HeaderParam("Comment") final String encComment,
@Auth final AuthUser user) throws UnsupportedEncodingException {
final String stationTitle = encStationTitle != null ? URLDecoder.decode(encStationTitle, "UTF-8") : null;
final String comment = encComment != null ? URLDecoder.decode(encComment, "UTF-8") : null;
LOG.info("Nickname: {}; Email: {}; Country: {}; Station-Id: {}; Coords: {},{}; Title: {}; Content-Type: {}",
user.getName(), user.getUser().getEmail(), country, stationId, latitude, longitude, stationTitle, contentType);
final InboxResponse inboxResponse = uploadPhoto(userAgent, body, StringUtils.trimToNull(stationId), StringUtils.trimToNull(country), contentType, stationTitle, latitude, longitude, comment, user);
return Response.status(inboxResponse.getState().getResponseStatus()).entity(inboxResponse).build();
}
@POST
@Path("reportProblem")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public InboxResponse reportProblem(@HeaderParam("User-Agent") final String userAgent,
@NotNull() final ProblemReport problemReport,
@Auth final AuthUser user) {
LOG.info("New problem report: Nickname: {}; Country: {}; Station-Id: {}",
user.getName(), problemReport.getCountryCode(), problemReport.getStationId());
final Station station = repository.findByCountryAndId(problemReport.getCountryCode(), problemReport.getStationId());
if (station == null) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Station not found");
}
if (StringUtils.isBlank(problemReport.getComment())) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Comment is mandatory");
}
if (problemReport.getType() == null) {
return new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Problem type is mandatory");
}
final InboxEntry inboxEntry = new InboxEntry(problemReport.getCountryCode(), problemReport.getStationId(),
null, null, user.getUser().getId(), null, problemReport.getComment(),
problemReport.getType());
monitor.sendMessage(String.format("New problem report for %s - %s:%s%n%s: %s%nby %s%nvia %s",
station.getTitle(), station.getKey().getCountry(), station.getKey().getId(), problemReport.getType(),
StringUtils.trimToEmpty(problemReport.getComment()), user.getName(), userAgent));
return new InboxResponse(InboxResponse.InboxResponseState.REVIEW, inboxDao.insert(inboxEntry));
}
@GET
@Path("publicInbox")
@Produces(MediaType.APPLICATION_JSON)
public List<PublicInboxEntry> publicInbox() {
return inboxDao.findPublicInboxEntries();
}
@POST
@Path("userInbox")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<InboxStateQuery> userInbox(@Auth final AuthUser user, @NotNull final List<InboxStateQuery> queries) {
LOG.info("Query uploadStatus for Nickname: {}", user.getName());
for (final InboxStateQuery query : queries) {
query.setState(InboxStateQuery.InboxState.UNKNOWN);
if (query.getId() != null) {
final InboxEntry inboxEntry = inboxDao.findById(query.getId());
if (inboxEntry != null && inboxEntry.getPhotographerId() == user.getUser().getId()) {
query.setRejectedReason(inboxEntry.getRejectReason());
query.setCountryCode(inboxEntry.getCountryCode());
query.setStationId(inboxEntry.getStationId());
query.setCoordinates(inboxEntry.getCoordinates());
query.setFilename(inboxEntry.getFilename());
query.setInboxUrl(getInboxUrl(inboxEntry.getFilename(), isProcessed(inboxEntry.getFilename())));
if (inboxEntry.isDone()) {
if (inboxEntry.getRejectReason() == null) {
query.setState(InboxStateQuery.InboxState.ACCEPTED);
} else {
query.setState(InboxStateQuery.InboxState.REJECTED);
}
} else {
if (hasConflict(inboxEntry.getId(),
repository.findByCountryAndId(query.getCountryCode(), query.getStationId()))
|| hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates())) {
query.setState(InboxStateQuery.InboxState.CONFLICT);
} else {
query.setState(InboxStateQuery.InboxState.REVIEW);
}
}
}
}
}
return queries;
}
@GET
@RolesAllowed("ADMIN")
@Path("adminInbox")
@Produces(MediaType.APPLICATION_JSON)
public List<InboxEntry> adminInbox(@Auth final AuthUser user) {
final List<InboxEntry> pendingInboxEntries = inboxDao.findPendingInboxEntries();
for (final InboxEntry inboxEntry : pendingInboxEntries) {
final String filename = inboxEntry.getFilename();
inboxEntry.isProcessed(isProcessed(filename));
if (!inboxEntry.isProblemReport()) {
inboxEntry.setInboxUrl(getInboxUrl(filename, inboxEntry.isProcessed()));
}
if (!inboxEntry.getCoordinates().hasNullCoords()) {
inboxEntry.setConflict(hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates()));
}
}
return pendingInboxEntries;
}
private String getInboxUrl(final String filename, final boolean processed) {
return inboxBaseUrl + (processed ? "/processed/" : "/") + filename;
}
private boolean isProcessed(final String filename) {
return filename != null && new File(inboxProcessedDir, filename).exists();
}
@POST
@RolesAllowed("ADMIN")
@Path("adminInbox")
@Consumes(MediaType.APPLICATION_JSON)
public Response adminInbox(@Auth final AuthUser user, final InboxEntry command) {
final InboxEntry inboxEntry = inboxDao.findById(command.getId());
if (inboxEntry == null || inboxEntry.isDone()) {
throw new WebApplicationException("No pending inbox entry found", Response.Status.BAD_REQUEST);
}
switch (command.getCommand()) {
case REJECT :
rejectInboxEntry(inboxEntry, command.getRejectReason());
break;
case IMPORT :
importUpload(inboxEntry, command);
break;
case DEACTIVATE_STATION:
deactivateStation(inboxEntry);
break;
case DELETE_STATION:
deleteStation(inboxEntry);
break;
case DELETE_PHOTO:
deletePhoto(inboxEntry);
break;
case MARK_SOLVED:
markProblemReportSolved(inboxEntry);
break;
default:
throw new WebApplicationException("Unexpected command value: " + command.getCommand(), Response.Status.BAD_REQUEST);
}
return Response.ok().build();
}
@GET
@RolesAllowed("ADMIN")
@Path("adminInboxCount")
@Produces(MediaType.APPLICATION_JSON)
public InboxCountResponse adminInboxCount(@Auth final AuthUser user) {
return new InboxCountResponse(inboxDao.countPendingInboxEntries());
}
private void deactivateStation(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
repository.deactivate(station);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} station {} deactivated", inboxEntry.getId(), station.getKey());
}
private void deleteStation(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
photoDao.delete(station.getKey());
repository.delete(station);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} station {} deleted", inboxEntry.getId(), station.getKey());
}
private void deletePhoto(final InboxEntry inboxEntry) {
final Station station = assertStationExists(inboxEntry);
photoDao.delete(station.getKey());
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} photo of station {} deleted", inboxEntry.getId(), station.getKey());
}
private void markProblemReportSolved(final InboxEntry inboxEntry) {
assertStationExists(inboxEntry);
inboxDao.done(inboxEntry.getId());
LOG.info("Problem report {} accepted", inboxEntry.getId());
}
private Station assertStationExists(final InboxEntry inboxEntry) {
final Station station = repository.findByCountryAndId(inboxEntry.getCountryCode(), inboxEntry.getStationId());
if (station == null) {
throw new WebApplicationException("Station not found", Response.Status.BAD_REQUEST);
}
return station;
}
private void importUpload(final InboxEntry inboxEntry, final InboxEntry command) {
final File originalFile = getUploadFile(inboxEntry.getFilename());
final File processedFile = new File(inboxProcessedDir, inboxEntry.getFilename());
final File fileToImport = processedFile.exists() ? processedFile : originalFile;
LOG.info("Importing upload {}, {}", inboxEntry.getId(), fileToImport);
boolean updateStationKey = false;
Station station = repository.findByCountryAndId(inboxEntry.getCountryCode(), inboxEntry.getStationId());
if (station == null) {
station = repository.findByCountryAndId(command.getCountryCode(), command.getStationId());
updateStationKey = true;
}
if (station == null) {
if (!command.createStation()
|| StringUtils.isNotBlank(inboxEntry.getCountryCode())
|| StringUtils.isNotBlank(inboxEntry.getStationId())) {
throw new WebApplicationException("Station not found", Response.Status.BAD_REQUEST);
}
// create station
final Optional<Country> country = countryDao.findById(StringUtils.lowerCase(command.getCountryCode()));
if (!country.isPresent()) {
throw new WebApplicationException("Country not found", Response.Status.BAD_REQUEST);
}
if (StringUtils.isBlank(command.getStationId())) {
throw new WebApplicationException("Station ID can't be empty", Response.Status.BAD_REQUEST);
}
if (hasConflict(inboxEntry.getId(), inboxEntry.getCoordinates()) && !command.ignoreConflict()) {
throw new WebApplicationException("There is a conflict with a nearby station", Response.Status.BAD_REQUEST);
}
station = new Station(new Station.Key(command.getCountryCode(), command.getStationId()), inboxEntry.getTitle(), inboxEntry.getCoordinates(), command.getDS100(), null, command.isActive());
repository.insert(station);
}
if (station.hasPhoto() && !command.ignoreConflict()) {
throw new WebApplicationException("Station already has a photo", Response.Status.BAD_REQUEST);
}
if (hasConflict(inboxEntry.getId(), station) && !command.ignoreConflict()) {
throw new WebApplicationException("There is a conflict with another upload", Response.Status.BAD_REQUEST);
}
final Optional<User> user = userDao.findById(inboxEntry.getPhotographerId());
final Optional<Country> country = countryDao.findById(StringUtils.lowerCase(station.getKey().getCountry()));
if (!country.isPresent()) {
throw new WebApplicationException("Country not found", Response.Status.BAD_REQUEST);
}
try {
final File countryDir = new File(photoDir, station.getKey().getCountry());
final Photo photo = PhotoImporter.createPhoto(station.getKey().getCountry(), country, station.getKey().getId(), user.get(), inboxEntry.getExtension());
if (station.hasPhoto()) {
photoDao.update(photo);
FileUtils.deleteQuietly(new File(countryDir, station.getKey().getId() + "." + inboxEntry.getExtension()));
} else {
photoDao.insert(photo);
}
if (processedFile.exists()) {
PhotoImporter.moveFile(processedFile, countryDir, station.getKey().getId(), inboxEntry.getExtension());
} else {
PhotoImporter.copyFile(originalFile, countryDir, station.getKey().getId(), inboxEntry.getExtension());
}
FileUtils.moveFileToDirectory(originalFile, new File(inboxDir, "done"), true);
if (updateStationKey) {
inboxDao.done(inboxEntry.getId(), command.getCountryCode(), command.getStationId());
} else {
inboxDao.done(inboxEntry.getId());
}
LOG.info("Upload {} accepted: {}", inboxEntry.getId(), fileToImport);
} catch (final Exception e) {
LOG.error("Error importing upload {} photo {}", inboxEntry.getId(), fileToImport);
throw new WebApplicationException("Error moving file: " + e.getMessage());
}
}
private void rejectInboxEntry(final InboxEntry inboxEntry, final String rejectReason) {
inboxDao.reject(inboxEntry.getId(), rejectReason);
if (inboxEntry.isProblemReport()) {
LOG.info("Rejecting problem report {}, {}", inboxEntry.getId(), rejectReason);
return;
}
final File file = getUploadFile(inboxEntry.getFilename());
LOG.info("Rejecting upload {}, {}, {}", inboxEntry.getId(), rejectReason, file);
try {
final File rejectDir = new File(inboxDir, "rejected");
FileUtils.moveFileToDirectory(file, rejectDir, true);
FileUtils.deleteQuietly(new File(inboxToProcessDir, inboxEntry.getFilename()));
FileUtils.deleteQuietly(new File(inboxProcessedDir, inboxEntry.getFilename()));
} catch (final IOException e) {
LOG.warn("Unable to move rejected file {}", file, e);
}
}
private InboxResponse uploadPhoto(final String userAgent, final InputStream body, final String stationId,
final String country, final String contentType, final String stationTitle,
final Double latitude, final Double longitude, final String comment,
final AuthUser user) {
final Station station = repository.findByCountryAndId(country, stationId);
Coordinates coordinates = null;
if (station == null) {
LOG.warn("Station not found");
if (StringUtils.isBlank(stationTitle) || latitude == null || longitude == null) {
LOG.warn("Not enough data for missing station: title={}, latitude={}, longitude={}", stationTitle, latitude, longitude);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.NOT_ENOUGH_DATA, "Not enough data: either 'country' and 'stationId' or 'title', 'latitude' and 'longitude' have to be provided"));
}
if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180) {
LOG.warn("Lat/Lon out of range: latitude={}, longitude={}", latitude, longitude);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.LAT_LON_OUT_OF_RANGE, "'latitude' and/or 'longitude' out of range"));
}
coordinates = new Coordinates(latitude, longitude);
}
final String extension = mimeToExtension(contentType);
if (extension == null) {
LOG.warn("Unknown contentType '{}'", contentType);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.UNSUPPORTED_CONTENT_TYPE, "unsupported content type (only jpg and png are supported)"));
}
final boolean conflict = hasConflict(null, station) || hasConflict(null, new Coordinates(latitude, longitude));
File file = null;
final String inboxUrl;
final Integer id;
try {
if (station != null) {
// existing station
id = inboxDao.insert(new InboxEntry(station.getKey().getCountry(), station.getKey().getId(), stationTitle,
coordinates, user.getUser().getId(), extension, comment, null));
} else {
// missing station
id = inboxDao.insert(new InboxEntry(null, null, stationTitle,
coordinates, user.getUser().getId(), extension, comment, null));
}
file = getUploadFile(InboxEntry.getFilename(id, extension));
LOG.info("Writing photo to {}", file);
// write the file to the inbox directory
FileUtils.forceMkdir(inboxDir);
final long bytesRead = IOUtils.copyLarge(body, new FileOutputStream(file), 0L, MAX_SIZE);
if (bytesRead == MAX_SIZE) {
FileUtils.deleteQuietly(file);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.PHOTO_TOO_LARGE, "Photo too large, max " + MAX_SIZE + " bytes allowed"));
}
// additionally write the file to the input directory for Vsion.AI
FileUtils.copyFileToDirectory(file, inboxToProcessDir, true);
String duplicateInfo = "";
if (conflict) {
duplicateInfo = " (possible duplicate!)";
}
inboxUrl = inboxBaseUrl + "/" + URIUtil.encodePath(file.getName());
if (station != null) {
monitor.sendMessage(String.format("New photo upload for %s - %s:%s%n%s%n%s%s%nby %s%nvia %s",
station.getTitle(), station.getKey().getCountry(), station.getKey().getId(),
StringUtils.trimToEmpty(comment), inboxUrl, duplicateInfo, user.getName(), userAgent));
} else {
monitor.sendMessage(String.format("Photo upload for missing station %s at http://www.openstreetmap.org/?mlat=%s&mlon=%s&zoom=18&layers=M%n%s%n%s%s%nby %s%nvia %s",
stationTitle, latitude, longitude,
StringUtils.trimToEmpty(comment), inboxUrl, duplicateInfo, user.getName(), userAgent));
}
} catch (final IOException e) {
LOG.error("Error copying the uploaded file to {}", file, e);
return consumeBodyAndReturn(body, new InboxResponse(InboxResponse.InboxResponseState.ERROR));
}
return new InboxResponse(conflict ? InboxResponse.InboxResponseState.CONFLICT : InboxResponse.InboxResponseState.REVIEW, id, file.getName(), inboxUrl);
}
private File getUploadFile(final String filename) {
return new File(inboxDir, filename);
}
private String createIFrameAnswer(final InboxResponse response, final String referer) throws JsonProcessingException {
return "<script language=\"javascript\" type=\"text/javascript\">" +
" window.top.window.postMessage('" + MAPPER.writeValueAsString(response) + "', '" + referer + "');" +
"</script>";
}
private boolean hasConflict(final Integer id, final Station station) {
if (station == null) {
return false;
}
if (station.hasPhoto()) {
return true;
}
return inboxDao.countPendingInboxEntriesForStation(id, station.getKey().getCountry(), station.getKey().getId()) > 0;
}
private boolean hasConflict(final Integer id, final Coordinates coordinates) {
if (coordinates == null || coordinates.hasNullCoords()) {
return false;
}
return inboxDao.countPendingInboxEntriesForNearbyCoordinates(id, coordinates) > 0 || repository.countNearbyCoordinates(coordinates) > 0;
}
private InboxResponse consumeBodyAndReturn(final InputStream body, final InboxResponse response) {
if (body != null) {
final InputStreamEntity inputStreamEntity = new InputStreamEntity(body);
try {
inputStreamEntity.writeTo(new NullOutputStream());
} catch (final IOException e) {
LOG.warn("Unable to consume body", e);
}
}
return response;
}
private String mimeToExtension(final String contentType) {
switch (contentType) {
case IMAGE_PNG:
return "png";
case IMAGE_JPEG:
return "jpg";
default:
return null;
}
}
private static class InboxCountResponse {
private final int pendingInboxEntries;
public InboxCountResponse(final int pendingInboxEntries) {
this.pendingInboxEntries = pendingInboxEntries;
}
public int getPendingInboxEntries() {
return pendingInboxEntries;
}
}
}
|
fix null latitude, longitude
|
src/main/java/org/railwaystations/api/resources/InboxResource.java
|
fix null latitude, longitude
|
|
Java
|
mit
|
772664650d84618444df02dbc9fb63103a7cb781
| 0
|
CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab
|
package org.xcolab.portlets.proposals.utils;
import com.ext.portlet.ProposalImpactAttributeKeys;
import com.ext.portlet.model.Contest;
import com.ext.portlet.model.FocusArea;
import com.ext.portlet.model.OntologyTerm;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.service.OntologyTermLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.Validator;
import org.xcolab.portlets.proposals.exceptions.ProposalImpactDataParserException;
import org.xcolab.portlets.proposals.wrappers.ProposalImpactSeries;
import org.xcolab.portlets.proposals.wrappers.ProposalImpactSeriesList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class is used to parse inline proposal impact data (tab-separated Excel string) to a
* ProposalImpactSeriesList object.
*
* Used for the IAF fellow impact series edit feature
*
* Created by kmang on 04/06/15.
*/
public class ProposalImpactDataParser {
private static final Log _log = LogFactoryUtil.getLog(ProposalImpactDataParser.class);
private static final String EXCEL_SERIES_TYPE_BAU_KEY = "Business as usual";
private static final String EXCEL_SERIES_TYPE_REDUCTION_KEY = "emission reduction";
private static final String EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY = "Adoption rate";
private static final String EXCEL_SERIES_TYPE_RESULT_KEY = "Estimated CO2 reduction";
private static final String[] excelSeriesTypeKeys = {EXCEL_SERIES_TYPE_BAU_KEY, EXCEL_SERIES_TYPE_REDUCTION_KEY, EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY, EXCEL_SERIES_TYPE_REDUCTION_KEY};
private static final Map<String, String> excelTermToOntologyTermNameMap;
static {
excelTermToOntologyTermNameMap = new HashMap<>();
excelTermToOntologyTermNameMap.put("Transport", "Transportation");
excelTermToOntologyTermNameMap.put("EnergySupply", "Energy supply");
excelTermToOntologyTermNameMap.put("Other", "Land use & other sectors");
excelTermToOntologyTermNameMap.put("All other developed countries", "Other developed countries");
excelTermToOntologyTermNameMap.put("All other developing countries", "Other developing countries");
}
private static final Map<String, String> excelSeriesTypeToSeriesTypeMap;
static {
excelSeriesTypeToSeriesTypeMap = new HashMap<>(excelSeriesTypeKeys.length);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_BAU_KEY, ProposalImpactSeries.SERIES_TYPE_BAU_KEY); // we don't need this one
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_REDUCTION_KEY, ProposalImpactAttributeKeys.IMPACT_REDUCTION);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY, ProposalImpactAttributeKeys.IMPACT_ADOPTION_RATE);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_RESULT_KEY, ""); // we don't need this one
}
private String tabSeparatedString;
private Proposal proposal;
private Contest contest;
/**
* Creates a new ProposalImpactDataParser object with the input String (tab-separated string copy-pasted from Excel)
* and the Contest of the proposal in question.
*
* @param tabSeparatedString
* @param contest
*/
public ProposalImpactDataParser(String tabSeparatedString, Proposal proposal, Contest contest) {
this.tabSeparatedString = tabSeparatedString;
this.proposal = proposal;
this.contest = contest;
}
public ProposalImpactSeriesList parse() throws PortalException, SystemException, ProposalImpactDataParserException {
String[] inputLines = getLines(tabSeparatedString);
List<String> parsedSeriesTypeKeys = getParsedSeriesTypeKeys(inputLines);
List<Long> iterationYears = getParsedIterationYears(inputLines);
return parseExcelData(Arrays.copyOfRange(inputLines, 2, inputLines.length), parsedSeriesTypeKeys, iterationYears);
}
private List<String> getParsedSeriesTypeKeys(String[] inputLines) throws ProposalImpactDataParserException {
if (ArrayUtil.isEmpty(inputLines)) {
return null;
}
String headLine = inputLines[0];
List<String> seriesTypes = new ArrayList<>();
for (String headLineColumn : getTabbedStrings(headLine)) {
boolean foundMatch = false;
// Ignore empty columns (tabs)
if (Validator.isNotNull(headLineColumn)) {
// Try to match excelSeriesType from input
for (String excelSeriesKey : excelSeriesTypeToSeriesTypeMap.keySet()) {
if (headLineColumn.contains(excelSeriesKey)) {
String seriesType = excelSeriesTypeToSeriesTypeMap.get(excelSeriesKey);
seriesTypes.add(seriesType);
foundMatch = true;
break;
}
}
if (!foundMatch) {
throw new ProposalImpactDataParserException("Could not match data column '" + headLineColumn + "'");
}
}
}
return seriesTypes;
}
private List<Long> getParsedIterationYears(String[] inputLines) {
if (ArrayUtil.isEmpty(inputLines)) {
return null;
}
String iterationYearLine = inputLines[1];
List<Long> iterationYears = new ArrayList<>();
for (String iterationYearColumn : getTabbedStrings(iterationYearLine)) {
// Ignore empty columns (tabs)
if (Validator.isNotNull(iterationYearColumn)) {
try {
long iterationYear = Long.parseLong(iterationYearColumn);
// Ignore duplicates
if (iterationYears.contains(iterationYear)) {
break;
}
iterationYears.add(iterationYear);
} catch (NumberFormatException e) {
_log.error("Could not parse string to iteration year '" + iterationYearColumn + "' of line 1 '" + iterationYearLine + "'", e);
throw e;
}
}
}
return iterationYears;
}
private ProposalImpactSeriesList parseExcelData(String[] inputLines,
List<String> parsedSeriesTypeKeys,
List<Long> iterationYears) throws SystemException, PortalException, ProposalImpactDataParserException {
ProposalImpactSeriesList seriesList = new ProposalImpactSeriesList(this.contest, this.proposal);
ProposalImpactUtil proposalImpactUtil = new ProposalImpactUtil(contest);
OntologyTerm regionTerm = null;
int inputLineNumber = 2;
for (String inputLine : inputLines) {
String[] dataStrings = getTabbedStrings(inputLine);
// We need at least the region+sector and one full iteration of years
if (ArrayUtil.isNotEmpty(dataStrings) && dataStrings.length >= 2 + iterationYears.size()) {
OntologyTerm sectorTerm;
try {
// Some of the first columns are empty - use old region term instead
if (Validator.isNotNull(dataStrings[0])) {
regionTerm = getOntologyTermByName(dataStrings[0]);
}
sectorTerm = getOntologyTermByName(dataStrings[1]);
} catch (Exception e) {
_log.error(e.getMessage() + " on line " + inputLineNumber);
throw new ProposalImpactDataParserException(e);
}
FocusArea focusArea = proposalImpactUtil.getFocusAreaAssociatedWithTerms(sectorTerm, regionTerm);
ProposalImpactSeries newProposalImpactSeries = new ProposalImpactSeries(contest, proposal, focusArea);
// Write the new impact series values
for (int idx = 2; idx < dataStrings.length; idx++) {
String dataString = dataStrings[idx];
String currentSeriesType = parsedSeriesTypeKeys.get(((idx - 2) / iterationYears.size()));
// If the seriesType is not set we just ignore all upcoming values
if (Validator.isNull(currentSeriesType)) {
idx += iterationYears.size() - 1;
continue;
}
// Empty lines are not tolerated - abort
if (Validator.isNull(dataString)) {
throw new ProposalImpactDataParserException("Empty data column detected in line '" + inputLine);
}
long year = iterationYears.get((idx - 2) % iterationYears.size());
try {
setProposalImpactSeriesValue(newProposalImpactSeries, currentSeriesType, year, dataString);
} catch (NumberFormatException e) {
_log.error("Could not parse string '" + dataString + "' to double value");
throw new ProposalImpactDataParserException("\"Could not parse string '\" + dataString + \"' to double value\"", e);
}
}
seriesList.addProposalImpactSeries(newProposalImpactSeries);
} else {
throw new ProposalImpactDataParserException("Could not parse data line '\" + StringUtils.join(dataStrings, \",\") + \"'; line too short");
}
}
return seriesList;
}
private void setProposalImpactSeriesValue(ProposalImpactSeries proposalImpactSeries, String seriesType, long year, String valueString) {
double value = parseDataValue(seriesType, valueString);
proposalImpactSeries.addSeriesValueWithType(seriesType, (int)year, value);
}
private double parseDataValue(String seriesType, String valueString) {
// percentage value
if (valueString.contains("%")) {
return Double.parseDouble(valueString.substring(0, valueString.length() - 1));
} else {
double value = Double.parseDouble(valueString.substring(0, valueString.length() - 1));
// Interpret impact reduction and adoption values as ratios
if ((seriesType.equals(ProposalImpactAttributeKeys.IMPACT_REDUCTION) || seriesType.equals(ProposalImpactAttributeKeys.IMPACT_ADOPTION_RATE))) {
return value * 100.; // impact reduction and adoption rate values are stored as percentage values (0-100%)
} else {
return value;
}
}
}
private OntologyTerm getOntologyTermByName(String name) throws SystemException, ProposalImpactDataParserException {
// Use mapped name value if it exists
if (Validator.isNotNull(excelTermToOntologyTermNameMap.get(name))) {
name = excelTermToOntologyTermNameMap.get(name);
}
List<OntologyTerm> ontologyTerms = OntologyTermLocalServiceUtil.findByOntologyTermName(name);
if (Validator.isNull(ontologyTerms) || ontologyTerms.size() == 0) {
throw new ProposalImpactDataParserException("Could not match ontology term with name '" + name + "'");
}
return ontologyTerms.get(0);
}
private String[] getTabbedStrings(String inputLine) {
return inputLine.split("\\t", -1);
}
private String[] getLines(String inputLines) {
return inputLines.split("\\n", -1);
}
}
|
portlets/proposals-portlet/src/main/java/org/xcolab/portlets/proposals/utils/ProposalImpactDataParser.java
|
package org.xcolab.portlets.proposals.utils;
import com.ext.portlet.ProposalImpactAttributeKeys;
import com.ext.portlet.model.Contest;
import com.ext.portlet.model.FocusArea;
import com.ext.portlet.model.OntologyTerm;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.service.OntologyTermLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import org.apache.commons.lang.StringUtils;
import org.xcolab.portlets.proposals.exceptions.ProposalImpactDataParserException;
import org.xcolab.portlets.proposals.wrappers.ProposalImpactSeries;
import org.xcolab.portlets.proposals.wrappers.ProposalImpactSeriesList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class is used to parse inline proposal impact data (tab-separated Excel string) to a
* ProposalImpactSeriesList object.
*
* Used for the IAF fellow impact series edit feature
*
* Created by kmang on 04/06/15.
*/
public class ProposalImpactDataParser {
private static final Log _log = LogFactoryUtil.getLog(ProposalImpactDataParser.class);
private static final String EXCEL_SERIES_TYPE_BAU_KEY = "Business as usual";
private static final String EXCEL_SERIES_TYPE_REDUCTION_KEY = "emission reduction";
private static final String EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY = "Adoption rate";
private static final String EXCEL_SERIES_TYPE_RESULT_KEY = "Estimated CO2 reduction";
private static final String[] excelSeriesTypeKeys = {EXCEL_SERIES_TYPE_BAU_KEY, EXCEL_SERIES_TYPE_REDUCTION_KEY, EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY, EXCEL_SERIES_TYPE_REDUCTION_KEY};
private static final Map<String, String> excelSectorToWhatTermNameMap;
static {
excelSectorToWhatTermNameMap = new HashMap<>();
excelSectorToWhatTermNameMap.put("Transport", "Transportation");
excelSectorToWhatTermNameMap.put("Generation", "Energy supply");
excelSectorToWhatTermNameMap.put("Consumption", "Land use & other sectors");
excelSectorToWhatTermNameMap.put("All other developed countries", "Other developed countries");
excelSectorToWhatTermNameMap.put("All other developing countries", "Other developing countries");
// Todo add more terms if neccessary
}
private static final Map<String, String> excelSeriesTypeToSeriesTypeMap;
static {
excelSeriesTypeToSeriesTypeMap = new HashMap<>(excelSeriesTypeKeys.length);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_BAU_KEY, ProposalImpactSeries.SERIES_TYPE_BAU_KEY); // we don't need this one
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_REDUCTION_KEY, ProposalImpactAttributeKeys.IMPACT_REDUCTION);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_ADOPTION_RATE_KEY, ProposalImpactAttributeKeys.IMPACT_ADOPTION_RATE);
excelSeriesTypeToSeriesTypeMap.put(EXCEL_SERIES_TYPE_RESULT_KEY, ""); // we don't need this one
}
private String tabSeparatedString;
private Proposal proposal;
private Contest contest;
/**
* Creates a new ProposalImpactDataParser object with the input String (tab-separated string copy-pasted from Excel)
* and the Contest of the proposal in question.
*
* @param tabSeparatedString
* @param contest
*/
public ProposalImpactDataParser(String tabSeparatedString, Proposal proposal, Contest contest) {
this.tabSeparatedString = tabSeparatedString;
this.proposal = proposal;
this.contest = contest;
}
public ProposalImpactSeriesList parse() throws PortalException, SystemException, ProposalImpactDataParserException {
String[] inputLines = getLines(tabSeparatedString);
List<String> parsedSeriesTypeKeys = getParsedSeriesTypeKeys(inputLines);
List<Long> iterationYears = getParsedIterationYears(inputLines);
return parseExcelData(Arrays.copyOfRange(inputLines, 2, inputLines.length), parsedSeriesTypeKeys, iterationYears);
}
private List<String> getParsedSeriesTypeKeys(String[] inputLines) throws ProposalImpactDataParserException {
if (ArrayUtil.isEmpty(inputLines)) {
return null;
}
String headLine = inputLines[0];
List<String> seriesTypes = new ArrayList<>();
for (String headLineColumn : getTabbedStrings(headLine)) {
boolean foundMatch = false;
// Ignore empty columns (tabs)
if (Validator.isNotNull(headLineColumn)) {
// Try to match excelSeriesType from input
for (String excelSeriesKey : excelSeriesTypeToSeriesTypeMap.keySet()) {
if (headLineColumn.contains(excelSeriesKey)) {
String seriesType = excelSeriesTypeToSeriesTypeMap.get(excelSeriesKey);
seriesTypes.add(seriesType);
foundMatch = true;
break;
}
}
if (!foundMatch) {
throw new ProposalImpactDataParserException("Could not match data column '" + headLineColumn + "'");
}
}
}
return seriesTypes;
}
private List<Long> getParsedIterationYears(String[] inputLines) {
if (ArrayUtil.isEmpty(inputLines)) {
return null;
}
String iterationYearLine = inputLines[1];
List<Long> iterationYears = new ArrayList<>();
for (String iterationYearColumn : getTabbedStrings(iterationYearLine)) {
// Ignore empty columns (tabs)
if (Validator.isNotNull(iterationYearColumn)) {
try {
long iterationYear = Long.parseLong(iterationYearColumn);
// Ignore duplicates
if (iterationYears.contains(iterationYear)) {
break;
}
iterationYears.add(iterationYear);
} catch (NumberFormatException e) {
_log.error("Could not parse string to iteration year '" + iterationYearColumn + "' of line 1 '" + iterationYearLine + "'", e);
throw e;
}
}
}
return iterationYears;
}
private ProposalImpactSeriesList parseExcelData(String[] inputLines,
List<String> parsedSeriesTypeKeys,
List<Long> iterationYears) throws SystemException, PortalException, ProposalImpactDataParserException {
ProposalImpactSeriesList seriesList = new ProposalImpactSeriesList(this.contest, this.proposal);
ProposalImpactUtil proposalImpactUtil = new ProposalImpactUtil(contest);
OntologyTerm regionTerm = null;
int inputLineNumber = 2;
for (String inputLine : inputLines) {
String[] dataStrings = getTabbedStrings(inputLine);
// We need at least the region+sector and one full iteration of years
if (ArrayUtil.isNotEmpty(dataStrings) && dataStrings.length >= 2 + iterationYears.size()) {
OntologyTerm sectorTerm;
try {
// Some of the first columns are empty - use old region term instead
if (Validator.isNotNull(dataStrings[0])) {
regionTerm = getOntologyTermByName(dataStrings[0]);
}
sectorTerm = getOntologyTermByName(dataStrings[1]);
} catch (Exception e) {
_log.error(e.getMessage() + " on line " + inputLineNumber);
throw new ProposalImpactDataParserException(e);
}
FocusArea focusArea = proposalImpactUtil.getFocusAreaAssociatedWithTerms(sectorTerm, regionTerm);
ProposalImpactSeries newProposalImpactSeries = new ProposalImpactSeries(contest, proposal, focusArea);
// Write the new impact series values
for (int idx = 2; idx < dataStrings.length; idx++) {
String dataString = dataStrings[idx];
String currentSeriesType = parsedSeriesTypeKeys.get(((idx - 2) / iterationYears.size()));
// If the seriesType is not set we just ignore all upcoming values
if (Validator.isNull(currentSeriesType)) {
idx += iterationYears.size() - 1;
continue;
}
// Empty lines are not tolerated - abort
if (Validator.isNull(dataString)) {
throw new ProposalImpactDataParserException("Empty data column detected in line '" + inputLine);
}
long year = iterationYears.get((idx - 2) % iterationYears.size());
try {
setProposalImpactSeriesValue(newProposalImpactSeries, currentSeriesType, year, dataString);
} catch (NumberFormatException e) {
_log.error("Could not parse string '" + dataString + "' to double value");
throw new ProposalImpactDataParserException("\"Could not parse string '\" + dataString + \"' to double value\"", e);
}
}
seriesList.addProposalImpactSeries(newProposalImpactSeries);
} else {
throw new ProposalImpactDataParserException("Could not parse data line '\" + StringUtils.join(dataStrings, \",\") + \"'; line too short");
}
}
return seriesList;
}
private void setProposalImpactSeriesValue(ProposalImpactSeries proposalImpactSeries, String seriesType, long year, String valueString) {
double value = parseDataValue(seriesType, valueString);
proposalImpactSeries.addSeriesValueWithType(seriesType, (int)year, value);
}
private double parseDataValue(String seriesType, String valueString) {
// percentage value
if (valueString.contains("%")) {
return Double.parseDouble(valueString.substring(0, valueString.length() - 1));
} else {
double value = Double.parseDouble(valueString.substring(0, valueString.length() - 1));
// Interpret impact reduction and adoption values as ratios
if ((seriesType.equals(ProposalImpactAttributeKeys.IMPACT_REDUCTION) || seriesType.equals(ProposalImpactAttributeKeys.IMPACT_ADOPTION_RATE))) {
return value * 100.; // impact reduction and adoption rate values are stored as percentage values (0-100%)
} else {
return value;
}
}
}
private OntologyTerm getOntologyTermByName(String name) throws SystemException, ProposalImpactDataParserException {
// Use mapped name value if it exists
if (Validator.isNotNull(excelSectorToWhatTermNameMap.get(name))) {
name = excelSectorToWhatTermNameMap.get(name);
}
List<OntologyTerm> ontologyTerms = OntologyTermLocalServiceUtil.findByOntologyTermName(name);
if (Validator.isNull(ontologyTerms) || ontologyTerms.size() == 0) {
throw new ProposalImpactDataParserException("Could not match ontology term with name '" + name + "'");
}
return ontologyTerms.get(0);
}
private String[] getTabbedStrings(String inputLine) {
return inputLine.split("\\t", -1);
}
private String[] getLines(String inputLines) {
return inputLines.split("\\n", -1);
}
}
|
[COLAB-378] Changed a few excelTermToOntologyTermNameMap strings
|
portlets/proposals-portlet/src/main/java/org/xcolab/portlets/proposals/utils/ProposalImpactDataParser.java
|
[COLAB-378] Changed a few excelTermToOntologyTermNameMap strings
|
|
Java
|
mit
|
914f71b8594f5e7a30b8028cc7b2adc78976f8b4
| 0
|
sonork/spongycastle,open-keychain/spongycastle,sergeypayu/bc-java,Skywalker-11/spongycastle,iseki-masaya/spongycastle,partheinstein/bc-java,lesstif/spongycastle,partheinstein/bc-java,isghe/bc-java,iseki-masaya/spongycastle,sonork/spongycastle,partheinstein/bc-java,FAU-Inf2/spongycastle,savichris/spongycastle,lesstif/spongycastle,onessimofalconi/bc-java,sonork/spongycastle,lesstif/spongycastle,bcgit/bc-java,iseki-masaya/spongycastle,bcgit/bc-java,savichris/spongycastle,savichris/spongycastle,Skywalker-11/spongycastle,sergeypayu/bc-java,open-keychain/spongycastle,onessimofalconi/bc-java,isghe/bc-java,open-keychain/spongycastle,FAU-Inf2/spongycastle,isghe/bc-java,Skywalker-11/spongycastle,FAU-Inf2/spongycastle,onessimofalconi/bc-java,bcgit/bc-java,sergeypayu/bc-java
|
package org.bouncycastle.crypto.tls.test;
import java.security.SecureRandom;
import junit.framework.TestCase;
import org.bouncycastle.crypto.tls.DTLSClientProtocol;
import org.bouncycastle.crypto.tls.DTLSServerProtocol;
import org.bouncycastle.crypto.tls.DTLSTransport;
import org.bouncycastle.crypto.tls.DatagramTransport;
import org.bouncycastle.util.Arrays;
public class DTLSProtocolTest extends TestCase {
public void testClientServer() throws Exception {
SecureRandom secureRandom = new SecureRandom();
DTLSClientProtocol clientProtocol = new DTLSClientProtocol(secureRandom);
DTLSServerProtocol serverProtocol = new DTLSServerProtocol(secureRandom);
MockDatagramAssociation network = new MockDatagramAssociation(1500);
ServerThread serverThread = new ServerThread(serverProtocol, network.getServer());
serverThread.start();
DatagramTransport clientTransport = network.getClient();
clientTransport = new UnreliableDatagramTransport(clientTransport, secureRandom, 0, 0);
clientTransport = new LoggingDatagramTransport(clientTransport, System.out);
MockDTLSClient client = new MockDTLSClient();
DTLSTransport dtlsClient = clientProtocol.connect(client, clientTransport);
for (int i = 1; i <= 10; ++i) {
byte[] data = new byte[i];
Arrays.fill(data, (byte)i);
dtlsClient.send(data, 0, data.length);
}
byte[] buf = new byte[dtlsClient.getReceiveLimit()];
while (dtlsClient.receive(buf, 0, buf.length, 1000) >= 0);
dtlsClient.close();
serverThread.shutdown();
}
static class ServerThread extends Thread {
private final DTLSServerProtocol serverProtocol;
private final DatagramTransport serverTransport;
private volatile boolean isShutdown = false;
ServerThread(DTLSServerProtocol serverProtocol, DatagramTransport serverTransport) {
this.serverProtocol = serverProtocol;
this.serverTransport = serverTransport;
}
public void run() {
try {
MockDTLSServer server = new MockDTLSServer();
DTLSTransport dtlsServer = serverProtocol.accept(server, serverTransport);
byte[] buf = new byte[dtlsServer.getReceiveLimit()];
while (!isShutdown) {
int length = dtlsServer.receive(buf, 0, buf.length, 1000);
if (length >= 0) {
dtlsServer.send(buf, 0, length);
}
}
dtlsServer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
void shutdown() throws InterruptedException {
if (!isShutdown) {
isShutdown = true;
this.join();
}
}
}
}
|
src/test/java/org/bouncycastle/crypto/tls/test/DTLSProtocolTest.java
|
package org.bouncycastle.crypto.tls.test;
import java.security.SecureRandom;
import junit.framework.TestCase;
import org.bouncycastle.crypto.tls.DTLSClientProtocol;
import org.bouncycastle.crypto.tls.DTLSServerProtocol;
import org.bouncycastle.crypto.tls.DTLSTransport;
import org.bouncycastle.crypto.tls.DatagramTransport;
public class DTLSProtocolTest extends TestCase {
public void testClientServer() throws Exception {
SecureRandom secureRandom = new SecureRandom();
DTLSClientProtocol clientProtocol = new DTLSClientProtocol(secureRandom);
DTLSServerProtocol serverProtocol = new DTLSServerProtocol(secureRandom);
MockDatagramAssociation network = new MockDatagramAssociation(1500);
ServerThread serverThread = new ServerThread(serverProtocol, network.getServer());
serverThread.start();
DatagramTransport clientTransport = network.getClient();
clientTransport = new UnreliableDatagramTransport(clientTransport, secureRandom, 0, 0);
clientTransport = new LoggingDatagramTransport(clientTransport, System.out);
MockDTLSClient client = new MockDTLSClient();
DTLSTransport dtlsClient = clientProtocol.connect(client, clientTransport);
// byte[] data = new byte[64];
// secureRandom.nextBytes(data);
//
// OutputStream output = clientProtocol.getOutputStream();
// output.write(data);
// output.close();
//
// byte[] echo = Streams.readAll(clientProtocol.getInputStream());
dtlsClient.close();
serverThread.shutdown();
// assertTrue(Arrays.areEqual(data, echo));
}
static class ServerThread extends Thread {
private final DTLSServerProtocol serverProtocol;
private final DatagramTransport serverTransport;
private volatile boolean isShutdown = false;
ServerThread(DTLSServerProtocol serverProtocol, DatagramTransport serverTransport) {
this.serverProtocol = serverProtocol;
this.serverTransport = serverTransport;
}
public void run() {
try {
MockDTLSServer server = new MockDTLSServer();
DTLSTransport dtlsServer = serverProtocol.accept(server, serverTransport);
byte[] buf = new byte[dtlsServer.getReceiveLimit()];
while (!isShutdown) {
int length = dtlsServer.receive(buf, 0, buf.length, 1000);
if (length >= 0) {
serverTransport.send(buf, 0, length);
}
}
dtlsServer.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
void shutdown() throws InterruptedException {
if (!isShutdown) {
isShutdown = true;
this.join();
}
}
}
}
|
Exchange some application packets after handshake
|
src/test/java/org/bouncycastle/crypto/tls/test/DTLSProtocolTest.java
|
Exchange some application packets after handshake
|
|
Java
|
epl-1.0
|
fb55ee14b1e6829ef043698011fcd17e0d32db5e
| 0
|
pecko/debrief,alastrina123/debrief,debrief/debrief,theanuradha/debrief,alastrina123/debrief,debrief/debrief,pecko/debrief,alastrina123/debrief,theanuradha/debrief,alastrina123/debrief,theanuradha/debrief,pecko/debrief,debrief/debrief,alastrina123/debrief,pecko/debrief,debrief/debrief,debrief/debrief,pecko/debrief,pecko/debrief,alastrina123/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,pecko/debrief,theanuradha/debrief,alastrina123/debrief
|
package com.borlander.rac353542.bislider;
import java.util.LinkedList;
public class DefaultBiSliderDataModel implements BiSliderDataModel.Writable {
private static final int DEFAULT_SEGMENTS_COUNT = 25;
private final double myPrecision;
private double myTotalMinimum;
private double myTotalMaximum;
private double myUserMinimum = Double.NEGATIVE_INFINITY;
private double myUserMaximum = Double.POSITIVE_INFINITY;
private final LinkedList myListeners;
private Listener[] myListenersArray;
private int myCompositeUpdateCounter;
private double mySegmentLength;
private int mySegmentsCount;
public DefaultBiSliderDataModel() {
this(0);
}
public DefaultBiSliderDataModel(double precision) {
this(0, 100, precision);
}
public DefaultBiSliderDataModel(double totalMin, double totalMax, double precision) {
myListeners = new LinkedList();
myPrecision = precision;
setTotalRange(totalMin, totalMax);
setSegmentCount(DEFAULT_SEGMENTS_COUNT);
}
public double getPrecision() {
return myPrecision;
}
public void addListener(Listener listener) {
if (listener != null){
myListeners.add(listener);
}
}
public void removeListener(Listener listener) {
if (listener != null){
myListeners.remove(listener);
}
}
public double getTotalDelta() {
return myTotalMaximum - myTotalMinimum;
}
public double getTotalMaximum() {
return myTotalMaximum;
}
public double getTotalMinimum() {
return myTotalMinimum;
}
public double getUserMaximum() {
return myUserMaximum;
}
public double getUserMinimum() {
return myUserMinimum;
}
public double getUserDelta() {
return myUserMaximum - myUserMinimum;
}
public double getSegmentLength() {
if (mySegmentLength <= 0){
if (mySegmentsCount <= 0){
throw new IllegalStateException();
}
return getTotalDelta() / mySegmentsCount;
} else {
return mySegmentLength;
}
}
public void setUserMinimum(double userMinimum) {
userMinimum = Math.min(userMinimum, myUserMaximum);
userMinimum = Math.max(userMinimum, myTotalMinimum);
if (userMinimum != myUserMinimum){
myUserMinimum = userMinimum;
fireChanged();
}
}
public void setUserMaximum(double userMaximum) {
userMaximum = Math.max(userMaximum, myUserMinimum);
userMaximum = Math.min(userMaximum, myTotalMaximum);
if (userMaximum != myUserMaximum){
myUserMaximum = userMaximum;
fireChanged();
}
}
public void setTotalRange(double minValue, double maxValue) {
if (minValue == maxValue) {
throw new IllegalArgumentException("Range is too small: (" + minValue + ", " + maxValue + ")");
}
if (minValue > maxValue) {
double temp = minValue;
minValue = maxValue;
maxValue = temp;
}
if (myTotalMaximum != maxValue || myTotalMinimum != minValue){
myTotalMinimum = minValue;
myTotalMaximum = maxValue;
myUserMinimum = Math.max(myUserMinimum, myTotalMinimum);
myUserMaximum = Math.min(myUserMaximum, myTotalMaximum);
fireChanged();
}
}
public void setSegmentLength(double segmentLength){
if (segmentLength > getTotalDelta()){
segmentLength = getTotalDelta();
}
if (mySegmentLength != segmentLength){
mySegmentLength = segmentLength;
mySegmentsCount = -1;
fireChanged();
}
}
public void setSegmentCount(int segmentsCount) {
if (segmentsCount < 1){
segmentsCount = 1;
}
if (mySegmentsCount != segmentsCount){
mySegmentsCount = segmentsCount;
mySegmentLength = -1;
fireChanged();
}
}
public void setUserRange(double userMin, double userMax) {
if (userMin > userMax){
double temp = userMin;
userMin = userMax;
userMax = temp;
}
userMin = checkTotalRange(userMin);
userMax = checkTotalRange(userMax);
if (userMax != myUserMaximum || userMin != myUserMinimum){
myUserMaximum = userMax;
myUserMinimum = userMin;
fireChanged();
}
}
private void fireChanged() {
if (!myListeners.isEmpty()) {
Listener[] listenersCopy = copyListeners();
for (int i = 0; i < listenersCopy.length; i++){
Listener next = listenersCopy[i];
if (next == null){
break;
}
next.dataModelChanged(this, myCompositeUpdateCounter > 0);
}
}
}
public void startCompositeUpdate() {
myCompositeUpdateCounter++;
}
public void finishCompositeUpdate() {
if (myCompositeUpdateCounter <= 0){
throw new IllegalStateException("Finish update without start update");
}
if (--myCompositeUpdateCounter == 0){
//nothing changed since last notification. However, we have to
//send last notification with moreChangesExpected = false
fireChanged();
}
}
/**
* Creates separate copy of listeners. It allows listeners to be
* unregistered during notification.
* <p>
* An array instance is cached to avoid unnecessary creation.
*/
private Listener[] copyListeners() {
if (myListenersArray == null) {
myListenersArray = new Listener[myListeners.size()];
}
myListenersArray = (Listener[]) myListeners.toArray(myListenersArray);
return myListenersArray;
}
private double checkTotalRange(double value){
value = Math.min(value, myTotalMaximum);
value = Math.max(value, myTotalMinimum);
return value;
}
}
|
trunk/CVSROOT/org.mwc.cmap.TimeController/src/com/borlander/rac353542/bislider/DefaultBiSliderDataModel.java
|
package com.borlander.rac353542.bislider;
import java.util.LinkedList;
public class DefaultBiSliderDataModel implements BiSliderDataModel.Writable {
private static final int DEFAULT_SEGMENTS_COUNT = 25;
private final double myPrecision;
private double myTotalMinimum;
private double myTotalMaximum;
private double myUserMinimum = Double.NEGATIVE_INFINITY;
private double myUserMaximum = Double.POSITIVE_INFINITY;
private int mySegmentCount;
private final LinkedList myListeners;
private Listener[] myListenersArray;
private int myCompositeUpdateCounter;
public DefaultBiSliderDataModel() {
this(0);
}
public DefaultBiSliderDataModel(double precision) {
this(0, 100, precision);
}
public DefaultBiSliderDataModel(double totalMin, double totalMax, double precision) {
myListeners = new LinkedList();
myPrecision = precision;
setTotalRange(totalMin, totalMax);
setSegmentCount(DEFAULT_SEGMENTS_COUNT);
}
public double getPrecision() {
return myPrecision;
}
public void addListener(Listener listener) {
if (listener != null){
myListeners.add(listener);
}
}
public void removeListener(Listener listener) {
if (listener != null){
myListeners.remove(listener);
}
}
public double getTotalDelta() {
return myTotalMaximum - myTotalMinimum;
}
public double getTotalMaximum() {
return myTotalMaximum;
}
public double getTotalMinimum() {
return myTotalMinimum;
}
public double getUserMaximum() {
return myUserMaximum;
}
public double getUserMinimum() {
return myUserMinimum;
}
public double getUserDelta() {
return myUserMaximum - myUserMinimum;
}
public double getSegmentLength() {
return getTotalDelta() / getSegmentsCount();
}
public int getSegmentsCount() {
return mySegmentCount;
}
public void setUserMinimum(double userMinimum) {
userMinimum = Math.min(userMinimum, myUserMaximum);
userMinimum = Math.max(userMinimum, myTotalMinimum);
if (userMinimum != myUserMinimum){
myUserMinimum = userMinimum;
fireChanged();
}
}
public void setUserMaximum(double userMaximum) {
userMaximum = Math.max(userMaximum, myUserMinimum);
userMaximum = Math.min(userMaximum, myTotalMaximum);
if (userMaximum != myUserMaximum){
myUserMaximum = userMaximum;
fireChanged();
}
}
public void setTotalRange(double minValue, double maxValue) {
if (minValue == maxValue) {
throw new IllegalArgumentException("Range is too small: (" + minValue + ", " + maxValue + ")");
}
if (minValue > maxValue) {
double temp = minValue;
minValue = maxValue;
maxValue = temp;
}
if (myTotalMaximum != maxValue || myTotalMinimum != minValue){
myTotalMinimum = minValue;
myTotalMaximum = maxValue;
myUserMinimum = Math.max(myUserMinimum, myTotalMinimum);
myUserMaximum = Math.min(myUserMaximum, myTotalMaximum);
fireChanged();
}
}
public void setSegmentCount(int segmentsCount) {
if (segmentsCount < 1){
segmentsCount = 1;
}
if (mySegmentCount != segmentsCount){
mySegmentCount = segmentsCount;
fireChanged();
}
}
public void setUserRange(double userMin, double userMax) {
if (userMin > userMax){
double temp = userMin;
userMin = userMax;
userMax = temp;
}
userMin = checkTotalRange(userMin);
userMax = checkTotalRange(userMax);
if (userMax != myUserMaximum || userMin != myUserMinimum){
myUserMaximum = userMax;
myUserMinimum = userMin;
fireChanged();
}
}
private void fireChanged() {
if (!myListeners.isEmpty()) {
Listener[] listenersCopy = copyListeners();
for (int i = 0; i < listenersCopy.length; i++){
Listener next = listenersCopy[i];
if (next == null){
break;
}
next.dataModelChanged(this, myCompositeUpdateCounter > 0);
}
}
}
public void startCompositeUpdate() {
myCompositeUpdateCounter++;
}
public void finishCompositeUpdate() {
if (myCompositeUpdateCounter <= 0){
throw new IllegalStateException("Finish update without start update");
}
if (--myCompositeUpdateCounter == 0){
//nothing changed since last notification. However, we have to
//send last notification with moreChangesExpected = false
fireChanged();
}
}
/**
* Creates separate copy of listeners. It allows listeners to be
* unregistered during notification.
* <p>
* An array instance is cached to avoid unnecessary creation.
*/
private Listener[] copyListeners() {
if (myListenersArray == null) {
myListenersArray = new Listener[myListeners.size()];
}
myListenersArray = (Listener[]) myListeners.toArray(myListenersArray);
return myListenersArray;
}
private double checkTotalRange(double value){
value = Math.min(value, myTotalMaximum);
value = Math.max(value, myTotalMinimum);
return value;
}
}
|
More convenience functions
git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@494 cb33b658-6c9e-41a7-9690-cba343611204
|
trunk/CVSROOT/org.mwc.cmap.TimeController/src/com/borlander/rac353542/bislider/DefaultBiSliderDataModel.java
|
More convenience functions
|
|
Java
|
agpl-3.0
|
6a36354a8da38bf428bce196d087f69673f95327
| 0
|
roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.opennms.core.utils.InetAddressUtils.addr;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.core.utils.BeanUtils;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml",
"classpath*:/META-INF/opennms/component-dao.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class MonitoredServiceDaoTest implements InitializingBean {
@Autowired
private MonitoredServiceDao m_monitoredServiceDao;
@Autowired
private DatabasePopulator m_databasePopulator;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
@Before
public void setUp() {
m_databasePopulator.populateDatabase();
}
@Test
@Transactional
@JUnitTemporaryDatabase
public void testLazy() {
List<OnmsMonitoredService> allSvcs = m_monitoredServiceDao.findAll();
assertTrue(allSvcs.size() > 1);
OnmsMonitoredService svc = allSvcs.iterator().next();
assertEquals(addr("192.168.1.1"), svc.getIpAddress());
assertEquals(1, svc.getIfIndex().intValue());
assertEquals(1, svc.getIpInterface().getNode().getId().intValue());
assertEquals("M", svc.getIpInterface().getIsManaged());
//assertEquals("SNMP", svc.getServiceType().getName());
}
@Test
@Transactional
@JUnitTemporaryDatabase
public void testGetByCompositeId() {
OnmsMonitoredService monSvc = m_monitoredServiceDao.get(m_databasePopulator.getNode1().getId(), addr("192.168.1.1"), "SNMP");
assertNotNull(monSvc);
OnmsMonitoredService monSvc2 = m_monitoredServiceDao.get(m_databasePopulator.getNode1().getId(), addr("192.168.1.1"), monSvc.getIfIndex(), monSvc.getServiceId());
assertNotNull(monSvc2);
}
}
|
opennms-dao/src/test/java/org/opennms/netmgt/dao/MonitoredServiceDaoTest.java
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.opennms.core.utils.InetAddressUtils.addr;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.core.utils.BeanUtils;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml",
"classpath*:/META-INF/opennms/component-dao.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class MonitoredServiceDaoTest implements InitializingBean {
@Autowired
private MonitoredServiceDao m_monitoredServiceDao;
@Autowired
private DatabasePopulator m_databasePopulator;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
@Before
public void setUp() {
m_databasePopulator.populateDatabase();
}
@Test
@Transactional
public void testLazy() {
List<OnmsMonitoredService> allSvcs = m_monitoredServiceDao.findAll();
assertTrue(allSvcs.size() > 1);
OnmsMonitoredService svc = allSvcs.iterator().next();
assertEquals(addr("192.168.1.1"), svc.getIpAddress());
assertEquals(1, svc.getIfIndex().intValue());
assertEquals(1, svc.getIpInterface().getNode().getId().intValue());
assertEquals("M", svc.getIpInterface().getIsManaged());
//assertEquals("SNMP", svc.getServiceType().getName());
}
@Test
@Transactional
public void testGetByCompositeId() {
OnmsMonitoredService monSvc = m_monitoredServiceDao.get(m_databasePopulator.getNode1().getId(), addr("192.168.1.1"), "SNMP");
assertNotNull(monSvc);
OnmsMonitoredService monSvc2 = m_monitoredServiceDao.get(m_databasePopulator.getNode1().getId(), addr("192.168.1.1"), monSvc.getIfIndex(), monSvc.getServiceId());
assertNotNull(monSvc2);
}
}
|
separate tests that care about ordering for OPENNMS-MASTER17-TEST-59
|
opennms-dao/src/test/java/org/opennms/netmgt/dao/MonitoredServiceDaoTest.java
|
separate tests that care about ordering for OPENNMS-MASTER17-TEST-59
|
|
Java
|
agpl-3.0
|
9085fd73a4a9165d546ceaf821234534e801f185
| 0
|
yinan-liu/scheduling,ow2-proactive/scheduling,sgRomaric/scheduling,ow2-proactive/scheduling,laurianed/scheduling,ShatalovYaroslav/scheduling,mbenguig/scheduling,lpellegr/scheduling,ow2-proactive/scheduling,sandrineBeauche/scheduling,laurianed/scheduling,zeineb/scheduling,ShatalovYaroslav/scheduling,youribonnaffe/scheduling,jrochas/scheduling,sgRomaric/scheduling,lpellegr/scheduling,jrochas/scheduling,tobwiens/scheduling,sgRomaric/scheduling,youribonnaffe/scheduling,yinan-liu/scheduling,tobwiens/scheduling,yinan-liu/scheduling,paraita/scheduling,sgRomaric/scheduling,fviale/scheduling,tobwiens/scheduling,youribonnaffe/scheduling,ShatalovYaroslav/scheduling,zeineb/scheduling,youribonnaffe/scheduling,sgRomaric/scheduling,laurianed/scheduling,youribonnaffe/scheduling,laurianed/scheduling,ShatalovYaroslav/scheduling,fviale/scheduling,marcocast/scheduling,laurianed/scheduling,paraita/scheduling,ShatalovYaroslav/scheduling,jrochas/scheduling,youribonnaffe/scheduling,marcocast/scheduling,zeineb/scheduling,sandrineBeauche/scheduling,lpellegr/scheduling,lpellegr/scheduling,mbenguig/scheduling,paraita/scheduling,mbenguig/scheduling,tobwiens/scheduling,sgRomaric/scheduling,mbenguig/scheduling,zeineb/scheduling,jrochas/scheduling,ow2-proactive/scheduling,paraita/scheduling,tobwiens/scheduling,paraita/scheduling,youribonnaffe/scheduling,jrochas/scheduling,ShatalovYaroslav/scheduling,yinan-liu/scheduling,zeineb/scheduling,paraita/scheduling,mbenguig/scheduling,fviale/scheduling,jrochas/scheduling,marcocast/scheduling,mbenguig/scheduling,laurianed/scheduling,tobwiens/scheduling,ow2-proactive/scheduling,marcocast/scheduling,tobwiens/scheduling,fviale/scheduling,ow2-proactive/scheduling,sandrineBeauche/scheduling,zeineb/scheduling,sandrineBeauche/scheduling,zeineb/scheduling,yinan-liu/scheduling,lpellegr/scheduling,mbenguig/scheduling,paraita/scheduling,jrochas/scheduling,sandrineBeauche/scheduling,marcocast/scheduling,lpellegr/scheduling,yinan-liu/scheduling,yinan-liu/scheduling,sandrineBeauche/scheduling,sgRomaric/scheduling,lpellegr/scheduling,laurianed/scheduling,fviale/scheduling,ShatalovYaroslav/scheduling,sandrineBeauche/scheduling,fviale/scheduling,ow2-proactive/scheduling,marcocast/scheduling,fviale/scheduling,marcocast/scheduling
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2010 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2
* or a different license than the GPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.resourcemanager.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Parser;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeFactory;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.authentication.RMAuthentication;
import org.ow2.proactive.resourcemanager.common.RMConstants;
import org.ow2.proactive.resourcemanager.exception.AddingNodesException;
import org.ow2.proactive.resourcemanager.frontend.RMConnection;
import org.ow2.proactive.resourcemanager.frontend.ResourceManager;
/**
* This class is responsible for creating a local node and add it
* to the Resource Manager.
*
* @author ProActive team
*/
public final class PAAgentServiceRMStarter {
/** The default url of the Resource Manager */
private static final String DEFAULT_RM_URL = "rmi://localhost:1099/";
/** The default name of the node */
private static final String PAAGENT_DEFAULT_NODE_NAME = "PA-AGENT_NODE";
/** Prefix for temp files that store nodes URL */
private static final String URL_TMPFILE_PREFIX = "PA-AGENT_URL";
/** Name of the java property to set the rank */
private final static String RANK_PROP_NAME = "proactive.agent.rank";
/** class' logger */
private static final Logger logger = Logger.getLogger(RMLoggers.RMNODE);
/**
* The starter will try to connect to the Resource Manager before killing
* itself that means that it will try to connect during
* WAIT_ON_JOIN_TIMEOUT_IN_MS milliseconds
*/
private static int WAIT_ON_JOIN_TIMEOUT_IN_MS = 60000;
/**
* The ping delay used in RMPinger that pings the RM and exists if the
* Resource Manager is down
*/
private static long PING_DELAY_IN_MS = 30000;
/** The number of attempts to add the local node to the RM before quitting */
private static int NB_OF_ADD_NODE_ATTEMPTS = 10;
/** The delay, in millis, between two attempts to add a node */
private static int ADD_NODE_ATTEMPTS_DELAY_IN_MS = 5000;
// The url of the created node
private String nodeURL = "Not defined";
// the rank of this node
private int rank;
// if true, previous nodes with different URLs are removed from the RM
private boolean removePrevious;
/**
* Returns the rank of this node
* @return the rank of this node
*/
public int getRank() {
return rank;
}
/**
* Returns the URL of the node handled by this starter.
* @return the URL of the node handled by this starter.
*/
public String getNodeURL() {
return this.nodeURL;
}
/**
* To define the default log4j configuration if log4j.configuration property has not been set.
*/
public static void checkLog4jConfiguration() {
try {
String log4jPath = System.getProperty("log4j.configuration");
if (log4jPath == null) {
//either sched-home/dist/lib/PA-RM.jar or sched-home/classes/resource-manager/
File origin = new File(PAAgentServiceRMStarter.class.getProtectionDomain().getCodeSource()
.getLocation().getFile());
File parent = origin.getParentFile();
configuration: {
while (parent != null && parent.isDirectory()) {
File[] childs = parent.listFiles();
for (File child : childs) {
if ("config".equals(child.getName())) {
//we have found the sched-home/config/ directory!
log4jPath = child.getAbsolutePath() + File.separator + "log4j" +
File.separator + "rm-log4j-server";
File log4j = new File(log4jPath);
if (log4j.exists()) {
URL log4jURL;
try {
log4jURL = log4j.toURL();
PropertyConfigurator.configure(log4jURL);
System.setProperty("log4j.configuration", log4jPath);
logger.trace("log4j.configuration not set, " + log4jPath +
" defiined as default log4j configuration.");
} catch (MalformedURLException e) {
logger.trace("Cannot configure log4j", e);
}
} else {
logger.trace("Log4J configuration not found. Cannot configure log4j");
}
break configuration;
}
}
parent = parent.getParentFile();
}
}
} else {
logger.trace("Does not override log4j.configuration");
}
} catch (Exception ex) {
logger.trace("Cannot set log4j Configuration", ex);
}
}
/**
* Fills the command line options.
* @param options the options to fill
*/
public static void fillOptions(final Options options) {
// The path to the file that contains the credential
final Option credentialFile = new Option("f", "credentialFile", true,
"path to file that contains the credential");
credentialFile.setRequired(false);
credentialFile.setArgName("path");
options.addOption(credentialFile);
// The credential passed as environment variable
final Option credentialEnv = new Option("e", "credentialEnv", true,
"name of the environment variable that contains the credential");
credentialEnv.setRequired(false);
credentialEnv.setArgName("name");
options.addOption(credentialEnv);
// The credential passed as value
final Option credVal = new Option("v", "credentialVal", true, "explicit value of the credential");
credVal.setRequired(false);
credVal.setArgName("credential");
options.addOption(credVal);
// The url of the resource manager
final Option rmURL = new Option("r", "rmURL", true, "URL of the resource manager");
rmURL.setRequired(false);
rmURL.setArgName("url");
options.addOption(rmURL);
// The node name
final Option nodeName = new Option("n", "nodeName", true, "node name (default is " +
PAAGENT_DEFAULT_NODE_NAME + ")");
nodeName.setRequired(false);
nodeName.setArgName("name");
options.addOption(nodeName);
// The node source name
final Option sourceName = new Option("s", "sourceName", true, "node source name");
sourceName.setRequired(false);
sourceName.setArgName("name");
options.addOption(sourceName);
// The wait on join timeout in millis
final Option waitOnJoinTimeout = new Option("w", "waitOnJoinTimeout", true,
"wait on join the resource manager timeout in millis (default is " + WAIT_ON_JOIN_TIMEOUT_IN_MS +
")");
waitOnJoinTimeout.setRequired(false);
waitOnJoinTimeout.setArgName("millis");
options.addOption(waitOnJoinTimeout);
// The ping delay in millis
final Option pingDelay = new Option(
"p",
"pingDelay",
true,
"ping delay in millis used by RMPinger thread that calls System.exit(1) if the resource manager is down (default is " +
PING_DELAY_IN_MS + ")");
pingDelay.setRequired(false);
pingDelay.setArgName("millis");
options.addOption(pingDelay);
// The number of attempts option
final Option addNodeAttempts = new Option("a", "addNodeAttempts", true,
"number of attempts to add the local node to the resource manager before quitting (default is " +
NB_OF_ADD_NODE_ATTEMPTS + ")");
addNodeAttempts.setRequired(false);
addNodeAttempts.setArgName("number");
options.addOption(addNodeAttempts);
// The delay between attempts option
final Option addNodeAttemptsDelay = new Option("d", "addNodeAttemptsDelay", true,
"delay in millis between attempts to add the local node to the resource manager (default is " +
ADD_NODE_ATTEMPTS_DELAY_IN_MS + ")");
addNodeAttemptsDelay.setRequired(false);
addNodeAttemptsDelay.setArgName("millis");
options.addOption(addNodeAttemptsDelay);
// Displays the help
final Option help = new Option("h", "help", false, "to display this help");
help.setRequired(false);
options.addOption(help);
}
/**
* Creates a new instance of this class and calls registersInRm method.
*
* @param args
* The arguments needed to join the Resource Manager
*/
public static void main(final String args[]) {
checkLog4jConfiguration();
Credentials credentials = null;
String rmURL = PAAgentServiceRMStarter.DEFAULT_RM_URL;
String nodeName = PAAgentServiceRMStarter.PAAGENT_DEFAULT_NODE_NAME;
String nodeSourceName = null;
boolean printHelp = false;
final Parser parser = new GnuParser();
final Options options = new Options();
PAAgentServiceRMStarter.fillOptions(options);
try {
// Parse the command line
final CommandLine cl = parser.parse(options, args);
// The path to the file that contains the credential
if (cl.hasOption('f')) {
credentials = Credentials.getCredentials(cl.getOptionValue('f'));
// The name of the env variable that contains
} else if (cl.hasOption('e')) {
final String variableName = cl.getOptionValue('e');
final String value = System.getenv(variableName);
if (value == null) {
throw new IllegalArgumentException("Unable to read the value of the " + variableName);
}
credentials = Credentials.getCredentialsBase64(value.getBytes());
// Read the credentials directly from the command-line argument
} else if (cl.hasOption('v')) {
final String str = cl.getOptionValue('v');
credentials = Credentials.getCredentialsBase64(str.getBytes());
} else {
credentials = Credentials.getCredentials();
}
// Mandatory rmURL option
if (cl.hasOption('r')) {
rmURL = cl.getOptionValue('r');
}
// Optional node name
if (cl.hasOption('n')) {
nodeName = cl.getOptionValue('n');
}
// Optional node source name
if (cl.hasOption('s')) {
nodeSourceName = cl.getOptionValue('s');
}
// Optional wait on join option
if (cl.hasOption('w')) {
PAAgentServiceRMStarter.WAIT_ON_JOIN_TIMEOUT_IN_MS = Integer.valueOf(cl.getOptionValue('w'));
}
// Optional ping delay
if (cl.hasOption('p')) {
PAAgentServiceRMStarter.PING_DELAY_IN_MS = Integer.valueOf(cl.getOptionValue('p'));
}
// Optional number of add node attempts before quitting
if (cl.hasOption('a')) {
PAAgentServiceRMStarter.NB_OF_ADD_NODE_ATTEMPTS = Integer.valueOf(cl.getOptionValue('a'));
}
// Optional delay between add node attempts
if (cl.hasOption('d')) {
PAAgentServiceRMStarter.ADD_NODE_ATTEMPTS_DELAY_IN_MS = Integer.valueOf(cl
.getOptionValue('d'));
}
// Optional help option
if (cl.hasOption('h')) {
printHelp = true;
}
} catch (Throwable t) {
printHelp = true;
System.out.println(t.getMessage());
return;
} finally {
if (printHelp) {
// Automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
// Prints usage
formatter.printHelp("java " + PAAgentServiceRMStarter.class.getName(), options);
}
}
final PAAgentServiceRMStarter starter = new PAAgentServiceRMStarter();
ResourceManager rm = starter.registerInRM(credentials, rmURL, nodeName, nodeSourceName);
if (rm != null) {
System.out.println("Connected to the Resource Manager at " + rmURL + "\n");
// start pinging...
// ping the rm to see if we are still connected
// if not connected just exit
// isActive throws an exception is not connected
try {
while (rm.nodeIsAvailable(starter.getNodeURL()).booleanValue()) {
try {
Thread.sleep(PING_DELAY_IN_MS);
} catch (InterruptedException e) {
}
}// while connected
} catch (Throwable e) {
// no more connected to the RM
System.out
.println("The connection to the Resource Manager has been lost. The application will exit.");
System.exit(1);
}
// if we are here it means we lost the connection. just exit..
System.out.println("The Resource Manager has been shutdown. The application will exit. ");
System.exit(2);
} else {
// Force system exit to bypass daemon threads
System.exit(3);
}
}
/**
* Creates a local node, tries to join to the Resource Manager with a specified timeout
* at the given URL, logs with provided credentials and adds the local node to
* the Resource Manager. Handles all errors/exceptions.
*/
private ResourceManager registerInRM(final Credentials credentials, final String rmURL,
final String nodeName, final String nodeSourceName) {
// 0 - read and set the rank
String rankAsString = System.getProperty(RANK_PROP_NAME);
if (rankAsString == null) {
System.out.println("[WARNING] Rank is not set. Previous URLs will not be stored");
this.removePrevious = false;
} else {
try {
this.rank = Integer.parseInt(rankAsString);
this.removePrevious = true;
System.out.println("Rank is " + this.rank);
} catch (Throwable e) {
System.out.println("[WARNING] Rank cannot be read due to " + e.getMessage() +
". Previous URLs will not be stored");
this.removePrevious = false;
}
}
// 1 - Create the local node that will be registered in RM
Node localNode = null;
try {
localNode = NodeFactory.createLocalNode(nodeName, false, null, null, null);
if (localNode == null) {
throw new RuntimeException("The node returned by the NodeFactory is null");
}
this.nodeURL = localNode.getNodeInformation().getURL();
} catch (Throwable t) {
System.out.println("Unable to create the local node " + nodeName);
t.printStackTrace();
return null;
}
// Create the full url to contact the Resource Manager
final String fullUrl = rmURL.endsWith("/") ? rmURL + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION
: rmURL + "/" + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION;
// 2 - Try to join the Resource Manager with a specified timeout
RMAuthentication auth = null;
try {
auth = RMConnection.waitAndJoin(fullUrl, WAIT_ON_JOIN_TIMEOUT_IN_MS);
if (auth == null) {
throw new RuntimeException("The RMAuthentication instance is null");
}
} catch (Throwable t) {
System.out.println("Unable to join the Resource Manager at " + rmURL);
t.printStackTrace();
return null;
}
ResourceManager rm = null;
// 3 - Log using credential
try {
rm = auth.login(credentials);
if (rm == null) {
throw new RuntimeException("The ResourceManager instance is null");
}
} catch (Throwable t) {
System.out.println("Unable to log into the Resource Manager at " + rmURL);
t.printStackTrace();
return null;
}
// 4 - Add the created node to the Resource Manager with a specified
// number of attempts and a timeout between each attempt
boolean isNodeAdded = false;
int attempts = 0;
while ((!isNodeAdded) && (attempts < NB_OF_ADD_NODE_ATTEMPTS)) {
attempts++;
try {
if (nodeSourceName == null) {
isNodeAdded = rm.addNode(this.nodeURL).booleanValue();
} else {
isNodeAdded = rm.addNode(this.nodeURL, nodeSourceName).booleanValue();
}
} catch (AddingNodesException ex) {
System.out.println("Unable to add the local node to the Resource Manager at " + rmURL);
ex.printStackTrace();
isNodeAdded = false;
} catch (SecurityException ex) {
System.out.println("Unable to add the local node to the Resource Manager at " + rmURL);
ex.printStackTrace();
isNodeAdded = false;
}
if (isNodeAdded) {
if (removePrevious) {
// try to remove previous URL if different...
String previousURL = this.getAndDeleteNodeURL(nodeName, rank);
if (previousURL != null && !previousURL.equals(this.nodeURL)) {
System.out
.println("Different previous URL registered by this agent has been found. Remove previous registration.");
rm.removeNode(previousURL, true);
}
// store the node URL
this.storeNodeURL(nodeName, rank, this.nodeURL);
System.out.println("Node " + this.nodeURL + " added. URL is stored in " +
getNodeURLFilename(nodeName, rank));
} else {
System.out.println("Node " + this.nodeURL + " added.");
}
} else { // not yet registered
System.out.println("Attempt number " + attempts + " out of " + NB_OF_ADD_NODE_ATTEMPTS +
" to add the local node to the Resource Manager at " + rmURL + " has failed.");
try {
Thread.sleep(ADD_NODE_ATTEMPTS_DELAY_IN_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}// while
if (!isNodeAdded) {
System.out.println("The Resource Manager was unable to add the local node " + this.nodeURL +
" after " + NB_OF_ADD_NODE_ATTEMPTS + " attempts. The application will exit.");
return null;
}// if not registered
return rm;
}
/**
* Store in a temp file the current URL of the node started by the agent
* @param nodeName the name of the node
* @param rank the rank of the node
* @param nodeURL the URL of the node
*/
private void storeNodeURL(String nodeName, int rank, String nodeURL) {
try {
File f = new File(getNodeURLFilename(nodeName, rank));
if (f.exists()) {
System.out.println("[WARNING] NodeURL file already exists ; delete it.");
f.delete();
}
BufferedWriter out = new BufferedWriter(new FileWriter(f));
out.write(nodeURL);
out.write(System.getProperty("line.separator"));
out.close();
} catch (IOException e) {
System.out.println("[WARNING] NodeURL cannot be created.");
e.printStackTrace();
}
}
/**
* Return the previous URL of this node
* @param nodeName the name of the node started by the Agent
* @param rank the rank of the node
* @return the previous URL of this node, null if none can be found
*/
private String getAndDeleteNodeURL(String nodeName, int rank) {
try {
File f = new File(getNodeURLFilename(nodeName, rank));
if (f.exists()) {
BufferedReader in = new BufferedReader(new FileReader(f));
String read = in.readLine();
in.close();
f.delete();
return read;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Create the name of the temp file for storing node URL.
*/
private String getNodeURLFilename(String nodeName, int rank) {
final String tmpDir = System.getProperty("java.io.tmpdir");
final String tmpFile = tmpDir + "_" + URL_TMPFILE_PREFIX + "_" + nodeName + "-" + rank;
return tmpFile;
}
}
|
src/resource-manager/src/org/ow2/proactive/resourcemanager/utils/PAAgentServiceRMStarter.java
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2010 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2
* or a different license than the GPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.resourcemanager.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Parser;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeFactory;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.authentication.RMAuthentication;
import org.ow2.proactive.resourcemanager.common.RMConstants;
import org.ow2.proactive.resourcemanager.exception.AddingNodesException;
import org.ow2.proactive.resourcemanager.frontend.RMConnection;
import org.ow2.proactive.resourcemanager.frontend.ResourceManager;
/**
* This class is responsible for creating a local node and add it
* to the Resource Manager.
*
* @author ProActive team
*/
public final class PAAgentServiceRMStarter {
/** The default url of the Resource Manager */
private static final String DEFAULT_RM_URL = "rmi://localhost:1099/";
/** The default name of the node */
private static final String PAAGENT_DEFAULT_NODE_NAME = "PA-AGENT_NODE";
/** Prefix for temp files that store nodes URL */
private static final String URL_TMPFILE_PREFIX = "PA-AGENT_URL";
/** Name of the java property to set the rank */
private final static String RANK_PROP_NAME = "proactive.agent.rank";
/**
* The starter will try to connect to the Resource Manager before killing
* itself that means that it will try to connect during
* WAIT_ON_JOIN_TIMEOUT_IN_MS milliseconds
*/
private static int WAIT_ON_JOIN_TIMEOUT_IN_MS = 60000;
/**
* The ping delay used in RMPinger that pings the RM and exists if the
* Resource Manager is down
*/
private static long PING_DELAY_IN_MS = 30000;
/** The number of attempts to add the local node to the RM before quitting */
private static int NB_OF_ADD_NODE_ATTEMPTS = 10;
/** The delay, in millis, between two attempts to add a node */
private static int ADD_NODE_ATTEMPTS_DELAY_IN_MS = 5000;
// The url of the created node
private String nodeURL = "Not defined";
// the rank of this node
private int rank;
// if true, previous nodes with different URLs are removed from the RM
private boolean removePrevious;
/**
* Returns the rank of this node
* @return the rank of this node
*/
public int getRank() {
return rank;
}
/**
* Returns the URL of the node handled by this starter.
* @return the URL of the node handled by this starter.
*/
public String getNodeURL() {
return this.nodeURL;
}
/**
* Fills the command line options.
* @param options the options to fill
*/
public static void fillOptions(final Options options) {
// The path to the file that contains the credential
final Option credentialFile = new Option("f", "credentialFile", true,
"path to file that contains the credential");
credentialFile.setRequired(false);
credentialFile.setArgName("path");
options.addOption(credentialFile);
// The credential passed as environment variable
final Option credentialEnv = new Option("e", "credentialEnv", true,
"name of the environment variable that contains the credential");
credentialEnv.setRequired(false);
credentialEnv.setArgName("name");
options.addOption(credentialEnv);
// The credential passed as value
final Option credVal = new Option("v", "credentialVal", true, "explicit value of the credential");
credVal.setRequired(false);
credVal.setArgName("credential");
options.addOption(credVal);
// The url of the resource manager
final Option rmURL = new Option("r", "rmURL", true, "URL of the resource manager");
rmURL.setRequired(false);
rmURL.setArgName("url");
options.addOption(rmURL);
// The node name
final Option nodeName = new Option("n", "nodeName", true, "node name (default is " +
PAAGENT_DEFAULT_NODE_NAME + ")");
nodeName.setRequired(false);
nodeName.setArgName("name");
options.addOption(nodeName);
// The node source name
final Option sourceName = new Option("s", "sourceName", true, "node source name");
sourceName.setRequired(false);
sourceName.setArgName("name");
options.addOption(sourceName);
// The wait on join timeout in millis
final Option waitOnJoinTimeout = new Option("w", "waitOnJoinTimeout", true,
"wait on join the resource manager timeout in millis (default is " + WAIT_ON_JOIN_TIMEOUT_IN_MS +
")");
waitOnJoinTimeout.setRequired(false);
waitOnJoinTimeout.setArgName("millis");
options.addOption(waitOnJoinTimeout);
// The ping delay in millis
final Option pingDelay = new Option(
"p",
"pingDelay",
true,
"ping delay in millis used by RMPinger thread that calls System.exit(1) if the resource manager is down (default is " +
PING_DELAY_IN_MS + ")");
pingDelay.setRequired(false);
pingDelay.setArgName("millis");
options.addOption(pingDelay);
// The number of attempts option
final Option addNodeAttempts = new Option("a", "addNodeAttempts", true,
"number of attempts to add the local node to the resource manager before quitting (default is " +
NB_OF_ADD_NODE_ATTEMPTS + ")");
addNodeAttempts.setRequired(false);
addNodeAttempts.setArgName("number");
options.addOption(addNodeAttempts);
// The delay between attempts option
final Option addNodeAttemptsDelay = new Option("d", "addNodeAttemptsDelay", true,
"delay in millis between attempts to add the local node to the resource manager (default is " +
ADD_NODE_ATTEMPTS_DELAY_IN_MS + ")");
addNodeAttemptsDelay.setRequired(false);
addNodeAttemptsDelay.setArgName("millis");
options.addOption(addNodeAttemptsDelay);
// Displays the help
final Option help = new Option("h", "help", false, "to display this help");
help.setRequired(false);
options.addOption(help);
}
/**
* Creates a new instance of this class and calls registersInRm method.
*
* @param args
* The arguments needed to join the Resource Manager
*/
public static void main(final String args[]) {
Credentials credentials = null;
String rmURL = PAAgentServiceRMStarter.DEFAULT_RM_URL;
String nodeName = PAAgentServiceRMStarter.PAAGENT_DEFAULT_NODE_NAME;
String nodeSourceName = null;
boolean printHelp = false;
final Parser parser = new GnuParser();
final Options options = new Options();
PAAgentServiceRMStarter.fillOptions(options);
try {
// Parse the command line
final CommandLine cl = parser.parse(options, args);
// The path to the file that contains the credential
if (cl.hasOption('f')) {
credentials = Credentials.getCredentials(cl.getOptionValue('f'));
// The name of the env variable that contains
} else if (cl.hasOption('e')) {
final String variableName = cl.getOptionValue('e');
final String value = System.getenv(variableName);
if (value == null) {
throw new IllegalArgumentException("Unable to read the value of the " + variableName);
}
credentials = Credentials.getCredentialsBase64(value.getBytes());
// Read the credentials directly from the command-line argument
} else if (cl.hasOption('v')) {
final String str = cl.getOptionValue('v');
credentials = Credentials.getCredentialsBase64(str.getBytes());
} else {
credentials = Credentials.getCredentials();
}
// Mandatory rmURL option
if (cl.hasOption('r')) {
rmURL = cl.getOptionValue('r');
}
// Optional node name
if (cl.hasOption('n')) {
nodeName = cl.getOptionValue('n');
}
// Optional node source name
if (cl.hasOption('s')) {
nodeSourceName = cl.getOptionValue('s');
}
// Optional wait on join option
if (cl.hasOption('w')) {
PAAgentServiceRMStarter.WAIT_ON_JOIN_TIMEOUT_IN_MS = Integer.valueOf(cl.getOptionValue('w'));
}
// Optional ping delay
if (cl.hasOption('p')) {
PAAgentServiceRMStarter.PING_DELAY_IN_MS = Integer.valueOf(cl.getOptionValue('p'));
}
// Optional number of add node attempts before quitting
if (cl.hasOption('a')) {
PAAgentServiceRMStarter.NB_OF_ADD_NODE_ATTEMPTS = Integer.valueOf(cl.getOptionValue('a'));
}
// Optional delay between add node attempts
if (cl.hasOption('d')) {
PAAgentServiceRMStarter.ADD_NODE_ATTEMPTS_DELAY_IN_MS = Integer.valueOf(cl
.getOptionValue('d'));
}
// Optional help option
if (cl.hasOption('h')) {
printHelp = true;
}
} catch (Throwable t) {
printHelp = true;
System.out.println(t.getMessage());
return;
} finally {
if (printHelp) {
// Automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
// Prints usage
formatter.printHelp("java " + PAAgentServiceRMStarter.class.getName(), options);
}
}
final PAAgentServiceRMStarter starter = new PAAgentServiceRMStarter();
ResourceManager rm = starter.registerInRM(credentials, rmURL, nodeName, nodeSourceName);
if (rm != null) {
System.out.println("Connected to the Resource Manager at " + rmURL + "\n");
// start pinging...
// ping the rm to see if we are still connected
// if not connected just exit
// isActive throws an exception is not connected
try {
while (rm.nodeIsAvailable(starter.getNodeURL()).booleanValue()) {
try {
Thread.sleep(PING_DELAY_IN_MS);
} catch (InterruptedException e) {
}
}// while connected
} catch (Throwable e) {
// no more connected to the RM
System.out
.println("The connection to the Resource Manager has been lost. The application will exit.");
System.exit(1);
}
// if we are here it means we lost the connection. just exit..
System.out.println("The Resource Manager has been shutdown. The application will exit. ");
System.exit(2);
} else {
// Force system exit to bypass daemon threads
System.exit(3);
}
}
/**
* Creates a local node, tries to join to the Resource Manager with a specified timeout
* at the given URL, logs with provided credentials and adds the local node to
* the Resource Manager. Handles all errors/exceptions.
*/
private ResourceManager registerInRM(final Credentials credentials, final String rmURL,
final String nodeName, final String nodeSourceName) {
// 0 - read and set the rank
String rankAsString = System.getProperty(RANK_PROP_NAME);
if (rankAsString == null) {
System.out.println("[WARNING] Rank is not set. Previous URLs will not be stored");
this.removePrevious = false;
} else {
try {
this.rank = Integer.parseInt(rankAsString);
this.removePrevious = true;
System.out.println("Rank is " + this.rank);
} catch (Throwable e) {
System.out.println("[WARNING] Rank cannot be read due to " + e.getMessage() +
". Previous URLs will not be stored");
this.removePrevious = false;
}
}
// 1 - Create the local node that will be registered in RM
Node localNode = null;
try {
localNode = NodeFactory.createLocalNode(nodeName, false, null, null, null);
if (localNode == null) {
throw new RuntimeException("The node returned by the NodeFactory is null");
}
this.nodeURL = localNode.getNodeInformation().getURL();
} catch (Throwable t) {
System.out.println("Unable to create the local node " + nodeName);
t.printStackTrace();
return null;
}
// Create the full url to contact the Resource Manager
final String fullUrl = rmURL.endsWith("/") ? rmURL + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION
: rmURL + "/" + RMConstants.NAME_ACTIVE_OBJECT_RMAUTHENTICATION;
// 2 - Try to join the Resource Manager with a specified timeout
RMAuthentication auth = null;
try {
auth = RMConnection.waitAndJoin(fullUrl, WAIT_ON_JOIN_TIMEOUT_IN_MS);
if (auth == null) {
throw new RuntimeException("The RMAuthentication instance is null");
}
} catch (Throwable t) {
System.out.println("Unable to join the Resource Manager at " + rmURL);
t.printStackTrace();
return null;
}
ResourceManager rm = null;
// 3 - Log using credential
try {
rm = auth.login(credentials);
if (rm == null) {
throw new RuntimeException("The ResourceManager instance is null");
}
} catch (Throwable t) {
System.out.println("Unable to log into the Resource Manager at " + rmURL);
t.printStackTrace();
return null;
}
// 4 - Add the created node to the Resource Manager with a specified
// number of attempts and a timeout between each attempt
boolean isNodeAdded = false;
int attempts = 0;
while ((!isNodeAdded) && (attempts < NB_OF_ADD_NODE_ATTEMPTS)) {
attempts++;
try {
if (nodeSourceName == null) {
isNodeAdded = rm.addNode(this.nodeURL).booleanValue();
} else {
isNodeAdded = rm.addNode(this.nodeURL, nodeSourceName).booleanValue();
}
} catch (AddingNodesException ex) {
System.out.println("Unable to add the local node to the Resource Manager at " + rmURL);
ex.printStackTrace();
isNodeAdded = false;
} catch (SecurityException ex) {
System.out.println("Unable to add the local node to the Resource Manager at " + rmURL);
ex.printStackTrace();
isNodeAdded = false;
}
if (isNodeAdded) {
if (removePrevious) {
// try to remove previous URL if different...
String previousURL = this.getAndDeleteNodeURL(nodeName, rank);
if (previousURL != null && !previousURL.equals(this.nodeURL)) {
System.out
.println("Different previous URL registered by this agent has been found. Remove previous registration.");
rm.removeNode(previousURL, true);
}
// store the node URL
this.storeNodeURL(nodeName, rank, this.nodeURL);
System.out.println("Node " + this.nodeURL + " added. URL is stored in " +
getNodeURLFilename(nodeName, rank));
} else {
System.out.println("Node " + this.nodeURL + " added.");
}
} else { // not yet registered
System.out.println("Attempt number " + attempts + " out of " + NB_OF_ADD_NODE_ATTEMPTS +
" to add the local node to the Resource Manager at " + rmURL + " has failed.");
try {
Thread.sleep(ADD_NODE_ATTEMPTS_DELAY_IN_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}// while
if (!isNodeAdded) {
System.out.println("The Resource Manager was unable to add the local node " + this.nodeURL +
" after " + NB_OF_ADD_NODE_ATTEMPTS + " attempts. The application will exit.");
return null;
}// if not registered
return rm;
}
/**
* Store in a temp file the current URL of the node started by the agent
* @param nodeName the name of the node
* @param rank the rank of the node
* @param nodeURL the URL of the node
*/
private void storeNodeURL(String nodeName, int rank, String nodeURL) {
try {
File f = new File(getNodeURLFilename(nodeName, rank));
if (f.exists()) {
System.out.println("[WARNING] NodeURL file already exists ; delete it.");
f.delete();
}
BufferedWriter out = new BufferedWriter(new FileWriter(f));
out.write(nodeURL);
out.write(System.getProperty("line.separator"));
out.close();
} catch (IOException e) {
System.out.println("[WARNING] NodeURL cannot be created.");
e.printStackTrace();
}
}
/**
* Return the previous URL of this node
* @param nodeName the name of the node started by the Agent
* @param rank the rank of the node
* @return the previous URL of this node, null if none can be found
*/
private String getAndDeleteNodeURL(String nodeName, int rank) {
try {
File f = new File(getNodeURLFilename(nodeName, rank));
if (f.exists()) {
BufferedReader in = new BufferedReader(new FileReader(f));
String read = in.readLine();
in.close();
f.delete();
return read;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Create the name of the temp file for storing node URL.
*/
private String getNodeURLFilename(String nodeName, int rank) {
final String tmpDir = System.getProperty("java.io.tmpdir");
final String tmpFile = tmpDir + "_" + URL_TMPFILE_PREFIX + "_" + nodeName + "-" + rank;
return tmpFile;
}
}
|
SCHEDULING-811
PAAgentServiceRMStarter new checks that the log4j.configuration property
is set
git-svn-id: 27916816d6cfa57849e9a885196bf7392b80e1ac@17103 28e8926c-6b08-0410-baaa-805c5e19b8d6
|
src/resource-manager/src/org/ow2/proactive/resourcemanager/utils/PAAgentServiceRMStarter.java
|
SCHEDULING-811
|
|
Java
|
lgpl-2.1
|
3047ad912bdce89bba9810a61258ff1494f3e37e
| 0
|
languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2012 Markus Brenneis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.similarity.LevenshteinDistance;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.language.German;
import org.languagetool.rules.Categories;
import org.languagetool.rules.Example;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.TextLevelRule;
import org.languagetool.rules.patterns.PatternToken;
import org.languagetool.rules.patterns.PatternTokenBuilder;
import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule;
import org.languagetool.tools.StringTools;
import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import static org.languagetool.rules.patterns.PatternRuleBuilderHelper.*;
/**
* Simple agreement checker for German verbs and subject. Checks agreement in:
*
* <ul>
* <li>VER:1:SIN w/o ich: e.g. "Max bin da." (incorrect) [same for VER:2:SIN w/o du, VER:1:PLU w/o wir]</li>
* <li>ich + VER:[123]:.* (not VER:1:SIN): e.g. "ich bist" (incorrect) [same for du, er, wir]</li>
* </ul>
*
* TODO:
* <ul>
* <li>wenn nur ein mögliches finites Verb -> das nehmen (Max machen das.)
* <li>Sie (i>1)
* <li>bei ich/du/er/wir sofort prüfen, damit alle vorkommen geprüft werden (Ich geht jetzt nach Hause und dort gehe ich sofort unter die Dusche.) [aber: isNear]
* <li>Alle Verbvorkommen merken (Er präsentieren wollte und Video hätte keine Pläne.)
* </ul>
*
* @author Markus Brenneis
*/
public class VerbAgreementRule extends TextLevelRule {
private static final List<List<PatternToken>> ANTI_PATTERNS = Arrays.asList(
Arrays.asList(
// "Ken dachte, du wärst ich."
token("du"),
token("wärst"),
token("ich")
),
Arrays.asList(
token("ich"),
token("schlafen"),
token("gehe")
),
Arrays.asList(
token("du"),
token("schlafen"),
token("gehst")
),
Arrays.asList(
token("per"),
token("du"),
tokenRegex("sind|waren|sein|wären|war|ist|gewesen")
),
Arrays.asList(
token("schnellst"),
token("möglich")
),
Arrays.asList(
// "Da freut er sich, wenn er schlafen geht und was findet."
token("er"),
token("schlafen"),
token("geht")
),
Arrays.asList(
token("vermittelst") // "Sie befestigen die Regalbretter vermittelst dreier Schrauben."
),
Arrays.asList(
token("du"),
token("denkst"),
token("ich")
),
Arrays.asList(
token("na"),
token("komm")
),
Arrays.asList(
tokenRegex("muß|mußten?|müßt?en?"), // alte rechtschreibung (andere fehler)
tokenRegex("ich|wir|sie|er|es")
),
Arrays.asList(
token("ich"),
tokenRegex("würd|könnt|werd|wollt|sollt|müsst|fürcht"),
tokenRegex("['’`´‘]")
),
Arrays.asList(
tokenRegex("wir|sie|zu"),
tokenRegex("seh|steh|geh"),
tokenRegex("['’`´‘]"),
token("n")
),
Arrays.asList(
token("ick"), // different error (berlinerisch)
tokenRegex("bin|war|wär|hab|hatte")
),
Arrays.asList(
// hash tag
token("#"),
posRegex("VER.*")
),
Arrays.asList(
// wie du war ich auch
token("wie"),
tokenRegex("du|ihr|er|es|sie"),
tokenRegex("bin|war"),
token("ich")
),
Arrays.asList(
// Arabic names: Aryat Abraha bin Sabah Kaaba
posRegex("UNKNOWN|EIG.*"),
token("bin"),
posRegex("UNKNOWN|EIG.*")
),
Arrays.asList(
// Du scheiß Idiot
tokenRegex("du|sie"),
tokenRegex("schei(ß|ss)"),
posRegex("SUB.*|UNKNOWN")
),
Arrays.asList(
token("Du"),
tokenRegex("bist|warst|wärst")
),
Arrays.asList(
token("als"),
token("auch"),
tokenRegex("er|sie|wir|du|ich|ihr")
),
Arrays.asList(
tokenRegex("so|wie|zu"),
token("lange"),
tokenRegex("er|sie|wir|du|ich|ihr")
),
Arrays.asList(
// Ich will nicht so wie er enden.
new PatternTokenBuilder().tokenRegex("so|genauso|ähnlich").matchInflectedForms().setSkip(2).build(),
token("wie"),
tokenRegex("er|sie|du|ihr|ich"),
posRegex("VER.*")
),
Arrays.asList(
// "Bekommst sogar eine Sicherheitszulage"
pos("SENT_START"),
posRegex("VER:2:SIN:.*"),
posRegex("ART.*|ADV.*|PRO:POS.*")
),
Arrays.asList(
// "A, B und auch ich"
token(","),
posRegex("EIG:.*|UNKNOWN"),
regex("und|oder"),
token("auch"),
token("ich")
),
Arrays.asList(
// "Dallun sagte nur, dass er gleich kommen wird und legte wieder auf."
// "Sie fragte, ob er bereit für die zweite Runde ist."
posRegex("VER.*"), // z.B. "Bist"
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("gleich|bereit|lange|schnelle?|halt|bitte") // ist hier kein Verb
),
Arrays.asList(
// "Dallun sagte nur, dass er gleich kommen wird und legte wieder auf."
posRegex("ADV.*|KON.*"),
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("gleich|bereit|lange|schnelle?|halt|bitte") // ist hier kein Verb
),
Arrays.asList(
// "Woraufhin ich verlegen lächelte"
posRegex("ADV.*|KON.*"),
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("verlegen"),
posRegex("VER.*")
),
Arrays.asList(
// "Bringst nicht einmal so etwas Einfaches zustande!"
pos("SENT_START"),
posRegex("VER:2:SIN:.*"),
token("nicht")
),
Arrays.asList(
// "Da machte er auch vor dem eigenen Volk nicht halt."
new PatternTokenBuilder().token("machen").matchInflectedForms().setSkip(-1).build(),
token("halt")
),
Arrays.asList( // "Ich hoffe du auch."
posRegex("VER:.*"),
tokenRegex("du|ihr"),
token("auch")
),
Arrays.asList(
// "Für Sie mache ich eine Ausnahme."
token("für"),
token("Sie"),
pos("VER:3:SIN:KJ1:SFT"),
token("ich")
),
Arrays.asList(
// "Einer wie du kennt ...", "Aber wenn jemand wie Du daherkommt"
tokenRegex("einer?|jemand"),
token("wie"),
token("du"),
posRegex("VER:3:.*")
),
Arrays.asList(
// "Kannst mich gerne anrufen" (ugs.)
pos("VER:MOD:2:SIN:PRÄ"),
posRegex("PRO:PER:.*")
),
Arrays.asList(
tokenRegex("die|welche"),
tokenRegex(".*"),
tokenRegex("mehr|weniger"),
token("als"),
tokenRegex("ich|du|e[rs]|sie")
),
Arrays.asList(
token("wenn"),
token("du"),
token("anstelle")
),
Arrays.asList( // "Ok bin ab morgen bei euch." (umgangssprachlich, benötigt eigene Regel)
tokenRegex("ok(ay)?|ja|nein|vielleicht|oh"),
tokenRegex("bin|sind")
),
Arrays.asList(
token("das"),
csToken("Du"),
new PatternTokenBuilder().token("anbieten").matchInflectedForms().build()
),
Arrays.asList(
token(","),
posRegex("VER:MOD:2:.*")
),
Arrays.asList(
csToken("Soll"),
token("ich")
),
Arrays.asList(
csToken("Solltest"),
token("du")
),
Arrays.asList(
csToken("Müsstest"), // Müsstest dir das mal genauer anschauen.
token("dir")
),
Arrays.asList(
csToken("Könntest"), // Könntest dir mal eine Scheibe davon abschneiden!
token("dir")
),
Arrays.asList(
csToken("Sollte"),
tokenRegex("er|sie")
),
Arrays.asList(
pos(JLanguageTool.SENTENCE_START_TAGNAME), // "Bin gleich wieder da"
tokenRegex("Bin|Kannst")
),
Arrays.asList(
token(","), // "..., hast aber keine Ahnung!"
tokenRegex("bin|hast|kannst")
),
Arrays.asList(
token("er"), // "egal, was er sagen wird, ..."
posRegex("VER:.*"),
token("wird")
),
Arrays.asList(
tokenRegex("wie|als"), // "Ein Mann wie ich braucht einen Hut"
token("ich"),
posRegex("VER:.*")
),
Arrays.asList(
tokenRegex("ich"), // "Ich weiß, was ich tun werde, falls etwas geschehen sollte."
pos("VER:INF:NON"),
token("werde")
),
Arrays.asList(
pos("VER:IMP:SIN:SFT"), // "Kümmere du dich mal nicht darum!"
token("du"),
tokenRegex("dich|dein|deine[srnm]?")
),
Arrays.asList(
token("sei"),
token("du"),
token("selbst")
),
Arrays.asList(
token("als"), // "Du bist in dem Moment angekommen, als ich gegangen bin."
token("ich"),
posRegex("PA2:.*"),
token("bin")
),
Arrays.asList(
token("als"),
tokenRegex("du|e[rs]|sie|ich"),
new PatternTokenBuilder().token("sein").matchInflectedForms().build(),
tokenRegex("[\\.,]")
),
Arrays.asList( // Musst du gehen?
tokenRegex("D[au]rf.*|Muss.*"),
posRegex("PRO:PER:NOM:.+"),
posRegex("VER:INF:.+"),
pos("PKT"),
tokenRegex("(?!die).+")
),
Arrays.asList(
csToken("("),
posRegex("VER:2:SIN:.+"),
csToken(")")
),
Arrays.asList(
posRegex("VER:MOD:1:PLU:.+"),
csToken("wir"),
csToken("bitte")
),
Arrays.asList( // Ohne sie hätte ich das nie geschafft.
token("ohne"),
token("sie"),
token("hätte"),
token("ich")
),
Arrays.asList( // Geh du mal!
pos(JLanguageTool.SENTENCE_START_TAGNAME),
posRegex("VER:IMP:SIN.+"),
csToken("du"),
new PatternTokenBuilder().csToken("?").negate().build()
),
Arrays.asList( // -Du fühlst dich unsicher?
tokenRegex("[^a-zäöüß]+du"),
pos("VER:2:SIN:PRÄ:SFT")
)
);
// Words that prevent a rule match when they occur directly before "bin":
private static final Set<String> BIN_IGNORE = new HashSet<>(Arrays.asList(
"Suleiman",
"Mohamed",
"Muhammad",
"Muhammed",
"Mohammed",
"Mohammad",
"Mansour",
"Qaboos",
"Qabus",
"Tamim",
"Majid",
"Salman",
"Ghazi",
"Mahathir",
"Madschid",
"Maktum",
"al-Aziz",
"Asis",
"Numan",
"Hussein",
"Abdul",
"Abdulla",
"Abdullah",
"Isa",
"Osama",
"Said",
"Zayid",
"Zayed",
"Hamad",
"Chalifa",
"Raschid",
"Turki",
"/"
));
private static final Set<String> CONJUNCTIONS = new HashSet<>(Arrays.asList(
"weil",
"obwohl",
"dass",
"indem",
"sodass"/*,
"damit",
"wenn"*/
));
private static final Set<String> QUOTATION_MARKS = new HashSet<>(Arrays.asList(
"\"", "„"
));
private final German language;
private final Supplier<List<DisambiguationPatternRule>> antiPatterns;
public VerbAgreementRule(ResourceBundle messages, German language) {
this.language = language;
super.setCategory(Categories.GRAMMAR.getCategory(messages));
addExamplePair(Example.wrong("Ich <marker>bist</marker> über die Entwicklung sehr froh."),
Example.fixed("Ich <marker>bin</marker> über die Entwicklung sehr froh."));
antiPatterns = cacheAntiPatterns(language, ANTI_PATTERNS);
}
@Override
public String getId() {
return "DE_VERBAGREEMENT";
}
@Override
public String getDescription() {
return "Kongruenz von Subjekt und Prädikat (nur 1. u. 2. Person oder m. Personalpronomen), z.B. 'Er bist (ist)'";
}
@Override
public RuleMatch[] match(List<AnalyzedSentence> sentences) {
List<RuleMatch> ruleMatches = new ArrayList<>();
int pos = 0;
for (AnalyzedSentence sentence : sentences) {
int idx = 0;
AnalyzedTokenReadings[] tokens = sentence.getTokens();
AnalyzedSentence partialSentence;
for(int i = 2; i < tokens.length; i++) {
if(",".equals(tokens[i-2].getToken()) && CONJUNCTIONS.contains(tokens[i].getToken())) {
partialSentence = new AnalyzedSentence(Arrays.copyOfRange(tokens, idx, i));
ruleMatches.addAll(match(partialSentence, pos));
idx = i;
}
}
partialSentence = new AnalyzedSentence(Arrays.copyOfRange(tokens, idx, tokens.length));
ruleMatches.addAll(match(partialSentence, pos));
pos += sentence.getCorrectedTextLength();
}
return toRuleMatchArray(ruleMatches);
}
private List<RuleMatch> match(AnalyzedSentence sentence, int pos) {
AnalyzedTokenReadings finiteVerb = null;
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace();
if (tokens.length < 4) { // ignore one-word sentences (3 tokens: SENT_START, one word, SENT_END)
return ruleMatches;
}
// position of the pronouns:
int posIch = -1;
int posDu = -1;
int posEr = -1;
int posWir = -1;
// positions of verbs which do match in person and number, and do not match any other person nor number:
int posVer1Sin = -1;
int posVer2Sin = -1;
int posVer1Plu = -1;
/*int posVer2Plu = -1;*/
// positions of verbs which do match in person and number:
int posPossibleVer1Sin = -1;
int posPossibleVer2Sin = -1;
int posPossibleVer3Sin = -1;
int posPossibleVer1Plu = -1;
/*int posPossibleVer2Plu = -1;*/
for (int i = 1; i < tokens.length; ++i) { // ignore SENT_START
String strToken = tokens[i].getToken().toLowerCase();
strToken = strToken.replace("‚", "");
switch (strToken) {
case "ich":
posIch = i;
break;
case "du":
posDu = i;
break;
case "er":
posEr = i;
break;
case "wir":
posWir = i;
break;
}
if (tokens[i].hasPartialPosTag("VER")
&& (Character.isLowerCase(tokens[i].getToken().charAt(0)) || i == 1 || isQuotationMark(tokens[i-1])) ) {
if (hasUnambiguouslyPersonAndNumber(tokens[i], "1", "SIN")
&& !(strToken.equals("bin") && (BIN_IGNORE.contains(tokens[i-1].getToken())
|| (tokens.length != i + 1 && tokens[i+1].getToken().startsWith("Laden")) ))) {
posVer1Sin = i;
}
else if (hasUnambiguouslyPersonAndNumber(tokens[i], "2", "SIN") && !"Probst".equals(tokens[i].getToken())) {
posVer2Sin = i;
} else if (hasUnambiguouslyPersonAndNumber(tokens[i], "1", "PLU")) {
posVer1Plu = i;
// } else if (hasUnambiguouslyPersonAndNumber(tokens[i], "2", "PLU")) {
// posVer2Plu = i;
}
if (tokens[i].hasPartialPosTag(":1:SIN")) {
posPossibleVer1Sin = i;
}
if (tokens[i].hasPartialPosTag(":2:SIN")) {
posPossibleVer2Sin = i;
}
if (tokens[i].hasPartialPosTag(":3:SIN")) {
posPossibleVer3Sin = i;
}
if (tokens[i].hasPartialPosTag(":1:PLU")) {
posPossibleVer1Plu = i;
}
// if (tokens[i].hasPartialPosTag(":2:PLU"))
// posPossibleVer2Plu = i;
}
} // for each token
// "ich", "du", and "wir" must be subject (no other interpretation possible)
// "ich", "du", "er", and "wir" must have a matching verb
if (posVer1Sin != -1 && posIch == -1 && !isQuotationMark(tokens[posVer1Sin-1])) { // 1st pers sg verb but no "ich"
if (!tokens[posVer1Sin].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer1Sin], pos, sentence));
}
} else if (posIch > 0 && !isNear(posPossibleVer1Sin, posIch) // check whether verb next to "ich" is 1st pers sg
&& (tokens[posIch].getToken().equals("ich") || tokens[posIch].getStartPos() <= 1 ||
(tokens[posIch].getToken().equals("Ich") && posIch >= 2 && tokens[posIch-2].getToken().equals(":")) ||
(tokens[posIch].getToken().equals("Ich") && posIch >= 1 && tokens[posIch-1].getToken().equals(":"))) // ignore "lyrisches Ich" etc.
&& (!isQuotationMark(tokens[posIch-1]) || posIch < 3 || (posIch > 1 && tokens[posIch-2].getToken().equals(":")))) {
int plus1 = ((posIch + 1) == tokens.length) ? 0 : +1; // prevent posIch+1 segfault
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posIch - 1], tokens[posIch + plus1], "1", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber && !nextButOneIsModal(tokens, posIch) && !"äußerst".equals(check.finiteVerb.getToken())) {
if (!tokens[posIch].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posIch], check.finiteVerb, "1:SIN", pos, sentence));
}
}
}
if (posVer2Sin != -1 && posDu == -1 && !isQuotationMark(tokens[posVer2Sin-1])) {
if (!tokens[posVer2Sin].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer2Sin], pos, sentence));
}
} else if (posDu > 0 && !isNear(posPossibleVer2Sin, posDu)
&&(!isQuotationMark(tokens[posDu-1]) || posDu < 3 || (posDu > 1 && tokens[posDu-2].getToken().equals(":")))) {
int plus1 = ((posDu + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posDu - 1], tokens[posDu + plus1], "2", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber &&
!tokens[posDu+plus1].hasPosTagStartingWith("VER:1:SIN:KJ2") && // "Wenn ich du wäre"
!(tokens[posDu+plus1].hasPosTagStartingWith("ADJ:") && !tokens[posDu+plus1].hasPosTag("ADJ:PRD:GRU"))&& // "dass du billige Klamotten..."
!tokens[posDu-1].hasPosTagStartingWith("VER:1:SIN:KJ2") &&
!nextButOneIsModal(tokens, posDu) &&
!tokens[posDu].isImmunized()
) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posDu], check.finiteVerb, "2:SIN", pos, sentence));
}
}
if (posEr > 0 && !isNear(posPossibleVer3Sin, posEr)
&& (!isQuotationMark(tokens[posEr-1]) || posEr < 3 || (posEr > 1 && tokens[posEr-2].getToken().equals(":")))) {
int plus1 = ((posEr + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posEr - 1], tokens[posEr + plus1], "3", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber
&& !nextButOneIsModal(tokens, posEr)
&& !"äußerst".equals(check.finiteVerb.getToken())
&& !"regen".equals(check.finiteVerb.getToken()) // "wo er regen Anteil nahm"
&& !tokens[posEr].isImmunized()
) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posEr], check.finiteVerb, "3:SIN", pos, sentence));
}
}
if (posVer1Plu != -1 && posWir == -1 && !isQuotationMark(tokens[posVer1Plu-1])) {
if (!tokens[posVer1Plu].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer1Plu], pos, sentence));
}
} else if (posWir > 0 && !isNear(posPossibleVer1Plu, posWir) && !isQuotationMark(tokens[posWir-1])) {
int plus1 = ((posWir + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posWir - 1], tokens[posWir + plus1], "1", "PLU", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber && !nextButOneIsModal(tokens, posWir) && !tokens[posWir].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posWir], check.finiteVerb, "1:PLU", pos, sentence));
}
}
return ruleMatches;
}
@Override
public List<DisambiguationPatternRule> getAntiPatterns() {
return antiPatterns.get();
}
// avoid false alarm on 'wenn ich sterben sollte ...':
private boolean nextButOneIsModal(AnalyzedTokenReadings[] tokens, int pos) {
return pos < tokens.length - 2 && tokens[pos+2].hasPartialPosTag(":MOD:");
}
/**
* @return true if |a - b| < 5, and a != -1
*/
private boolean isNear(int a, int b) {
return a != -1 && (Math.abs(a - b) < 5);
}
private boolean isQuotationMark(AnalyzedTokenReadings token) {
return QUOTATION_MARKS.contains(token.getToken());
}
/**
* @return true if the verb @param token (if it is a verb) matches @param person and @param number, and matches no other person/number
*/
private boolean hasUnambiguouslyPersonAndNumber(AnalyzedTokenReadings tokenReadings, String person, String number) {
if (tokenReadings.getToken().length() == 0
|| (Character.isUpperCase(tokenReadings.getToken().charAt(0)) && tokenReadings.getStartPos() != 0)
|| !tokenReadings.hasPosTagStartingWith("VER")) {
return false;
}
for (AnalyzedToken analyzedToken : tokenReadings) {
String postag = analyzedToken.getPOSTag();
if (postag == null || postag.endsWith("_END")) { // ignore SENT_END and PARA_END
continue;
}
if (!postag.contains(":" + person + ":" + number)) {
return false;
}
}
return true;
}
/**
* @return true if @param token is a finite verb, and it is no participle, pronoun or number
*/
private boolean isFiniteVerb(AnalyzedTokenReadings token) {
if (token.getToken().length() == 0
|| (Character.isUpperCase(token.getToken().charAt(0)) && token.getStartPos() != 0)
|| !token.hasPosTagStartingWith("VER")
|| token.hasAnyPartialPosTag("PA2", "PRO:", "ZAL")
|| "einst".equals(token.getToken())) {
return false;
}
return token.hasAnyPartialPosTag(":1:", ":2:", ":3:");
}
/**
* @return false if neither the verb @param token1 (if any) nor @param token2 match @param person and @param number, and none of them is "und" or ","
* if a finite verb is found, it is saved in finiteVerb
*/
private BooleanAndFiniteVerb verbDoesMatchPersonAndNumber(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2,
String person, String number, AnalyzedTokenReadings finiteVerb) {
if (StringUtils.equalsAny(token1.getToken(), ",", "und", "sowie", "&") ||
StringUtils.equalsAny(token2.getToken(), ",", "und", "sowie", "&")) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
boolean foundFiniteVerb = false;
if (isFiniteVerb(token1)) {
foundFiniteVerb = true;
finiteVerb = token1;
if (token1.hasPartialPosTag(":" + person + ":" + number)) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
}
if (isFiniteVerb(token2)) {
foundFiniteVerb = true;
finiteVerb = token2;
if (token2.hasPartialPosTag(":" + person + ":" + number)) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
}
return new BooleanAndFiniteVerb(!foundFiniteVerb, finiteVerb);
}
/**
* @return a list of forms of @param verb which match @param expectedVerbPOS (person:number)
* @param toUppercase true when the suggestions should be capitalized
*/
private List<String> getVerbSuggestions(AnalyzedTokenReadings verb, String expectedVerbPOS, boolean toUppercase) {
// find the first verb reading
AnalyzedToken verbToken = new AnalyzedToken("", "", "");
for (AnalyzedToken token : verb.getReadings()) {
//noinspection ConstantConditions
if (token.getPOSTag().startsWith("VER:")) {
verbToken = token;
break;
}
}
try {
String[] synthesized = language.getSynthesizer().synthesize(verbToken, "VER.*:"+expectedVerbPOS+".*", true);
Set<String> suggestionSet = new HashSet<>(Arrays.asList(synthesized)); // remove duplicates
List<String> suggestions = new ArrayList<>(suggestionSet);
if (toUppercase) {
for (int i = 0; i < suggestions.size(); ++i) {
suggestions.set(i, StringTools.uppercaseFirstChar(suggestions.get(i)));
}
}
return suggestions;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @return a list of pronouns which match the person and number of @param verb
* @param toUppercase true when the suggestions should be capitalized
*/
private List<String> getPronounSuggestions(AnalyzedTokenReadings verb, boolean toUppercase) {
List<String> result = new ArrayList<>();
if (verb.hasPartialPosTag(":1:SIN")) {
result.add("ich");
}
if (verb.hasPartialPosTag(":2:SIN")) {
result.add("du");
}
if (verb.hasPartialPosTag(":3:SIN")) {
result.add("er");
result.add("sie");
result.add("es");
}
if (verb.hasPartialPosTag(":1:PLU")) {
result.add("wir");
}
if (verb.hasPartialPosTag(":2:PLU")) {
result.add("ihr");
}
if (verb.hasPartialPosTag(":3:PLU") && !result.contains("sie")) { // do not add "sie" twice
result.add("sie");
}
if (toUppercase) {
for (int i = 0; i < result.size(); ++i) {
result.set(i, StringTools.uppercaseFirstChar(result.get(i)));
}
}
return result;
}
private RuleMatch ruleMatchWrongVerb(AnalyzedTokenReadings token, int pos, AnalyzedSentence sentence) {
String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Subjekt und Prädikat (" +
token.getToken() + ") bezüglich Person oder Numerus (Einzahl, Mehrzahl - Beispiel: " +
"'Max bist' statt 'Max ist').";
return new RuleMatch(this, sentence, pos+token.getStartPos(), pos+token.getEndPos(), msg);
}
private RuleMatch ruleMatchWrongVerbSubject(AnalyzedTokenReadings subject, AnalyzedTokenReadings verb, String expectedVerbPOS, int pos, AnalyzedSentence sentence) {
String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Subjekt (" + subject.getToken() +
") und Prädikat (" + verb.getToken() + ") bezüglich Person oder Numerus (Einzahl, Mehrzahl - Beispiel: " +
"'ich sind' statt 'ich bin').";
List<String> suggestions = new ArrayList<>();
List<String> verbSuggestions = new ArrayList<>();
List<String> pronounSuggestions = new ArrayList<>();
RuleMatch ruleMatch;
if (subject.getStartPos() < verb.getStartPos()) {
ruleMatch = new RuleMatch(this, sentence, pos+subject.getStartPos(), pos+verb.getStartPos()+verb.getToken().length(), msg);
verbSuggestions.addAll(getVerbSuggestions(verb, expectedVerbPOS, false));
for (String verbSuggestion : verbSuggestions) {
suggestions.add(subject.getToken() + " " + verbSuggestion);
}
pronounSuggestions.addAll(getPronounSuggestions(verb, Character.isUpperCase(subject.getToken().charAt(0))));
for (String pronounSuggestion : pronounSuggestions) {
suggestions.add(pronounSuggestion + " " + verb.getToken());
}
String markedText = sentence.getText().substring(subject.getStartPos(), verb.getStartPos()+verb.getToken().length());
sortBySimilarity(suggestions, markedText);
ruleMatch.setSuggestedReplacements(suggestions);
} else {
ruleMatch = new RuleMatch(this, sentence, pos+verb.getStartPos(), pos+subject.getStartPos()+subject.getToken().length(), msg);
verbSuggestions.addAll(getVerbSuggestions(verb, expectedVerbPOS, Character.isUpperCase(verb.getToken().charAt(0))));
for (String verbSuggestion : verbSuggestions) {
suggestions.add(verbSuggestion + " " + subject.getToken());
}
pronounSuggestions.addAll(getPronounSuggestions(verb, false));
for (String pronounSuggestion : pronounSuggestions) {
suggestions.add(verb.getToken() + " " + pronounSuggestion);
}
String markedText = sentence.getText().substring(verb.getStartPos(), subject.getStartPos()+subject.getToken().length());
sortBySimilarity(suggestions, markedText);
ruleMatch.setSuggestedReplacements(suggestions);
}
return ruleMatch;
}
private void sortBySimilarity(List<String> suggestions, String markedText) {
suggestions.sort((o1, o2) -> {
int diff1 = LevenshteinDistance.getDefaultInstance().apply(markedText, o1);
int diff2 = LevenshteinDistance.getDefaultInstance().apply(markedText, o2);
return diff1 - diff2;
});
}
static class BooleanAndFiniteVerb {
boolean verbDoesMatchPersonAndNumber;
AnalyzedTokenReadings finiteVerb;
private BooleanAndFiniteVerb(boolean verbDoesMatchPersonAndNumber, AnalyzedTokenReadings finiteVerb) {
this.verbDoesMatchPersonAndNumber = verbDoesMatchPersonAndNumber;
this.finiteVerb = finiteVerb;
}
}
@Override
public int minToCheckParagraph() {
return 0;
}
}
|
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/VerbAgreementRule.java
|
/* LanguageTool, a natural language style checker
* Copyright (C) 2012 Markus Brenneis
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.de;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.similarity.LevenshteinDistance;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.language.German;
import org.languagetool.rules.Categories;
import org.languagetool.rules.Example;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.TextLevelRule;
import org.languagetool.rules.patterns.PatternToken;
import org.languagetool.rules.patterns.PatternTokenBuilder;
import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule;
import org.languagetool.tools.StringTools;
import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import static org.languagetool.rules.patterns.PatternRuleBuilderHelper.*;
/**
* Simple agreement checker for German verbs and subject. Checks agreement in:
*
* <ul>
* <li>VER:1:SIN w/o ich: e.g. "Max bin da." (incorrect) [same for VER:2:SIN w/o du, VER:1:PLU w/o wir]</li>
* <li>ich + VER:[123]:.* (not VER:1:SIN): e.g. "ich bist" (incorrect) [same for du, er, wir]</li>
* </ul>
*
* TODO:
* <ul>
* <li>wenn nur ein mögliches finites Verb -> das nehmen (Max machen das.)
* <li>Sie (i>1)
* <li>bei ich/du/er/wir sofort prüfen, damit alle vorkommen geprüft werden (Ich geht jetzt nach Hause und dort gehe ich sofort unter die Dusche.) [aber: isNear]
* <li>Alle Verbvorkommen merken (Er präsentieren wollte und Video hätte keine Pläne.)
* </ul>
*
* @author Markus Brenneis
*/
public class VerbAgreementRule extends TextLevelRule {
private static final List<List<PatternToken>> ANTI_PATTERNS = Arrays.asList(
Arrays.asList(
// "Ken dachte, du wärst ich."
token("du"),
token("wärst"),
token("ich")
),
Arrays.asList(
token("ich"),
token("schlafen"),
token("gehe")
),
Arrays.asList(
token("du"),
token("schlafen"),
token("gehst")
),
Arrays.asList(
token("per"),
token("du"),
tokenRegex("sind|waren|sein|wären|war|ist|gewesen")
),
Arrays.asList(
token("schnellst"),
token("möglich")
),
Arrays.asList(
// "Da freut er sich, wenn er schlafen geht und was findet."
token("er"),
token("schlafen"),
token("geht")
),
Arrays.asList(
token("vermittelst") // "Sie befestigen die Regalbretter vermittelst dreier Schrauben."
),
Arrays.asList(
token("du"),
token("denkst"),
token("ich")
),
Arrays.asList(
token("na"),
token("komm")
),
Arrays.asList(
tokenRegex("muß|mußten?|müßt?en?"), // alte rechtschreibung (andere fehler)
tokenRegex("ich|wir|sie|er|es")
),
Arrays.asList(
token("ich"),
tokenRegex("würd|könnt|werd|wollt|sollt|müsst|fürcht"),
tokenRegex("['’`´‘]")
),
Arrays.asList(
tokenRegex("wir|sie|zu"),
tokenRegex("seh|steh|geh"),
tokenRegex("['’`´‘]"),
token("n")
),
Arrays.asList(
token("ick"), // different error (berlinerisch)
tokenRegex("bin|war|wär|hab|hatte")
),
Arrays.asList(
// hash tag
token("#"),
posRegex("VER.*")
),
Arrays.asList(
// wie du war ich auch
token("wie"),
tokenRegex("du|ihr|er|es|sie"),
tokenRegex("bin|war"),
token("ich")
),
Arrays.asList(
// Arabic names: Aryat Abraha bin Sabah Kaaba
posRegex("UNKNOWN|EIG.*"),
token("bin"),
posRegex("UNKNOWN|EIG.*")
),
Arrays.asList(
// Du scheiß Idiot
tokenRegex("du|sie"),
tokenRegex("schei(ß|ss)"),
posRegex("SUB.*|UNKNOWN")
),
Arrays.asList(
token("Du"),
tokenRegex("bist|warst|wärst")
),
Arrays.asList(
token("als"),
token("auch"),
tokenRegex("er|sie|wir|du|ich|ihr")
),
Arrays.asList(
tokenRegex("so|wie|zu"),
token("lange"),
tokenRegex("er|sie|wir|du|ich|ihr")
),
Arrays.asList(
// Ich will nicht so wie er enden.
new PatternTokenBuilder().tokenRegex("so|genauso|ähnlich").matchInflectedForms().setSkip(2).build(),
token("wie"),
tokenRegex("er|sie|du|ihr|ich"),
posRegex("VER.*")
),
Arrays.asList(
// "Bekommst sogar eine Sicherheitszulage"
pos("SENT_START"),
posRegex("VER:2:SIN:.*"),
posRegex("ART.*|ADV.*|PRO:POS.*")
),
Arrays.asList(
// "A, B und auch ich"
token(","),
posRegex("EIG:.*|UNKNOWN"),
regex("und|oder"),
token("auch"),
token("ich")
),
Arrays.asList(
// "Dallun sagte nur, dass er gleich kommen wird und legte wieder auf."
// "Sie fragte, ob er bereit für die zweite Runde ist."
posRegex("VER.*"), // z.B. "Bist"
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("gleich|bereit|lange|schnelle?|halt|bitte") // ist hier kein Verb
),
Arrays.asList(
// "Dallun sagte nur, dass er gleich kommen wird und legte wieder auf."
posRegex("ADV.*|KON.*"),
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("gleich|bereit|lange|schnelle?|halt|bitte") // ist hier kein Verb
),
Arrays.asList(
// "Woraufhin ich verlegen lächelte"
posRegex("ADV.*|KON.*"),
tokenRegex("er|sie|ich|wir|du|es|ihr"),
tokenRegex("verlegen"),
posRegex("VER.*")
),
Arrays.asList(
// "Bringst nicht einmal so etwas Einfaches zustande!"
pos("SENT_START"),
posRegex("VER:2:SIN:.*"),
token("nicht")
),
Arrays.asList(
// "Da machte er auch vor dem eigenen Volk nicht halt."
new PatternTokenBuilder().token("machen").matchInflectedForms().setSkip(-1).build(),
token("halt")
),
Arrays.asList( // "Ich hoffe du auch."
posRegex("VER:.*"),
tokenRegex("du|ihr"),
token("auch")
),
Arrays.asList(
// "Für Sie mache ich eine Ausnahme."
token("für"),
token("Sie"),
pos("VER:3:SIN:KJ1:SFT"),
token("ich")
),
Arrays.asList(
// "Einer wie du kennt ...", "Aber jemand wie Du daherkommt"
tokenRegex("einer?|jemand"),
token("wie"),
token("du"),
posRegex("VER:3:.*")
),
Arrays.asList(
// "Kannst mich gerne anrufen" (ugs.)
pos("VER:MOD:2:SIN:PRÄ"),
posRegex("PRO:PER:.*")
),
Arrays.asList(
tokenRegex("die|welche"),
tokenRegex(".*"),
tokenRegex("mehr|weniger"),
token("als"),
tokenRegex("ich|du|e[rs]|sie")
),
Arrays.asList(
token("wenn"),
token("du"),
token("anstelle")
),
Arrays.asList( // "Ok bin ab morgen bei euch." (umgangssprachlich, benötigt eigene Regel)
tokenRegex("ok(ay)?|ja|nein|vielleicht|oh"),
tokenRegex("bin|sind")
),
Arrays.asList(
token("das"),
csToken("Du"),
new PatternTokenBuilder().token("anbieten").matchInflectedForms().build()
),
Arrays.asList(
token(","),
posRegex("VER:MOD:2:.*")
),
Arrays.asList(
csToken("Soll"),
token("ich")
),
Arrays.asList(
csToken("Solltest"),
token("du")
),
Arrays.asList(
csToken("Müsstest"), // Müsstest dir das mal genauer anschauen.
token("dir")
),
Arrays.asList(
csToken("Könntest"), // Könntest dir mal eine Scheibe davon abschneiden!
token("dir")
),
Arrays.asList(
csToken("Sollte"),
tokenRegex("er|sie")
),
Arrays.asList(
pos(JLanguageTool.SENTENCE_START_TAGNAME), // "Bin gleich wieder da"
tokenRegex("Bin|Kannst")
),
Arrays.asList(
token(","), // "..., hast aber keine Ahnung!"
tokenRegex("bin|hast|kannst")
),
Arrays.asList(
token("er"), // "egal, was er sagen wird, ..."
posRegex("VER:.*"),
token("wird")
),
Arrays.asList(
tokenRegex("wie|als"), // "Ein Mann wie ich braucht einen Hut"
token("ich"),
posRegex("VER:.*")
),
Arrays.asList(
tokenRegex("ich"), // "Ich weiß, was ich tun werde, falls etwas geschehen sollte."
pos("VER:INF:NON"),
token("werde")
),
Arrays.asList(
pos("VER:IMP:SIN:SFT"), // "Kümmere du dich mal nicht darum!"
token("du"),
tokenRegex("dich|dein|deine[srnm]?")
),
Arrays.asList(
token("sei"),
token("du"),
token("selbst")
),
Arrays.asList(
token("als"), // "Du bist in dem Moment angekommen, als ich gegangen bin."
token("ich"),
posRegex("PA2:.*"),
token("bin")
),
Arrays.asList(
token("als"),
tokenRegex("du|e[rs]|sie|ich"),
new PatternTokenBuilder().token("sein").matchInflectedForms().build(),
tokenRegex("[\\.,]")
),
Arrays.asList( // Musst du gehen?
tokenRegex("D[au]rf.*|Muss.*"),
posRegex("PRO:PER:NOM:.+"),
posRegex("VER:INF:.+"),
pos("PKT"),
tokenRegex("(?!die).+")
),
Arrays.asList(
csToken("("),
posRegex("VER:2:SIN:.+"),
csToken(")")
),
Arrays.asList(
posRegex("VER:MOD:1:PLU:.+"),
csToken("wir"),
csToken("bitte")
),
Arrays.asList( // Ohne sie hätte ich das nie geschafft.
token("ohne"),
token("sie"),
token("hätte"),
token("ich")
),
Arrays.asList( // Geh du mal!
pos(JLanguageTool.SENTENCE_START_TAGNAME),
posRegex("VER:IMP:SIN.+"),
csToken("du"),
new PatternTokenBuilder().csToken("?").negate().build()
),
Arrays.asList( // -Du fühlst dich unsicher?
tokenRegex("[^a-zäöüß]+du"),
pos("VER:2:SIN:PRÄ:SFT")
)
);
// Words that prevent a rule match when they occur directly before "bin":
private static final Set<String> BIN_IGNORE = new HashSet<>(Arrays.asList(
"Suleiman",
"Mohamed",
"Muhammad",
"Muhammed",
"Mohammed",
"Mohammad",
"Mansour",
"Qaboos",
"Qabus",
"Tamim",
"Majid",
"Salman",
"Ghazi",
"Mahathir",
"Madschid",
"Maktum",
"al-Aziz",
"Asis",
"Numan",
"Hussein",
"Abdul",
"Abdulla",
"Abdullah",
"Isa",
"Osama",
"Said",
"Zayid",
"Zayed",
"Hamad",
"Chalifa",
"Raschid",
"Turki",
"/"
));
private static final Set<String> CONJUNCTIONS = new HashSet<>(Arrays.asList(
"weil",
"obwohl",
"dass",
"indem",
"sodass"/*,
"damit",
"wenn"*/
));
private static final Set<String> QUOTATION_MARKS = new HashSet<>(Arrays.asList(
"\"", "„"
));
private final German language;
private final Supplier<List<DisambiguationPatternRule>> antiPatterns;
public VerbAgreementRule(ResourceBundle messages, German language) {
this.language = language;
super.setCategory(Categories.GRAMMAR.getCategory(messages));
addExamplePair(Example.wrong("Ich <marker>bist</marker> über die Entwicklung sehr froh."),
Example.fixed("Ich <marker>bin</marker> über die Entwicklung sehr froh."));
antiPatterns = cacheAntiPatterns(language, ANTI_PATTERNS);
}
@Override
public String getId() {
return "DE_VERBAGREEMENT";
}
@Override
public String getDescription() {
return "Kongruenz von Subjekt und Prädikat (nur 1. u. 2. Person oder m. Personalpronomen), z.B. 'Er bist (ist)'";
}
@Override
public RuleMatch[] match(List<AnalyzedSentence> sentences) {
List<RuleMatch> ruleMatches = new ArrayList<>();
int pos = 0;
for (AnalyzedSentence sentence : sentences) {
int idx = 0;
AnalyzedTokenReadings[] tokens = sentence.getTokens();
AnalyzedSentence partialSentence;
for(int i = 2; i < tokens.length; i++) {
if(",".equals(tokens[i-2].getToken()) && CONJUNCTIONS.contains(tokens[i].getToken())) {
partialSentence = new AnalyzedSentence(Arrays.copyOfRange(tokens, idx, i));
ruleMatches.addAll(match(partialSentence, pos));
idx = i;
}
}
partialSentence = new AnalyzedSentence(Arrays.copyOfRange(tokens, idx, tokens.length));
ruleMatches.addAll(match(partialSentence, pos));
pos += sentence.getCorrectedTextLength();
}
return toRuleMatchArray(ruleMatches);
}
private List<RuleMatch> match(AnalyzedSentence sentence, int pos) {
AnalyzedTokenReadings finiteVerb = null;
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace();
if (tokens.length < 4) { // ignore one-word sentences (3 tokens: SENT_START, one word, SENT_END)
return ruleMatches;
}
// position of the pronouns:
int posIch = -1;
int posDu = -1;
int posEr = -1;
int posWir = -1;
// positions of verbs which do match in person and number, and do not match any other person nor number:
int posVer1Sin = -1;
int posVer2Sin = -1;
int posVer1Plu = -1;
/*int posVer2Plu = -1;*/
// positions of verbs which do match in person and number:
int posPossibleVer1Sin = -1;
int posPossibleVer2Sin = -1;
int posPossibleVer3Sin = -1;
int posPossibleVer1Plu = -1;
/*int posPossibleVer2Plu = -1;*/
for (int i = 1; i < tokens.length; ++i) { // ignore SENT_START
String strToken = tokens[i].getToken().toLowerCase();
strToken = strToken.replace("‚", "");
switch (strToken) {
case "ich":
posIch = i;
break;
case "du":
posDu = i;
break;
case "er":
posEr = i;
break;
case "wir":
posWir = i;
break;
}
if (tokens[i].hasPartialPosTag("VER")
&& (Character.isLowerCase(tokens[i].getToken().charAt(0)) || i == 1 || isQuotationMark(tokens[i-1])) ) {
if (hasUnambiguouslyPersonAndNumber(tokens[i], "1", "SIN")
&& !(strToken.equals("bin") && (BIN_IGNORE.contains(tokens[i-1].getToken())
|| (tokens.length != i + 1 && tokens[i+1].getToken().startsWith("Laden")) ))) {
posVer1Sin = i;
}
else if (hasUnambiguouslyPersonAndNumber(tokens[i], "2", "SIN") && !"Probst".equals(tokens[i].getToken())) {
posVer2Sin = i;
} else if (hasUnambiguouslyPersonAndNumber(tokens[i], "1", "PLU")) {
posVer1Plu = i;
// } else if (hasUnambiguouslyPersonAndNumber(tokens[i], "2", "PLU")) {
// posVer2Plu = i;
}
if (tokens[i].hasPartialPosTag(":1:SIN")) {
posPossibleVer1Sin = i;
}
if (tokens[i].hasPartialPosTag(":2:SIN")) {
posPossibleVer2Sin = i;
}
if (tokens[i].hasPartialPosTag(":3:SIN")) {
posPossibleVer3Sin = i;
}
if (tokens[i].hasPartialPosTag(":1:PLU")) {
posPossibleVer1Plu = i;
}
// if (tokens[i].hasPartialPosTag(":2:PLU"))
// posPossibleVer2Plu = i;
}
} // for each token
// "ich", "du", and "wir" must be subject (no other interpretation possible)
// "ich", "du", "er", and "wir" must have a matching verb
if (posVer1Sin != -1 && posIch == -1 && !isQuotationMark(tokens[posVer1Sin-1])) { // 1st pers sg verb but no "ich"
if (!tokens[posVer1Sin].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer1Sin], pos, sentence));
}
} else if (posIch > 0 && !isNear(posPossibleVer1Sin, posIch) // check whether verb next to "ich" is 1st pers sg
&& (tokens[posIch].getToken().equals("ich") || tokens[posIch].getStartPos() <= 1 ||
(tokens[posIch].getToken().equals("Ich") && posIch >= 2 && tokens[posIch-2].getToken().equals(":")) ||
(tokens[posIch].getToken().equals("Ich") && posIch >= 1 && tokens[posIch-1].getToken().equals(":"))) // ignore "lyrisches Ich" etc.
&& (!isQuotationMark(tokens[posIch-1]) || posIch < 3 || (posIch > 1 && tokens[posIch-2].getToken().equals(":")))) {
int plus1 = ((posIch + 1) == tokens.length) ? 0 : +1; // prevent posIch+1 segfault
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posIch - 1], tokens[posIch + plus1], "1", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber && !nextButOneIsModal(tokens, posIch) && !"äußerst".equals(check.finiteVerb.getToken())) {
if (!tokens[posIch].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posIch], check.finiteVerb, "1:SIN", pos, sentence));
}
}
}
if (posVer2Sin != -1 && posDu == -1 && !isQuotationMark(tokens[posVer2Sin-1])) {
if (!tokens[posVer2Sin].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer2Sin], pos, sentence));
}
} else if (posDu > 0 && !isNear(posPossibleVer2Sin, posDu)
&&(!isQuotationMark(tokens[posDu-1]) || posDu < 3 || (posDu > 1 && tokens[posDu-2].getToken().equals(":")))) {
int plus1 = ((posDu + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posDu - 1], tokens[posDu + plus1], "2", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber &&
!tokens[posDu+plus1].hasPosTagStartingWith("VER:1:SIN:KJ2") && // "Wenn ich du wäre"
!(tokens[posDu+plus1].hasPosTagStartingWith("ADJ:") && !tokens[posDu+plus1].hasPosTag("ADJ:PRD:GRU"))&& // "dass du billige Klamotten..."
!tokens[posDu-1].hasPosTagStartingWith("VER:1:SIN:KJ2") &&
!nextButOneIsModal(tokens, posDu) &&
!tokens[posDu].isImmunized()
) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posDu], check.finiteVerb, "2:SIN", pos, sentence));
}
}
if (posEr > 0 && !isNear(posPossibleVer3Sin, posEr)
&& (!isQuotationMark(tokens[posEr-1]) || posEr < 3 || (posEr > 1 && tokens[posEr-2].getToken().equals(":")))) {
int plus1 = ((posEr + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posEr - 1], tokens[posEr + plus1], "3", "SIN", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber
&& !nextButOneIsModal(tokens, posEr)
&& !"äußerst".equals(check.finiteVerb.getToken())
&& !"regen".equals(check.finiteVerb.getToken()) // "wo er regen Anteil nahm"
&& !tokens[posEr].isImmunized()
) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posEr], check.finiteVerb, "3:SIN", pos, sentence));
}
}
if (posVer1Plu != -1 && posWir == -1 && !isQuotationMark(tokens[posVer1Plu-1])) {
if (!tokens[posVer1Plu].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerb(tokens[posVer1Plu], pos, sentence));
}
} else if (posWir > 0 && !isNear(posPossibleVer1Plu, posWir) && !isQuotationMark(tokens[posWir-1])) {
int plus1 = ((posWir + 1) == tokens.length) ? 0 : +1;
BooleanAndFiniteVerb check = verbDoesMatchPersonAndNumber(tokens[posWir - 1], tokens[posWir + plus1], "1", "PLU", finiteVerb);
if (!check.verbDoesMatchPersonAndNumber && !nextButOneIsModal(tokens, posWir) && !tokens[posWir].isImmunized()) {
ruleMatches.add(ruleMatchWrongVerbSubject(tokens[posWir], check.finiteVerb, "1:PLU", pos, sentence));
}
}
return ruleMatches;
}
@Override
public List<DisambiguationPatternRule> getAntiPatterns() {
return antiPatterns.get();
}
// avoid false alarm on 'wenn ich sterben sollte ...':
private boolean nextButOneIsModal(AnalyzedTokenReadings[] tokens, int pos) {
return pos < tokens.length - 2 && tokens[pos+2].hasPartialPosTag(":MOD:");
}
/**
* @return true if |a - b| < 5, and a != -1
*/
private boolean isNear(int a, int b) {
return a != -1 && (Math.abs(a - b) < 5);
}
private boolean isQuotationMark(AnalyzedTokenReadings token) {
return QUOTATION_MARKS.contains(token.getToken());
}
/**
* @return true if the verb @param token (if it is a verb) matches @param person and @param number, and matches no other person/number
*/
private boolean hasUnambiguouslyPersonAndNumber(AnalyzedTokenReadings tokenReadings, String person, String number) {
if (tokenReadings.getToken().length() == 0
|| (Character.isUpperCase(tokenReadings.getToken().charAt(0)) && tokenReadings.getStartPos() != 0)
|| !tokenReadings.hasPosTagStartingWith("VER")) {
return false;
}
for (AnalyzedToken analyzedToken : tokenReadings) {
String postag = analyzedToken.getPOSTag();
if (postag == null || postag.endsWith("_END")) { // ignore SENT_END and PARA_END
continue;
}
if (!postag.contains(":" + person + ":" + number)) {
return false;
}
}
return true;
}
/**
* @return true if @param token is a finite verb, and it is no participle, pronoun or number
*/
private boolean isFiniteVerb(AnalyzedTokenReadings token) {
if (token.getToken().length() == 0
|| (Character.isUpperCase(token.getToken().charAt(0)) && token.getStartPos() != 0)
|| !token.hasPosTagStartingWith("VER")
|| token.hasAnyPartialPosTag("PA2", "PRO:", "ZAL")
|| "einst".equals(token.getToken())) {
return false;
}
return token.hasAnyPartialPosTag(":1:", ":2:", ":3:");
}
/**
* @return false if neither the verb @param token1 (if any) nor @param token2 match @param person and @param number, and none of them is "und" or ","
* if a finite verb is found, it is saved in finiteVerb
*/
private BooleanAndFiniteVerb verbDoesMatchPersonAndNumber(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2,
String person, String number, AnalyzedTokenReadings finiteVerb) {
if (StringUtils.equalsAny(token1.getToken(), ",", "und", "sowie", "&") ||
StringUtils.equalsAny(token2.getToken(), ",", "und", "sowie", "&")) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
boolean foundFiniteVerb = false;
if (isFiniteVerb(token1)) {
foundFiniteVerb = true;
finiteVerb = token1;
if (token1.hasPartialPosTag(":" + person + ":" + number)) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
}
if (isFiniteVerb(token2)) {
foundFiniteVerb = true;
finiteVerb = token2;
if (token2.hasPartialPosTag(":" + person + ":" + number)) {
return new BooleanAndFiniteVerb(true, finiteVerb);
}
}
return new BooleanAndFiniteVerb(!foundFiniteVerb, finiteVerb);
}
/**
* @return a list of forms of @param verb which match @param expectedVerbPOS (person:number)
* @param toUppercase true when the suggestions should be capitalized
*/
private List<String> getVerbSuggestions(AnalyzedTokenReadings verb, String expectedVerbPOS, boolean toUppercase) {
// find the first verb reading
AnalyzedToken verbToken = new AnalyzedToken("", "", "");
for (AnalyzedToken token : verb.getReadings()) {
//noinspection ConstantConditions
if (token.getPOSTag().startsWith("VER:")) {
verbToken = token;
break;
}
}
try {
String[] synthesized = language.getSynthesizer().synthesize(verbToken, "VER.*:"+expectedVerbPOS+".*", true);
Set<String> suggestionSet = new HashSet<>(Arrays.asList(synthesized)); // remove duplicates
List<String> suggestions = new ArrayList<>(suggestionSet);
if (toUppercase) {
for (int i = 0; i < suggestions.size(); ++i) {
suggestions.set(i, StringTools.uppercaseFirstChar(suggestions.get(i)));
}
}
return suggestions;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @return a list of pronouns which match the person and number of @param verb
* @param toUppercase true when the suggestions should be capitalized
*/
private List<String> getPronounSuggestions(AnalyzedTokenReadings verb, boolean toUppercase) {
List<String> result = new ArrayList<>();
if (verb.hasPartialPosTag(":1:SIN")) {
result.add("ich");
}
if (verb.hasPartialPosTag(":2:SIN")) {
result.add("du");
}
if (verb.hasPartialPosTag(":3:SIN")) {
result.add("er");
result.add("sie");
result.add("es");
}
if (verb.hasPartialPosTag(":1:PLU")) {
result.add("wir");
}
if (verb.hasPartialPosTag(":2:PLU")) {
result.add("ihr");
}
if (verb.hasPartialPosTag(":3:PLU") && !result.contains("sie")) { // do not add "sie" twice
result.add("sie");
}
if (toUppercase) {
for (int i = 0; i < result.size(); ++i) {
result.set(i, StringTools.uppercaseFirstChar(result.get(i)));
}
}
return result;
}
private RuleMatch ruleMatchWrongVerb(AnalyzedTokenReadings token, int pos, AnalyzedSentence sentence) {
String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Subjekt und Prädikat (" +
token.getToken() + ") bezüglich Person oder Numerus (Einzahl, Mehrzahl - Beispiel: " +
"'Max bist' statt 'Max ist').";
return new RuleMatch(this, sentence, pos+token.getStartPos(), pos+token.getEndPos(), msg);
}
private RuleMatch ruleMatchWrongVerbSubject(AnalyzedTokenReadings subject, AnalyzedTokenReadings verb, String expectedVerbPOS, int pos, AnalyzedSentence sentence) {
String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Subjekt (" + subject.getToken() +
") und Prädikat (" + verb.getToken() + ") bezüglich Person oder Numerus (Einzahl, Mehrzahl - Beispiel: " +
"'ich sind' statt 'ich bin').";
List<String> suggestions = new ArrayList<>();
List<String> verbSuggestions = new ArrayList<>();
List<String> pronounSuggestions = new ArrayList<>();
RuleMatch ruleMatch;
if (subject.getStartPos() < verb.getStartPos()) {
ruleMatch = new RuleMatch(this, sentence, pos+subject.getStartPos(), pos+verb.getStartPos()+verb.getToken().length(), msg);
verbSuggestions.addAll(getVerbSuggestions(verb, expectedVerbPOS, false));
for (String verbSuggestion : verbSuggestions) {
suggestions.add(subject.getToken() + " " + verbSuggestion);
}
pronounSuggestions.addAll(getPronounSuggestions(verb, Character.isUpperCase(subject.getToken().charAt(0))));
for (String pronounSuggestion : pronounSuggestions) {
suggestions.add(pronounSuggestion + " " + verb.getToken());
}
String markedText = sentence.getText().substring(subject.getStartPos(), verb.getStartPos()+verb.getToken().length());
sortBySimilarity(suggestions, markedText);
ruleMatch.setSuggestedReplacements(suggestions);
} else {
ruleMatch = new RuleMatch(this, sentence, pos+verb.getStartPos(), pos+subject.getStartPos()+subject.getToken().length(), msg);
verbSuggestions.addAll(getVerbSuggestions(verb, expectedVerbPOS, Character.isUpperCase(verb.getToken().charAt(0))));
for (String verbSuggestion : verbSuggestions) {
suggestions.add(verbSuggestion + " " + subject.getToken());
}
pronounSuggestions.addAll(getPronounSuggestions(verb, false));
for (String pronounSuggestion : pronounSuggestions) {
suggestions.add(verb.getToken() + " " + pronounSuggestion);
}
String markedText = sentence.getText().substring(verb.getStartPos(), subject.getStartPos()+subject.getToken().length());
sortBySimilarity(suggestions, markedText);
ruleMatch.setSuggestedReplacements(suggestions);
}
return ruleMatch;
}
private void sortBySimilarity(List<String> suggestions, String markedText) {
suggestions.sort((o1, o2) -> {
int diff1 = LevenshteinDistance.getDefaultInstance().apply(markedText, o1);
int diff2 = LevenshteinDistance.getDefaultInstance().apply(markedText, o2);
return diff1 - diff2;
});
}
static class BooleanAndFiniteVerb {
boolean verbDoesMatchPersonAndNumber;
AnalyzedTokenReadings finiteVerb;
private BooleanAndFiniteVerb(boolean verbDoesMatchPersonAndNumber, AnalyzedTokenReadings finiteVerb) {
this.verbDoesMatchPersonAndNumber = verbDoesMatchPersonAndNumber;
this.finiteVerb = finiteVerb;
}
}
@Override
public int minToCheckParagraph() {
return 0;
}
}
|
[de] typo in comment
|
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/VerbAgreementRule.java
|
[de] typo in comment
|
|
Java
|
apache-2.0
|
bb28e954497513d93318efb7a38eeb5148c4bfde
| 0
|
metaborg/runtime-libraries
|
package org.metaborg.runtime.task.digest;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoInt;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoReal;
import org.spoofax.interpreter.terms.IStrategoString;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.IStrategoTuple;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.io.binary.SAFWriter;
public class SHA1TermDigester implements ITermDigester {
private final MessageDigest digest;
private final Map<IStrategoTerm, IStrategoTerm> mapping = new HashMap<IStrategoTerm, IStrategoTerm>();
private final ByteBuffer intBuffer = ByteBuffer.allocate(4);
private final ByteBuffer doubleBuffer = ByteBuffer.allocate(8);
public SHA1TermDigester() throws NoSuchAlgorithmException {
digest = MessageDigest.getInstance("SHA-1");
}
public IStrategoTerm digest(IStrategoTerm term, ITermFactory factory) {
IStrategoTerm digestedTerm = mapping.get(term);
if(digestedTerm == null) {
digest.reset();
digestTopSerializer(term);
byte[] data = digest.digest();
digestedTerm = factory.makeTuple(factory.makeInt(toInt(data, 0)), factory.makeInt(toInt(data, 4)));
mapping.put(term, digestedTerm);
}
return digestedTerm;
}
public void undigest(IStrategoTerm term) {
mapping.remove(term);
}
public boolean digested(IStrategoTerm term) {
return mapping.containsKey(term);
}
public IStrategoTerm state(ITermFactory factory) {
IStrategoList mappingTerm = factory.makeList();
for (Entry<IStrategoTerm, IStrategoTerm> entry : mapping.entrySet())
mappingTerm = factory.makeListCons(
factory.makeTuple(entry.getKey(), entry.getValue()),
mappingTerm);
return mappingTerm;
}
public void setState(IStrategoTerm state) {
mapping.clear();
for (IStrategoTerm entry : state)
mapping.put(entry.getSubterm(0), entry.getSubterm(1));
}
public void reset() {
mapping.clear();
}
private void digestTopSerializer(IStrategoTerm term) {
digest.update(SAFWriter.writeTermToSAFString(term));
}
private void digestTop(IStrategoTerm term) {
digestTerm(term);
digestTerm(term.getAnnotations());
}
private void digestTerm(IStrategoTerm term) {
switch(term.getTermType()) {
case IStrategoTerm.APPL: {
final IStrategoAppl t = (IStrategoAppl) term;
digest.update(t.getConstructor().getName().getBytes());
intBuffer.position(0);
digest.update(intBuffer.putInt(t.getConstructor().getArity()).array());
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.TUPLE: {
final IStrategoTuple t = (IStrategoTuple) term;
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.LIST: {
final IStrategoList t = (IStrategoList) term;
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.INT: {
final IStrategoInt t = (IStrategoInt) term;
intBuffer.position(0);
digest.update(intBuffer.putInt(t.intValue()).array());
break;
}
case IStrategoTerm.REAL: {
final IStrategoReal t = (IStrategoReal) term;
doubleBuffer.position(0);
digest.update(doubleBuffer.putDouble(t.realValue()).array());
break;
}
case IStrategoTerm.STRING: {
final IStrategoString t = (IStrategoString) term;
digest.update(t.stringValue().getBytes());
break;
}
}
}
private int toInt(final byte[] digest, final int offset) {
return ((digest[offset + 0] & 0xFF) << 24) | ((digest[offset + 1] & 0xFF) << 16)
| ((digest[offset + 2] & 0xFF) << 8) | (digest[offset + 3] & 0xFF);
}
}
|
org.metaborg.runtime.task/src/main/java/org/metaborg/runtime/task/digest/SHA1TermDigester.java
|
package org.metaborg.runtime.task.digest;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoInt;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoReal;
import org.spoofax.interpreter.terms.IStrategoString;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.IStrategoTuple;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.io.binary.SAFWriter;
public class SHA1TermDigester implements ITermDigester {
private final MessageDigest digest;
private final Map<IStrategoTerm, IStrategoTerm> mapping = new HashMap<IStrategoTerm, IStrategoTerm>();
private final ByteBuffer intBuffer = ByteBuffer.allocate(4);
private final ByteBuffer doubleBuffer = ByteBuffer.allocate(8);
public SHA1TermDigester() throws NoSuchAlgorithmException {
digest = MessageDigest.getInstance("SHA-1");
}
public IStrategoTerm digest(IStrategoTerm term, ITermFactory factory) {
IStrategoTerm digestedTerm = mapping.get(term);
if(digestedTerm == null) {
digest.reset();
digestTopSerializer(term);
byte[] data = digest.digest();
digestedTerm = factory.makeTuple(factory.makeInt(toInt(data, 0)), factory.makeInt(toInt(data, 4)));
mapping.put(term, digestedTerm);
}
return digestedTerm;
}
public void undigest(IStrategoTerm term) {
mapping.remove(term);
}
public boolean digested(IStrategoTerm term) {
return mapping.containsKey(term);
}
public IStrategoTerm state(ITermFactory factory) {
IStrategoList mappingTerm = factory.makeList();
for (Entry<IStrategoTerm, IStrategoTerm> entry : mapping.entrySet())
mappingTerm = factory.makeListCons(
factory.makeTuple(entry.getKey(), entry.getValue()),
mappingTerm);
return mappingTerm;
}
public void setState(IStrategoTerm state) {
mapping.clear();
for (IStrategoTerm entry : state.getSubterm(1))
mapping.put(entry.getSubterm(0), entry.getSubterm(1));
}
public void reset() {
mapping.clear();
}
private void digestTopSerializer(IStrategoTerm term) {
digest.update(SAFWriter.writeTermToSAFString(term));
}
private void digestTop(IStrategoTerm term) {
digestTerm(term);
digestTerm(term.getAnnotations());
}
private void digestTerm(IStrategoTerm term) {
switch(term.getTermType()) {
case IStrategoTerm.APPL: {
final IStrategoAppl t = (IStrategoAppl) term;
digest.update(t.getConstructor().getName().getBytes());
intBuffer.position(0);
digest.update(intBuffer.putInt(t.getConstructor().getArity()).array());
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.TUPLE: {
final IStrategoTuple t = (IStrategoTuple) term;
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.LIST: {
final IStrategoList t = (IStrategoList) term;
for(IStrategoTerm subterm : t)
digestTop(subterm);
break;
}
case IStrategoTerm.INT: {
final IStrategoInt t = (IStrategoInt) term;
intBuffer.position(0);
digest.update(intBuffer.putInt(t.intValue()).array());
break;
}
case IStrategoTerm.REAL: {
final IStrategoReal t = (IStrategoReal) term;
doubleBuffer.position(0);
digest.update(doubleBuffer.putDouble(t.realValue()).array());
break;
}
case IStrategoTerm.STRING: {
final IStrategoString t = (IStrategoString) term;
digest.update(t.stringValue().getBytes());
break;
}
}
}
private int toInt(final byte[] digest, final int offset) {
return ((digest[offset + 0] & 0xFF) << 24) | ((digest[offset + 1] & 0xFF) << 16)
| ((digest[offset + 2] & 0xFF) << 8) | (digest[offset + 3] & 0xFF);
}
}
|
Fix incorrect SHA1TermDigester.state.
|
org.metaborg.runtime.task/src/main/java/org/metaborg/runtime/task/digest/SHA1TermDigester.java
|
Fix incorrect SHA1TermDigester.state.
|
|
Java
|
apache-2.0
|
18a8f4c3ce33c542f69d957195d4de6c3ff4f353
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework;
import com.intellij.execution.Location;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.actions.CopyReferenceAction;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiElement;
import com.intellij.ui.AnimatedIcon;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.popup.HintUpdateSupply;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.EditSourceOnEnterKeyHandler;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.datatransfer.StringSelection;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import static com.intellij.ui.render.RenderingHelper.SHRINK_LONG_RENDERER;
public abstract class TestTreeView extends Tree implements DataProvider, CopyProvider {
public static final DataKey<TestFrameworkRunningModel> MODEL_DATA_KEY = DataKey.create("testFrameworkModel.dataId");
private TestFrameworkRunningModel myModel;
public TestTreeView() {
setLargeModel(true);
}
protected abstract TreeCellRenderer getRenderer(TestConsoleProperties properties);
public abstract AbstractTestProxy getSelectedTest(@NotNull TreePath selectionPath);
protected TestFrameworkRunningModel getTestFrameworkRunningModel() {
return myModel;
}
@Nullable
public AbstractTestProxy getSelectedTest() {
TreePath[] paths = getSelectionPaths();
if (paths != null && paths.length > 1) return null;
final TreePath selectionPath = getSelectionPath();
return selectionPath != null ? getSelectedTest(selectionPath) : null;
}
public void attachToModel(final TestFrameworkRunningModel model) {
setModel(new DefaultTreeModel(new DefaultMutableTreeNode(model.getRoot())));
getSelectionModel().setSelectionMode(model.getProperties().getSelectionMode());
myModel = model;
Disposer.register(myModel, myModel.getRoot());
Disposer.register(myModel, new Disposable() {
@Override
public void dispose() {
setModel(null);
myModel = null;
}
});
installHandlers();
setCellRenderer(getRenderer(myModel.getProperties()));
putClientProperty(SHRINK_LONG_RENDERER, true);
putClientProperty(AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED, true);
}
@Override
public Object getData(@NotNull final String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return this;
}
if (AbstractTestProxy.DATA_KEYS.is(dataId)) {
TreePath[] paths = getSelectionPaths();
if (paths != null) {
return Arrays.stream(paths)
.map(path -> getSelectedTest(path))
.filter(Objects::nonNull)
.toArray(AbstractTestProxy[]::new);
}
}
if (MODEL_DATA_KEY.is(dataId)) {
return myModel;
}
TreePath selectionPath = getSelectionPath();
if (selectionPath == null) return null;
AbstractTestProxy testProxy = getSelectedTest(selectionPath);
if (testProxy == null) return null;
if (AbstractTestProxy.DATA_KEY.is(dataId)) {
return testProxy;
}
if (PlatformDataKeys.SLOW_DATA_PROVIDERS.is(dataId)) {
TestFrameworkRunningModel model = myModel;
return Collections.<DataProvider>singletonList(dataId1 -> getSlowData(dataId1, testProxy, model));
}
if (RunConfiguration.DATA_KEY.is(dataId)) {
RunProfile configuration = myModel.getProperties().getConfiguration();
if (configuration instanceof RunConfiguration) {
return configuration;
}
}
return null;
}
@Nullable
private Object getSlowData(@NotNull String dataId,
@NotNull AbstractTestProxy testProxy,
@NotNull TestFrameworkRunningModel model) {
Project project = model.getProperties().getProject();
if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
return TestsUIUtil.getOpenFileDescriptor(testProxy, model);
}
else if (CommonDataKeys.PSI_ELEMENT.is(dataId)) {
Location<?> location = testProxy.getLocation(project, model.getProperties().getScope());
PsiElement psiElement = location != null ? location.getPsiElement() : null;
return psiElement == null || !psiElement.isValid() ? null : psiElement;
}
else if (Location.DATA_KEY.is(dataId)) {
return testProxy.getLocation(project, model.getProperties().getScope());
}
else if (Location.DATA_KEYS.is(dataId)) {
AbstractTestProxy[] proxies = AbstractTestProxy.DATA_KEYS.getData(this);
return proxies == null ? null : Arrays.stream(proxies)
.map(p -> p.getLocation(project, model.getProperties().getScope()))
.filter(Objects::nonNull)
.toArray(Location[]::new);
}
else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) {
AbstractTestProxy[] proxies = AbstractTestProxy.DATA_KEYS.getData(this);
return proxies == null ? null : Arrays.stream(proxies)
.map(p -> p.getLocation(project, model.getProperties().getScope()))
.filter(Objects::nonNull).map(l -> l.getPsiElement())
.toArray(PsiElement[]::new);
}
return null;
}
@Override
public void performCopy(@NotNull DataContext dataContext) {
final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
final String fqn;
if (element != null) {
fqn = CopyReferenceAction.elementToFqn(element);
}
else {
AbstractTestProxy selectedTest = getSelectedTest();
fqn = selectedTest != null ? selectedTest.getLocationUrl() : null;
}
CopyPasteManager.getInstance().setContents(new StringSelection(fqn));
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
AbstractTestProxy test = getSelectedTest();
return test != null && test.getLocationUrl() != null;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
protected void installHandlers() {
EditSourceOnDoubleClickHandler.install(this);
EditSourceOnEnterKeyHandler.install(this);
new TreeSpeedSearch(this, path -> {
final AbstractTestProxy testProxy = getSelectedTest(path);
if (testProxy == null) return null;
return getPresentableName(testProxy);
}, Registry.is("tests.view.node.expanding.search"));
TreeUtil.installActions(this);
PopupHandler.installPopupHandler(this, IdeActions.GROUP_TESTTREE_POPUP, ActionPlaces.TESTTREE_VIEW_POPUP);
HintUpdateSupply.installHintUpdateSupply(this, obj -> {
Object userObject = TreeUtil.getUserObject(obj);
Object element = userObject instanceof NodeDescriptor? ((NodeDescriptor<?>)userObject).getElement() : null;
if (element instanceof AbstractTestProxy) {
return (PsiElement)getSlowData(CommonDataKeys.PSI_ELEMENT.getName(), (AbstractTestProxy)element, myModel);
}
return null;
});
}
protected String getPresentableName(AbstractTestProxy testProxy) {
return testProxy.getName();
}
}
|
platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework;
import com.intellij.execution.Location;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.actions.CopyReferenceAction;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.PsiElement;
import com.intellij.ui.AnimatedIcon;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.popup.HintUpdateSupply;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.EditSourceOnEnterKeyHandler;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.datatransfer.StringSelection;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import static com.intellij.ui.render.RenderingHelper.SHRINK_LONG_RENDERER;
public abstract class TestTreeView extends Tree implements DataProvider, CopyProvider {
public static final DataKey<TestFrameworkRunningModel> MODEL_DATA_KEY = DataKey.create("testFrameworkModel.dataId");
private TestFrameworkRunningModel myModel;
public TestTreeView() {
setLargeModel(true);
}
protected abstract TreeCellRenderer getRenderer(TestConsoleProperties properties);
public abstract AbstractTestProxy getSelectedTest(@NotNull TreePath selectionPath);
protected TestFrameworkRunningModel getTestFrameworkRunningModel() {
return myModel;
}
@Nullable
public AbstractTestProxy getSelectedTest() {
TreePath[] paths = getSelectionPaths();
if (paths != null && paths.length > 1) return null;
final TreePath selectionPath = getSelectionPath();
return selectionPath != null ? getSelectedTest(selectionPath) : null;
}
public void attachToModel(final TestFrameworkRunningModel model) {
setModel(new DefaultTreeModel(new DefaultMutableTreeNode(model.getRoot())));
getSelectionModel().setSelectionMode(model.getProperties().getSelectionMode());
myModel = model;
Disposer.register(myModel, myModel.getRoot());
Disposer.register(myModel, new Disposable() {
@Override
public void dispose() {
setModel(null);
myModel = null;
}
});
installHandlers();
setCellRenderer(getRenderer(myModel.getProperties()));
putClientProperty(SHRINK_LONG_RENDERER, true);
putClientProperty(AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED, true);
}
@Override
public Object getData(@NotNull final String dataId) {
if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return this;
}
if (AbstractTestProxy.DATA_KEYS.is(dataId)) {
TreePath[] paths = getSelectionPaths();
if (paths != null) {
return Arrays.stream(paths)
.map(path -> getSelectedTest(path))
.filter(Objects::nonNull)
.toArray(AbstractTestProxy[]::new);
}
}
if (MODEL_DATA_KEY.is(dataId)) {
return myModel;
}
TreePath selectionPath = getSelectionPath();
if (selectionPath == null) return null;
AbstractTestProxy testProxy = getSelectedTest(selectionPath);
if (testProxy == null) return null;
if (AbstractTestProxy.DATA_KEY.is(dataId)) {
return testProxy;
}
if (PlatformDataKeys.SLOW_DATA_PROVIDERS.is(dataId)) {
return Collections.<DataProvider>singletonList(dataId1 -> getSlowData(dataId1, testProxy, myModel));
}
if (RunConfiguration.DATA_KEY.is(dataId)) {
RunProfile configuration = myModel.getProperties().getConfiguration();
if (configuration instanceof RunConfiguration) {
return configuration;
}
}
return null;
}
@Nullable
private Object getSlowData(@NotNull String dataId,
@NotNull AbstractTestProxy testProxy,
@NotNull TestFrameworkRunningModel model) {
Project project = model.getProperties().getProject();
if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
return TestsUIUtil.getOpenFileDescriptor(testProxy, model);
}
else if (CommonDataKeys.PSI_ELEMENT.is(dataId)) {
Location<?> location = testProxy.getLocation(project, model.getProperties().getScope());
PsiElement psiElement = location != null ? location.getPsiElement() : null;
return psiElement == null || !psiElement.isValid() ? null : psiElement;
}
else if (Location.DATA_KEY.is(dataId)) {
return testProxy.getLocation(project, model.getProperties().getScope());
}
else if (Location.DATA_KEYS.is(dataId)) {
AbstractTestProxy[] proxies = AbstractTestProxy.DATA_KEYS.getData(this);
return proxies == null ? null : Arrays.stream(proxies)
.map(p -> p.getLocation(project, model.getProperties().getScope()))
.filter(Objects::nonNull)
.toArray(Location[]::new);
}
else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) {
AbstractTestProxy[] proxies = AbstractTestProxy.DATA_KEYS.getData(this);
return proxies == null ? null : Arrays.stream(proxies)
.map(p -> p.getLocation(project, model.getProperties().getScope()))
.filter(Objects::nonNull).map(l -> l.getPsiElement())
.toArray(PsiElement[]::new);
}
return null;
}
@Override
public void performCopy(@NotNull DataContext dataContext) {
final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
final String fqn;
if (element != null) {
fqn = CopyReferenceAction.elementToFqn(element);
}
else {
AbstractTestProxy selectedTest = getSelectedTest();
fqn = selectedTest != null ? selectedTest.getLocationUrl() : null;
}
CopyPasteManager.getInstance().setContents(new StringSelection(fqn));
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
AbstractTestProxy test = getSelectedTest();
return test != null && test.getLocationUrl() != null;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
protected void installHandlers() {
EditSourceOnDoubleClickHandler.install(this);
EditSourceOnEnterKeyHandler.install(this);
new TreeSpeedSearch(this, path -> {
final AbstractTestProxy testProxy = getSelectedTest(path);
if (testProxy == null) return null;
return getPresentableName(testProxy);
}, Registry.is("tests.view.node.expanding.search"));
TreeUtil.installActions(this);
PopupHandler.installPopupHandler(this, IdeActions.GROUP_TESTTREE_POPUP, ActionPlaces.TESTTREE_VIEW_POPUP);
HintUpdateSupply.installHintUpdateSupply(this, obj -> {
Object userObject = TreeUtil.getUserObject(obj);
Object element = userObject instanceof NodeDescriptor? ((NodeDescriptor<?>)userObject).getElement() : null;
if (element instanceof AbstractTestProxy) {
return (PsiElement)getSlowData(CommonDataKeys.PSI_ELEMENT.getName(), (AbstractTestProxy)element, myModel);
}
return null;
});
}
protected String getPresentableName(AbstractTestProxy testProxy) {
return testProxy.getName();
}
}
|
EA-260302 - IAE: TestTreeView.$$$reportNull$$$0
GitOrigin-RevId: fd8d762511bd976a4ed954f1902c38446c4509b8
|
platform/testRunner/src/com/intellij/execution/testframework/TestTreeView.java
|
EA-260302 - IAE: TestTreeView.$$$reportNull$$$0
|
|
Java
|
apache-2.0
|
4a770fc63a77e44cecbf6615b55a10113055e042
| 0
|
DaanHoogland/cloudstack,resmo/cloudstack,wido/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,wido/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.storage.template;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.storage.command.DownloadCommand;
import org.apache.cloudstack.storage.command.DownloadCommand.ResourceType;
import org.apache.cloudstack.storage.command.DownloadProgressCommand;
import org.apache.cloudstack.storage.command.DownloadProgressCommand.RequestType;
import org.apache.cloudstack.storage.resource.SecondaryStorageResource;
import org.apache.log4j.Logger;
import com.cloud.agent.api.storage.DownloadAnswer;
import com.cloud.agent.api.storage.Proxy;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.S3TO;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.template.HttpTemplateDownloader;
import com.cloud.storage.template.IsoProcessor;
import com.cloud.storage.template.LocalTemplateDownloader;
import com.cloud.storage.template.OVAProcessor;
import com.cloud.storage.template.Processor;
import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.RawImageProcessor;
import com.cloud.storage.template.S3TemplateDownloader;
import com.cloud.storage.template.ScpTemplateDownloader;
import com.cloud.storage.template.TARProcessor;
import com.cloud.storage.template.TemplateConstants;
import com.cloud.storage.template.TemplateDownloader;
import com.cloud.storage.template.TemplateDownloader.DownloadCompleteCallback;
import com.cloud.storage.template.TemplateDownloader.Status;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.storage.template.TemplateProp;
import com.cloud.storage.template.VhdProcessor;
import com.cloud.storage.template.VmdkProcessor;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.utils.storage.QCOW2Utils;
@Local(value = DownloadManager.class)
public class DownloadManagerImpl extends ManagerBase implements DownloadManager {
private String _name;
StorageLayer _storage;
public Map<String, Processor> _processors;
public class Completion implements DownloadCompleteCallback {
private final String jobId;
public Completion(String jobId) {
this.jobId = jobId;
}
@Override
public void downloadComplete(Status status) {
setDownloadStatus(jobId, status);
}
}
@Override
public Map<String, Processor> getProcessors() {
return _processors;
}
private static class DownloadJob {
private final TemplateDownloader td;
private final String tmpltName;
private final boolean hvm;
private final ImageFormat format;
private String tmpltPath;
private final String description;
private String checksum;
private final String installPathPrefix;
private long templatesize;
private long templatePhysicalSize;
private final long id;
private final ResourceType resourceType;
public DownloadJob(TemplateDownloader td, String jobId, long id, String tmpltName, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, ResourceType resourceType) {
super();
this.td = td;
this.tmpltName = tmpltName;
this.format = format;
this.hvm = hvm;
this.description = descr;
this.checksum = cksum;
this.installPathPrefix = installPathPrefix;
this.templatesize = 0;
this.id = id;
this.resourceType = resourceType;
}
public String getDescription() {
return description;
}
public String getChecksum() {
return checksum;
}
public TemplateDownloader getTemplateDownloader() {
return td;
}
public String getTmpltName() {
return tmpltName;
}
public ImageFormat getFormat() {
return format;
}
public boolean isHvm() {
return hvm;
}
public long getId() {
return id;
}
public ResourceType getResourceType() {
return resourceType;
}
public void setTmpltPath(String tmpltPath) {
this.tmpltPath = tmpltPath;
}
public String getTmpltPath() {
return tmpltPath;
}
public String getInstallPathPrefix() {
return installPathPrefix;
}
public void cleanup() {
if (td != null) {
String dnldPath = td.getDownloadLocalPath();
if (dnldPath != null) {
File f = new File(dnldPath);
File dir = f.getParentFile();
f.delete();
if (dir != null) {
dir.delete();
}
}
}
}
public void setTemplatesize(long templatesize) {
this.templatesize = templatesize;
}
public long getTemplatesize() {
return templatesize;
}
public void setTemplatePhysicalSize(long templatePhysicalSize) {
this.templatePhysicalSize = templatePhysicalSize;
}
public long getTemplatePhysicalSize() {
return templatePhysicalSize;
}
public void setCheckSum(String checksum) {
this.checksum = checksum;
}
}
public static final Logger s_logger = Logger.getLogger(DownloadManagerImpl.class);
private String _templateDir;
private String _volumeDir;
private String createTmpltScr;
private String createVolScr;
private ExecutorService threadPool;
private final Map<String, DownloadJob> jobs = new ConcurrentHashMap<String, DownloadJob>();
private String listTmpltScr;
private String listVolScr;
private int installTimeoutPerGig = 180 * 60 * 1000;
public void setThreadPool(ExecutorService threadPool) {
this.threadPool = threadPool;
}
public void setStorageLayer(StorageLayer storage) {
_storage = storage;
}
/**
* Get notified of change of job status. Executed in context of downloader
* thread
*
* @param jobId
* the id of the job
* @param status
* the status of the job
*/
public void setDownloadStatus(String jobId, Status status) {
DownloadJob dj = jobs.get(jobId);
if (dj == null) {
s_logger.warn("setDownloadStatus for jobId: " + jobId + ", status=" + status + " no job found");
return;
}
TemplateDownloader td = dj.getTemplateDownloader();
s_logger.info("Download Completion for jobId: " + jobId + ", status=" + status);
s_logger.info("local: " + td.getDownloadLocalPath() + ", bytes=" + td.getDownloadedBytes() + ", error=" + td.getDownloadError() + ", pct=" +
td.getDownloadPercent());
switch (status) {
case ABORTED:
case NOT_STARTED:
case UNRECOVERABLE_ERROR:
// TODO
dj.cleanup();
break;
case UNKNOWN:
return;
case IN_PROGRESS:
s_logger.info("Resuming jobId: " + jobId + ", status=" + status);
td.setResume(true);
threadPool.execute(td);
break;
case RECOVERABLE_ERROR:
threadPool.execute(td);
break;
case DOWNLOAD_FINISHED:
if(td instanceof S3TemplateDownloader) {
// For S3 and Swift, which are considered "remote",
// as in the file cannot be accessed locally,
// we run the postRemoteDownload() method.
td.setDownloadError("Download success, starting install ");
String result = postRemoteDownload(jobId);
if (result != null) {
s_logger.error("Failed post download install: " + result);
td.setStatus(Status.UNRECOVERABLE_ERROR);
td.setDownloadError("Failed post download install: " + result);
((S3TemplateDownloader) td).cleanupAfterError();
} else {
td.setStatus(Status.POST_DOWNLOAD_FINISHED);
td.setDownloadError("Install completed successfully at " + new SimpleDateFormat().format(new Date()));
}
}
else {
// For other TemplateDownloaders where files are locally available,
// we run the postLocalDownload() method.
td.setDownloadError("Download success, starting install ");
String result = postLocalDownload(jobId);
if (result != null) {
s_logger.error("Failed post download script: " + result);
td.setStatus(Status.UNRECOVERABLE_ERROR);
td.setDownloadError("Failed post download script: " + result);
} else {
td.setStatus(Status.POST_DOWNLOAD_FINISHED);
td.setDownloadError("Install completed successfully at " + new SimpleDateFormat().format(new Date()));
}
}
dj.cleanup();
break;
default:
break;
}
}
private String computeCheckSum(File f) {
byte[] buffer = new byte[8192];
int read = 0;
MessageDigest digest;
String checksum = null;
InputStream is = null;
try {
digest = MessageDigest.getInstance("MD5");
is = new FileInputStream(f);
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
checksum = String.format("%032x", bigInt);
return checksum;
} catch (IOException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
return null;
}
}
}
/**
* Post remote download activity (install and cleanup). Executed in context of the downloader thread.
*/
private String postRemoteDownload(String jobId) {
String result = null;
DownloadJob dnld = jobs.get(jobId);
S3TemplateDownloader td = (S3TemplateDownloader)dnld.getTemplateDownloader();
if (td.getFileExtension().equalsIgnoreCase("QCOW2")) {
// The QCOW2 is the only format with a header,
// and as such can be easily read.
try {
InputStream inputStream = td.getS3ObjectInputStream();
dnld.setTemplatesize(QCOW2Utils.getVirtualSize(inputStream));
inputStream.close();
}
catch (IOException e) {
result = "Couldn't read QCOW2 virtual size. Error: " + e.getMessage();
}
}
else {
// For the other formats, both the virtual
// and actual file size are set the same.
dnld.setTemplatesize(td.getTotalBytes());
}
dnld.setTemplatePhysicalSize(td.getTotalBytes());
dnld.setTmpltPath(td.getDownloadLocalPath());
return result;
}
/**
* Post local download activity (install and cleanup). Executed in context of
* downloader thread
*
* @throws IOException
*/
private String postLocalDownload(String jobId) {
DownloadJob dnld = jobs.get(jobId);
TemplateDownloader td = dnld.getTemplateDownloader();
String resourcePath = dnld.getInstallPathPrefix(); // path with mount
// directory
String finalResourcePath = dnld.getTmpltPath(); // template download
// path on secondary
// storage
ResourceType resourceType = dnld.getResourceType();
File originalTemplate = new File(td.getDownloadLocalPath());
String checkSum = computeCheckSum(originalTemplate);
if (checkSum == null) {
s_logger.warn("Something wrong happened when try to calculate the checksum of downloaded template!");
}
dnld.setCheckSum(checkSum);
int imgSizeGigs = (int)Math.ceil(_storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
imgSizeGigs++; // add one just in case
long timeout = (long)imgSizeGigs * installTimeoutPerGig;
Script scr = null;
String script = resourceType == ResourceType.TEMPLATE ? createTmpltScr : createVolScr;
scr = new Script(script, timeout, s_logger);
scr.add("-s", Integer.toString(imgSizeGigs));
scr.add("-S", Long.toString(td.getMaxTemplateSizeInBytes()));
if (dnld.getDescription() != null && dnld.getDescription().length() > 1) {
scr.add("-d", dnld.getDescription());
}
if (dnld.isHvm()) {
scr.add("-h");
}
// add options common to ISO and template
String extension = dnld.getFormat().getFileExtension();
String templateName = "";
if (extension.equals("iso")) {
templateName = jobs.get(jobId).getTmpltName().trim().replace(" ", "_");
} else {
templateName = java.util.UUID.nameUUIDFromBytes((jobs.get(jobId).getTmpltName() + System.currentTimeMillis()).getBytes(StringUtils.getPreferredCharset())).toString();
}
// run script to mv the temporary template file to the final template
// file
String templateFilename = templateName + "." + extension;
dnld.setTmpltPath(finalResourcePath + "/" + templateFilename);
scr.add("-n", templateFilename);
scr.add("-t", resourcePath);
scr.add("-f", td.getDownloadLocalPath()); // this is the temporary
// template file downloaded
if (dnld.getChecksum() != null && dnld.getChecksum().length() > 1) {
scr.add("-c", dnld.getChecksum());
}
scr.add("-u"); // cleanup
String result;
result = scr.execute();
if (result != null) {
return result;
}
// Set permissions for the downloaded template
File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
_storage.setWorldReadableAndWriteable(downloadedTemplate);
// Set permissions for template/volume.properties
String propertiesFile = resourcePath;
if (resourceType == ResourceType.TEMPLATE) {
propertiesFile += "/template.properties";
} else {
propertiesFile += "/volume.properties";
}
File templateProperties = new File(propertiesFile);
_storage.setWorldReadableAndWriteable(templateProperties);
TemplateLocation loc = new TemplateLocation(_storage, resourcePath);
try {
loc.create(dnld.getId(), true, dnld.getTmpltName());
} catch (IOException e) {
s_logger.warn("Something is wrong with template location " + resourcePath, e);
loc.purge();
return "Unable to download due to " + e.getMessage();
}
Iterator<Processor> en = _processors.values().iterator();
while (en.hasNext()) {
Processor processor = en.next();
FormatInfo info = null;
try {
info = processor.process(resourcePath, null, templateName);
} catch (InternalErrorException e) {
s_logger.error("Template process exception ", e);
return e.toString();
}
if (info != null) {
loc.addFormat(info);
dnld.setTemplatesize(info.virtualSize);
dnld.setTemplatePhysicalSize(info.size);
break;
}
}
if (!loc.save()) {
s_logger.warn("Cleaning up because we're unable to save the formats");
loc.purge();
}
return null;
}
@Override
public Status getDownloadStatus(String jobId) {
DownloadJob job = jobs.get(jobId);
if (job != null) {
TemplateDownloader td = job.getTemplateDownloader();
if (td != null) {
return td.getStatus();
}
}
return Status.UNKNOWN;
}
@Override
public String downloadS3Template(S3TO s3, long id, String url, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, String user, String password, long maxTemplateSizeInBytes, Proxy proxy, ResourceType resourceType) {
UUID uuid = UUID.randomUUID();
String jobId = uuid.toString();
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
TemplateDownloader td;
if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
td = new S3TemplateDownloader(s3, url, installPathPrefix, new Completion(jobId), maxTemplateSizeInBytes, user, password, proxy, resourceType);
} else {
throw new CloudRuntimeException("Scheme is not supported " + url);
}
} else {
throw new CloudRuntimeException("Unable to download from URL: " + url);
}
DownloadJob dj = new DownloadJob(td, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix, resourceType);
dj.setTmpltPath(installPathPrefix);
jobs.put(jobId, dj);
threadPool.execute(td);
return jobId;
}
@Override
public String downloadPublicTemplate(long id, String url, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, String templatePath, String user, String password, long maxTemplateSizeInBytes, Proxy proxy, ResourceType resourceType) {
UUID uuid = UUID.randomUUID();
String jobId = uuid.toString();
String tmpDir = installPathPrefix;
try {
if (!_storage.mkdirs(tmpDir)) {
s_logger.warn("Unable to create " + tmpDir);
return "Unable to create " + tmpDir;
}
// TO DO - define constant for volume properties.
File file =
ResourceType.TEMPLATE == resourceType ? _storage.getFile(tmpDir + File.separator + TemplateLocation.Filename) : _storage.getFile(tmpDir + File.separator +
"volume.properties");
if (file.exists()) {
file.delete();
}
if (!file.createNewFile()) {
s_logger.warn("Unable to create new file: " + file.getAbsolutePath());
return "Unable to create new file: " + file.getAbsolutePath();
}
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
TemplateDownloader td;
if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
td = new HttpTemplateDownloader(_storage, url, tmpDir, new Completion(jobId), maxTemplateSizeInBytes, user, password, proxy, resourceType);
} else if (uri.getScheme().equalsIgnoreCase("file")) {
td = new LocalTemplateDownloader(_storage, url, tmpDir, maxTemplateSizeInBytes, new Completion(jobId));
} else if (uri.getScheme().equalsIgnoreCase("scp")) {
td = new ScpTemplateDownloader(_storage, url, tmpDir, maxTemplateSizeInBytes, new Completion(jobId));
} else if (uri.getScheme().equalsIgnoreCase("nfs") || uri.getScheme().equalsIgnoreCase("cifs")) {
td = null;
// TODO: implement this.
throw new CloudRuntimeException("Scheme is not supported " + url);
} else {
throw new CloudRuntimeException("Scheme is not supported " + url);
}
} else {
throw new CloudRuntimeException("Unable to download from URL: " + url);
}
// NOTE the difference between installPathPrefix and templatePath
// here. instalPathPrefix is the absolute path for template
// including mount directory
// on ssvm, while templatePath is the final relative path on
// secondary storage.
DownloadJob dj = new DownloadJob(td, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix, resourceType);
dj.setTmpltPath(templatePath);
jobs.put(jobId, dj);
threadPool.execute(td);
return jobId;
} catch (IOException e) {
s_logger.warn("Unable to download to " + tmpDir, e);
return null;
}
}
@Override
public String getDownloadError(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadError();
}
return null;
}
public long getDownloadTemplateSize(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplatesize();
}
return 0;
}
public String getDownloadCheckSum(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getChecksum();
}
return null;
}
public long getDownloadTemplatePhysicalSize(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplatePhysicalSize();
}
return 0;
}
// @Override
public String getDownloadLocalPath(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadLocalPath();
}
return null;
}
@Override
public int getDownloadPct(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadPercent();
}
return 0;
}
public static VMTemplateHostVO.Status convertStatus(Status tds) {
switch (tds) {
case ABORTED:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case DOWNLOAD_FINISHED:
return VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS;
case IN_PROGRESS:
return VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS;
case NOT_STARTED:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case RECOVERABLE_ERROR:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case UNKNOWN:
return VMTemplateHostVO.Status.UNKNOWN;
case UNRECOVERABLE_ERROR:
return VMTemplateHostVO.Status.DOWNLOAD_ERROR;
case POST_DOWNLOAD_FINISHED:
return VMTemplateHostVO.Status.DOWNLOADED;
default:
return VMTemplateHostVO.Status.UNKNOWN;
}
}
@Override
public com.cloud.storage.VMTemplateHostVO.Status getDownloadStatus2(String jobId) {
return convertStatus(getDownloadStatus(jobId));
}
@Override
public DownloadAnswer handleDownloadCommand(SecondaryStorageResource resource, DownloadCommand cmd) {
ResourceType resourceType = cmd.getResourceType();
if (cmd instanceof DownloadProgressCommand) {
return handleDownloadProgressCmd(resource, (DownloadProgressCommand)cmd);
}
if (cmd.getUrl() == null) {
return new DownloadAnswer(resourceType.toString() + " is corrupted on storage due to an invalid url , cannot download",
VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
if (cmd.getName() == null) {
return new DownloadAnswer("Invalid Name", VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
DataStoreTO dstore = cmd.getDataStore();
String installPathPrefix = cmd.getInstallPath();
// for NFS, we need to get mounted path
if (dstore instanceof NfsTO) {
installPathPrefix = resource.getRootDir(((NfsTO)dstore).getUrl()) + File.separator + installPathPrefix;
}
String user = null;
String password = null;
if (cmd.getAuth() != null) {
user = cmd.getAuth().getUserName();
password = cmd.getAuth().getPassword();
}
// TO DO - Define Volume max size as well
long maxDownloadSizeInBytes =
(cmd.getMaxDownloadSizeInBytes() == null) ? TemplateDownloader.DEFAULT_MAX_TEMPLATE_SIZE_IN_BYTES : (cmd.getMaxDownloadSizeInBytes());
String jobId = null;
if (dstore instanceof S3TO) {
jobId =
downloadS3Template((S3TO)dstore, cmd.getId(), cmd.getUrl(), cmd.getName(), cmd.getFormat(), cmd.isHvm(), cmd.getAccountId(), cmd.getDescription(),
cmd.getChecksum(), installPathPrefix, user, password, maxDownloadSizeInBytes, cmd.getProxy(), resourceType);
} else {
jobId =
downloadPublicTemplate(cmd.getId(), cmd.getUrl(), cmd.getName(), cmd.getFormat(), cmd.isHvm(), cmd.getAccountId(), cmd.getDescription(),
cmd.getChecksum(), installPathPrefix, cmd.getInstallPath(), user, password, maxDownloadSizeInBytes, cmd.getProxy(), resourceType);
}
sleep();
if (jobId == null) {
return new DownloadAnswer("Internal Error", VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
return new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId), getInstallPath(jobId),
getDownloadTemplateSize(jobId), getDownloadTemplateSize(jobId), getDownloadCheckSum(jobId));
}
private void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignore
}
}
private DownloadAnswer handleDownloadProgressCmd(SecondaryStorageResource resource, DownloadProgressCommand cmd) {
String jobId = cmd.getJobId();
DownloadAnswer answer;
DownloadJob dj = null;
if (jobId != null) {
dj = jobs.get(jobId);
}
if (dj == null) {
if (cmd.getRequest() == RequestType.GET_OR_RESTART) {
DownloadCommand dcmd = new DownloadCommand(cmd);
return handleDownloadCommand(resource, dcmd);
} else {
return new DownloadAnswer("Cannot find job", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.UNKNOWN);
}
}
TemplateDownloader td = dj.getTemplateDownloader();
switch (cmd.getRequest()) {
case GET_STATUS:
break;
case ABORT:
td.stopDownload();
sleep();
break;
case RESTART:
td.stopDownload();
sleep();
threadPool.execute(td);
break;
case PURGE:
td.stopDownload();
answer =
new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId),
getInstallPath(jobId), getDownloadTemplateSize(jobId), getDownloadTemplatePhysicalSize(jobId), getDownloadCheckSum(jobId));
jobs.remove(jobId);
return answer;
default:
break; // TODO
}
return new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId), getInstallPath(jobId),
getDownloadTemplateSize(jobId), getDownloadTemplatePhysicalSize(jobId), getDownloadCheckSum(jobId));
}
private String getInstallPath(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTmpltPath();
}
return null;
}
private List<String> listVolumes(String rootdir) {
List<String> result = new ArrayList<String>();
Script script = new Script(listVolScr, s_logger);
script.add("-r", rootdir);
ZfsPathParser zpp = new ZfsPathParser(rootdir);
script.execute(zpp);
result.addAll(zpp.getPaths());
s_logger.info("found " + zpp.getPaths().size() + " volumes" + zpp.getPaths());
return result;
}
private List<String> listTemplates(String rootdir) {
List<String> result = new ArrayList<String>();
Script script = new Script(listTmpltScr, s_logger);
script.add("-r", rootdir);
ZfsPathParser zpp = new ZfsPathParser(rootdir);
script.execute(zpp);
result.addAll(zpp.getPaths());
s_logger.info("found " + zpp.getPaths().size() + " templates" + zpp.getPaths());
return result;
}
@Override
public Map<String, TemplateProp> gatherTemplateInfo(String rootDir) {
Map<String, TemplateProp> result = new HashMap<String, TemplateProp>();
String templateDir = rootDir + File.separator + _templateDir;
if (!_storage.exists(templateDir)) {
_storage.mkdirs(templateDir);
}
List<String> publicTmplts = listTemplates(templateDir);
for (String tmplt : publicTmplts) {
String path = tmplt.substring(0, tmplt.lastIndexOf(File.separator));
TemplateLocation loc = new TemplateLocation(_storage, path);
try {
if (!loc.load()) {
s_logger.warn("Post download installation was not completed for " + path);
// loc.purge();
_storage.cleanup(path, templateDir);
continue;
}
} catch (IOException e) {
s_logger.warn("Unable to load template location " + path, e);
continue;
}
TemplateProp tInfo = loc.getTemplateInfo();
if ((tInfo.getSize() == tInfo.getPhysicalSize()) && (tInfo.getInstallPath().endsWith(ImageFormat.OVA.getFileExtension()))) {
try {
Processor processor = _processors.get("OVA Processor");
OVAProcessor vmdkProcessor = (OVAProcessor)processor;
long vSize = vmdkProcessor.getTemplateVirtualSize(path, tInfo.getInstallPath().substring(tInfo.getInstallPath().lastIndexOf(File.separator) + 1));
tInfo.setSize(vSize);
loc.updateVirtualSize(vSize);
loc.save();
} catch (Exception e) {
s_logger.error("Unable to get the virtual size of the template: " + tInfo.getInstallPath() + " due to " + e.getMessage());
}
}
result.put(tInfo.getTemplateName(), tInfo);
s_logger.debug("Added template name: " + tInfo.getTemplateName() + ", path: " + tmplt);
}
/*
for (String tmplt : isoTmplts) {
String tmp[];
tmp = tmplt.split("/");
String tmpltName = tmp[tmp.length - 2];
tmplt = tmplt.substring(tmplt.lastIndexOf("iso/"));
TemplateInfo tInfo = new TemplateInfo(tmpltName, tmplt, false);
s_logger.debug("Added iso template name: " + tmpltName + ", path: " + tmplt);
result.put(tmpltName, tInfo);
}
*/
return result;
}
@Override
public Map<Long, TemplateProp> gatherVolumeInfo(String rootDir) {
Map<Long, TemplateProp> result = new HashMap<Long, TemplateProp>();
String volumeDir = rootDir + File.separator + _volumeDir;
if (!_storage.exists(volumeDir)) {
_storage.mkdirs(volumeDir);
}
List<String> vols = listVolumes(volumeDir);
for (String vol : vols) {
String path = vol.substring(0, vol.lastIndexOf(File.separator));
TemplateLocation loc = new TemplateLocation(_storage, path);
try {
if (!loc.load()) {
s_logger.warn("Post download installation was not completed for " + path);
// loc.purge();
_storage.cleanup(path, volumeDir);
continue;
}
} catch (IOException e) {
s_logger.warn("Unable to load volume location " + path, e);
continue;
}
TemplateProp vInfo = loc.getTemplateInfo();
if ((vInfo.getSize() == vInfo.getPhysicalSize()) && (vInfo.getInstallPath().endsWith(ImageFormat.OVA.getFileExtension()))) {
try {
Processor processor = _processors.get("OVA Processor");
OVAProcessor vmdkProcessor = (OVAProcessor)processor;
long vSize = vmdkProcessor.getTemplateVirtualSize(path, vInfo.getInstallPath().substring(vInfo.getInstallPath().lastIndexOf(File.separator) + 1));
vInfo.setSize(vSize);
loc.updateVirtualSize(vSize);
loc.save();
} catch (Exception e) {
s_logger.error("Unable to get the virtual size of the volume: " + vInfo.getInstallPath() + " due to " + e.getMessage());
}
}
result.put(vInfo.getId(), vInfo);
s_logger.debug("Added volume name: " + vInfo.getTemplateName() + ", path: " + vol);
}
return result;
}
public static class ZfsPathParser extends OutputInterpreter {
String _parent;
List<String> paths = new ArrayList<String>();
public ZfsPathParser(String parent) {
_parent = parent;
}
@Override
public String interpret(BufferedReader reader) throws IOException {
String line = null;
while ((line = reader.readLine()) != null) {
paths.add(line);
}
return null;
}
public List<String> getPaths() {
return paths;
}
@Override
public boolean drain() {
return true;
}
}
public DownloadManagerImpl() {
}
@Override
@SuppressWarnings("unchecked")
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
String value = null;
_storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
value = (String)params.get(StorageLayer.ClassConfigKey);
if (value == null) {
throw new ConfigurationException("Unable to find the storage layer");
}
Class<StorageLayer> clazz;
try {
clazz = (Class<StorageLayer>)Class.forName(value);
_storage = clazz.newInstance();
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} catch (InstantiationException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Unable to instantiate " + value);
}
}
String inSystemVM = (String)params.get("secondary.storage.vm");
if (inSystemVM != null && "true".equalsIgnoreCase(inSystemVM)) {
s_logger.info("DownloadManager: starting additional services since we are inside system vm");
startAdditionalServices();
blockOutgoingOnPrivate();
}
value = (String)params.get("install.timeout.pergig");
installTimeoutPerGig = NumbersUtil.parseInt(value, 15 * 60) * 1000;
value = (String)params.get("install.numthreads");
final int numInstallThreads = NumbersUtil.parseInt(value, 10);
String scriptsDir = (String)params.get("template.scripts.dir");
if (scriptsDir == null) {
scriptsDir = "scripts/storage/secondary";
}
listTmpltScr = Script.findScript(scriptsDir, "listvmtmplt.sh");
if (listTmpltScr == null) {
throw new ConfigurationException("Unable to find the listvmtmplt.sh");
}
s_logger.info("listvmtmplt.sh found in " + listTmpltScr);
createTmpltScr = Script.findScript(scriptsDir, "createtmplt.sh");
if (createTmpltScr == null) {
throw new ConfigurationException("Unable to find createtmplt.sh");
}
s_logger.info("createtmplt.sh found in " + createTmpltScr);
listVolScr = Script.findScript(scriptsDir, "listvolume.sh");
if (listVolScr == null) {
throw new ConfigurationException("Unable to find the listvolume.sh");
}
s_logger.info("listvolume.sh found in " + listVolScr);
createVolScr = Script.findScript(scriptsDir, "createvolume.sh");
if (createVolScr == null) {
throw new ConfigurationException("Unable to find createvolume.sh");
}
s_logger.info("createvolume.sh found in " + createVolScr);
_processors = new HashMap<String, Processor>();
Processor processor = new VhdProcessor();
processor.configure("VHD Processor", params);
_processors.put("VHD Processor", processor);
processor = new IsoProcessor();
processor.configure("ISO Processor", params);
_processors.put("ISO Processor", processor);
processor = new QCOW2Processor();
processor.configure("QCOW2 Processor", params);
_processors.put("QCOW2 Processor", processor);
processor = new OVAProcessor();
processor.configure("OVA Processor", params);
_processors.put("OVA Processor", processor);
processor = new VmdkProcessor();
processor.configure("VMDK Processor", params);
_processors.put("VMDK Processor", processor);
processor = new RawImageProcessor();
processor.configure("Raw Image Processor", params);
_processors.put("Raw Image Processor", processor);
processor = new TARProcessor();
processor.configure("TAR Processor", params);
_processors.put("TAR Processor", processor);
_templateDir = (String)params.get("public.templates.root.dir");
if (_templateDir == null) {
_templateDir = TemplateConstants.DEFAULT_TMPLT_ROOT_DIR;
}
_templateDir += File.separator + TemplateConstants.DEFAULT_TMPLT_FIRST_LEVEL_DIR;
_volumeDir = TemplateConstants.DEFAULT_VOLUME_ROOT_DIR + File.separator;
// Add more processors here.
threadPool = Executors.newFixedThreadPool(numInstallThreads);
return true;
}
private void blockOutgoingOnPrivate() {
Script command = new Script("/bin/bash", s_logger);
String intf = "eth1";
command.add("-c");
command.add("iptables -A OUTPUT -o " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "80" + " -j REJECT;" + "iptables -A OUTPUT -o " + intf +
" -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j REJECT;");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in blocking outgoing to port 80/443 err=" + result);
return;
}
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
private void startAdditionalServices() {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 stop; else service httpd stop; fi ");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in stopping httpd service err=" + result);
}
String port = Integer.toString(TemplateConstants.DEFAULT_TMPLT_COPY_PORT);
String intf = TemplateConstants.DEFAULT_TMPLT_COPY_INTF;
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j ACCEPT;" + "iptables -I INPUT -i " + intf +
" -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j ACCEPT;");
result = command.execute();
if (result != null) {
s_logger.warn("Error in opening up httpd port err=" + result);
return;
}
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 start; else service httpd start; fi ");
result = command.execute();
if (result != null) {
s_logger.warn("Error in starting httpd service err=" + result);
return;
}
command = new Script("mkdir", s_logger);
command.add("-p");
command.add("/var/www/html/copy/template");
result = command.execute();
if (result != null) {
s_logger.warn("Error in creating directory =" + result);
return;
}
}
}
|
services/secondary-storage/server/src/org/apache/cloudstack/storage/template/DownloadManagerImpl.java
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.storage.template;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.storage.command.DownloadCommand;
import org.apache.cloudstack.storage.command.DownloadCommand.ResourceType;
import org.apache.cloudstack.storage.command.DownloadProgressCommand;
import org.apache.cloudstack.storage.command.DownloadProgressCommand.RequestType;
import org.apache.cloudstack.storage.resource.SecondaryStorageResource;
import org.apache.log4j.Logger;
import com.cloud.agent.api.storage.DownloadAnswer;
import com.cloud.agent.api.storage.Proxy;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.S3TO;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.template.HttpTemplateDownloader;
import com.cloud.storage.template.IsoProcessor;
import com.cloud.storage.template.LocalTemplateDownloader;
import com.cloud.storage.template.OVAProcessor;
import com.cloud.storage.template.Processor;
import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.RawImageProcessor;
import com.cloud.storage.template.S3TemplateDownloader;
import com.cloud.storage.template.ScpTemplateDownloader;
import com.cloud.storage.template.TARProcessor;
import com.cloud.storage.template.TemplateConstants;
import com.cloud.storage.template.TemplateDownloader;
import com.cloud.storage.template.TemplateDownloader.DownloadCompleteCallback;
import com.cloud.storage.template.TemplateDownloader.Status;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.storage.template.TemplateProp;
import com.cloud.storage.template.VhdProcessor;
import com.cloud.storage.template.VmdkProcessor;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.utils.storage.QCOW2Utils;
@Local(value = DownloadManager.class)
public class DownloadManagerImpl extends ManagerBase implements DownloadManager {
private String _name;
StorageLayer _storage;
public Map<String, Processor> _processors;
public class Completion implements DownloadCompleteCallback {
private final String jobId;
public Completion(String jobId) {
this.jobId = jobId;
}
@Override
public void downloadComplete(Status status) {
setDownloadStatus(jobId, status);
}
}
@Override
public Map<String, Processor> getProcessors() {
return _processors;
}
private static class DownloadJob {
private final TemplateDownloader td;
private final String tmpltName;
private final boolean hvm;
private final ImageFormat format;
private String tmpltPath;
private final String description;
private String checksum;
private final String installPathPrefix;
private long templatesize;
private long templatePhysicalSize;
private final long id;
private final ResourceType resourceType;
public DownloadJob(TemplateDownloader td, String jobId, long id, String tmpltName, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, ResourceType resourceType) {
super();
this.td = td;
this.tmpltName = tmpltName;
this.format = format;
this.hvm = hvm;
this.description = descr;
this.checksum = cksum;
this.installPathPrefix = installPathPrefix;
this.templatesize = 0;
this.id = id;
this.resourceType = resourceType;
}
public String getDescription() {
return description;
}
public String getChecksum() {
return checksum;
}
public TemplateDownloader getTemplateDownloader() {
return td;
}
public String getTmpltName() {
return tmpltName;
}
public ImageFormat getFormat() {
return format;
}
public boolean isHvm() {
return hvm;
}
public long getId() {
return id;
}
public ResourceType getResourceType() {
return resourceType;
}
public void setTmpltPath(String tmpltPath) {
this.tmpltPath = tmpltPath;
}
public String getTmpltPath() {
return tmpltPath;
}
public String getInstallPathPrefix() {
return installPathPrefix;
}
public void cleanup() {
if (td != null) {
String dnldPath = td.getDownloadLocalPath();
if (dnldPath != null) {
File f = new File(dnldPath);
File dir = f.getParentFile();
f.delete();
if (dir != null) {
dir.delete();
}
}
}
}
public void setTemplatesize(long templatesize) {
this.templatesize = templatesize;
}
public long getTemplatesize() {
return templatesize;
}
public void setTemplatePhysicalSize(long templatePhysicalSize) {
this.templatePhysicalSize = templatePhysicalSize;
}
public long getTemplatePhysicalSize() {
return templatePhysicalSize;
}
public void setCheckSum(String checksum) {
this.checksum = checksum;
}
}
public static final Logger s_logger = Logger.getLogger(DownloadManagerImpl.class);
private String _templateDir;
private String _volumeDir;
private String createTmpltScr;
private String createVolScr;
private ExecutorService threadPool;
private final Map<String, DownloadJob> jobs = new ConcurrentHashMap<String, DownloadJob>();
private String listTmpltScr;
private String listVolScr;
private int installTimeoutPerGig = 180 * 60 * 1000;
public void setThreadPool(ExecutorService threadPool) {
this.threadPool = threadPool;
}
public void setStorageLayer(StorageLayer storage) {
_storage = storage;
}
/**
* Get notified of change of job status. Executed in context of downloader
* thread
*
* @param jobId
* the id of the job
* @param status
* the status of the job
*/
public void setDownloadStatus(String jobId, Status status) {
DownloadJob dj = jobs.get(jobId);
if (dj == null) {
s_logger.warn("setDownloadStatus for jobId: " + jobId + ", status=" + status + " no job found");
return;
}
TemplateDownloader td = dj.getTemplateDownloader();
s_logger.info("Download Completion for jobId: " + jobId + ", status=" + status);
s_logger.info("local: " + td.getDownloadLocalPath() + ", bytes=" + td.getDownloadedBytes() + ", error=" + td.getDownloadError() + ", pct=" +
td.getDownloadPercent());
switch (status) {
case ABORTED:
case NOT_STARTED:
case UNRECOVERABLE_ERROR:
// TODO
dj.cleanup();
break;
case UNKNOWN:
return;
case IN_PROGRESS:
s_logger.info("Resuming jobId: " + jobId + ", status=" + status);
td.setResume(true);
threadPool.execute(td);
break;
case RECOVERABLE_ERROR:
threadPool.execute(td);
break;
case DOWNLOAD_FINISHED:
if(td instanceof S3TemplateDownloader) {
// For S3 and Swift, which are considered "remote",
// as in the file cannot be accessed locally,
// we run the postRemoteDownload() method.
td.setDownloadError("Download success, starting install ");
String result = postRemoteDownload(jobId);
if (result != null) {
s_logger.error("Failed post download install: " + result);
td.setStatus(Status.UNRECOVERABLE_ERROR);
td.setDownloadError("Failed post download install: " + result);
((S3TemplateDownloader) td).cleanupAfterError();
} else {
td.setStatus(Status.POST_DOWNLOAD_FINISHED);
td.setDownloadError("Install completed successfully at " + new SimpleDateFormat().format(new Date()));
}
}
else {
// For other TemplateDownloaders where files are locally available,
// we run the postLocalDownload() method.
td.setDownloadError("Download success, starting install ");
String result = postLocalDownload(jobId);
if (result != null) {
s_logger.error("Failed post download script: " + result);
td.setStatus(Status.UNRECOVERABLE_ERROR);
td.setDownloadError("Failed post download script: " + result);
} else {
td.setStatus(Status.POST_DOWNLOAD_FINISHED);
td.setDownloadError("Install completed successfully at " + new SimpleDateFormat().format(new Date()));
}
}
dj.cleanup();
break;
default:
break;
}
}
private String computeCheckSum(File f) {
byte[] buffer = new byte[8192];
int read = 0;
MessageDigest digest;
String checksum = null;
InputStream is = null;
try {
digest = MessageDigest.getInstance("MD5");
is = new FileInputStream(f);
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
checksum = String.format("%032x", bigInt);
return checksum;
} catch (IOException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
return null;
}
}
}
/**
* Post remote download activity (install and cleanup). Executed in context of the downloader thread.
*/
private String postRemoteDownload(String jobId) {
String result = null;
DownloadJob dnld = jobs.get(jobId);
S3TemplateDownloader td = (S3TemplateDownloader)dnld.getTemplateDownloader();
if (td.getFileExtension().equalsIgnoreCase("QCOW2")) {
// The QCOW2 is the only format with a header,
// and as such can be easily read.
try {
InputStream inputStream = td.getS3ObjectInputStream();
dnld.setTemplatesize(QCOW2Utils.getVirtualSize(inputStream));
inputStream.close();
}
catch (IOException e) {
result = "Couldn't read QCOW2 virtual size. Error: " + e.getMessage();
}
}
else {
// For the other formats, both the virtual
// and actual file size are set the same.
dnld.setTemplatesize(td.getTotalBytes());
}
dnld.setTemplatePhysicalSize(td.getTotalBytes());
dnld.setTmpltPath(td.getDownloadLocalPath());
return result;
}
/**
* Post local download activity (install and cleanup). Executed in context of
* downloader thread
*
* @throws IOException
*/
private String postLocalDownload(String jobId) {
DownloadJob dnld = jobs.get(jobId);
TemplateDownloader td = dnld.getTemplateDownloader();
String resourcePath = dnld.getInstallPathPrefix(); // path with mount
// directory
String finalResourcePath = dnld.getTmpltPath(); // template download
// path on secondary
// storage
ResourceType resourceType = dnld.getResourceType();
File originalTemplate = new File(td.getDownloadLocalPath());
String checkSum = computeCheckSum(originalTemplate);
if (checkSum == null) {
s_logger.warn("Something wrong happened when try to calculate the checksum of downloaded template!");
}
dnld.setCheckSum(checkSum);
int imgSizeGigs = (int)Math.ceil(_storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
imgSizeGigs++; // add one just in case
long timeout = (long)imgSizeGigs * installTimeoutPerGig;
Script scr = null;
String script = resourceType == ResourceType.TEMPLATE ? createTmpltScr : createVolScr;
scr = new Script(script, timeout, s_logger);
scr.add("-s", Integer.toString(imgSizeGigs));
scr.add("-S", Long.toString(td.getMaxTemplateSizeInBytes()));
if (dnld.getDescription() != null && dnld.getDescription().length() > 1) {
scr.add("-d", dnld.getDescription());
}
if (dnld.isHvm()) {
scr.add("-h");
}
// add options common to ISO and template
String extension = dnld.getFormat().getFileExtension();
String templateName = "";
if (extension.equals("iso")) {
templateName = jobs.get(jobId).getTmpltName().trim().replace(" ", "_");
} else {
templateName = java.util.UUID.nameUUIDFromBytes((jobs.get(jobId).getTmpltName() + System.currentTimeMillis()).getBytes()).toString();
}
// run script to mv the temporary template file to the final template
// file
String templateFilename = templateName + "." + extension;
dnld.setTmpltPath(finalResourcePath + "/" + templateFilename);
scr.add("-n", templateFilename);
scr.add("-t", resourcePath);
scr.add("-f", td.getDownloadLocalPath()); // this is the temporary
// template file downloaded
if (dnld.getChecksum() != null && dnld.getChecksum().length() > 1) {
scr.add("-c", dnld.getChecksum());
}
scr.add("-u"); // cleanup
String result;
result = scr.execute();
if (result != null) {
return result;
}
// Set permissions for the downloaded template
File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
_storage.setWorldReadableAndWriteable(downloadedTemplate);
// Set permissions for template/volume.properties
String propertiesFile = resourcePath;
if (resourceType == ResourceType.TEMPLATE) {
propertiesFile += "/template.properties";
} else {
propertiesFile += "/volume.properties";
}
File templateProperties = new File(propertiesFile);
_storage.setWorldReadableAndWriteable(templateProperties);
TemplateLocation loc = new TemplateLocation(_storage, resourcePath);
try {
loc.create(dnld.getId(), true, dnld.getTmpltName());
} catch (IOException e) {
s_logger.warn("Something is wrong with template location " + resourcePath, e);
loc.purge();
return "Unable to download due to " + e.getMessage();
}
Iterator<Processor> en = _processors.values().iterator();
while (en.hasNext()) {
Processor processor = en.next();
FormatInfo info = null;
try {
info = processor.process(resourcePath, null, templateName);
} catch (InternalErrorException e) {
s_logger.error("Template process exception ", e);
return e.toString();
}
if (info != null) {
loc.addFormat(info);
dnld.setTemplatesize(info.virtualSize);
dnld.setTemplatePhysicalSize(info.size);
break;
}
}
if (!loc.save()) {
s_logger.warn("Cleaning up because we're unable to save the formats");
loc.purge();
}
return null;
}
@Override
public Status getDownloadStatus(String jobId) {
DownloadJob job = jobs.get(jobId);
if (job != null) {
TemplateDownloader td = job.getTemplateDownloader();
if (td != null) {
return td.getStatus();
}
}
return Status.UNKNOWN;
}
@Override
public String downloadS3Template(S3TO s3, long id, String url, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, String user, String password, long maxTemplateSizeInBytes, Proxy proxy, ResourceType resourceType) {
UUID uuid = UUID.randomUUID();
String jobId = uuid.toString();
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
TemplateDownloader td;
if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
td = new S3TemplateDownloader(s3, url, installPathPrefix, new Completion(jobId), maxTemplateSizeInBytes, user, password, proxy, resourceType);
} else {
throw new CloudRuntimeException("Scheme is not supported " + url);
}
} else {
throw new CloudRuntimeException("Unable to download from URL: " + url);
}
DownloadJob dj = new DownloadJob(td, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix, resourceType);
dj.setTmpltPath(installPathPrefix);
jobs.put(jobId, dj);
threadPool.execute(td);
return jobId;
}
@Override
public String downloadPublicTemplate(long id, String url, String name, ImageFormat format, boolean hvm, Long accountId, String descr, String cksum,
String installPathPrefix, String templatePath, String user, String password, long maxTemplateSizeInBytes, Proxy proxy, ResourceType resourceType) {
UUID uuid = UUID.randomUUID();
String jobId = uuid.toString();
String tmpDir = installPathPrefix;
try {
if (!_storage.mkdirs(tmpDir)) {
s_logger.warn("Unable to create " + tmpDir);
return "Unable to create " + tmpDir;
}
// TO DO - define constant for volume properties.
File file =
ResourceType.TEMPLATE == resourceType ? _storage.getFile(tmpDir + File.separator + TemplateLocation.Filename) : _storage.getFile(tmpDir + File.separator +
"volume.properties");
if (file.exists()) {
file.delete();
}
if (!file.createNewFile()) {
s_logger.warn("Unable to create new file: " + file.getAbsolutePath());
return "Unable to create new file: " + file.getAbsolutePath();
}
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
TemplateDownloader td;
if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) {
td = new HttpTemplateDownloader(_storage, url, tmpDir, new Completion(jobId), maxTemplateSizeInBytes, user, password, proxy, resourceType);
} else if (uri.getScheme().equalsIgnoreCase("file")) {
td = new LocalTemplateDownloader(_storage, url, tmpDir, maxTemplateSizeInBytes, new Completion(jobId));
} else if (uri.getScheme().equalsIgnoreCase("scp")) {
td = new ScpTemplateDownloader(_storage, url, tmpDir, maxTemplateSizeInBytes, new Completion(jobId));
} else if (uri.getScheme().equalsIgnoreCase("nfs") || uri.getScheme().equalsIgnoreCase("cifs")) {
td = null;
// TODO: implement this.
throw new CloudRuntimeException("Scheme is not supported " + url);
} else {
throw new CloudRuntimeException("Scheme is not supported " + url);
}
} else {
throw new CloudRuntimeException("Unable to download from URL: " + url);
}
// NOTE the difference between installPathPrefix and templatePath
// here. instalPathPrefix is the absolute path for template
// including mount directory
// on ssvm, while templatePath is the final relative path on
// secondary storage.
DownloadJob dj = new DownloadJob(td, jobId, id, name, format, hvm, accountId, descr, cksum, installPathPrefix, resourceType);
dj.setTmpltPath(templatePath);
jobs.put(jobId, dj);
threadPool.execute(td);
return jobId;
} catch (IOException e) {
s_logger.warn("Unable to download to " + tmpDir, e);
return null;
}
}
@Override
public String getDownloadError(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadError();
}
return null;
}
public long getDownloadTemplateSize(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplatesize();
}
return 0;
}
public String getDownloadCheckSum(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getChecksum();
}
return null;
}
public long getDownloadTemplatePhysicalSize(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplatePhysicalSize();
}
return 0;
}
// @Override
public String getDownloadLocalPath(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadLocalPath();
}
return null;
}
@Override
public int getDownloadPct(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTemplateDownloader().getDownloadPercent();
}
return 0;
}
public static VMTemplateHostVO.Status convertStatus(Status tds) {
switch (tds) {
case ABORTED:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case DOWNLOAD_FINISHED:
return VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS;
case IN_PROGRESS:
return VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS;
case NOT_STARTED:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case RECOVERABLE_ERROR:
return VMTemplateHostVO.Status.NOT_DOWNLOADED;
case UNKNOWN:
return VMTemplateHostVO.Status.UNKNOWN;
case UNRECOVERABLE_ERROR:
return VMTemplateHostVO.Status.DOWNLOAD_ERROR;
case POST_DOWNLOAD_FINISHED:
return VMTemplateHostVO.Status.DOWNLOADED;
default:
return VMTemplateHostVO.Status.UNKNOWN;
}
}
@Override
public com.cloud.storage.VMTemplateHostVO.Status getDownloadStatus2(String jobId) {
return convertStatus(getDownloadStatus(jobId));
}
@Override
public DownloadAnswer handleDownloadCommand(SecondaryStorageResource resource, DownloadCommand cmd) {
ResourceType resourceType = cmd.getResourceType();
if (cmd instanceof DownloadProgressCommand) {
return handleDownloadProgressCmd(resource, (DownloadProgressCommand)cmd);
}
if (cmd.getUrl() == null) {
return new DownloadAnswer(resourceType.toString() + " is corrupted on storage due to an invalid url , cannot download",
VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
if (cmd.getName() == null) {
return new DownloadAnswer("Invalid Name", VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
DataStoreTO dstore = cmd.getDataStore();
String installPathPrefix = cmd.getInstallPath();
// for NFS, we need to get mounted path
if (dstore instanceof NfsTO) {
installPathPrefix = resource.getRootDir(((NfsTO)dstore).getUrl()) + File.separator + installPathPrefix;
}
String user = null;
String password = null;
if (cmd.getAuth() != null) {
user = cmd.getAuth().getUserName();
password = cmd.getAuth().getPassword();
}
// TO DO - Define Volume max size as well
long maxDownloadSizeInBytes =
(cmd.getMaxDownloadSizeInBytes() == null) ? TemplateDownloader.DEFAULT_MAX_TEMPLATE_SIZE_IN_BYTES : (cmd.getMaxDownloadSizeInBytes());
String jobId = null;
if (dstore instanceof S3TO) {
jobId =
downloadS3Template((S3TO)dstore, cmd.getId(), cmd.getUrl(), cmd.getName(), cmd.getFormat(), cmd.isHvm(), cmd.getAccountId(), cmd.getDescription(),
cmd.getChecksum(), installPathPrefix, user, password, maxDownloadSizeInBytes, cmd.getProxy(), resourceType);
} else {
jobId =
downloadPublicTemplate(cmd.getId(), cmd.getUrl(), cmd.getName(), cmd.getFormat(), cmd.isHvm(), cmd.getAccountId(), cmd.getDescription(),
cmd.getChecksum(), installPathPrefix, cmd.getInstallPath(), user, password, maxDownloadSizeInBytes, cmd.getProxy(), resourceType);
}
sleep();
if (jobId == null) {
return new DownloadAnswer("Internal Error", VMTemplateStorageResourceAssoc.Status.DOWNLOAD_ERROR);
}
return new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId), getInstallPath(jobId),
getDownloadTemplateSize(jobId), getDownloadTemplateSize(jobId), getDownloadCheckSum(jobId));
}
private void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignore
}
}
private DownloadAnswer handleDownloadProgressCmd(SecondaryStorageResource resource, DownloadProgressCommand cmd) {
String jobId = cmd.getJobId();
DownloadAnswer answer;
DownloadJob dj = null;
if (jobId != null) {
dj = jobs.get(jobId);
}
if (dj == null) {
if (cmd.getRequest() == RequestType.GET_OR_RESTART) {
DownloadCommand dcmd = new DownloadCommand(cmd);
return handleDownloadCommand(resource, dcmd);
} else {
return new DownloadAnswer("Cannot find job", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.UNKNOWN);
}
}
TemplateDownloader td = dj.getTemplateDownloader();
switch (cmd.getRequest()) {
case GET_STATUS:
break;
case ABORT:
td.stopDownload();
sleep();
break;
case RESTART:
td.stopDownload();
sleep();
threadPool.execute(td);
break;
case PURGE:
td.stopDownload();
answer =
new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId),
getInstallPath(jobId), getDownloadTemplateSize(jobId), getDownloadTemplatePhysicalSize(jobId), getDownloadCheckSum(jobId));
jobs.remove(jobId);
return answer;
default:
break; // TODO
}
return new DownloadAnswer(jobId, getDownloadPct(jobId), getDownloadError(jobId), getDownloadStatus2(jobId), getDownloadLocalPath(jobId), getInstallPath(jobId),
getDownloadTemplateSize(jobId), getDownloadTemplatePhysicalSize(jobId), getDownloadCheckSum(jobId));
}
private String getInstallPath(String jobId) {
DownloadJob dj = jobs.get(jobId);
if (dj != null) {
return dj.getTmpltPath();
}
return null;
}
private List<String> listVolumes(String rootdir) {
List<String> result = new ArrayList<String>();
Script script = new Script(listVolScr, s_logger);
script.add("-r", rootdir);
ZfsPathParser zpp = new ZfsPathParser(rootdir);
script.execute(zpp);
result.addAll(zpp.getPaths());
s_logger.info("found " + zpp.getPaths().size() + " volumes" + zpp.getPaths());
return result;
}
private List<String> listTemplates(String rootdir) {
List<String> result = new ArrayList<String>();
Script script = new Script(listTmpltScr, s_logger);
script.add("-r", rootdir);
ZfsPathParser zpp = new ZfsPathParser(rootdir);
script.execute(zpp);
result.addAll(zpp.getPaths());
s_logger.info("found " + zpp.getPaths().size() + " templates" + zpp.getPaths());
return result;
}
@Override
public Map<String, TemplateProp> gatherTemplateInfo(String rootDir) {
Map<String, TemplateProp> result = new HashMap<String, TemplateProp>();
String templateDir = rootDir + File.separator + _templateDir;
if (!_storage.exists(templateDir)) {
_storage.mkdirs(templateDir);
}
List<String> publicTmplts = listTemplates(templateDir);
for (String tmplt : publicTmplts) {
String path = tmplt.substring(0, tmplt.lastIndexOf(File.separator));
TemplateLocation loc = new TemplateLocation(_storage, path);
try {
if (!loc.load()) {
s_logger.warn("Post download installation was not completed for " + path);
// loc.purge();
_storage.cleanup(path, templateDir);
continue;
}
} catch (IOException e) {
s_logger.warn("Unable to load template location " + path, e);
continue;
}
TemplateProp tInfo = loc.getTemplateInfo();
if ((tInfo.getSize() == tInfo.getPhysicalSize()) && (tInfo.getInstallPath().endsWith(ImageFormat.OVA.getFileExtension()))) {
try {
Processor processor = _processors.get("OVA Processor");
OVAProcessor vmdkProcessor = (OVAProcessor)processor;
long vSize = vmdkProcessor.getTemplateVirtualSize(path, tInfo.getInstallPath().substring(tInfo.getInstallPath().lastIndexOf(File.separator) + 1));
tInfo.setSize(vSize);
loc.updateVirtualSize(vSize);
loc.save();
} catch (Exception e) {
s_logger.error("Unable to get the virtual size of the template: " + tInfo.getInstallPath() + " due to " + e.getMessage());
}
}
result.put(tInfo.getTemplateName(), tInfo);
s_logger.debug("Added template name: " + tInfo.getTemplateName() + ", path: " + tmplt);
}
/*
for (String tmplt : isoTmplts) {
String tmp[];
tmp = tmplt.split("/");
String tmpltName = tmp[tmp.length - 2];
tmplt = tmplt.substring(tmplt.lastIndexOf("iso/"));
TemplateInfo tInfo = new TemplateInfo(tmpltName, tmplt, false);
s_logger.debug("Added iso template name: " + tmpltName + ", path: " + tmplt);
result.put(tmpltName, tInfo);
}
*/
return result;
}
@Override
public Map<Long, TemplateProp> gatherVolumeInfo(String rootDir) {
Map<Long, TemplateProp> result = new HashMap<Long, TemplateProp>();
String volumeDir = rootDir + File.separator + _volumeDir;
if (!_storage.exists(volumeDir)) {
_storage.mkdirs(volumeDir);
}
List<String> vols = listVolumes(volumeDir);
for (String vol : vols) {
String path = vol.substring(0, vol.lastIndexOf(File.separator));
TemplateLocation loc = new TemplateLocation(_storage, path);
try {
if (!loc.load()) {
s_logger.warn("Post download installation was not completed for " + path);
// loc.purge();
_storage.cleanup(path, volumeDir);
continue;
}
} catch (IOException e) {
s_logger.warn("Unable to load volume location " + path, e);
continue;
}
TemplateProp vInfo = loc.getTemplateInfo();
if ((vInfo.getSize() == vInfo.getPhysicalSize()) && (vInfo.getInstallPath().endsWith(ImageFormat.OVA.getFileExtension()))) {
try {
Processor processor = _processors.get("OVA Processor");
OVAProcessor vmdkProcessor = (OVAProcessor)processor;
long vSize = vmdkProcessor.getTemplateVirtualSize(path, vInfo.getInstallPath().substring(vInfo.getInstallPath().lastIndexOf(File.separator) + 1));
vInfo.setSize(vSize);
loc.updateVirtualSize(vSize);
loc.save();
} catch (Exception e) {
s_logger.error("Unable to get the virtual size of the volume: " + vInfo.getInstallPath() + " due to " + e.getMessage());
}
}
result.put(vInfo.getId(), vInfo);
s_logger.debug("Added volume name: " + vInfo.getTemplateName() + ", path: " + vol);
}
return result;
}
public static class ZfsPathParser extends OutputInterpreter {
String _parent;
List<String> paths = new ArrayList<String>();
public ZfsPathParser(String parent) {
_parent = parent;
}
@Override
public String interpret(BufferedReader reader) throws IOException {
String line = null;
while ((line = reader.readLine()) != null) {
paths.add(line);
}
return null;
}
public List<String> getPaths() {
return paths;
}
@Override
public boolean drain() {
return true;
}
}
public DownloadManagerImpl() {
}
@Override
@SuppressWarnings("unchecked")
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
String value = null;
_storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey);
if (_storage == null) {
value = (String)params.get(StorageLayer.ClassConfigKey);
if (value == null) {
throw new ConfigurationException("Unable to find the storage layer");
}
Class<StorageLayer> clazz;
try {
clazz = (Class<StorageLayer>)Class.forName(value);
_storage = clazz.newInstance();
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} catch (InstantiationException e) {
throw new ConfigurationException("Unable to instantiate " + value);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Unable to instantiate " + value);
}
}
String inSystemVM = (String)params.get("secondary.storage.vm");
if (inSystemVM != null && "true".equalsIgnoreCase(inSystemVM)) {
s_logger.info("DownloadManager: starting additional services since we are inside system vm");
startAdditionalServices();
blockOutgoingOnPrivate();
}
value = (String)params.get("install.timeout.pergig");
installTimeoutPerGig = NumbersUtil.parseInt(value, 15 * 60) * 1000;
value = (String)params.get("install.numthreads");
final int numInstallThreads = NumbersUtil.parseInt(value, 10);
String scriptsDir = (String)params.get("template.scripts.dir");
if (scriptsDir == null) {
scriptsDir = "scripts/storage/secondary";
}
listTmpltScr = Script.findScript(scriptsDir, "listvmtmplt.sh");
if (listTmpltScr == null) {
throw new ConfigurationException("Unable to find the listvmtmplt.sh");
}
s_logger.info("listvmtmplt.sh found in " + listTmpltScr);
createTmpltScr = Script.findScript(scriptsDir, "createtmplt.sh");
if (createTmpltScr == null) {
throw new ConfigurationException("Unable to find createtmplt.sh");
}
s_logger.info("createtmplt.sh found in " + createTmpltScr);
listVolScr = Script.findScript(scriptsDir, "listvolume.sh");
if (listVolScr == null) {
throw new ConfigurationException("Unable to find the listvolume.sh");
}
s_logger.info("listvolume.sh found in " + listVolScr);
createVolScr = Script.findScript(scriptsDir, "createvolume.sh");
if (createVolScr == null) {
throw new ConfigurationException("Unable to find createvolume.sh");
}
s_logger.info("createvolume.sh found in " + createVolScr);
_processors = new HashMap<String, Processor>();
Processor processor = new VhdProcessor();
processor.configure("VHD Processor", params);
_processors.put("VHD Processor", processor);
processor = new IsoProcessor();
processor.configure("ISO Processor", params);
_processors.put("ISO Processor", processor);
processor = new QCOW2Processor();
processor.configure("QCOW2 Processor", params);
_processors.put("QCOW2 Processor", processor);
processor = new OVAProcessor();
processor.configure("OVA Processor", params);
_processors.put("OVA Processor", processor);
processor = new VmdkProcessor();
processor.configure("VMDK Processor", params);
_processors.put("VMDK Processor", processor);
processor = new RawImageProcessor();
processor.configure("Raw Image Processor", params);
_processors.put("Raw Image Processor", processor);
processor = new TARProcessor();
processor.configure("TAR Processor", params);
_processors.put("TAR Processor", processor);
_templateDir = (String)params.get("public.templates.root.dir");
if (_templateDir == null) {
_templateDir = TemplateConstants.DEFAULT_TMPLT_ROOT_DIR;
}
_templateDir += File.separator + TemplateConstants.DEFAULT_TMPLT_FIRST_LEVEL_DIR;
_volumeDir = TemplateConstants.DEFAULT_VOLUME_ROOT_DIR + File.separator;
// Add more processors here.
threadPool = Executors.newFixedThreadPool(numInstallThreads);
return true;
}
private void blockOutgoingOnPrivate() {
Script command = new Script("/bin/bash", s_logger);
String intf = "eth1";
command.add("-c");
command.add("iptables -A OUTPUT -o " + intf + " -p tcp -m state --state NEW -m tcp --dport " + "80" + " -j REJECT;" + "iptables -A OUTPUT -o " + intf +
" -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j REJECT;");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in blocking outgoing to port 80/443 err=" + result);
return;
}
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
private void startAdditionalServices() {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 stop; else service httpd stop; fi ");
String result = command.execute();
if (result != null) {
s_logger.warn("Error in stopping httpd service err=" + result);
}
String port = Integer.toString(TemplateConstants.DEFAULT_TMPLT_COPY_PORT);
String intf = TemplateConstants.DEFAULT_TMPLT_COPY_INTF;
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("iptables -I INPUT -i " + intf + " -p tcp -m state --state NEW -m tcp --dport " + port + " -j ACCEPT;" + "iptables -I INPUT -i " + intf +
" -p tcp -m state --state NEW -m tcp --dport " + "443" + " -j ACCEPT;");
result = command.execute();
if (result != null) {
s_logger.warn("Error in opening up httpd port err=" + result);
return;
}
command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("if [ -d /etc/apache2 ] ; then service apache2 start; else service httpd start; fi ");
result = command.execute();
if (result != null) {
s_logger.warn("Error in starting httpd service err=" + result);
return;
}
command = new Script("mkdir", s_logger);
command.add("-p");
command.add("/var/www/html/copy/template");
result = command.execute();
if (result != null) {
s_logger.warn("Error in creating directory =" + result);
return;
}
}
}
|
Fixed Findbugs issue introduced by 1c6378ec0056e8c75990a4a0c15e99b2df162a75 PR #795.
|
services/secondary-storage/server/src/org/apache/cloudstack/storage/template/DownloadManagerImpl.java
|
Fixed Findbugs issue introduced by 1c6378ec0056e8c75990a4a0c15e99b2df162a75 PR #795.
|
|
Java
|
apache-2.0
|
5f816e8aab74859a4f8215d13e5ba551875a77be
| 0
|
apache/commons-beanutils,apache/commons-beanutils,apache/commons-beanutils
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils2.locale;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils2.BeanUtils;
import org.apache.commons.beanutils2.WeakFastHashMap;
import org.apache.commons.beanutils2.locale.converters.BigDecimalLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.BigIntegerLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.ByteLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.DoubleLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.FloatLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.IntegerLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.LongLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.ShortLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlDateLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlTimeLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlTimestampLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.StringLocaleConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p>Utility methods for converting locale-sensitive String scalar values to objects of the
* specified Class, String arrays to arrays of the specified Class and
* object to locale-sensitive String scalar value.</p>
*
* <p>This class provides the implementations used by the static utility methods in
* {@link LocaleConvertUtils}.</p>
*
* <p>The actual {@link LocaleConverter} instance to be used
* can be registered for each possible destination Class. Unless you override them, standard
* {@link LocaleConverter} instances are provided for all of the following
* destination Classes:</p>
* <ul>
* <li>java.lang.BigDecimal</li>
* <li>java.lang.BigInteger</li>
* <li>byte and java.lang.Byte</li>
* <li>double and java.lang.Double</li>
* <li>float and java.lang.Float</li>
* <li>int and java.lang.Integer</li>
* <li>long and java.lang.Long</li>
* <li>short and java.lang.Short</li>
* <li>java.lang.String</li>
* <li>java.sql.Date</li>
* <li>java.sql.Time</li>
* <li>java.sql.Timestamp</li>
* </ul>
*
* <p>For backwards compatibility, the standard locale converters
* for primitive types (and the corresponding wrapper classes).
*
* If you prefer to have another {@link LocaleConverter}
* thrown instead, replace the standard {@link LocaleConverter} instances
* with ones created with the one of the appropriate constructors.
*
* It's important that {@link LocaleConverter} should be registered for
* the specified locale and Class (or primitive type).
*
* @since 1.7
*/
public class LocaleConvertUtilsBean {
/**
* Gets singleton instance.
* This is the same as the instance used by the default {@link LocaleBeanUtilsBean} singleton.
* @return the singleton instance
*/
public static LocaleConvertUtilsBean getInstance() {
return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getLocaleConvertUtils();
}
/** The locale - default for conversion. */
private Locale defaultLocale = Locale.getDefault();
/** Indicate whether the pattern is localized or not */
private boolean applyLocalized;
/** The {@code Log} instance for this class. */
private final Log log = LogFactory.getLog(LocaleConvertUtilsBean.class);
/** Every entry of the mapConverters is:
* key = locale
* value = map of converters for the certain locale.
*/
private final DelegateFastHashMap mapConverters = new DelegateFastHashMap(BeanUtils.createCache());
/**
* Makes the state by default (deregisters all converters for all locales)
* and then registers default locale converters.
*/
public LocaleConvertUtilsBean() {
mapConverters.setFast(false);
deregister();
mapConverters.setFast(true);
}
/**
* getter for defaultLocale.
* @return the default locale
*/
public Locale getDefaultLocale() {
return defaultLocale;
}
/**
* setter for defaultLocale.
* @param locale the default locale
*/
public void setDefaultLocale(final Locale locale) {
if (locale == null) {
defaultLocale = Locale.getDefault();
}
else {
defaultLocale = locale;
}
}
/**
* getter for applyLocalized
*
* @return {@code true} if pattern is localized,
* otherwise {@code false}
*/
public boolean getApplyLocalized() {
return applyLocalized;
}
/**
* setter for applyLocalized
*
* @param newApplyLocalized {@code true} if pattern is localized,
* otherwise {@code false}
*/
public void setApplyLocalized(final boolean newApplyLocalized) {
applyLocalized = newApplyLocalized;
}
/**
* Convert the specified locale-sensitive value into a String.
*
* @param value The Value to be converted
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value) {
return convert(value, defaultLocale, null);
}
/**
* Convert the specified locale-sensitive value into a String
* using the conversion pattern.
*
* @param value The Value to be converted
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value, final String pattern) {
return convert(value, defaultLocale, pattern);
}
/**
* Convert the specified locale-sensitive value into a String
* using the particular conversion pattern.
*
* @param value The Value to be converted
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value, final Locale locale, final String pattern) {
final LocaleConverter converter = lookup(String.class, locale);
return converter.convert(String.class, value, pattern);
}
/**
* Convert the specified value to an object of the specified class (if
* possible). Otherwise, return a String representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz) {
return convert(value, clazz, defaultLocale, null);
}
/**
* Convert the specified value to an object of the specified class (if
* possible) using the conversion pattern. Otherwise, return a String
* representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz, final String pattern) {
return convert(value, clazz, defaultLocale, pattern);
}
/**
* Convert the specified value to an object of the specified class (if
* possible) using the conversion pattern. Otherwise, return a String
* representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz, final Locale locale, final String pattern) {
if (log.isDebugEnabled()) {
log.debug("Convert string " + value + " to class " +
clazz.getName() + " using " + locale +
" locale and " + pattern + " pattern");
}
Class<?> targetClass = clazz;
LocaleConverter converter = lookup(clazz, locale);
if (converter == null) {
converter = lookup(String.class, locale);
targetClass = String.class;
}
if (log.isTraceEnabled()) {
log.trace(" Using converter " + converter);
}
return converter.convert(targetClass, value, pattern);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) using the conversion pattern.
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz, final String pattern) {
return convert(values, clazz, getDefaultLocale(), pattern);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) .
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz) {
return convert(values, clazz, getDefaultLocale(), null);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) using the conversion pattern.
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz, final Locale locale, final String pattern) {
Class<?> type = clazz;
if (clazz.isArray()) {
type = clazz.getComponentType();
}
if (log.isDebugEnabled()) {
log.debug("Convert String[" + values.length + "] to class " +
type.getName() + "[] using " + locale +
" locale and " + pattern + " pattern");
}
final Object array = Array.newInstance(type, values.length);
for (int i = 0; i < values.length; i++) {
Array.set(array, i, convert(values[i], type, locale, pattern));
}
return array;
}
/**
* Register a custom {@link LocaleConverter} for the specified destination
* {@code Class}, replacing any previously registered converter.
*
* @param converter The LocaleConverter to be registered
* @param clazz The Destination class for conversions performed by this
* Converter
* @param locale The locale
*/
public void register(final LocaleConverter converter, final Class<?> clazz, final Locale locale) {
lookup(locale).put(clazz, converter);
}
/**
* Remove any registered {@link LocaleConverter}.
*/
public void deregister() {
final Map<Class<?>, LocaleConverter> defaultConverter = lookup(defaultLocale);
mapConverters.setFast(false);
mapConverters.clear();
mapConverters.put(defaultLocale, defaultConverter);
mapConverters.setFast(true);
}
/**
* Remove any registered {@link LocaleConverter} for the specified locale
*
* @param locale The locale
*/
public void deregister(final Locale locale) {
mapConverters.remove(locale);
}
/**
* Remove any registered {@link LocaleConverter} for the specified locale and Class.
*
* @param clazz Class for which to remove a registered Converter
* @param locale The locale
*/
public void deregister(final Class<?> clazz, final Locale locale) {
lookup(locale).remove(clazz);
}
/**
* Look up and return any registered {@link LocaleConverter} for the specified
* destination class and locale; if there is no registered Converter, return
* {@code null}.
*
* @param clazz Class for which to return a registered Converter
* @param locale The Locale
* @return The registered locale Converter, if any
*/
public LocaleConverter lookup(final Class<?> clazz, final Locale locale) {
final LocaleConverter converter = lookup(locale).get(clazz);
if (log.isTraceEnabled()) {
log.trace("LocaleConverter:" + converter);
}
return converter;
}
/**
* Look up and return any registered map instance for the specified locale;
* if there is no registered one, return {@code null}.
*
* @param locale The Locale
* @return The map instance contains the all {@link LocaleConverter} types for
* the specified locale.
*/
protected Map<Class<?>, LocaleConverter> lookup(final Locale locale) {
Map<Class<?>, LocaleConverter> localeConverters;
if (locale == null) {
localeConverters = (Map<Class<?>, LocaleConverter>) mapConverters.get(defaultLocale);
}
else {
localeConverters = (Map<Class<?>, LocaleConverter>) mapConverters.get(locale);
if (localeConverters == null) {
localeConverters = create(locale);
mapConverters.put(locale, localeConverters);
}
}
return localeConverters;
}
/**
* Create all {@link LocaleConverter} types for specified locale.
*
* @param locale The Locale
* @return The map instance contains the all {@link LocaleConverter} types
* for the specified locale.
*/
protected Map<Class<?>, LocaleConverter> create(final Locale locale) {
final DelegateFastHashMap converter = new DelegateFastHashMap(BeanUtils.createCache());
converter.setFast(false);
converter.put(BigDecimal.class, new BigDecimalLocaleConverter(locale, applyLocalized));
converter.put(BigInteger.class, new BigIntegerLocaleConverter(locale, applyLocalized));
converter.put(Byte.class, new ByteLocaleConverter(locale, applyLocalized));
converter.put(Byte.TYPE, new ByteLocaleConverter(locale, applyLocalized));
converter.put(Double.class, new DoubleLocaleConverter(locale, applyLocalized));
converter.put(Double.TYPE, new DoubleLocaleConverter(locale, applyLocalized));
converter.put(Float.class, new FloatLocaleConverter(locale, applyLocalized));
converter.put(Float.TYPE, new FloatLocaleConverter(locale, applyLocalized));
converter.put(Integer.class, new IntegerLocaleConverter(locale, applyLocalized));
converter.put(Integer.TYPE, new IntegerLocaleConverter(locale, applyLocalized));
converter.put(Long.class, new LongLocaleConverter(locale, applyLocalized));
converter.put(Long.TYPE, new LongLocaleConverter(locale, applyLocalized));
converter.put(Short.class, new ShortLocaleConverter(locale, applyLocalized));
converter.put(Short.TYPE, new ShortLocaleConverter(locale, applyLocalized));
converter.put(String.class, new StringLocaleConverter(locale, applyLocalized));
// conversion format patterns of java.sql.* types should correspond to default
// behavior of toString and valueOf methods of these classes
converter.put(java.sql.Date.class, new SqlDateLocaleConverter(locale, "yyyy-MM-dd"));
converter.put(java.sql.Time.class, new SqlTimeLocaleConverter(locale, "HH:mm:ss"));
converter.put( java.sql.Timestamp.class,
new SqlTimestampLocaleConverter(locale, "yyyy-MM-dd HH:mm:ss.S")
);
converter.setFast(true);
return converter;
}
private static class DelegateFastHashMap implements Map {
private final Map<Object, Object> map;
private DelegateFastHashMap(final Map<Object, Object> map) {
this.map = map;
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean containsKey(final Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(final Object value) {
return map.containsValue(value);
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
return map.entrySet();
}
@Override
public boolean equals(final Object o) {
return map.equals(o);
}
@Override
public Object get(final Object key) {
return map.get(key);
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Set<Object> keySet() {
return map.keySet();
}
@Override
public Object put(final Object key, final Object value) {
return map.put(key, value);
}
// we operate on very generic types (<Object, Object>), so there is
// no need for doing type checks
@Override
public void putAll(final Map m) {
map.putAll(m);
}
@Override
public Object remove(final Object key) {
return map.remove(key);
}
@Override
public int size() {
return map.size();
}
@Override
public Collection<Object> values() {
return map.values();
}
public void setFast(final boolean fast) {
if (map instanceof WeakFastHashMap) {
((WeakFastHashMap<?, ?>) map).setFast(fast);
}
}
}
}
|
src/main/java/org/apache/commons/beanutils2/locale/LocaleConvertUtilsBean.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils2.locale;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils2.BeanUtils;
import org.apache.commons.beanutils2.WeakFastHashMap;
import org.apache.commons.beanutils2.locale.converters.BigDecimalLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.BigIntegerLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.ByteLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.DoubleLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.FloatLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.IntegerLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.LongLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.ShortLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlDateLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlTimeLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.SqlTimestampLocaleConverter;
import org.apache.commons.beanutils2.locale.converters.StringLocaleConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p>Utility methods for converting locale-sensitive String scalar values to objects of the
* specified Class, String arrays to arrays of the specified Class and
* object to locale-sensitive String scalar value.</p>
*
* <p>This class provides the implementations used by the static utility methods in
* {@link LocaleConvertUtils}.</p>
*
* <p>The actual {@link LocaleConverter} instance to be used
* can be registered for each possible destination Class. Unless you override them, standard
* {@link LocaleConverter} instances are provided for all of the following
* destination Classes:</p>
* <ul>
* <li>java.lang.BigDecimal</li>
* <li>java.lang.BigInteger</li>
* <li>byte and java.lang.Byte</li>
* <li>double and java.lang.Double</li>
* <li>float and java.lang.Float</li>
* <li>int and java.lang.Integer</li>
* <li>long and java.lang.Long</li>
* <li>short and java.lang.Short</li>
* <li>java.lang.String</li>
* <li>java.sql.Date</li>
* <li>java.sql.Time</li>
* <li>java.sql.Timestamp</li>
* </ul>
*
* <p>For backwards compatibility, the standard locale converters
* for primitive types (and the corresponding wrapper classes).
*
* If you prefer to have another {@link LocaleConverter}
* thrown instead, replace the standard {@link LocaleConverter} instances
* with ones created with the one of the appropriate constructors.
*
* It's important that {@link LocaleConverter} should be registered for
* the specified locale and Class (or primitive type).
*
* @since 1.7
*/
public class LocaleConvertUtilsBean {
/**
* Gets singleton instance.
* This is the same as the instance used by the default {@link LocaleBeanUtilsBean} singleton.
* @return the singleton instance
*/
public static LocaleConvertUtilsBean getInstance() {
return LocaleBeanUtilsBean.getLocaleBeanUtilsInstance().getLocaleConvertUtils();
}
/** The locale - default for conversion. */
private Locale defaultLocale = Locale.getDefault();
/** Indicate whether the pattern is localized or not */
private boolean applyLocalized;
/** The {@code Log} instance for this class. */
private final Log log = LogFactory.getLog(LocaleConvertUtilsBean.class);
/** Every entry of the mapConverters is:
* key = locale
* value = map of converters for the certain locale.
*/
private final DelegateFastHashMap mapConverters = new DelegateFastHashMap(BeanUtils.createCache());
/**
* Makes the state by default (deregisters all converters for all locales)
* and then registers default locale converters.
*/
public LocaleConvertUtilsBean() {
mapConverters.setFast(false);
deregister();
mapConverters.setFast(true);
}
/**
* getter for defaultLocale.
* @return the default locale
*/
public Locale getDefaultLocale() {
return defaultLocale;
}
/**
* setter for defaultLocale.
* @param locale the default locale
*/
public void setDefaultLocale(final Locale locale) {
if (locale == null) {
defaultLocale = Locale.getDefault();
}
else {
defaultLocale = locale;
}
}
/**
* getter for applyLocalized
*
* @return {@code true} if pattern is localized,
* otherwise {@code false}
*/
public boolean getApplyLocalized() {
return applyLocalized;
}
/**
* setter for applyLocalized
*
* @param newApplyLocalized {@code true} if pattern is localized,
* otherwise {@code false}
*/
public void setApplyLocalized(final boolean newApplyLocalized) {
applyLocalized = newApplyLocalized;
}
/**
* Convert the specified locale-sensitive value into a String.
*
* @param value The Value to be converted
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value) {
return convert(value, defaultLocale, null);
}
/**
* Convert the specified locale-sensitive value into a String
* using the conversion pattern.
*
* @param value The Value to be converted
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value, final String pattern) {
return convert(value, defaultLocale, pattern);
}
/**
* Convert the specified locale-sensitive value into a String
* using the particular conversion pattern.
*
* @param value The Value to be converted
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public String convert(final Object value, final Locale locale, final String pattern) {
final LocaleConverter converter = lookup(String.class, locale);
return converter.convert(String.class, value, pattern);
}
/**
* Convert the specified value to an object of the specified class (if
* possible). Otherwise, return a String representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz) {
return convert(value, clazz, defaultLocale, null);
}
/**
* Convert the specified value to an object of the specified class (if
* possible) using the conversion pattern. Otherwise, return a String
* representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz, final String pattern) {
return convert(value, clazz, defaultLocale, pattern);
}
/**
* Convert the specified value to an object of the specified class (if
* possible) using the conversion pattern. Otherwise, return a String
* representation of the value.
*
* @param value The String scalar value to be converted
* @param clazz The Data type to which this value should be converted.
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String value, final Class<?> clazz, final Locale locale, final String pattern) {
if (log.isDebugEnabled()) {
log.debug("Convert string " + value + " to class " +
clazz.getName() + " using " + locale +
" locale and " + pattern + " pattern");
}
Class<?> targetClass = clazz;
LocaleConverter converter = lookup(clazz, locale);
if (converter == null) {
converter = lookup(String.class, locale);
targetClass = String.class;
}
if (log.isTraceEnabled()) {
log.trace(" Using converter " + converter);
}
return converter.convert(targetClass, value, pattern);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) using the conversion pattern.
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz, final String pattern) {
return convert(values, clazz, getDefaultLocale(), pattern);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) .
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz) {
return convert(values, clazz, getDefaultLocale(), null);
}
/**
* Convert an array of specified values to an array of objects of the
* specified class (if possible) using the conversion pattern.
*
* @param values Value to be converted (may be null)
* @param clazz Java array or element class to be converted to
* @param locale The locale
* @param pattern The conversion pattern
* @return the converted value
*
* @throws org.apache.commons.beanutils2.ConversionException if thrown by an
* underlying Converter
*/
public Object convert(final String[] values, final Class<?> clazz, final Locale locale, final String pattern) {
Class<?> type = clazz;
if (clazz.isArray()) {
type = clazz.getComponentType();
}
if (log.isDebugEnabled()) {
log.debug("Convert String[" + values.length + "] to class " +
type.getName() + "[] using " + locale +
" locale and " + pattern + " pattern");
}
final Object array = Array.newInstance(type, values.length);
for (int i = 0; i < values.length; i++) {
Array.set(array, i, convert(values[i], type, locale, pattern));
}
return array;
}
/**
* Register a custom {@link LocaleConverter} for the specified destination
* {@code Class}, replacing any previously registered converter.
*
* @param converter The LocaleConverter to be registered
* @param clazz The Destination class for conversions performed by this
* Converter
* @param locale The locale
*/
public void register(final LocaleConverter converter, final Class<?> clazz, final Locale locale) {
lookup(locale).put(clazz, converter);
}
/**
* Remove any registered {@link LocaleConverter}.
*/
public void deregister() {
final Map<Class<?>, LocaleConverter> defaultConverter = lookup(defaultLocale);
mapConverters.setFast(false);
mapConverters.clear();
mapConverters.put(defaultLocale, defaultConverter);
mapConverters.setFast(true);
}
/**
* Remove any registered {@link LocaleConverter} for the specified locale
*
* @param locale The locale
*/
public void deregister(final Locale locale) {
mapConverters.remove(locale);
}
/**
* Remove any registered {@link LocaleConverter} for the specified locale and Class.
*
* @param clazz Class for which to remove a registered Converter
* @param locale The locale
*/
public void deregister(final Class<?> clazz, final Locale locale) {
lookup(locale).remove(clazz);
}
/**
* Look up and return any registered {@link LocaleConverter} for the specified
* destination class and locale; if there is no registered Converter, return
* {@code null}.
*
* @param clazz Class for which to return a registered Converter
* @param locale The Locale
* @return The registered locale Converter, if any
*/
public LocaleConverter lookup(final Class<?> clazz, final Locale locale) {
final LocaleConverter converter = lookup(locale).get(clazz);
if (log.isTraceEnabled()) {
log.trace("LocaleConverter:" + converter);
}
return converter;
}
/**
* Look up and return any registered map instance for the specified locale;
* if there is no registered one, return {@code null}.
*
* @param locale The Locale
* @return The map instance contains the all {@link LocaleConverter} types for
* the specified locale.
*/
protected Map<Class<?>, LocaleConverter> lookup(final Locale locale) {
Map<Class<?>, LocaleConverter> localeConverters;
if (locale == null) {
localeConverters = (Map<Class<?>, LocaleConverter>) mapConverters.get(defaultLocale);
}
else {
localeConverters = (Map<Class<?>, LocaleConverter>) mapConverters.get(locale);
if (localeConverters == null) {
localeConverters = create(locale);
mapConverters.put(locale, localeConverters);
}
}
return localeConverters;
}
/**
* Create all {@link LocaleConverter} types for specified locale.
*
* @param locale The Locale
* @return The map instance contains the all {@link LocaleConverter} types
* for the specified locale.
*/
protected Map<Class<?>, LocaleConverter> create(final Locale locale) {
final DelegateFastHashMap converter = new DelegateFastHashMap(BeanUtils.createCache());
converter.setFast(false);
converter.put(BigDecimal.class, new BigDecimalLocaleConverter(locale, applyLocalized));
converter.put(BigInteger.class, new BigIntegerLocaleConverter(locale, applyLocalized));
converter.put(Byte.class, new ByteLocaleConverter(locale, applyLocalized));
converter.put(Byte.TYPE, new ByteLocaleConverter(locale, applyLocalized));
converter.put(Double.class, new DoubleLocaleConverter(locale, applyLocalized));
converter.put(Double.TYPE, new DoubleLocaleConverter(locale, applyLocalized));
converter.put(Float.class, new FloatLocaleConverter(locale, applyLocalized));
converter.put(Float.TYPE, new FloatLocaleConverter(locale, applyLocalized));
converter.put(Integer.class, new IntegerLocaleConverter(locale, applyLocalized));
converter.put(Integer.TYPE, new IntegerLocaleConverter(locale, applyLocalized));
converter.put(Long.class, new LongLocaleConverter(locale, applyLocalized));
converter.put(Long.TYPE, new LongLocaleConverter(locale, applyLocalized));
converter.put(Short.class, new ShortLocaleConverter(locale, applyLocalized));
converter.put(Short.TYPE, new ShortLocaleConverter(locale, applyLocalized));
converter.put(String.class, new StringLocaleConverter(locale, applyLocalized));
// conversion format patterns of java.sql.* types should correspond to default
// behavior of toString and valueOf methods of these classes
converter.put(java.sql.Date.class, new SqlDateLocaleConverter(locale, "yyyy-MM-dd"));
converter.put(java.sql.Time.class, new SqlTimeLocaleConverter(locale, "HH:mm:ss"));
converter.put( java.sql.Timestamp.class,
new SqlTimestampLocaleConverter(locale, "yyyy-MM-dd HH:mm:ss.S")
);
converter.setFast(true);
return converter;
}
private static class DelegateFastHashMap implements Map {
private final Map<Object, Object> map;
private DelegateFastHashMap(final Map<Object, Object> map) {
this.map = map;
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean containsKey(final Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(final Object value) {
return map.containsValue(value);
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
return map.entrySet();
}
@Override
public boolean equals(final Object o) {
return map.equals(o);
}
@Override
public Object get(final Object key) {
return map.get(key);
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Set<Object> keySet() {
return map.keySet();
}
@Override
public Object put(final Object key, final Object value) {
return map.put(key, value);
}
// we operate on very generic types (<Object, Object>), so there is
// no need for doing type checks
@Override
public void putAll(final Map m) {
map.putAll(m);
}
@Override
public Object remove(final Object key) {
return map.remove(key);
}
@Override
public int size() {
return map.size();
}
@Override
public Collection<Object> values() {
return map.values();
}
public void setFast(final boolean fast) {
if (map instanceof WeakFastHashMap) {
((WeakFastHashMap<?, ?>)map).setFast(fast);
}
}
}
}
|
Whitespace.
|
src/main/java/org/apache/commons/beanutils2/locale/LocaleConvertUtilsBean.java
|
Whitespace.
|
|
Java
|
apache-2.0
|
b0c0df78d2f975f97e6a76a0d84cc31e8ddd10b3
| 0
|
apache/groovy,paulk-asert/groovy,paulk-asert/groovy,apache/groovy,apache/groovy,paulk-asert/groovy,apache/incubator-groovy,apache/incubator-groovy,apache/incubator-groovy,apache/incubator-groovy,paulk-asert/groovy,apache/groovy
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.runtime.metaclass;
import groovy.lang.ExpandoMetaClass;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassRegistry;
import groovy.lang.MetaClassRegistryChangeEvent;
import groovy.lang.MetaClassRegistryChangeEventListener;
import groovy.lang.MetaMethod;
import org.apache.groovy.util.SystemUtil;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.reflection.CachedClass;
import org.codehaus.groovy.reflection.CachedMethod;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.reflection.GeneratedMetaMethod;
import org.codehaus.groovy.reflection.ReflectionCache;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
import org.codehaus.groovy.runtime.m12n.ExtensionModule;
import org.codehaus.groovy.runtime.m12n.ExtensionModuleRegistry;
import org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner;
import org.codehaus.groovy.util.FastArray;
import org.codehaus.groovy.util.ManagedConcurrentLinkedQueue;
import org.codehaus.groovy.util.ReferenceBundle;
import org.codehaus.groovy.vmplugin.VMPluginFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* A registry of MetaClass instances which caches introspection and
* reflection information and allows methods to be dynamically added to
* existing classes at runtime
*/
public class MetaClassRegistryImpl implements MetaClassRegistry{
/**
* @deprecated Use {@link ExtensionModuleScanner#MODULE_META_INF_FILE} instead
*/
@Deprecated
public static final String MODULE_META_INF_FILE = "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule";
private static final MetaClass[] EMPTY_METACLASS_ARRAY = new MetaClass[0];
private static final MetaClassRegistryChangeEventListener[] EMPTY_METACLASSREGISTRYCHANGEEVENTLISTENER_ARRAY = new MetaClassRegistryChangeEventListener[0];
public static final String EXTENSION_DISABLE_PROPERTY = "groovy.extension.disable";
private final boolean useAccessible;
private final FastArray instanceMethods = new FastArray();
private final FastArray staticMethods = new FastArray();
private final LinkedList<MetaClassRegistryChangeEventListener> changeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>();
private final LinkedList<MetaClassRegistryChangeEventListener> nonRemoveableChangeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>();
private final ManagedConcurrentLinkedQueue<MetaClass> metaClassInfo = new ManagedConcurrentLinkedQueue<MetaClass>(ReferenceBundle.getWeakBundle());
private final ExtensionModuleRegistry moduleRegistry = new ExtensionModuleRegistry();
private final String disabledString = SystemUtil.getSystemPropertySafe(EXTENSION_DISABLE_PROPERTY);
private final boolean disabling = disabledString != null;
private final Set<String> disabledNames = disabling ? new HashSet<>(Arrays.asList(disabledString.split(","))) : null;
public static final int LOAD_DEFAULT = 0;
public static final int DONT_LOAD_DEFAULT = 1;
private static MetaClassRegistry instanceInclude;
private static MetaClassRegistry instanceExclude;
public MetaClassRegistryImpl() {
this(LOAD_DEFAULT, true);
}
public MetaClassRegistryImpl(int loadDefault) {
this(loadDefault, true);
}
/**
* @param useAccessible defines whether or not the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)}
* method will be called to enable access to all methods when using reflection
*/
public MetaClassRegistryImpl(boolean useAccessible) {
this(LOAD_DEFAULT, useAccessible);
}
public MetaClassRegistryImpl(final int loadDefault, final boolean useAccessible) {
this.useAccessible = useAccessible;
if (loadDefault == LOAD_DEFAULT) {
final Map<CachedClass, List<MetaMethod>> map = new HashMap<CachedClass, List<MetaMethod>>();
// let's register the default methods
registerMethods(null, true, true, map);
final Class[] additionals = DefaultGroovyMethods.ADDITIONAL_CLASSES;
for (int i = 0; i != additionals.length; ++i) {
createMetaMethodFromClass(map, additionals[i]);
}
Class[] pluginDGMs = VMPluginFactory.getPlugin().getPluginDefaultGroovyMethods();
for (Class plugin : pluginDGMs) {
registerMethods(plugin, false, true, map);
}
registerMethods(DefaultGroovyStaticMethods.class, false, false, map);
Class[] staticPluginDGMs = VMPluginFactory.getPlugin().getPluginStaticGroovyMethods();
for (Class plugin : staticPluginDGMs) {
registerMethods(plugin, false, false, map);
}
ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), this.getClass().getClassLoader());
scanner.scanClasspathModules();
refreshMopMethods(map);
}
installMetaClassCreationHandle();
final MetaClass emcMetaClass = metaClassCreationHandle.create(ExpandoMetaClass.class, this);
emcMetaClass.initialize();
ClassInfo.getClassInfo(ExpandoMetaClass.class).setStrongMetaClass(emcMetaClass);
addNonRemovableMetaClassRegistryChangeEventListener(cmcu -> {
// The calls to DefaultMetaClassInfo.setPrimitiveMeta and sdyn.setBoolean need to be
// ordered. Even though metaClassInfo is thread-safe, it is included in the block
// so the meta classes are added to the queue in the same order.
synchronized (metaClassInfo) {
metaClassInfo.add(cmcu.getNewMetaClass());
DefaultMetaClassInfo.getNewConstantMetaClassVersioning();
Class c = cmcu.getClassToUpdate();
DefaultMetaClassInfo.setPrimitiveMeta(c, cmcu.getNewMetaClass()==null);
Field sdyn;
try {
sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL);
sdyn.setBoolean(null, cmcu.getNewMetaClass()!=null);
} catch (Throwable e) {
//DO NOTHING
}
}
});
}
private static void refreshMopMethods(final Map<CachedClass, List<MetaMethod>> map) {
for (Map.Entry<CachedClass, List<MetaMethod>> e : map.entrySet()) {
CachedClass cls = e.getKey();
cls.setNewMopMethods(e.getValue());
}
}
public void registerExtensionModuleFromProperties(final Properties properties, final ClassLoader classLoader, final Map<CachedClass, List<MetaMethod>> map) {
ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), classLoader);
scanner.scanExtensionModuleFromProperties(properties);
}
public ExtensionModuleRegistry getModuleRegistry() {
return moduleRegistry;
}
/**
* Looks for a class called 'groovy.runtime.metaclass.CustomMetaClassCreationHandle' and if it exists uses it as the MetaClassCreationHandle
* otherwise uses the default
*
* @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle
*/
private void installMetaClassCreationHandle() {
try {
final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle");
final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor();
this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance();
} catch (final ClassNotFoundException e) {
this.metaClassCreationHandle = new MetaClassCreationHandle();
} catch (final Exception e) {
throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e);
}
}
private void registerMethods(final Class theClass, final boolean useMethodWrapper, final boolean useInstanceMethods, Map<CachedClass, List<MetaMethod>> map) {
if (useMethodWrapper) {
// Here we instantiate objects representing MetaMethods for DGM methods.
// Calls for such meta methods done without reflection, so more effectively.
try {
List<GeneratedMetaMethod.DgmMethodRecord> records = GeneratedMetaMethod.DgmMethodRecord.loadDgmInfo();
for (GeneratedMetaMethod.DgmMethodRecord record : records) {
if (disabling && disabledNames.contains(record.methodName)) continue;
Class[] newParams = new Class[record.parameters.length - 1];
System.arraycopy(record.parameters, 1, newParams, 0, newParams.length);
MetaMethod method = new GeneratedMetaMethod.Proxy(
record.className,
record.methodName,
ReflectionCache.getCachedClass(record.parameters[0]),
record.returnType,
newParams
);
final CachedClass declClass = method.getDeclaringClass();
List<MetaMethod> arr = map.computeIfAbsent(declClass, k -> new ArrayList<MetaMethod>(4));
arr.add(method);
instanceMethods.add(method);
}
} catch (Throwable e) {
e.printStackTrace();
// we print the error, but we don't stop with an exception here
// since it is more comfortable this way for development
}
} else {
CachedMethod[] methods = ReflectionCache.getCachedClass(theClass).getMethods();
for (CachedMethod method : methods) {
final int mod = method.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && method.getAnnotation(Deprecated.class) == null) {
if (disabling && disabledNames.contains(method.getName())) continue;
CachedClass[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
List<MetaMethod> arr = map.computeIfAbsent(paramTypes[0], k -> new ArrayList<MetaMethod>(4));
if (useInstanceMethods) {
final NewInstanceMetaMethod metaMethod = new NewInstanceMetaMethod(method);
arr.add(metaMethod);
instanceMethods.add(metaMethod);
} else {
final NewStaticMetaMethod metaMethod = new NewStaticMetaMethod(method);
arr.add(metaMethod);
staticMethods.add(metaMethod);
}
}
}
}
}
}
private void createMetaMethodFromClass(Map<CachedClass, List<MetaMethod>> map, Class aClass) {
try {
MetaMethod method = (MetaMethod) aClass.getDeclaredConstructor().newInstance();
final CachedClass declClass = method.getDeclaringClass();
List<MetaMethod> arr = map.computeIfAbsent(declClass, k -> new ArrayList<MetaMethod>(4));
arr.add(method);
instanceMethods.add(method);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { /* ignore */
}
}
@Override
public final MetaClass getMetaClass(Class theClass) {
return ClassInfo.getClassInfo(theClass).getMetaClass();
}
public MetaClass getMetaClass(Object obj) {
return ClassInfo.getClassInfo(obj.getClass()).getMetaClass(obj);
}
/**
* if oldMc is null, newMc will replace whatever meta class was used before.
* if oldMc is not null, then newMc will be used only if the stored mc is
* the same as oldMc
*/
private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) {
final ClassInfo info = ClassInfo.getClassInfo(theClass);
MetaClass mc = null;
info.lock();
try {
mc = info.getStrongMetaClass();
info.setStrongMetaClass(newMc);
} finally {
info.unlock();
}
if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) {
fireConstantMetaClassUpdate(null, theClass, mc, newMc);
}
}
@Override
public void removeMetaClass(Class theClass) {
setMetaClass(theClass, null, null);
}
/**
* Registers a new MetaClass in the registry to customize the type
*
* @param theClass
* @param theMetaClass
*/
@Override
public void setMetaClass(Class theClass, MetaClass theMetaClass) {
setMetaClass(theClass,null,theMetaClass);
}
public void setMetaClass(Object obj, MetaClass theMetaClass) {
Class theClass = obj.getClass ();
final ClassInfo info = ClassInfo.getClassInfo(theClass);
MetaClass oldMC = null;
info.lock();
try {
oldMC = info.getPerInstanceMetaClass(obj);
info.setPerInstanceMetaClass(obj, theMetaClass);
}
finally {
info.unlock();
}
fireConstantMetaClassUpdate(obj, theClass, oldMC, theMetaClass);
}
public boolean useAccessible() {
return useAccessible;
}
private volatile MetaClassCreationHandle metaClassCreationHandle = new MetaClassCreationHandle();
/**
* Gets a handle internally used to create MetaClass implementations
* WARNING: experimental code, likely to change soon
* @return the handle
*/
@Override
public MetaClassCreationHandle getMetaClassCreationHandler() {
return metaClassCreationHandle;
}
/**
* Sets a handle internally used to create MetaClass implementations.
* When replacing the handle with a custom version, you should
* reuse the old handle to keep custom logic and to use the
* default logic as fall back.
* WARNING: experimental code, likely to change soon
* @param handle the handle
*/
@Override
public void setMetaClassCreationHandle(MetaClassCreationHandle handle) {
if(handle == null) throw new IllegalArgumentException("Cannot set MetaClassCreationHandle to null value!");
ClassInfo.clearModifiedExpandos();
handle.setDisableCustomMetaClassLookup(metaClassCreationHandle.isDisableCustomMetaClassLookup());
metaClassCreationHandle = handle;
}
/**
* Adds a listener for constant meta classes.
* @param listener the listener
*/
@Override
public void addMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
changeListenerList.add(listener);
}
}
/**
* Adds a listener for constant meta classes. This listener cannot be removed!
* @param listener the listener
*/
@Override
public void addNonRemovableMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
nonRemoveableChangeListenerList.add(listener);
}
}
/**
* Removes a constant meta class listener.
* @param listener the listener
*/
@Override
public void removeMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
changeListenerList.remove(listener);
}
}
/**
* Causes the execution of all registered listeners. This method is used mostly
* internal to kick of the listener notification. It can also be used by subclasses
* to achieve the same.
*
* @param obj object instance if the MetaClass change is on a per-instance metaclass (or null if global)
* @param c the class
* @param oldMC the old MetaClass
* @param newMc the new MetaClass
*/
protected void fireConstantMetaClassUpdate(Object obj, Class c, final MetaClass oldMC, MetaClass newMc) {
MetaClassRegistryChangeEventListener[] listener = getMetaClassRegistryChangeEventListeners();
MetaClassRegistryChangeEvent cmcu = new MetaClassRegistryChangeEvent(this, obj, c, oldMC, newMc);
for (MetaClassRegistryChangeEventListener metaClassRegistryChangeEventListener : listener) {
metaClassRegistryChangeEventListener.updateConstantMetaClass(cmcu);
}
}
/**
* Gets an array of all registered ConstantMetaClassListener instances.
*/
@Override
public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {
synchronized (changeListenerList) {
ArrayList<MetaClassRegistryChangeEventListener> ret =
new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());
ret.addAll(nonRemoveableChangeListenerList);
ret.addAll(changeListenerList);
return ret.toArray(EMPTY_METACLASSREGISTRYCHANGEEVENTLISTENER_ARRAY);
}
}
/**
* Singleton of MetaClassRegistry.
*
* @param includeExtension
* @return the registry
*/
public static synchronized MetaClassRegistry getInstance(int includeExtension) {
if (includeExtension != DONT_LOAD_DEFAULT) {
if (instanceInclude == null) {
instanceInclude = new MetaClassRegistryImpl();
}
return instanceInclude;
} else {
if (instanceExclude == null) {
instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT);
}
return instanceExclude;
}
}
public FastArray getInstanceMethods() {
return instanceMethods;
}
public FastArray getStaticMethods() {
return staticMethods;
}
/**
* Returns an iterator to iterate over all constant meta classes.
* This iterator can be seen as making a snapshot of the current state
* of the registry. The snapshot will include all meta classes that has
* been used unless they are already collected. Collected meta classes
* will be skipped automatically, so you can expect that each element
* of the iteration is not null. Calling this method is thread safe, the
* usage of the iterator is not.
*
* @return the iterator.
*/
@Override
public Iterator iterator() {
final MetaClass[] refs = metaClassInfo.toArray(EMPTY_METACLASS_ARRAY);
return new Iterator() {
// index in the ref array
private int index = 0;
// the current meta class
private MetaClass currentMeta;
// used to ensure that hasNext has been called
private boolean hasNextCalled = false;
// the cached hasNext call value
private boolean hasNext = false;
@Override
public boolean hasNext() {
if (hasNextCalled) return hasNext;
hasNextCalled = true;
if(index < refs.length) {
hasNext = true;
currentMeta = refs[index];
index++;
} else {
hasNext = false;
}
return hasNext;
}
private void ensureNext() {
// we ensure that hasNext has been called before
// next is called
hasNext();
hasNextCalled = false;
}
@Override
public Object next() {
ensureNext();
return currentMeta;
}
@Override
public void remove() {
ensureNext();
setMetaClass(currentMeta.getTheClass(), currentMeta, null);
currentMeta = null;
}
};
}
private class DefaultModuleListener implements ExtensionModuleScanner.ExtensionModuleListener {
private final Map<CachedClass, List<MetaMethod>> map;
public DefaultModuleListener(final Map<CachedClass, List<MetaMethod>> map) {
this.map = map;
}
@Override
public void onModule(final ExtensionModule module) {
if (moduleRegistry.hasModule(module.getName())) {
ExtensionModule loadedModule = moduleRegistry.getModule(module.getName());
if (loadedModule.getVersion().equals(module.getVersion())) {
// already registered
return;
} else {
throw new GroovyRuntimeException("Conflicting module versions. Module [" + module.getName() + " is loaded in version " +
loadedModule.getVersion() + " and you are trying to load version " + module.getVersion());
}
}
moduleRegistry.addModule(module);
// register MetaMethods
List<MetaMethod> metaMethods = module.getMetaMethods();
for (MetaMethod metaMethod : metaMethods) {
CachedClass cachedClass = metaMethod.getDeclaringClass();
List<MetaMethod> methods = map.computeIfAbsent(cachedClass, k -> new ArrayList<MetaMethod>(4));
methods.add(metaMethod);
if (metaMethod.isStatic()) {
staticMethods.add(metaMethod);
} else {
instanceMethods.add(metaMethod);
}
}
}
}
}
|
src/main/java/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.runtime.metaclass;
import groovy.lang.ExpandoMetaClass;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassRegistry;
import groovy.lang.MetaClassRegistryChangeEvent;
import groovy.lang.MetaClassRegistryChangeEventListener;
import groovy.lang.MetaMethod;
import org.apache.groovy.util.SystemUtil;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.reflection.CachedClass;
import org.codehaus.groovy.reflection.CachedMethod;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.reflection.GeneratedMetaMethod;
import org.codehaus.groovy.reflection.ReflectionCache;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
import org.codehaus.groovy.runtime.m12n.ExtensionModule;
import org.codehaus.groovy.runtime.m12n.ExtensionModuleRegistry;
import org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner;
import org.codehaus.groovy.util.FastArray;
import org.codehaus.groovy.util.ManagedConcurrentLinkedQueue;
import org.codehaus.groovy.util.ReferenceBundle;
import org.codehaus.groovy.vmplugin.VMPluginFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* A registry of MetaClass instances which caches introspection and
* reflection information and allows methods to be dynamically added to
* existing classes at runtime
*/
public class MetaClassRegistryImpl implements MetaClassRegistry{
/**
* @deprecated Use {@link ExtensionModuleScanner#MODULE_META_INF_FILE} instead
*/
@Deprecated
public static final String MODULE_META_INF_FILE = "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule";
private static final MetaClass[] EMPTY_METACLASS_ARRAY = new MetaClass[0];
private static final MetaClassRegistryChangeEventListener[] EMPTY_METACLASSREGISTRYCHANGEEVENTLISTENER_ARRAY = new MetaClassRegistryChangeEventListener[0];
public static final String EXTENSION_DISABLE_PROPERTY = "groovy.extension.disable";
private final boolean useAccessible;
private final FastArray instanceMethods = new FastArray();
private final FastArray staticMethods = new FastArray();
private final LinkedList<MetaClassRegistryChangeEventListener> changeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>();
private final LinkedList<MetaClassRegistryChangeEventListener> nonRemoveableChangeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>();
private final ManagedConcurrentLinkedQueue<MetaClass> metaClassInfo = new ManagedConcurrentLinkedQueue<MetaClass>(ReferenceBundle.getWeakBundle());
private final ExtensionModuleRegistry moduleRegistry = new ExtensionModuleRegistry();
private final String disabledString = SystemUtil.getSystemPropertySafe(EXTENSION_DISABLE_PROPERTY);
private final boolean disabling = disabledString != null;
private final Set<String> disabledNames = disabling ? new HashSet<>(Arrays.asList(disabledString.split(","))) : null;
public static final int LOAD_DEFAULT = 0;
public static final int DONT_LOAD_DEFAULT = 1;
private static MetaClassRegistry instanceInclude;
private static MetaClassRegistry instanceExclude;
public MetaClassRegistryImpl() {
this(LOAD_DEFAULT, true);
}
public MetaClassRegistryImpl(int loadDefault) {
this(loadDefault, true);
}
/**
* @param useAccessible defines whether or not the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)}
* method will be called to enable access to all methods when using reflection
*/
public MetaClassRegistryImpl(boolean useAccessible) {
this(LOAD_DEFAULT, useAccessible);
}
public MetaClassRegistryImpl(final int loadDefault, final boolean useAccessible) {
this.useAccessible = useAccessible;
if (loadDefault == LOAD_DEFAULT) {
final Map<CachedClass, List<MetaMethod>> map = new HashMap<CachedClass, List<MetaMethod>>();
// let's register the default methods
registerMethods(null, true, true, map);
final Class[] additionals = DefaultGroovyMethods.ADDITIONAL_CLASSES;
for (int i = 0; i != additionals.length; ++i) {
createMetaMethodFromClass(map, additionals[i]);
}
Class[] pluginDGMs = VMPluginFactory.getPlugin().getPluginDefaultGroovyMethods();
for (Class plugin : pluginDGMs) {
registerMethods(plugin, false, true, map);
}
registerMethods(DefaultGroovyStaticMethods.class, false, false, map);
Class[] staticPluginDGMs = VMPluginFactory.getPlugin().getPluginStaticGroovyMethods();
for (Class plugin : staticPluginDGMs) {
registerMethods(plugin, false, false, map);
}
ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), this.getClass().getClassLoader());
scanner.scanClasspathModules();
refreshMopMethods(map);
}
installMetaClassCreationHandle();
final MetaClass emcMetaClass = metaClassCreationHandle.create(ExpandoMetaClass.class, this);
emcMetaClass.initialize();
ClassInfo.getClassInfo(ExpandoMetaClass.class).setStrongMetaClass(emcMetaClass);
addNonRemovableMetaClassRegistryChangeEventListener(cmcu -> {
// The calls to DefaultMetaClassInfo.setPrimitiveMeta and sdyn.setBoolean need to be
// ordered. Even though metaClassInfo is thread-safe, it is included in the block
// so the meta classes are added to the queue in the same order.
synchronized (metaClassInfo) {
metaClassInfo.add(cmcu.getNewMetaClass());
DefaultMetaClassInfo.getNewConstantMetaClassVersioning();
Class c = cmcu.getClassToUpdate();
DefaultMetaClassInfo.setPrimitiveMeta(c, cmcu.getNewMetaClass()==null);
Field sdyn;
try {
sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL);
sdyn.setBoolean(null, cmcu.getNewMetaClass()!=null);
} catch (Throwable e) {
//DO NOTHING
}
}
});
}
private static void refreshMopMethods(final Map<CachedClass, List<MetaMethod>> map) {
for (Map.Entry<CachedClass, List<MetaMethod>> e : map.entrySet()) {
CachedClass cls = e.getKey();
cls.setNewMopMethods(e.getValue());
}
}
public void registerExtensionModuleFromProperties(final Properties properties, final ClassLoader classLoader, final Map<CachedClass, List<MetaMethod>> map) {
ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), classLoader);
scanner.scanExtensionModuleFromProperties(properties);
}
public ExtensionModuleRegistry getModuleRegistry() {
return moduleRegistry;
}
/**
* Looks for a class called 'groovy.runtime.metaclass.CustomMetaClassCreationHandle' and if it exists uses it as the MetaClassCreationHandle
* otherwise uses the default
*
* @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle
*/
private void installMetaClassCreationHandle() {
try {
final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle");
final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor();
this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance();
} catch (final ClassNotFoundException e) {
this.metaClassCreationHandle = new MetaClassCreationHandle();
} catch (final Exception e) {
throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e);
}
}
private void registerMethods(final Class theClass, final boolean useMethodWrapper, final boolean useInstanceMethods, Map<CachedClass, List<MetaMethod>> map) {
if (useMethodWrapper) {
// Here we instantiate objects representing MetaMethods for DGM methods.
// Calls for such meta methods done without reflection, so more effectively.
try {
List<GeneratedMetaMethod.DgmMethodRecord> records = GeneratedMetaMethod.DgmMethodRecord.loadDgmInfo();
for (GeneratedMetaMethod.DgmMethodRecord record : records) {
if (disabling && disabledNames.contains(record.methodName)) continue;
Class[] newParams = new Class[record.parameters.length - 1];
System.arraycopy(record.parameters, 1, newParams, 0, record.parameters.length-1);
MetaMethod method = new GeneratedMetaMethod.Proxy(
record.className,
record.methodName,
ReflectionCache.getCachedClass(record.parameters[0]),
record.returnType,
newParams
);
final CachedClass declClass = method.getDeclaringClass();
List<MetaMethod> arr = map.computeIfAbsent(declClass, k -> new ArrayList<MetaMethod>(4));
arr.add(method);
instanceMethods.add(method);
}
} catch (Throwable e) {
e.printStackTrace();
// we print the error, but we don't stop with an exception here
// since it is more comfortable this way for development
}
} else {
CachedMethod[] methods = ReflectionCache.getCachedClass(theClass).getMethods();
for (CachedMethod method : methods) {
final int mod = method.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && method.getAnnotation(Deprecated.class) == null) {
if (disabling && disabledNames.contains(method.getName())) continue;
CachedClass[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
List<MetaMethod> arr = map.computeIfAbsent(paramTypes[0], k -> new ArrayList<MetaMethod>(4));
if (useInstanceMethods) {
final NewInstanceMetaMethod metaMethod = new NewInstanceMetaMethod(method);
arr.add(metaMethod);
instanceMethods.add(metaMethod);
} else {
final NewStaticMetaMethod metaMethod = new NewStaticMetaMethod(method);
arr.add(metaMethod);
staticMethods.add(metaMethod);
}
}
}
}
}
}
private void createMetaMethodFromClass(Map<CachedClass, List<MetaMethod>> map, Class aClass) {
try {
MetaMethod method = (MetaMethod) aClass.getDeclaredConstructor().newInstance();
final CachedClass declClass = method.getDeclaringClass();
List<MetaMethod> arr = map.computeIfAbsent(declClass, k -> new ArrayList<MetaMethod>(4));
arr.add(method);
instanceMethods.add(method);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { /* ignore */
}
}
@Override
public final MetaClass getMetaClass(Class theClass) {
return ClassInfo.getClassInfo(theClass).getMetaClass();
}
public MetaClass getMetaClass(Object obj) {
return ClassInfo.getClassInfo(obj.getClass()).getMetaClass(obj);
}
/**
* if oldMc is null, newMc will replace whatever meta class was used before.
* if oldMc is not null, then newMc will be used only if the stored mc is
* the same as oldMc
*/
private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) {
final ClassInfo info = ClassInfo.getClassInfo(theClass);
MetaClass mc = null;
info.lock();
try {
mc = info.getStrongMetaClass();
info.setStrongMetaClass(newMc);
} finally {
info.unlock();
}
if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) {
fireConstantMetaClassUpdate(null, theClass, mc, newMc);
}
}
@Override
public void removeMetaClass(Class theClass) {
setMetaClass(theClass, null, null);
}
/**
* Registers a new MetaClass in the registry to customize the type
*
* @param theClass
* @param theMetaClass
*/
@Override
public void setMetaClass(Class theClass, MetaClass theMetaClass) {
setMetaClass(theClass,null,theMetaClass);
}
public void setMetaClass(Object obj, MetaClass theMetaClass) {
Class theClass = obj.getClass ();
final ClassInfo info = ClassInfo.getClassInfo(theClass);
MetaClass oldMC = null;
info.lock();
try {
oldMC = info.getPerInstanceMetaClass(obj);
info.setPerInstanceMetaClass(obj, theMetaClass);
}
finally {
info.unlock();
}
fireConstantMetaClassUpdate(obj, theClass, oldMC, theMetaClass);
}
public boolean useAccessible() {
return useAccessible;
}
private volatile MetaClassCreationHandle metaClassCreationHandle = new MetaClassCreationHandle();
/**
* Gets a handle internally used to create MetaClass implementations
* WARNING: experimental code, likely to change soon
* @return the handle
*/
@Override
public MetaClassCreationHandle getMetaClassCreationHandler() {
return metaClassCreationHandle;
}
/**
* Sets a handle internally used to create MetaClass implementations.
* When replacing the handle with a custom version, you should
* reuse the old handle to keep custom logic and to use the
* default logic as fall back.
* WARNING: experimental code, likely to change soon
* @param handle the handle
*/
@Override
public void setMetaClassCreationHandle(MetaClassCreationHandle handle) {
if(handle == null) throw new IllegalArgumentException("Cannot set MetaClassCreationHandle to null value!");
ClassInfo.clearModifiedExpandos();
handle.setDisableCustomMetaClassLookup(metaClassCreationHandle.isDisableCustomMetaClassLookup());
metaClassCreationHandle = handle;
}
/**
* Adds a listener for constant meta classes.
* @param listener the listener
*/
@Override
public void addMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
changeListenerList.add(listener);
}
}
/**
* Adds a listener for constant meta classes. This listener cannot be removed!
* @param listener the listener
*/
@Override
public void addNonRemovableMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
nonRemoveableChangeListenerList.add(listener);
}
}
/**
* Removes a constant meta class listener.
* @param listener the listener
*/
@Override
public void removeMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) {
synchronized (changeListenerList) {
changeListenerList.remove(listener);
}
}
/**
* Causes the execution of all registered listeners. This method is used mostly
* internal to kick of the listener notification. It can also be used by subclasses
* to achieve the same.
*
* @param obj object instance if the MetaClass change is on a per-instance metaclass (or null if global)
* @param c the class
* @param oldMC the old MetaClass
* @param newMc the new MetaClass
*/
protected void fireConstantMetaClassUpdate(Object obj, Class c, final MetaClass oldMC, MetaClass newMc) {
MetaClassRegistryChangeEventListener[] listener = getMetaClassRegistryChangeEventListeners();
MetaClassRegistryChangeEvent cmcu = new MetaClassRegistryChangeEvent(this, obj, c, oldMC, newMc);
for (MetaClassRegistryChangeEventListener metaClassRegistryChangeEventListener : listener) {
metaClassRegistryChangeEventListener.updateConstantMetaClass(cmcu);
}
}
/**
* Gets an array of all registered ConstantMetaClassListener instances.
*/
@Override
public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() {
synchronized (changeListenerList) {
ArrayList<MetaClassRegistryChangeEventListener> ret =
new ArrayList<MetaClassRegistryChangeEventListener>(changeListenerList.size()+nonRemoveableChangeListenerList.size());
ret.addAll(nonRemoveableChangeListenerList);
ret.addAll(changeListenerList);
return ret.toArray(EMPTY_METACLASSREGISTRYCHANGEEVENTLISTENER_ARRAY);
}
}
/**
* Singleton of MetaClassRegistry.
*
* @param includeExtension
* @return the registry
*/
public static synchronized MetaClassRegistry getInstance(int includeExtension) {
if (includeExtension != DONT_LOAD_DEFAULT) {
if (instanceInclude == null) {
instanceInclude = new MetaClassRegistryImpl();
}
return instanceInclude;
} else {
if (instanceExclude == null) {
instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT);
}
return instanceExclude;
}
}
public FastArray getInstanceMethods() {
return instanceMethods;
}
public FastArray getStaticMethods() {
return staticMethods;
}
/**
* Returns an iterator to iterate over all constant meta classes.
* This iterator can be seen as making a snapshot of the current state
* of the registry. The snapshot will include all meta classes that has
* been used unless they are already collected. Collected meta classes
* will be skipped automatically, so you can expect that each element
* of the iteration is not null. Calling this method is thread safe, the
* usage of the iterator is not.
*
* @return the iterator.
*/
@Override
public Iterator iterator() {
final MetaClass[] refs = metaClassInfo.toArray(EMPTY_METACLASS_ARRAY);
return new Iterator() {
// index in the ref array
private int index = 0;
// the current meta class
private MetaClass currentMeta;
// used to ensure that hasNext has been called
private boolean hasNextCalled = false;
// the cached hasNext call value
private boolean hasNext = false;
@Override
public boolean hasNext() {
if (hasNextCalled) return hasNext;
hasNextCalled = true;
if(index < refs.length) {
hasNext = true;
currentMeta = refs[index];
index++;
} else {
hasNext = false;
}
return hasNext;
}
private void ensureNext() {
// we ensure that hasNext has been called before
// next is called
hasNext();
hasNextCalled = false;
}
@Override
public Object next() {
ensureNext();
return currentMeta;
}
@Override
public void remove() {
ensureNext();
setMetaClass(currentMeta.getTheClass(), currentMeta, null);
currentMeta = null;
}
};
}
private class DefaultModuleListener implements ExtensionModuleScanner.ExtensionModuleListener {
private final Map<CachedClass, List<MetaMethod>> map;
public DefaultModuleListener(final Map<CachedClass, List<MetaMethod>> map) {
this.map = map;
}
@Override
public void onModule(final ExtensionModule module) {
if (moduleRegistry.hasModule(module.getName())) {
ExtensionModule loadedModule = moduleRegistry.getModule(module.getName());
if (loadedModule.getVersion().equals(module.getVersion())) {
// already registered
return;
} else {
throw new GroovyRuntimeException("Conflicting module versions. Module [" + module.getName() + " is loaded in version " +
loadedModule.getVersion() + " and you are trying to load version " + module.getVersion());
}
}
moduleRegistry.addModule(module);
// register MetaMethods
List<MetaMethod> metaMethods = module.getMetaMethods();
for (MetaMethod metaMethod : metaMethods) {
CachedClass cachedClass = metaMethod.getDeclaringClass();
List<MetaMethod> methods = map.computeIfAbsent(cachedClass, k -> new ArrayList<MetaMethod>(4));
methods.add(metaMethod);
if (metaMethod.isStatic()) {
staticMethods.add(metaMethod);
} else {
instanceMethods.add(metaMethod);
}
}
}
}
}
|
Trivial refactoring: remove duplicated code
|
src/main/java/org/codehaus/groovy/runtime/metaclass/MetaClassRegistryImpl.java
|
Trivial refactoring: remove duplicated code
|
|
Java
|
apache-2.0
|
d83910510077966d3ff26c0c8f98c7b8d12743cc
| 0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition;
import com.yahoo.document.ArrayDataType;
import com.yahoo.document.CollectionDataType;
import com.yahoo.document.DataType;
import com.yahoo.document.DocumentType;
import com.yahoo.document.Field;
import com.yahoo.document.MapDataType;
import com.yahoo.documentmodel.NewDocumentReferenceDataType;
import com.yahoo.document.StructDataType;
import com.yahoo.document.StructuredDataType;
import com.yahoo.document.TemporaryStructuredDataType;
import com.yahoo.document.WeightedSetDataType;
import com.yahoo.document.annotation.AnnotationReferenceDataType;
import com.yahoo.document.annotation.AnnotationType;
import com.yahoo.documentmodel.DataTypeCollection;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.documentmodel.VespaDocumentType;
import com.yahoo.searchdefinition.document.Attribute;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.document.SDField;
import com.yahoo.searchdefinition.document.TemporaryImportedFields;
import com.yahoo.searchdefinition.document.annotation.SDAnnotationType;
import com.yahoo.searchdefinition.document.annotation.TemporaryAnnotationReferenceDataType;
import com.yahoo.vespa.documentmodel.DocumentModel;
import com.yahoo.vespa.documentmodel.FieldView;
import com.yahoo.vespa.documentmodel.SearchDef;
import com.yahoo.vespa.documentmodel.SearchField;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author baldersheim
*/
public class DocumentModelBuilder {
private final DocumentModel model;
public DocumentModelBuilder() {
this.model = new DocumentModel();
this.model.getDocumentManager().add(VespaDocumentType.INSTANCE);
}
public DocumentModel build(Collection<Schema> schemaList) {
List<SDDocumentType> docList = new LinkedList<>();
for (Schema schema : schemaList) {
docList.add(schema.getDocument());
}
docList = sortDocumentTypes(docList);
addDocumentTypes(docList);
for (Collection<Schema> toAdd = tryAdd(schemaList);
! toAdd.isEmpty() && (toAdd.size() < schemaList.size());
toAdd = tryAdd(schemaList)) {
schemaList = toAdd;
}
return model;
}
private List<SDDocumentType> sortDocumentTypes(List<SDDocumentType> docList) {
Set<String> doneNames = new HashSet<>();
doneNames.add(SDDocumentType.VESPA_DOCUMENT.getName());
List<SDDocumentType> doneList = new LinkedList<>();
List<SDDocumentType> prevList = null;
List<SDDocumentType> nextList = docList;
while (prevList == null || nextList.size() < prevList.size()) {
prevList = nextList;
nextList = new LinkedList<>();
for (SDDocumentType doc : prevList) {
boolean isDone = true;
for (SDDocumentType inherited : doc.getInheritedTypes()) {
if (!doneNames.contains(inherited.getName())) {
isDone = false;
break;
}
}
if (isDone) {
doneNames.add(doc.getName());
doneList.add(doc);
} else {
nextList.add(doc);
}
}
}
if (!nextList.isEmpty()) {
throw new IllegalArgumentException("Could not resolve inheritance of document types " +
toString(prevList) + ".");
}
return doneList;
}
private static String toString(List<SDDocumentType> lst) {
StringBuilder out = new StringBuilder();
for (int i = 0, len = lst.size(); i < len; ++i) {
out.append("'").append(lst.get(i).getName()).append("'");
if (i < len - 2) {
out.append(", ");
} else if (i < len - 1) {
out.append(" and ");
}
}
return out.toString();
}
private Collection<Schema> tryAdd(Collection<Schema> schemaList) {
Collection<Schema> left = new ArrayList<>();
for (Schema schema : schemaList) {
try {
addToModel(schema);
} catch (RetryLaterException e) {
left.add(schema);
}
}
return left;
}
private void addToModel(Schema schema) {
// Then we add the search specific stuff
SearchDef searchDef = new SearchDef(schema.getName());
addSearchFields(schema.extraFieldList(), searchDef);
for (Field f : schema.getDocument().fieldSet()) {
addSearchField((SDField) f, searchDef);
}
for (SDField field : schema.allConcreteFields()) {
for (Attribute attribute : field.getAttributes().values()) {
if ( ! searchDef.getFields().containsKey(attribute.getName())) {
searchDef.add(new SearchField(new Field(attribute.getName(), field), !field.getIndices().isEmpty(), true));
}
}
}
for (Field f : schema.getDocument().fieldSet()) {
addAlias((SDField) f, searchDef);
}
model.getSearchManager().add(searchDef);
}
private static void addSearchFields(Collection<SDField> fields, SearchDef searchDef) {
for (SDField field : fields) {
addSearchField(field, searchDef);
}
}
private static void addSearchField(SDField field, SearchDef searchDef) {
SearchField searchField =
new SearchField(field,
field.getIndices().containsKey(field.getName()) && field.getIndices().get(field.getName()).getType().equals(Index.Type.VESPA),
field.getAttributes().containsKey(field.getName()));
searchDef.add(searchField);
// Add field to views
addToView(field.getIndices().keySet(), searchField, searchDef);
}
private static void addAlias(SDField field, SearchDef searchDef) {
for (Map.Entry<String, String> entry : field.getAliasToName().entrySet()) {
searchDef.addAlias(entry.getKey(), entry.getValue());
}
}
private static void addToView(Collection<String> views, Field field, SearchDef searchDef) {
for (String viewName : views) {
addToView(viewName, field, searchDef);
}
}
private static void addToView(String viewName, Field field, SearchDef searchDef) {
if (searchDef.getViews().containsKey(viewName)) {
searchDef.getViews().get(viewName).add(field);
} else {
if (!searchDef.getFields().containsKey(viewName)) {
FieldView view = new FieldView(viewName);
view.add(field);
searchDef.add(view);
}
}
}
private static String descT(DataType type) {
if (type == null) { return "<null>"; }
return "'" + type.getName() + "' [" + type.getId() + "] {"+type.getClass() + "}";
}
private void addDocumentTypes(List<SDDocumentType> docList) {
LinkedList<NewDocumentType> lst = new LinkedList<>();
for (SDDocumentType doc : docList) {
lst.add(convert(doc));
model.getDocumentManager().add(lst.getLast());
}
Map<DataType, DataType> replacements = new IdentityHashMap<>();
for(NewDocumentType doc : lst) {
resolveTemporaries(doc.getAllTypes(), lst, replacements);
}
for(NewDocumentType doc : lst) {
for (var entry : replacements.entrySet()) {
var old = entry.getKey();
if (doc.getDataType(old.getId()) == old) {
doc.replace(entry.getValue());
}
}
}
}
private static void resolveTemporaries(DataTypeCollection dtc,
Collection<NewDocumentType> docs,
Map<DataType, DataType> replacements) {
for (DataType type : dtc.getTypes()) {
resolveTemporariesRecurse(type, dtc, docs, replacements);
}
}
@SuppressWarnings("deprecation")
private static DataType resolveTemporariesRecurse(DataType type, DataTypeCollection repo,
Collection<NewDocumentType> docs,
Map<DataType, DataType> replacements) {
if (replacements.containsKey(type)) {
return replacements.get(type);
}
DataType original = type;
if (type instanceof TemporaryStructuredDataType) {
DataType other = repo.getDataType(type.getId());
if (other == null || other == type) {
other = getDocumentType(docs, type.getId());
}
if (other != null) {
type = other;
}
} else if (type instanceof DocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
} else if (! type.getName().equals("document")) {
throw new IllegalArgumentException
("Can not handle nested document definitions. Undefined document type: " + type.toString());
}
} else if (type instanceof NewDocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
}
} else if (type instanceof StructDataType) {
// trick avoids infinite recursion:
var old = replacements.put(original, type);
assert(old == null);
StructDataType dt = (StructDataType) type;
for (com.yahoo.document.Field field : dt.getFields()) {
var ft = field.getDataType();
var newft = resolveTemporariesRecurse(ft, repo, docs, replacements);
if (ft != newft) {
// XXX deprecated:
field.setDataType(newft);
}
}
old = replacements.remove(original);
assert(old == type);
}
else if (type instanceof MapDataType) {
MapDataType t = (MapDataType) type;
var old_kt = t.getKeyType();
var old_vt = t.getValueType();
var kt = resolveTemporariesRecurse(old_kt, repo, docs, replacements);
var vt = resolveTemporariesRecurse(old_vt, repo, docs, replacements);
if (kt != old_kt || vt != old_vt) {
type = new MapDataType(kt, vt, t.getId());
}
}
else if (type instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) type;
var old_nt = t.getNestedType();
var nt = resolveTemporariesRecurse(old_nt, repo, docs, replacements);
if (nt != old_nt) {
type = new ArrayDataType(nt, t.getId());
}
}
else if (type instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) type;
var old_nt = t.getNestedType();
var nt = resolveTemporariesRecurse(old_nt, repo, docs, replacements);
if (nt != old_nt) {
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
type = new WeightedSetDataType(nt, c, r, t.getId());
}
}
else if (type instanceof NewDocumentReferenceDataType) {
var t = (NewDocumentReferenceDataType) type;
var doc = getDocumentType(docs, t.getTargetTypeId());
type = doc.getReferenceDataType();
}
if (type != original) {
replacements.put(original, type);
}
return type;
}
private static NewDocumentType getDocumentType(Collection<NewDocumentType> docs, int id) {
for (NewDocumentType doc : docs) {
if (doc.getId() == id) {
return doc;
}
}
return null;
}
private static boolean anyParentsHavePayLoad(SDAnnotationType sa, SDDocumentType sdoc) {
if (sa.getInherits() != null) {
AnnotationType tmp = sdoc.findAnnotation(sa.getInherits());
SDAnnotationType inherited = (SDAnnotationType) tmp;
return ((inherited.getSdDocType() != null) || anyParentsHavePayLoad(inherited, sdoc));
}
return false;
}
private NewDocumentType convert(SDDocumentType sdoc) {
NewDocumentType dt = new NewDocumentType(new NewDocumentType.Name(sdoc.getName()),
sdoc.getDocumentType().contentStruct(),
sdoc.getFieldSets(),
convertDocumentReferencesToNames(sdoc.getDocumentReferences()),
convertTemporaryImportedFieldsToNames(sdoc.getTemporaryImportedFields()));
for (SDDocumentType n : sdoc.getInheritedTypes()) {
NewDocumentType.Name name = new NewDocumentType.Name(n.getName());
NewDocumentType inherited = model.getDocumentManager().getDocumentType(name);
if (inherited != null) {
dt.inherit(inherited);
}
}
var extractor = new TypeExtractor(dt);
extractor.extract(sdoc);
return dt;
}
static class TypeExtractor {
private final NewDocumentType targetDt;
Map<AnnotationType, String> annotationInheritance = new LinkedHashMap<>();
Map<StructDataType, String> structInheritance = new LinkedHashMap<>();
private final Map<Object, Object> inProgress = new IdentityHashMap<>();
TypeExtractor(NewDocumentType target) {
this.targetDt = target;
}
void extract(SDDocumentType sdoc) {
for (SDDocumentType type : sdoc.getTypes()) {
if (type.isStruct()) {
handleStruct(type);
} else {
throw new IllegalArgumentException("Data type '" + type.getName() + "' is not a struct => tostring='" + type.toString() + "'.");
}
}
for (SDDocumentType type : sdoc.getTypes()) {
for (SDDocumentType proxy : type.getInheritedTypes()) {
var inherited = (StructDataType) targetDt.getDataTypeRecursive(proxy.getName());
var converted = (StructDataType) targetDt.getDataType(type.getName());
if (! converted.inherits(inherited)) {
converted.inherit(inherited);
}
}
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
targetDt.add(annotation);
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
SDAnnotationType sa = (SDAnnotationType) annotation;
if (annotation.getInheritedTypes().isEmpty() && (sa.getInherits() != null) ) {
annotationInheritance.put(annotation, sa.getInherits());
}
if (annotation.getDataType() == null) {
if (sa.getSdDocType() != null) {
StructDataType s = handleStruct(sa.getSdDocType());
annotation.setDataType(s);
if ((sa.getInherits() != null)) {
structInheritance.put(s, "annotation."+sa.getInherits());
}
} else if (sa.getInherits() != null) {
StructDataType s = new StructDataType("annotation."+annotation.getName());
if (anyParentsHavePayLoad(sa, sdoc)) {
annotation.setDataType(s);
addType(s);
}
structInheritance.put(s, "annotation."+sa.getInherits());
}
} else {
var dt = annotation.getDataType();
if (dt instanceof StructDataType) {
handleStruct((StructDataType) dt);
}
}
}
for (Map.Entry<AnnotationType, String> e : annotationInheritance.entrySet()) {
e.getKey().inherit(targetDt.getAnnotationType(e.getValue()));
}
for (Map.Entry<StructDataType, String> e : structInheritance.entrySet()) {
StructDataType s = (StructDataType)targetDt.getDataType(e.getValue());
if (s != null) {
e.getKey().inherit(s);
}
}
handleStruct(sdoc.getDocumentType().contentStruct());
extractDataTypesFromFields(sdoc.fieldSet());
}
private void extractDataTypesFromFields(Collection<Field> fields) {
for (Field f : fields) {
DataType type = f.getDataType();
if (testAddType(type)) {
extractNestedTypes(type);
addType(type);
}
}
}
private void extractNestedTypes(DataType type) {
if (inProgress.containsKey(type)) {
return;
}
inProgress.put(type, this);
if (type instanceof StructDataType) {
StructDataType tmp = (StructDataType) type;
extractDataTypesFromFields(tmp.getFieldsThisTypeOnly());
} else if (type instanceof CollectionDataType) {
CollectionDataType tmp = (CollectionDataType) type;
extractNestedTypes(tmp.getNestedType());
addType(tmp.getNestedType());
} else if (type instanceof MapDataType) {
MapDataType tmp = (MapDataType) type;
extractNestedTypes(tmp.getKeyType());
extractNestedTypes(tmp.getValueType());
addType(tmp.getKeyType());
addType(tmp.getValueType());
} else if (type instanceof TemporaryAnnotationReferenceDataType) {
throw new IllegalArgumentException(type.toString());
}
}
private boolean testAddType(DataType type) { return internalAddType(type, true); }
private boolean addType(DataType type) { return internalAddType(type, false); }
private boolean internalAddType(DataType type, boolean dryRun) {
DataType oldType = targetDt.getDataTypeRecursive(type.getId());
if (oldType == null) {
if ( ! dryRun) {
targetDt.add(type);
}
return true;
} else if ((type instanceof StructDataType) && (oldType instanceof StructDataType)) {
StructDataType s = (StructDataType) type;
StructDataType os = (StructDataType) oldType;
if ((os.getFieldCount() == 0) && (s.getFieldCount() > os.getFieldCount())) {
if ( ! dryRun) {
targetDt.replace(type);
}
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
private void specialHandleAnnotationReference(Field field) {
DataType fieldType = specialHandleAnnotationReferenceRecurse(field.getName(), field.getDataType());
if (fieldType == null) {
return;
}
field.setDataType(fieldType); // XXX deprecated
}
private DataType specialHandleAnnotationReferenceRecurse(String fieldName,
DataType dataType) {
if (dataType instanceof TemporaryAnnotationReferenceDataType) {
TemporaryAnnotationReferenceDataType refType = (TemporaryAnnotationReferenceDataType)dataType;
if (refType.getId() != 0) {
return null;
}
AnnotationType target = targetDt.getAnnotationType(refType.getTarget());
if (target == null) {
throw new RetryLaterException("Annotation '" + refType.getTarget() + "' in reference '" + fieldName +
"' does not exist.");
}
dataType = new AnnotationReferenceDataType(target);
addType(dataType);
return dataType;
}
else if (dataType instanceof MapDataType) {
MapDataType t = (MapDataType)dataType;
DataType valueType = specialHandleAnnotationReferenceRecurse(fieldName, t.getValueType());
if (valueType == null) {
return null;
}
var mapType = new MapDataType(t.getKeyType(), valueType, t.getId());
addType(mapType);
return mapType;
}
else if (dataType instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
var lstType = new ArrayDataType(nestedType, t.getId());
addType(lstType);
return lstType;
}
else if (dataType instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
var lstType = new WeightedSetDataType(nestedType, c, r, t.getId());
addType(lstType);
return lstType;
}
return null;
}
@SuppressWarnings("deprecation")
private StructDataType handleStruct(SDDocumentType type) {
if (type.isStruct()) {
var st = type.getStruct();
if (st.getName().equals(type.getName()) &&
(st instanceof StructDataType) &&
! (st instanceof TemporaryStructuredDataType))
{
return handleStruct((StructDataType) st);
}
}
StructDataType s = new StructDataType(type.getName());
for (Field f : type.getDocumentType().contentStruct().getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
s.addField(f);
}
for (StructDataType inherited : type.getDocumentType().contentStruct().getInheritedTypes()) {
s.inherit(inherited);
}
extractNestedTypes(s);
addType(s);
return s;
}
private StructDataType handleStruct(StructDataType s) {
for (Field f : s.getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
}
extractNestedTypes(s);
addType(s);
return s;
}
}
private static Set<NewDocumentType.Name> convertDocumentReferencesToNames(Optional<DocumentReferences> documentReferences) {
if (!documentReferences.isPresent()) {
return Set.of();
}
return documentReferences.get().referenceMap().values().stream()
.map(documentReference -> documentReference.targetSearch().getDocument())
.map(documentType -> new NewDocumentType.Name(documentType.getName()))
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
}
private static Set<String> convertTemporaryImportedFieldsToNames(TemporaryImportedFields importedFields) {
if (importedFields == null) {
return Set.of();
}
return Collections.unmodifiableSet(importedFields.fields().keySet());
}
public static class RetryLaterException extends IllegalArgumentException {
public RetryLaterException(String message) {
super(message);
}
}
}
|
config-model/src/main/java/com/yahoo/searchdefinition/DocumentModelBuilder.java
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition;
import com.yahoo.document.ArrayDataType;
import com.yahoo.document.CollectionDataType;
import com.yahoo.document.DataType;
import com.yahoo.document.DocumentType;
import com.yahoo.document.Field;
import com.yahoo.document.MapDataType;
import com.yahoo.documentmodel.NewDocumentReferenceDataType;
import com.yahoo.document.StructDataType;
import com.yahoo.document.StructuredDataType;
import com.yahoo.document.TemporaryStructuredDataType;
import com.yahoo.document.WeightedSetDataType;
import com.yahoo.document.annotation.AnnotationReferenceDataType;
import com.yahoo.document.annotation.AnnotationType;
import com.yahoo.documentmodel.DataTypeCollection;
import com.yahoo.documentmodel.NewDocumentType;
import com.yahoo.documentmodel.VespaDocumentType;
import com.yahoo.searchdefinition.document.Attribute;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.document.SDField;
import com.yahoo.searchdefinition.document.TemporaryImportedFields;
import com.yahoo.searchdefinition.document.annotation.SDAnnotationType;
import com.yahoo.searchdefinition.document.annotation.TemporaryAnnotationReferenceDataType;
import com.yahoo.vespa.documentmodel.DocumentModel;
import com.yahoo.vespa.documentmodel.FieldView;
import com.yahoo.vespa.documentmodel.SearchDef;
import com.yahoo.vespa.documentmodel.SearchField;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author baldersheim
*/
public class DocumentModelBuilder {
private final DocumentModel model;
public DocumentModelBuilder() {
this.model = new DocumentModel();
this.model.getDocumentManager().add(VespaDocumentType.INSTANCE);
}
public DocumentModel build(Collection<Schema> schemaList) {
List<SDDocumentType> docList = new LinkedList<>();
for (Schema schema : schemaList) {
docList.add(schema.getDocument());
}
docList = sortDocumentTypes(docList);
addDocumentTypes(docList);
for (Collection<Schema> toAdd = tryAdd(schemaList);
! toAdd.isEmpty() && (toAdd.size() < schemaList.size());
toAdd = tryAdd(schemaList)) {
schemaList = toAdd;
}
return model;
}
private List<SDDocumentType> sortDocumentTypes(List<SDDocumentType> docList) {
Set<String> doneNames = new HashSet<>();
doneNames.add(SDDocumentType.VESPA_DOCUMENT.getName());
List<SDDocumentType> doneList = new LinkedList<>();
List<SDDocumentType> prevList = null;
List<SDDocumentType> nextList = docList;
while (prevList == null || nextList.size() < prevList.size()) {
prevList = nextList;
nextList = new LinkedList<>();
for (SDDocumentType doc : prevList) {
boolean isDone = true;
for (SDDocumentType inherited : doc.getInheritedTypes()) {
if (!doneNames.contains(inherited.getName())) {
isDone = false;
break;
}
}
if (isDone) {
doneNames.add(doc.getName());
doneList.add(doc);
} else {
nextList.add(doc);
}
}
}
if (!nextList.isEmpty()) {
throw new IllegalArgumentException("Could not resolve inheritance of document types " +
toString(prevList) + ".");
}
return doneList;
}
private static String toString(List<SDDocumentType> lst) {
StringBuilder out = new StringBuilder();
for (int i = 0, len = lst.size(); i < len; ++i) {
out.append("'").append(lst.get(i).getName()).append("'");
if (i < len - 2) {
out.append(", ");
} else if (i < len - 1) {
out.append(" and ");
}
}
return out.toString();
}
private Collection<Schema> tryAdd(Collection<Schema> schemaList) {
Collection<Schema> left = new ArrayList<>();
for (Schema schema : schemaList) {
try {
addToModel(schema);
} catch (RetryLaterException e) {
left.add(schema);
}
}
return left;
}
private void addToModel(Schema schema) {
// Then we add the search specific stuff
SearchDef searchDef = new SearchDef(schema.getName());
addSearchFields(schema.extraFieldList(), searchDef);
for (Field f : schema.getDocument().fieldSet()) {
addSearchField((SDField) f, searchDef);
}
for (SDField field : schema.allConcreteFields()) {
for (Attribute attribute : field.getAttributes().values()) {
if ( ! searchDef.getFields().containsKey(attribute.getName())) {
searchDef.add(new SearchField(new Field(attribute.getName(), field), !field.getIndices().isEmpty(), true));
}
}
}
for (Field f : schema.getDocument().fieldSet()) {
addAlias((SDField) f, searchDef);
}
model.getSearchManager().add(searchDef);
}
private static void addSearchFields(Collection<SDField> fields, SearchDef searchDef) {
for (SDField field : fields) {
addSearchField(field, searchDef);
}
}
private static void addSearchField(SDField field, SearchDef searchDef) {
SearchField searchField =
new SearchField(field,
field.getIndices().containsKey(field.getName()) && field.getIndices().get(field.getName()).getType().equals(Index.Type.VESPA),
field.getAttributes().containsKey(field.getName()));
searchDef.add(searchField);
// Add field to views
addToView(field.getIndices().keySet(), searchField, searchDef);
}
private static void addAlias(SDField field, SearchDef searchDef) {
for (Map.Entry<String, String> entry : field.getAliasToName().entrySet()) {
searchDef.addAlias(entry.getKey(), entry.getValue());
}
}
private static void addToView(Collection<String> views, Field field, SearchDef searchDef) {
for (String viewName : views) {
addToView(viewName, field, searchDef);
}
}
private static void addToView(String viewName, Field field, SearchDef searchDef) {
if (searchDef.getViews().containsKey(viewName)) {
searchDef.getViews().get(viewName).add(field);
} else {
if (!searchDef.getFields().containsKey(viewName)) {
FieldView view = new FieldView(viewName);
view.add(field);
searchDef.add(view);
}
}
}
// This is how you make a "Pair" class in java....
private static class TypeReplacement {
private final DataType oldType;
private final DataType newType;
DataType oldType() { return oldType; }
DataType newType() { return newType; }
public TypeReplacement(DataType oldType, DataType newType) {
this.oldType = oldType;
this.newType = newType;
}
}
private static String descT(DataType type) {
if (type == null) { return "<null>"; }
return "'" + type.getName() + "' [" + type.getId() + "] {"+type.getClass() + "}";
}
private void addDocumentTypes(List<SDDocumentType> docList) {
LinkedList<NewDocumentType> lst = new LinkedList<>();
for (SDDocumentType doc : docList) {
lst.add(convert(doc));
model.getDocumentManager().add(lst.getLast());
}
Map<DataType, DataType> replacements = new IdentityHashMap<>();
for(NewDocumentType doc : lst) {
resolveTemporaries(doc.getAllTypes(), lst, replacements);
}
for(NewDocumentType doc : lst) {
for (var entry : replacements.entrySet()) {
var old = entry.getKey();
if (doc.getDataType(old.getId()) == old) {
doc.replace(entry.getValue());
}
}
}
}
private static void resolveTemporaries(DataTypeCollection dtc,
Collection<NewDocumentType> docs,
Map<DataType, DataType> replacements) {
for (DataType type : dtc.getTypes()) {
resolveTemporariesRecurse(type, dtc, docs, replacements);
}
}
@SuppressWarnings("deprecation")
private static DataType resolveTemporariesRecurse(DataType type, DataTypeCollection repo,
Collection<NewDocumentType> docs,
Map<DataType, DataType> replacements) {
if (replacements.containsKey(type)) {
return replacements.get(type);
}
DataType original = type;
if (type instanceof TemporaryStructuredDataType) {
DataType other = repo.getDataType(type.getId());
if (other == null || other == type) {
other = getDocumentType(docs, type.getId());
}
if (other != null) {
type = other;
}
} else if (type instanceof DocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
} else if (! type.getName().equals("document")) {
throw new IllegalArgumentException
("Can not handle nested document definitions. Undefined document type: " + type.toString());
}
} else if (type instanceof NewDocumentType) {
DataType other = getDocumentType(docs, type.getId());
if (other != null) {
type = other;
}
} else if (type instanceof StructDataType) {
// trick avoids infinite recursion:
var old = replacements.put(original, type);
assert(old == null);
StructDataType dt = (StructDataType) type;
for (com.yahoo.document.Field field : dt.getFields()) {
var ft = field.getDataType();
var newft = resolveTemporariesRecurse(ft, repo, docs, replacements);
if (ft != newft) {
// XXX deprecated:
field.setDataType(newft);
}
}
old = replacements.remove(original);
assert(old == type);
}
else if (type instanceof MapDataType) {
MapDataType t = (MapDataType) type;
var old_kt = t.getKeyType();
var old_vt = t.getValueType();
var kt = resolveTemporariesRecurse(old_kt, repo, docs, replacements);
var vt = resolveTemporariesRecurse(old_vt, repo, docs, replacements);
if (kt != old_kt || vt != old_vt) {
type = new MapDataType(kt, vt, t.getId());
}
}
else if (type instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) type;
var old_nt = t.getNestedType();
var nt = resolveTemporariesRecurse(old_nt, repo, docs, replacements);
if (nt != old_nt) {
type = new ArrayDataType(nt, t.getId());
}
}
else if (type instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) type;
var old_nt = t.getNestedType();
var nt = resolveTemporariesRecurse(old_nt, repo, docs, replacements);
if (nt != old_nt) {
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
type = new WeightedSetDataType(nt, c, r, t.getId());
}
}
else if (type instanceof NewDocumentReferenceDataType) {
var t = (NewDocumentReferenceDataType) type;
var doc = getDocumentType(docs, t.getTargetTypeId());
type = doc.getReferenceDataType();
}
if (type != original) {
replacements.put(original, type);
}
return type;
}
private static NewDocumentType getDocumentType(Collection<NewDocumentType> docs, int id) {
for (NewDocumentType doc : docs) {
if (doc.getId() == id) {
return doc;
}
}
return null;
}
private static boolean anyParentsHavePayLoad(SDAnnotationType sa, SDDocumentType sdoc) {
if (sa.getInherits() != null) {
AnnotationType tmp = sdoc.findAnnotation(sa.getInherits());
SDAnnotationType inherited = (SDAnnotationType) tmp;
return ((inherited.getSdDocType() != null) || anyParentsHavePayLoad(inherited, sdoc));
}
return false;
}
private NewDocumentType convert(SDDocumentType sdoc) {
NewDocumentType dt = new NewDocumentType(new NewDocumentType.Name(sdoc.getName()),
sdoc.getDocumentType().contentStruct(),
sdoc.getFieldSets(),
convertDocumentReferencesToNames(sdoc.getDocumentReferences()),
convertTemporaryImportedFieldsToNames(sdoc.getTemporaryImportedFields()));
for (SDDocumentType n : sdoc.getInheritedTypes()) {
NewDocumentType.Name name = new NewDocumentType.Name(n.getName());
NewDocumentType inherited = model.getDocumentManager().getDocumentType(name);
if (inherited != null) {
dt.inherit(inherited);
}
}
var extractor = new TypeExtractor(dt);
extractor.extract(sdoc);
return dt;
}
static class TypeExtractor {
private final NewDocumentType targetDt;
Map<AnnotationType, String> annotationInheritance = new LinkedHashMap<>();
Map<StructDataType, String> structInheritance = new LinkedHashMap<>();
private final Map<Object, Object> inProgress = new IdentityHashMap<>();
TypeExtractor(NewDocumentType target) {
this.targetDt = target;
}
void extract(SDDocumentType sdoc) {
for (SDDocumentType type : sdoc.getTypes()) {
if (type.isStruct()) {
handleStruct(type);
} else {
throw new IllegalArgumentException("Data type '" + type.getName() + "' is not a struct => tostring='" + type.toString() + "'.");
}
}
for (SDDocumentType type : sdoc.getTypes()) {
for (SDDocumentType proxy : type.getInheritedTypes()) {
var inherited = (StructDataType) targetDt.getDataTypeRecursive(proxy.getName());
var converted = (StructDataType) targetDt.getDataType(type.getName());
if (! converted.inherits(inherited)) {
converted.inherit(inherited);
}
}
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
targetDt.add(annotation);
}
for (AnnotationType annotation : sdoc.getAnnotations().values()) {
SDAnnotationType sa = (SDAnnotationType) annotation;
if (annotation.getInheritedTypes().isEmpty() && (sa.getInherits() != null) ) {
annotationInheritance.put(annotation, sa.getInherits());
}
if (annotation.getDataType() == null) {
if (sa.getSdDocType() != null) {
StructDataType s = handleStruct(sa.getSdDocType());
annotation.setDataType(s);
if ((sa.getInherits() != null)) {
structInheritance.put(s, "annotation."+sa.getInherits());
}
} else if (sa.getInherits() != null) {
StructDataType s = new StructDataType("annotation."+annotation.getName());
if (anyParentsHavePayLoad(sa, sdoc)) {
annotation.setDataType(s);
addType(s);
}
structInheritance.put(s, "annotation."+sa.getInherits());
}
} else {
var dt = annotation.getDataType();
if (dt instanceof StructDataType) {
handleStruct((StructDataType) dt);
}
}
}
for (Map.Entry<AnnotationType, String> e : annotationInheritance.entrySet()) {
e.getKey().inherit(targetDt.getAnnotationType(e.getValue()));
}
for (Map.Entry<StructDataType, String> e : structInheritance.entrySet()) {
StructDataType s = (StructDataType)targetDt.getDataType(e.getValue());
if (s != null) {
e.getKey().inherit(s);
}
}
handleStruct(sdoc.getDocumentType().contentStruct());
extractDataTypesFromFields(sdoc.fieldSet());
}
private void extractDataTypesFromFields(Collection<Field> fields) {
for (Field f : fields) {
DataType type = f.getDataType();
if (testAddType(type)) {
extractNestedTypes(type);
addType(type);
}
}
}
private void extractNestedTypes(DataType type) {
if (inProgress.containsKey(type)) {
return;
}
inProgress.put(type, this);
if (type instanceof StructDataType) {
StructDataType tmp = (StructDataType) type;
extractDataTypesFromFields(tmp.getFieldsThisTypeOnly());
} else if (type instanceof CollectionDataType) {
CollectionDataType tmp = (CollectionDataType) type;
extractNestedTypes(tmp.getNestedType());
addType(tmp.getNestedType());
} else if (type instanceof MapDataType) {
MapDataType tmp = (MapDataType) type;
extractNestedTypes(tmp.getKeyType());
extractNestedTypes(tmp.getValueType());
addType(tmp.getKeyType());
addType(tmp.getValueType());
} else if (type instanceof TemporaryAnnotationReferenceDataType) {
throw new IllegalArgumentException(type.toString());
}
}
private boolean testAddType(DataType type) { return internalAddType(type, true); }
private boolean addType(DataType type) { return internalAddType(type, false); }
private boolean internalAddType(DataType type, boolean dryRun) {
DataType oldType = targetDt.getDataTypeRecursive(type.getId());
if (oldType == null) {
if ( ! dryRun) {
targetDt.add(type);
}
return true;
} else if ((type instanceof StructDataType) && (oldType instanceof StructDataType)) {
StructDataType s = (StructDataType) type;
StructDataType os = (StructDataType) oldType;
if ((os.getFieldCount() == 0) && (s.getFieldCount() > os.getFieldCount())) {
if ( ! dryRun) {
targetDt.replace(type);
}
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
private void specialHandleAnnotationReference(Field field) {
DataType fieldType = specialHandleAnnotationReferenceRecurse(field.getName(), field.getDataType());
if (fieldType == null) {
return;
}
field.setDataType(fieldType); // XXX deprecated
}
private DataType specialHandleAnnotationReferenceRecurse(String fieldName,
DataType dataType) {
if (dataType instanceof TemporaryAnnotationReferenceDataType) {
TemporaryAnnotationReferenceDataType refType = (TemporaryAnnotationReferenceDataType)dataType;
if (refType.getId() != 0) {
return null;
}
AnnotationType target = targetDt.getAnnotationType(refType.getTarget());
if (target == null) {
throw new RetryLaterException("Annotation '" + refType.getTarget() + "' in reference '" + fieldName +
"' does not exist.");
}
dataType = new AnnotationReferenceDataType(target);
addType(dataType);
return dataType;
}
else if (dataType instanceof MapDataType) {
MapDataType t = (MapDataType)dataType;
DataType valueType = specialHandleAnnotationReferenceRecurse(fieldName, t.getValueType());
if (valueType == null) {
return null;
}
var mapType = new MapDataType(t.getKeyType(), valueType, t.getId());
addType(mapType);
return mapType;
}
else if (dataType instanceof ArrayDataType) {
ArrayDataType t = (ArrayDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
var lstType = new ArrayDataType(nestedType, t.getId());
addType(lstType);
return lstType;
}
else if (dataType instanceof WeightedSetDataType) {
WeightedSetDataType t = (WeightedSetDataType) dataType;
DataType nestedType = specialHandleAnnotationReferenceRecurse(fieldName, t.getNestedType());
if (nestedType == null) {
return null;
}
boolean c = t.createIfNonExistent();
boolean r = t.removeIfZero();
var lstType = new WeightedSetDataType(nestedType, c, r, t.getId());
addType(lstType);
return lstType;
}
return null;
}
@SuppressWarnings("deprecation")
private StructDataType handleStruct(SDDocumentType type) {
if (type.isStruct()) {
var st = type.getStruct();
if (st.getName().equals(type.getName()) &&
(st instanceof StructDataType) &&
! (st instanceof TemporaryStructuredDataType))
{
return handleStruct((StructDataType) st);
}
}
StructDataType s = new StructDataType(type.getName());
for (Field f : type.getDocumentType().contentStruct().getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
s.addField(f);
}
for (StructDataType inherited : type.getDocumentType().contentStruct().getInheritedTypes()) {
s.inherit(inherited);
}
extractNestedTypes(s);
addType(s);
return s;
}
private StructDataType handleStruct(StructDataType s) {
for (Field f : s.getFieldsThisTypeOnly()) {
specialHandleAnnotationReference(f);
}
extractNestedTypes(s);
addType(s);
return s;
}
}
private static Set<NewDocumentType.Name> convertDocumentReferencesToNames(Optional<DocumentReferences> documentReferences) {
if (!documentReferences.isPresent()) {
return Set.of();
}
return documentReferences.get().referenceMap().values().stream()
.map(documentReference -> documentReference.targetSearch().getDocument())
.map(documentType -> new NewDocumentType.Name(documentType.getName()))
.collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
}
private static Set<String> convertTemporaryImportedFieldsToNames(TemporaryImportedFields importedFields) {
if (importedFields == null) {
return Set.of();
}
return Collections.unmodifiableSet(importedFields.fields().keySet());
}
public static class RetryLaterException extends IllegalArgumentException {
public RetryLaterException(String message) {
super(message);
}
}
}
|
remove leftover unused class
|
config-model/src/main/java/com/yahoo/searchdefinition/DocumentModelBuilder.java
|
remove leftover unused class
|
|
Java
|
apache-2.0
|
19591d92aad12f6b09be7fd71f73f416a34f80be
| 0
|
rifatdover/generator-jhipster,gmarziou/generator-jhipster,hdurix/generator-jhipster,nkolosnjaji/generator-jhipster,erikkemperman/generator-jhipster,cbornet/generator-jhipster,duderoot/generator-jhipster,maniacneron/generator-jhipster,wmarques/generator-jhipster,mosoft521/generator-jhipster,liseri/generator-jhipster,sendilkumarn/generator-jhipster,eosimosu/generator-jhipster,lrkwz/generator-jhipster,atomfrede/generator-jhipster,jhipster/generator-jhipster,wmarques/generator-jhipster,atomfrede/generator-jhipster,deepu105/generator-jhipster,hdurix/generator-jhipster,mraible/generator-jhipster,stevehouel/generator-jhipster,JulienMrgrd/generator-jhipster,ziogiugno/generator-jhipster,siliconharborlabs/generator-jhipster,vivekmore/generator-jhipster,cbornet/generator-jhipster,eosimosu/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,ctamisier/generator-jhipster,ctamisier/generator-jhipster,robertmilowski/generator-jhipster,robertmilowski/generator-jhipster,robertmilowski/generator-jhipster,gmarziou/generator-jhipster,siliconharborlabs/generator-jhipster,PierreBesson/generator-jhipster,ziogiugno/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,cbornet/generator-jhipster,erikkemperman/generator-jhipster,ziogiugno/generator-jhipster,ruddell/generator-jhipster,danielpetisme/generator-jhipster,mosoft521/generator-jhipster,duderoot/generator-jhipster,liseri/generator-jhipster,wmarques/generator-jhipster,cbornet/generator-jhipster,rkohel/generator-jhipster,JulienMrgrd/generator-jhipster,dalbelap/generator-jhipster,nkolosnjaji/generator-jhipster,dimeros/generator-jhipster,hdurix/generator-jhipster,jkutner/generator-jhipster,Tcharl/generator-jhipster,gzsombor/generator-jhipster,danielpetisme/generator-jhipster,ramzimaalej/generator-jhipster,dalbelap/generator-jhipster,dimeros/generator-jhipster,jkutner/generator-jhipster,jhipster/generator-jhipster,ctamisier/generator-jhipster,cbornet/generator-jhipster,lrkwz/generator-jhipster,robertmilowski/generator-jhipster,atomfrede/generator-jhipster,mraible/generator-jhipster,wmarques/generator-jhipster,jhipster/generator-jhipster,vivekmore/generator-jhipster,jkutner/generator-jhipster,xetys/generator-jhipster,JulienMrgrd/generator-jhipster,lrkwz/generator-jhipster,gmarziou/generator-jhipster,ruddell/generator-jhipster,rkohel/generator-jhipster,deepu105/generator-jhipster,deepu105/generator-jhipster,sendilkumarn/generator-jhipster,ramzimaalej/generator-jhipster,gmarziou/generator-jhipster,wmarques/generator-jhipster,deepu105/generator-jhipster,erikkemperman/generator-jhipster,ruddell/generator-jhipster,baskeboler/generator-jhipster,sendilkumarn/generator-jhipster,JulienMrgrd/generator-jhipster,dynamicguy/generator-jhipster,erikkemperman/generator-jhipster,liseri/generator-jhipster,sohibegit/generator-jhipster,baskeboler/generator-jhipster,Tcharl/generator-jhipster,dalbelap/generator-jhipster,pascalgrimaud/generator-jhipster,gzsombor/generator-jhipster,mosoft521/generator-jhipster,mosoft521/generator-jhipster,liseri/generator-jhipster,siliconharborlabs/generator-jhipster,robertmilowski/generator-jhipster,ruddell/generator-jhipster,jkutner/generator-jhipster,yongli82/generator-jhipster,rkohel/generator-jhipster,Tcharl/generator-jhipster,gzsombor/generator-jhipster,jkutner/generator-jhipster,mraible/generator-jhipster,sohibegit/generator-jhipster,dimeros/generator-jhipster,Tcharl/generator-jhipster,danielpetisme/generator-jhipster,eosimosu/generator-jhipster,dynamicguy/generator-jhipster,maniacneron/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,xetys/generator-jhipster,xetys/generator-jhipster,stevehouel/generator-jhipster,vivekmore/generator-jhipster,sendilkumarn/generator-jhipster,sohibegit/generator-jhipster,vivekmore/generator-jhipster,danielpetisme/generator-jhipster,gmarziou/generator-jhipster,Tcharl/generator-jhipster,siliconharborlabs/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,jhipster/generator-jhipster,baskeboler/generator-jhipster,maniacneron/generator-jhipster,dimeros/generator-jhipster,vivekmore/generator-jhipster,dalbelap/generator-jhipster,maniacneron/generator-jhipster,ramzimaalej/generator-jhipster,eosimosu/generator-jhipster,hdurix/generator-jhipster,PierreBesson/generator-jhipster,duderoot/generator-jhipster,lrkwz/generator-jhipster,dynamicguy/generator-jhipster,ruddell/generator-jhipster,nkolosnjaji/generator-jhipster,liseri/generator-jhipster,sohibegit/generator-jhipster,stevehouel/generator-jhipster,sendilkumarn/generator-jhipster,duderoot/generator-jhipster,PierreBesson/generator-jhipster,dynamicguy/generator-jhipster,PierreBesson/generator-jhipster,baskeboler/generator-jhipster,erikkemperman/generator-jhipster,xetys/generator-jhipster,ctamisier/generator-jhipster,yongli82/generator-jhipster,JulienMrgrd/generator-jhipster,PierreBesson/generator-jhipster,lrkwz/generator-jhipster,sohibegit/generator-jhipster,gzsombor/generator-jhipster,rkohel/generator-jhipster,deepu105/generator-jhipster,duderoot/generator-jhipster,pascalgrimaud/generator-jhipster,maniacneron/generator-jhipster,nkolosnjaji/generator-jhipster,danielpetisme/generator-jhipster,dimeros/generator-jhipster,nkolosnjaji/generator-jhipster,rifatdover/generator-jhipster,atomfrede/generator-jhipster,dalbelap/generator-jhipster,stevehouel/generator-jhipster,siliconharborlabs/generator-jhipster,jhipster/generator-jhipster,ctamisier/generator-jhipster,mosoft521/generator-jhipster,atomfrede/generator-jhipster,eosimosu/generator-jhipster,mraible/generator-jhipster,stevehouel/generator-jhipster,gzsombor/generator-jhipster,ziogiugno/generator-jhipster,ziogiugno/generator-jhipster,baskeboler/generator-jhipster,rkohel/generator-jhipster,hdurix/generator-jhipster
|
package <%=packageName%>.repository;
<% if (databaseType == 'cassandra') { %>
import com.datastax.driver.core.*;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;<% } %>
import <%=packageName%>.domain.User;
import org.joda.time.DateTime;<% if (databaseType == 'sql') { %>
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;<% } %><% if (databaseType == 'mongodb') { %>
import org.springframework.data.mongodb.repository.MongoRepository;<% } %>
import java.util.List;<% if (javaVersion == '8') { %>
import java.util.Optional;<%}%><% if (databaseType == 'cassandra') { %>
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;<%}%>
<% if (databaseType == 'sql') { %>/**
* Spring Data JPA repository for the User entity.
*/<% } %><% if (databaseType == 'mongodb') { %>/**
* Spring Data MongoDB repository for the User entity.
*/<% } %><% if (databaseType == 'cassandra') { %>/**
* Cassandra repository for the User entity.
*/<% } %><% if ((databaseType == 'sql' || databaseType == 'mongodb') && javaVersion == '8') { %>
public interface UserRepository extends <% if (databaseType == 'sql') { %>JpaRepository<User, Long><% } %><% if (databaseType == 'mongodb') { %>MongoRepository<User, String><% } %> {
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmail(String email);
Optional<User> findOneByLogin(String login);
@Override
void delete(User t);
}<% } else if ((databaseType == 'sql' || databaseType == 'mongodb') && javaVersion == '7') { %>
public interface UserRepository extends <% if (databaseType == 'sql') { %>JpaRepository<User, Long><% } %><% if (databaseType == 'mongodb') { %>MongoRepository<User, String><% } %> {
User findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);
User findOneByResetKey(String resetKey);
User findOneByLogin(String login);
User findOneByEmail(String email);
}<% } else if (databaseType == 'cassandra') { %>
@Repository
public class UserRepository {
@Inject
private Session session;
private Mapper<User> mapper;
private PreparedStatement findAllStmt;
private PreparedStatement findOneByActivationKeyStmt;
private PreparedStatement findOneByResetKeyStmt;
private PreparedStatement insertByActivationKeyStmt;
private PreparedStatement insertByResetKeyStmt;
private PreparedStatement deleteByActivationKeyStmt;
private PreparedStatement deleteByResetKeyStmt;
private PreparedStatement findOneByLoginStmt;
private PreparedStatement insertByLoginStmt;
private PreparedStatement deleteByLoginStmt;
private PreparedStatement findOneByEmailStmt;
private PreparedStatement insertByEmailStmt;
private PreparedStatement deleteByEmailStmt;
@PostConstruct
public void init() {
mapper = new MappingManager(session).mapper(User.class);
findAllStmt = session.prepare("SELECT * FROM user");
findOneByActivationKeyStmt = session.prepare(
"SELECT id " +
"FROM user_by_activation_key " +
"WHERE activation_key = :activation_key");
findOneByResetKeyStmt = session.prepare(
"SELECT id " +
"FROM user_by_reset_key " +
"WHERE reset_key = :reset_key");
insertByActivationKeyStmt = session.prepare(
"INSERT INTO user_by_activation_key (activation_key, id) " +
"VALUES (:activation_key, :id)");
insertByResetKeyStmt = session.prepare(
"INSERT INTO user_by_reset_key (reset_key, id) " +
"VALUES (:reset_key, :id)");
deleteByActivationKeyStmt = session.prepare(
"DELETE FROM user_by_activation_key " +
"WHERE activation_key = :activation_key");
deleteByResetKeyStmt = session.prepare(
"DELETE FROM user_by_reset_key " +
"WHERE reset_key = :reset_key");
findOneByLoginStmt = session.prepare(
"SELECT id " +
"FROM user_by_login " +
"WHERE login = :login");
insertByLoginStmt = session.prepare(
"INSERT INTO user_by_login (login, id) " +
"VALUES (:login, :id)");
deleteByLoginStmt = session.prepare(
"DELETE FROM user_by_login " +
"WHERE login = :login");
findOneByEmailStmt = session.prepare(
"SELECT id " +
"FROM user_by_email " +
"WHERE email = :email");
insertByEmailStmt = session.prepare(
"INSERT INTO user_by_email (email, id) " +
"VALUES (:email, :id)");
deleteByEmailStmt = session.prepare(
"DELETE FROM user_by_email " +
"WHERE email = :email");
}
public Optional<User> findOneByActivationKey(String activationKey) {
BoundStatement stmt = findOneByActivationKeyStmt.bind();
stmt.setString("activation_key", activationKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByResetKey(String resetKey) {
BoundStatement stmt = findOneByResetKeyStmt.bind();
stmt.setString("reset_key", resetKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByEmail(String email) {
BoundStatement stmt = findOneByEmailStmt.bind();
stmt.setString("email", email);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByLogin(String login) {
BoundStatement stmt = findOneByLoginStmt.bind();
stmt.setString("login", login);
return findOneFromIndex(stmt);
}
public List<User> findAll() {
return mapper.map(session.execute(findAllStmt.bind())).all();
}
public void save(User user) {
User oldUser = mapper.get(user.getId());
if (oldUser != null) {
if (!StringUtils.isEmpty(oldUser.getActivationKey()) && !oldUser.getActivationKey().equals(user.getActivationKey())) {
session.execute(deleteByActivationKeyStmt.bind().setString("activation_key", oldUser.getActivationKey()));
}
if (!StringUtils.isEmpty(oldUser.getResetKey()) && !oldUser.getResetKey().equals(user.getResetKey())) {
session.execute(deleteByResetKeyStmt.bind().setString("reset_key", oldUser.getResetKey()));
}
if (!StringUtils.isEmpty(oldUser.getLogin()) && !oldUser.getLogin().equals(user.getLogin())) {
session.execute(deleteByLoginStmt.bind().setString("login", oldUser.getLogin()));
}
if (!StringUtils.isEmpty(oldUser.getEmail()) && !oldUser.getEmail().equals(user.getEmail())) {
session.execute(deleteByEmailStmt.bind().setString("email", oldUser.getEmail()));
}
}
BatchStatement batch = new BatchStatement();
batch.add(mapper.saveQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.add(insertByActivationKeyStmt.bind()
.setString("activation_key", user.getActivationKey())
.setString("id", user.getId()));
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.add(insertByResetKeyStmt.bind()
.setString("reset_key", user.getResetKey())
.setString("id", user.getId()));
}
batch.add(insertByLoginStmt.bind()
.setString("login", user.getLogin())
.setString("id", user.getId()));
batch.add(insertByEmailStmt.bind()
.setString("email", user.getEmail())
.setString("id", user.getId()));
session.execute(batch);
}
public void delete(User user) {
BatchStatement batch = new BatchStatement();
batch.add(mapper.deleteQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.add(deleteByActivationKeyStmt.bind().setString("activation_key", user.getActivationKey()));
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.add(deleteByResetKeyStmt.bind().setString("reset_key", user.getResetKey()));
}
batch.add(deleteByLoginStmt.bind().setString("login", user.getLogin()));
batch.add(deleteByEmailStmt.bind().setString("email", user.getEmail()));
session.execute(batch);
}
private Optional<User> findOneFromIndex(BoundStatement stmt) {
ResultSet rs = session.execute(stmt);
if (rs.isExhausted()) {
return Optional.empty();
}
return Optional.ofNullable(rs.one().getString("id"))
.map(id -> Optional.ofNullable(mapper.get(id)))
.get();
}
}<% } %>
|
app/templates/src/main/java/package/repository/_UserRepository.java
|
package <%=packageName%>.repository;
<% if (databaseType == 'cassandra') { %>
import com.datastax.driver.core.*;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;<% } %>
import <%=packageName%>.domain.User;
import org.joda.time.DateTime;<% if (databaseType == 'sql') { %>
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;<% } %><% if (databaseType == 'mongodb') { %>
import org.springframework.data.mongodb.repository.MongoRepository;<% } %>
import org.springframework.data.repository.query.Param;
import java.util.List;<% if (javaVersion == '8') { %>
import java.util.Optional;<%}%><% if (databaseType == 'cassandra') { %>
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;<%}%>
<% if (databaseType == 'sql') { %>/**
* Spring Data JPA repository for the User entity.
*/<% } %><% if (databaseType == 'mongodb') { %>/**
* Spring Data MongoDB repository for the User entity.
*/<% } %><% if (databaseType == 'cassandra') { %>/**
* Cassandra repository for the User entity.
*/<% } %><% if ((databaseType == 'sql' || databaseType == 'mongodb') && javaVersion == '8') { %>
public interface UserRepository extends <% if (databaseType == 'sql') { %>JpaRepository<User, Long><% } %><% if (databaseType == 'mongodb') { %>MongoRepository<User, String><% } %> {
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmail(String email);
Optional<User> findOneByLogin(String login);
@Override
void delete(User t);
}<% } else if ((databaseType == 'sql' || databaseType == 'mongodb') && javaVersion == '7') { %>
public interface UserRepository extends <% if (databaseType == 'sql') { %>JpaRepository<User, Long><% } %><% if (databaseType == 'mongodb') { %>MongoRepository<User, String><% } %> {
User findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);
User findOneByResetKey(String resetKey);
User findOneByLogin(String login);
User findOneByEmail(String email);
}<% } else if (databaseType == 'cassandra') { %>
@Repository
public class UserRepository {
@Inject
private Session session;
private Mapper<User> mapper;
private PreparedStatement findAllStmt;
private PreparedStatement findOneByActivationKeyStmt;
private PreparedStatement findOneByResetKeyStmt;
private PreparedStatement insertByActivationKeyStmt;
private PreparedStatement insertByResetKeyStmt;
private PreparedStatement deleteByActivationKeyStmt;
private PreparedStatement deleteByResetKeyStmt;
private PreparedStatement findOneByLoginStmt;
private PreparedStatement insertByLoginStmt;
private PreparedStatement deleteByLoginStmt;
private PreparedStatement findOneByEmailStmt;
private PreparedStatement insertByEmailStmt;
private PreparedStatement deleteByEmailStmt;
@PostConstruct
public void init() {
mapper = new MappingManager(session).mapper(User.class);
findAllStmt = session.prepare("SELECT * FROM user");
findOneByActivationKeyStmt = session.prepare(
"SELECT id " +
"FROM user_by_activation_key " +
"WHERE activation_key = :activation_key");
findOneByResetKeyStmt = session.prepare(
"SELECT id " +
"FROM user_by_reset_key " +
"WHERE reset_key = :reset_key");
insertByActivationKeyStmt = session.prepare(
"INSERT INTO user_by_activation_key (activation_key, id) " +
"VALUES (:activation_key, :id)");
insertByResetKeyStmt = session.prepare(
"INSERT INTO user_by_reset_key (reset_key, id) " +
"VALUES (:reset_key, :id)");
deleteByActivationKeyStmt = session.prepare(
"DELETE FROM user_by_activation_key " +
"WHERE activation_key = :activation_key");
deleteByResetKeyStmt = session.prepare(
"DELETE FROM user_by_reset_key " +
"WHERE reset_key = :reset_key");
findOneByLoginStmt = session.prepare(
"SELECT id " +
"FROM user_by_login " +
"WHERE login = :login");
insertByLoginStmt = session.prepare(
"INSERT INTO user_by_login (login, id) " +
"VALUES (:login, :id)");
deleteByLoginStmt = session.prepare(
"DELETE FROM user_by_login " +
"WHERE login = :login");
findOneByEmailStmt = session.prepare(
"SELECT id " +
"FROM user_by_email " +
"WHERE email = :email");
insertByEmailStmt = session.prepare(
"INSERT INTO user_by_email (email, id) " +
"VALUES (:email, :id)");
deleteByEmailStmt = session.prepare(
"DELETE FROM user_by_email " +
"WHERE email = :email");
}
public Optional<User> findOneByActivationKey(String activationKey) {
BoundStatement stmt = findOneByActivationKeyStmt.bind();
stmt.setString("activation_key", activationKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByResetKey(String resetKey) {
BoundStatement stmt = findOneByResetKeyStmt.bind();
stmt.setString("reset_key", resetKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByEmail(String email) {
BoundStatement stmt = findOneByEmailStmt.bind();
stmt.setString("email", email);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByLogin(String login) {
BoundStatement stmt = findOneByLoginStmt.bind();
stmt.setString("login", login);
return findOneFromIndex(stmt);
}
public List<User> findAll() {
return mapper.map(session.execute(findAllStmt.bind())).all();
}
public void save(User user) {
User oldUser = mapper.get(user.getId());
if (oldUser != null) {
if (!StringUtils.isEmpty(oldUser.getActivationKey()) && !oldUser.getActivationKey().equals(user.getActivationKey())) {
session.execute(deleteByActivationKeyStmt.bind().setString("activation_key", oldUser.getActivationKey()));
}
if (!StringUtils.isEmpty(oldUser.getResetKey()) && !oldUser.getResetKey().equals(user.getResetKey())) {
session.execute(deleteByResetKeyStmt.bind().setString("reset_key", oldUser.getResetKey()));
}
if (!StringUtils.isEmpty(oldUser.getLogin()) && !oldUser.getLogin().equals(user.getLogin())) {
session.execute(deleteByLoginStmt.bind().setString("login", oldUser.getLogin()));
}
if (!StringUtils.isEmpty(oldUser.getEmail()) && !oldUser.getEmail().equals(user.getEmail())) {
session.execute(deleteByEmailStmt.bind().setString("email", oldUser.getEmail()));
}
}
BatchStatement batch = new BatchStatement();
batch.add(mapper.saveQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.add(insertByActivationKeyStmt.bind()
.setString("activation_key", user.getActivationKey())
.setString("id", user.getId()));
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.add(insertByResetKeyStmt.bind()
.setString("reset_key", user.getResetKey())
.setString("id", user.getId()));
}
batch.add(insertByLoginStmt.bind()
.setString("login", user.getLogin())
.setString("id", user.getId()));
batch.add(insertByEmailStmt.bind()
.setString("email", user.getEmail())
.setString("id", user.getId()));
session.execute(batch);
}
public void delete(User user) {
BatchStatement batch = new BatchStatement();
batch.add(mapper.deleteQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.add(deleteByActivationKeyStmt.bind().setString("activation_key", user.getActivationKey()));
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.add(deleteByResetKeyStmt.bind().setString("reset_key", user.getResetKey()));
}
batch.add(deleteByLoginStmt.bind().setString("login", user.getLogin()));
batch.add(deleteByEmailStmt.bind().setString("email", user.getEmail()));
session.execute(batch);
}
private Optional<User> findOneFromIndex(BoundStatement stmt) {
ResultSet rs = session.execute(stmt);
if (rs.isExhausted()) {
return Optional.empty();
}
return Optional.ofNullable(rs.one().getString("id"))
.map(id -> Optional.ofNullable(mapper.get(id)))
.get();
}
}<% } %>
|
Unused import Param
|
app/templates/src/main/java/package/repository/_UserRepository.java
|
Unused import Param
|
|
Java
|
apache-2.0
|
28e5b8978dcd85af0574aec7e1a753ca4736e9f0
| 0
|
liupugong/drools,Buble1981/MyDroolsFork,lanceleverich/drools,ngs-mtech/drools,ThomasLau/drools,amckee23/drools,TonnyFeng/drools,prabasn/drools,kevinpeterson/drools,jomarko/drools,manstis/drools,ngs-mtech/drools,romartin/drools,vinodkiran/drools,yurloc/drools,jomarko/drools,vinodkiran/drools,droolsjbpm/drools,ngs-mtech/drools,reynoldsm88/drools,sotty/drools,ngs-mtech/drools,mrrodriguez/drools,ThiagoGarciaAlves/drools,ThiagoGarciaAlves/drools,OnePaaS/drools,liupugong/drools,HHzzhz/drools,mrietveld/drools,kevinpeterson/drools,jiripetrlik/drools,psiroky/drools,OnePaaS/drools,romartin/drools,mswiderski/drools,ChallenHB/drools,pwachira/droolsexamples,rajashekharmunthakewill/drools,292388900/drools,prabasn/drools,prabasn/drools,rajashekharmunthakewill/drools,droolsjbpm/drools,Buble1981/MyDroolsFork,reynoldsm88/drools,rajashekharmunthakewill/drools,Buble1981/MyDroolsFork,yurloc/drools,vinodkiran/drools,sotty/drools,ThiagoGarciaAlves/drools,prabasn/drools,manstis/drools,droolsjbpm/drools,amckee23/drools,mrrodriguez/drools,liupugong/drools,sutaakar/drools,ThomasLau/drools,reynoldsm88/drools,romartin/drools,liupugong/drools,ThiagoGarciaAlves/drools,prabasn/drools,jiripetrlik/drools,sutaakar/drools,iambic69/drools,kedzie/drools-android,mrietveld/drools,ThomasLau/drools,292388900/drools,OnePaaS/drools,lanceleverich/drools,psiroky/drools,yurloc/drools,sutaakar/drools,kedzie/drools-android,jiripetrlik/drools,pperboires/PocDrools,sotty/drools,292388900/drools,HHzzhz/drools,vinodkiran/drools,pperboires/PocDrools,sotty/drools,lanceleverich/drools,rajashekharmunthakewill/drools,iambic69/drools,winklerm/drools,292388900/drools,ChallenHB/drools,HHzzhz/drools,kevinpeterson/drools,amckee23/drools,iambic69/drools,vinodkiran/drools,jomarko/drools,sotty/drools,yurloc/drools,jomarko/drools,ngs-mtech/drools,droolsjbpm/drools,HHzzhz/drools,kedzie/drools-android,winklerm/drools,droolsjbpm/drools,OnePaaS/drools,manstis/drools,mrietveld/drools,mswiderski/drools,kedzie/drools-android,amckee23/drools,mrietveld/drools,ChallenHB/drools,ChallenHB/drools,TonnyFeng/drools,manstis/drools,mrrodriguez/drools,ChallenHB/drools,liupugong/drools,pperboires/PocDrools,lanceleverich/drools,HHzzhz/drools,TonnyFeng/drools,winklerm/drools,mrrodriguez/drools,pperboires/PocDrools,TonnyFeng/drools,ThiagoGarciaAlves/drools,lanceleverich/drools,kedzie/drools-android,romartin/drools,mswiderski/drools,iambic69/drools,mswiderski/drools,Buble1981/MyDroolsFork,reynoldsm88/drools,sutaakar/drools,mrietveld/drools,292388900/drools,rajashekharmunthakewill/drools,jiripetrlik/drools,kevinpeterson/drools,winklerm/drools,amckee23/drools,ThomasLau/drools,ThomasLau/drools,romartin/drools,OnePaaS/drools,jomarko/drools,iambic69/drools,winklerm/drools,manstis/drools,jiripetrlik/drools,TonnyFeng/drools,mrrodriguez/drools,sutaakar/drools,psiroky/drools,reynoldsm88/drools,psiroky/drools,kevinpeterson/drools
|
/**
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.management;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.ObjectName;
import org.drools.WorkingMemory;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.event.ActivationCancelledEvent;
import org.drools.event.ActivationCreatedEvent;
import org.drools.event.AfterActivationFiredEvent;
import org.drools.event.AgendaEventListener;
import org.drools.event.AgendaGroupPoppedEvent;
import org.drools.event.AgendaGroupPushedEvent;
import org.drools.event.BeforeActivationFiredEvent;
import org.drools.event.RuleFlowGroupActivatedEvent;
import org.drools.event.RuleFlowGroupDeactivatedEvent;
import org.drools.event.process.ProcessCompletedEvent;
import org.drools.event.process.ProcessEventListener;
import org.drools.event.process.ProcessNodeLeftEvent;
import org.drools.event.process.ProcessNodeTriggeredEvent;
import org.drools.event.process.ProcessStartedEvent;
import org.drools.event.process.ProcessVariableChangedEvent;
import org.drools.management.KnowledgeSessionMonitoring.AgendaStats.AgendaStatsData;
import org.drools.management.KnowledgeSessionMonitoring.ProcessStats.ProcessInstanceStatsData;
import org.drools.management.KnowledgeSessionMonitoring.ProcessStats.ProcessStatsData;
/**
* An MBean to monitor a given knowledge session
*
* @author etirelli
*/
public class KnowledgeSessionMonitoring implements KnowledgeSessionMonitoringMBean {
private static final String KSESSION_PREFIX = "org.drools.kbases";
private static final long NANO_TO_MILLISEC = 1000000;
private InternalWorkingMemory ksession;
private InternalRuleBase kbase;
private ObjectName name;
public AgendaStats agendaStats;
public ProcessStats processStats;
public KnowledgeSessionMonitoring(InternalWorkingMemory ksession) {
this.ksession = ksession;
this.kbase = (InternalRuleBase) ksession.getRuleBase();
this.name = DroolsManagementAgent.createObjectName(KSESSION_PREFIX + ":type="+kbase.getId()+",group=Sessions,sessionId=Session-"+ksession.getId());
this.agendaStats = new AgendaStats();
this.processStats = new ProcessStats();
this.ksession.addEventListener( agendaStats );
if (ksession.getProcessRuntime() != null) {
this.ksession.getProcessRuntime().addEventListener( processStats );
}
}
public void dispose() {
this.ksession.removeEventListener( agendaStats );
if (ksession.getProcessRuntime() != null) {
this.ksession.getProcessRuntime().removeEventListener( processStats );
}
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#reset()
*/
public void reset() {
this.agendaStats.reset();
this.processStats.reset();
}
public InternalWorkingMemory getKsession() {
return ksession;
}
public InternalRuleBase getKbase() {
return kbase;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getName()
*/
public ObjectName getName() {
return name;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getKnowledgeBaseId()
*/
public String getKnowledgeBaseId() {
return kbase.getId();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getKnowledgeSessionId()
*/
public int getKnowledgeSessionId() {
return ksession.getId();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalFactCount()
*/
public long getTotalFactCount() {
return ksession.getTotalFactCount();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsFired()
*/
public long getTotalActivationsFired() {
return this.agendaStats.getConsolidatedStats().activationsFired.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsCancelled()
*/
public long getTotalActivationsCancelled() {
return this.agendaStats.getConsolidatedStats().activationsCancelled.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsCreated()
*/
public long getTotalActivationsCreated() {
return this.agendaStats.getConsolidatedStats().activationsCreated.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalFiringTime()
*/
public long getTotalFiringTime() {
// converting nano secs to milli secs
return this.agendaStats.getConsolidatedStats().firingTime.get()/NANO_TO_MILLISEC;
}
public Date getLastReset() {
return this.agendaStats.getConsolidatedStats().lastReset.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getAverageFiringTime()
*/
public double getAverageFiringTime() {
long fires = this.agendaStats.getConsolidatedStats().activationsFired.get();
long time = this.agendaStats.getConsolidatedStats().firingTime.get();
// calculating the average and converting it from nano secs to milli secs
return fires > 0 ? (((double) time / (double) fires) / (double) NANO_TO_MILLISEC) : 0;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getStatsForRule(java.lang.String)
*/
public String getStatsForRule( String ruleName ) {
AgendaStatsData data = this.agendaStats.getRuleStats( ruleName );
String result = data == null ? "activationsCreated=0 activationsCancelled=0 activationsFired=0 firingTime=0ms" : data.toString();
return result;
}
public Map<String,String> getStatsByRule() {
Map<String, String> result = new HashMap<String, String>();
for( Map.Entry<String, AgendaStatsData> entry : this.agendaStats.getRulesStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public static class AgendaStats implements AgendaEventListener {
private AgendaStatsData consolidated = new AgendaStatsData();
private ConcurrentHashMap<String, AgendaStatsData> ruleStats = new ConcurrentHashMap<String, AgendaStatsData>();
public AgendaStats() {
}
public AgendaStatsData getConsolidatedStats() {
return this.consolidated;
}
public Map<String, AgendaStatsData> getRulesStats() {
return this.ruleStats;
}
public AgendaStatsData getRuleStats( String ruleName ) {
return this.ruleStats.get( ruleName );
}
public void reset() {
this.consolidated.reset();
this.ruleStats.clear();
}
public void activationCancelled(ActivationCancelledEvent event,
WorkingMemory workingMemory) {
this.consolidated.activationsCancelled.incrementAndGet();
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
data.activationsCancelled.incrementAndGet();
}
public void activationCreated(ActivationCreatedEvent event,
WorkingMemory workingMemory) {
this.consolidated.activationsCreated.incrementAndGet();
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
data.activationsCreated.incrementAndGet();
}
public void afterActivationFired(AfterActivationFiredEvent event,
WorkingMemory workingMemory) {
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
this.consolidated.stopFireClock();
data.stopFireClock();
this.consolidated.activationsFired.incrementAndGet();
data.activationsFired.incrementAndGet();
}
public void agendaGroupPopped(AgendaGroupPoppedEvent event,
WorkingMemory workingMemory) {
// no stats gathered for now
}
public void agendaGroupPushed(AgendaGroupPushedEvent event,
WorkingMemory workingMemory) {
// no stats gathered for now
}
public void afterRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void afterRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeActivationFired(BeforeActivationFiredEvent event,
WorkingMemory workingMemory) {
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
this.consolidated.startFireClock();
data.startFireClock();
}
private AgendaStatsData getRuleStatsInstance(String ruleName) {
AgendaStatsData data = this.ruleStats.get( ruleName );
if( data == null ) {
data = new AgendaStatsData();
this.ruleStats.put( ruleName, data );
}
return data;
}
public static class AgendaStatsData {
public AtomicLong activationsFired;
public AtomicLong activationsCreated;
public AtomicLong activationsCancelled;
public AtomicLong firingTime;
public AtomicReference<Date> lastReset;
// no need for synch, because two activations cannot fire concurrently
public long start;
public AgendaStatsData() {
this.activationsFired = new AtomicLong(0);
this.activationsCreated = new AtomicLong(0);
this.activationsCancelled = new AtomicLong(0);
this.firingTime = new AtomicLong(0);
this.lastReset = new AtomicReference<Date>(new Date());
}
public void startFireClock() {
this.start = System.nanoTime();
}
public void stopFireClock() {
this.firingTime.addAndGet( System.nanoTime()-this.start );
}
public void reset() {
this.activationsFired.set( 0 );
this.activationsCreated.set( 0 );
this.activationsCancelled.set( 0 );
this.firingTime.set( 0 );
this.lastReset.set( new Date() );
}
public String toString() {
return "activationsCreated="+activationsCreated.get()+" activationsCancelled="+activationsCancelled.get()+
" activationsFired="+this.activationsFired.get()+" firingTime="+(firingTime.get()/NANO_TO_MILLISEC)+"ms";
}
}
}
public long getTotalProcessInstancesStarted() {
return this.processStats.getConsolidatedStats().processInstancesStarted.get();
}
public long getTotalProcessInstancesCompleted() {
return this.processStats.getConsolidatedStats().processInstancesCompleted.get();
}
public String getStatsForProcess( String processId ) {
ProcessStatsData data = this.processStats.getProcessStats( processId );
String result = data == null ? "processInstancesStarted=0 processInstancesCompleted=0 processNodesTriggered=0" : data.toString();
return result;
}
public Map<String,String> getStatsByProcess() {
Map<String, String> result = new HashMap<String, String>();
for( Map.Entry<String, ProcessStatsData> entry : this.processStats.getProcessStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public String getStatsForProcessInstance( long processInstanceId ) {
ProcessInstanceStatsData data = this.processStats.getProcessInstanceStats( processInstanceId );
String result = data == null ? "Process instance not found" : data.toString();
return result;
}
public Map<Long,String> getStatsByProcessInstance() {
Map<Long, String> result = new HashMap<Long, String>();
for( Map.Entry<Long, ProcessInstanceStatsData> entry : this.processStats.getProcessInstanceStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public static class ProcessStats implements ProcessEventListener {
private GlobalProcessStatsData consolidated = new GlobalProcessStatsData();
private ConcurrentHashMap<String, ProcessStatsData> processStats = new ConcurrentHashMap<String, ProcessStatsData>();
private ConcurrentHashMap<Long, ProcessInstanceStatsData> processInstanceStats = new ConcurrentHashMap<Long, ProcessInstanceStatsData>();
public GlobalProcessStatsData getConsolidatedStats() {
return this.consolidated;
}
public Map<String, ProcessStatsData> getProcessStats() {
return this.processStats;
}
public ProcessStatsData getProcessStats(String processId) {
return this.processStats.get(processId);
}
public Map<Long, ProcessInstanceStatsData> getProcessInstanceStats() {
return this.processInstanceStats;
}
public ProcessInstanceStatsData getProcessInstanceStats(Long processInstanceId) {
return this.processInstanceStats.get(processInstanceId);
}
public void reset() {
this.consolidated.reset();
this.processStats.clear();
this.processInstanceStats.clear();
}
private ProcessStatsData getProcessStatsInstance(String processId) {
ProcessStatsData data = this.processStats.get(processId);
if (data == null) {
data = new ProcessStatsData();
this.processStats.put(processId, data);
}
return data;
}
private ProcessInstanceStatsData getProcessInstanceStatsInstance(Long processInstanceId) {
ProcessInstanceStatsData data = this.processInstanceStats.get(processInstanceId);
if (data == null) {
data = new ProcessInstanceStatsData();
this.processInstanceStats.put(processInstanceId, data);
}
return data;
}
public void afterProcessStarted(ProcessStartedEvent event) {
this.consolidated.processInstancesStarted.incrementAndGet();
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processInstancesStarted.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processStarted = new Date();
}
public void afterProcessCompleted(ProcessCompletedEvent event) {
this.consolidated.processInstancesCompleted.incrementAndGet();
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processInstancesCompleted.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processCompleted = new Date();
}
public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processNodesTriggered.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processNodesTriggered++;
}
public void afterNodeLeft(ProcessNodeLeftEvent event) {
// TODO Auto-generated method stub
}
public void beforeNodeLeft(ProcessNodeLeftEvent event) {
// TODO Auto-generated method stub
}
public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
// TODO Auto-generated method stub
}
public void beforeProcessCompleted(ProcessCompletedEvent event) {
// TODO Auto-generated method stub
}
public void beforeProcessStarted(ProcessStartedEvent event) {
// TODO Auto-generated method stub
}
public void afterVariableChanged(ProcessVariableChangedEvent event) {
// TODO Auto-generated method stub
}
public void beforeVariableChanged(ProcessVariableChangedEvent event) {
// TODO Auto-generated method stub
}
public static class GlobalProcessStatsData {
public AtomicLong processInstancesStarted;
public AtomicLong processInstancesCompleted;
public AtomicReference<Date> lastReset;
public GlobalProcessStatsData() {
this.processInstancesStarted = new AtomicLong(0);
this.processInstancesCompleted = new AtomicLong(0);
this.lastReset = new AtomicReference<Date>(new Date());
}
public void reset() {
this.processInstancesStarted.set( 0 );
this.processInstancesCompleted.set( 0 );
this.lastReset.set( new Date() );
}
public String toString() {
return "processInstancesStarted=" + processInstancesStarted.get()
+ " processInstancesCompleted=" + processInstancesCompleted.get();
}
}
public static class ProcessStatsData extends GlobalProcessStatsData {
public AtomicLong processNodesTriggered;
public ProcessStatsData() {
this.processNodesTriggered = new AtomicLong(0);
}
public void reset() {
super.reset();
this.processNodesTriggered.set( 0 );
}
public String toString() {
return super.toString() + " processNodesTriggered=" + processNodesTriggered.get();
}
}
public static class ProcessInstanceStatsData {
// no need for synch, because one process instance cannot be executed concurrently
public Date processStarted;
public Date processCompleted;
public long processNodesTriggered;
public ProcessInstanceStatsData() {
this.processNodesTriggered = 0;
}
public void reset() {
this.processNodesTriggered = 0;
}
public String toString() {
return
(processStarted != null ? "processStarted=" + processStarted + " ": "") +
(processCompleted != null ? "processCompleted=" + processCompleted + " ": "") +
"processNodesTriggered=" + processNodesTriggered;
}
}
}
}
|
drools-core/src/main/java/org/drools/management/KnowledgeSessionMonitoring.java
|
/**
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.management;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.management.ObjectName;
import org.drools.WorkingMemory;
import org.drools.common.InternalRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.event.ActivationCancelledEvent;
import org.drools.event.ActivationCreatedEvent;
import org.drools.event.AfterActivationFiredEvent;
import org.drools.event.AgendaEventListener;
import org.drools.event.AgendaGroupPoppedEvent;
import org.drools.event.AgendaGroupPushedEvent;
import org.drools.event.BeforeActivationFiredEvent;
import org.drools.event.RuleFlowGroupActivatedEvent;
import org.drools.event.RuleFlowGroupDeactivatedEvent;
import org.drools.event.process.ProcessCompletedEvent;
import org.drools.event.process.ProcessEventListener;
import org.drools.event.process.ProcessNodeLeftEvent;
import org.drools.event.process.ProcessNodeTriggeredEvent;
import org.drools.event.process.ProcessStartedEvent;
import org.drools.event.process.ProcessVariableChangedEvent;
import org.drools.management.KnowledgeSessionMonitoring.AgendaStats.AgendaStatsData;
import org.drools.management.KnowledgeSessionMonitoring.ProcessStats.ProcessInstanceStatsData;
import org.drools.management.KnowledgeSessionMonitoring.ProcessStats.ProcessStatsData;
/**
* An MBean to monitor a given knowledge session
*
* @author etirelli
*/
public class KnowledgeSessionMonitoring implements KnowledgeSessionMonitoringMBean {
private static final String KSESSION_PREFIX = "org.drools.kbases";
private static final long NANO_TO_MILLISEC = 1000000;
private InternalWorkingMemory ksession;
private InternalRuleBase kbase;
private ObjectName name;
public AgendaStats agendaStats;
public ProcessStats processStats;
public KnowledgeSessionMonitoring(InternalWorkingMemory ksession) {
this.ksession = ksession;
this.kbase = (InternalRuleBase) ksession.getRuleBase();
this.name = DroolsManagementAgent.createObjectName(KSESSION_PREFIX + ":type="+kbase.getId()+",group=Sessions,sessionId=Session-"+ksession.getId());
this.agendaStats = new AgendaStats();
this.processStats = new ProcessStats();
this.ksession.addEventListener( agendaStats );
if (ksession.getProcessRuntime() != null) {
this.ksession.getProcessRuntime().addEventListener( processStats );
}
}
public void dispose() {
this.ksession.removeEventListener( agendaStats );
if (ksession.getProcessRuntime() != null) {
this.ksession.getProcessRuntime().removeEventListener( processStats );
}
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#reset()
*/
public void reset() {
this.agendaStats.reset();
this.processStats.reset();
}
public InternalWorkingMemory getKsession() {
return ksession;
}
public InternalRuleBase getKbase() {
return kbase;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getName()
*/
public ObjectName getName() {
return name;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getKnowledgeBaseId()
*/
public String getKnowledgeBaseId() {
return kbase.getId();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getKnowledgeSessionId()
*/
public long getKnowledgeSessionId() {
return ksession.getId();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalFactCount()
*/
public long getTotalFactCount() {
return ksession.getTotalFactCount();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsFired()
*/
public long getTotalActivationsFired() {
return this.agendaStats.getConsolidatedStats().activationsFired.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsCancelled()
*/
public long getTotalActivationsCancelled() {
return this.agendaStats.getConsolidatedStats().activationsCancelled.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalActivationsCreated()
*/
public long getTotalActivationsCreated() {
return this.agendaStats.getConsolidatedStats().activationsCreated.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getTotalFiringTime()
*/
public long getTotalFiringTime() {
// converting nano secs to milli secs
return this.agendaStats.getConsolidatedStats().firingTime.get()/NANO_TO_MILLISEC;
}
public Date getLastReset() {
return this.agendaStats.getConsolidatedStats().lastReset.get();
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getAverageFiringTime()
*/
public double getAverageFiringTime() {
long fires = this.agendaStats.getConsolidatedStats().activationsFired.get();
long time = this.agendaStats.getConsolidatedStats().firingTime.get();
// calculating the average and converting it from nano secs to milli secs
return fires > 0 ? (((double) time / (double) fires) / (double) NANO_TO_MILLISEC) : 0;
}
/* (non-Javadoc)
* @see org.drools.management.KnowledgeSessionMonitoringMBean#getStatsForRule(java.lang.String)
*/
public String getStatsForRule( String ruleName ) {
AgendaStatsData data = this.agendaStats.getRuleStats( ruleName );
String result = data == null ? "activationsCreated=0 activationsCancelled=0 activationsFired=0 firingTime=0ms" : data.toString();
return result;
}
public Map<String,String> getStatsByRule() {
Map<String, String> result = new HashMap<String, String>();
for( Map.Entry<String, AgendaStatsData> entry : this.agendaStats.getRulesStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public static class AgendaStats implements AgendaEventListener {
private AgendaStatsData consolidated = new AgendaStatsData();
private ConcurrentHashMap<String, AgendaStatsData> ruleStats = new ConcurrentHashMap<String, AgendaStatsData>();
public AgendaStats() {
}
public AgendaStatsData getConsolidatedStats() {
return this.consolidated;
}
public Map<String, AgendaStatsData> getRulesStats() {
return this.ruleStats;
}
public AgendaStatsData getRuleStats( String ruleName ) {
return this.ruleStats.get( ruleName );
}
public void reset() {
this.consolidated.reset();
this.ruleStats.clear();
}
public void activationCancelled(ActivationCancelledEvent event,
WorkingMemory workingMemory) {
this.consolidated.activationsCancelled.incrementAndGet();
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
data.activationsCancelled.incrementAndGet();
}
public void activationCreated(ActivationCreatedEvent event,
WorkingMemory workingMemory) {
this.consolidated.activationsCreated.incrementAndGet();
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
data.activationsCreated.incrementAndGet();
}
public void afterActivationFired(AfterActivationFiredEvent event,
WorkingMemory workingMemory) {
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
this.consolidated.stopFireClock();
data.stopFireClock();
this.consolidated.activationsFired.incrementAndGet();
data.activationsFired.incrementAndGet();
}
public void agendaGroupPopped(AgendaGroupPoppedEvent event,
WorkingMemory workingMemory) {
// no stats gathered for now
}
public void agendaGroupPushed(AgendaGroupPushedEvent event,
WorkingMemory workingMemory) {
// no stats gathered for now
}
public void afterRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void afterRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeRuleFlowGroupActivated(
RuleFlowGroupActivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeRuleFlowGroupDeactivated(
RuleFlowGroupDeactivatedEvent event, WorkingMemory workingMemory) {
// no stats gathered for now
}
public void beforeActivationFired(BeforeActivationFiredEvent event,
WorkingMemory workingMemory) {
AgendaStatsData data = getRuleStatsInstance( event.getActivation().getRule().getName() );
this.consolidated.startFireClock();
data.startFireClock();
}
private AgendaStatsData getRuleStatsInstance(String ruleName) {
AgendaStatsData data = this.ruleStats.get( ruleName );
if( data == null ) {
data = new AgendaStatsData();
this.ruleStats.put( ruleName, data );
}
return data;
}
public static class AgendaStatsData {
public AtomicLong activationsFired;
public AtomicLong activationsCreated;
public AtomicLong activationsCancelled;
public AtomicLong firingTime;
public AtomicReference<Date> lastReset;
// no need for synch, because two activations cannot fire concurrently
public long start;
public AgendaStatsData() {
this.activationsFired = new AtomicLong(0);
this.activationsCreated = new AtomicLong(0);
this.activationsCancelled = new AtomicLong(0);
this.firingTime = new AtomicLong(0);
this.lastReset = new AtomicReference<Date>(new Date());
}
public void startFireClock() {
this.start = System.nanoTime();
}
public void stopFireClock() {
this.firingTime.addAndGet( System.nanoTime()-this.start );
}
public void reset() {
this.activationsFired.set( 0 );
this.activationsCreated.set( 0 );
this.activationsCancelled.set( 0 );
this.firingTime.set( 0 );
this.lastReset.set( new Date() );
}
public String toString() {
return "activationsCreated="+activationsCreated.get()+" activationsCancelled="+activationsCancelled.get()+
" activationsFired="+this.activationsFired.get()+" firingTime="+(firingTime.get()/NANO_TO_MILLISEC)+"ms";
}
}
}
public long getTotalProcessInstancesStarted() {
return this.processStats.getConsolidatedStats().processInstancesStarted.get();
}
public long getTotalProcessInstancesCompleted() {
return this.processStats.getConsolidatedStats().processInstancesCompleted.get();
}
public String getStatsForProcess( String processId ) {
ProcessStatsData data = this.processStats.getProcessStats( processId );
String result = data == null ? "processInstancesStarted=0 processInstancesCompleted=0 processNodesTriggered=0" : data.toString();
return result;
}
public Map<String,String> getStatsByProcess() {
Map<String, String> result = new HashMap<String, String>();
for( Map.Entry<String, ProcessStatsData> entry : this.processStats.getProcessStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public String getStatsForProcessInstance( long processInstanceId ) {
ProcessInstanceStatsData data = this.processStats.getProcessInstanceStats( processInstanceId );
String result = data == null ? "Process instance not found" : data.toString();
return result;
}
public Map<Long,String> getStatsByProcessInstance() {
Map<Long, String> result = new HashMap<Long, String>();
for( Map.Entry<Long, ProcessInstanceStatsData> entry : this.processStats.getProcessInstanceStats().entrySet() ) {
result.put( entry.getKey(), entry.getValue().toString() );
}
return result;
}
public static class ProcessStats implements ProcessEventListener {
private GlobalProcessStatsData consolidated = new GlobalProcessStatsData();
private ConcurrentHashMap<String, ProcessStatsData> processStats = new ConcurrentHashMap<String, ProcessStatsData>();
private ConcurrentHashMap<Long, ProcessInstanceStatsData> processInstanceStats = new ConcurrentHashMap<Long, ProcessInstanceStatsData>();
public GlobalProcessStatsData getConsolidatedStats() {
return this.consolidated;
}
public Map<String, ProcessStatsData> getProcessStats() {
return this.processStats;
}
public ProcessStatsData getProcessStats(String processId) {
return this.processStats.get(processId);
}
public Map<Long, ProcessInstanceStatsData> getProcessInstanceStats() {
return this.processInstanceStats;
}
public ProcessInstanceStatsData getProcessInstanceStats(Long processInstanceId) {
return this.processInstanceStats.get(processInstanceId);
}
public void reset() {
this.consolidated.reset();
this.processStats.clear();
this.processInstanceStats.clear();
}
private ProcessStatsData getProcessStatsInstance(String processId) {
ProcessStatsData data = this.processStats.get(processId);
if (data == null) {
data = new ProcessStatsData();
this.processStats.put(processId, data);
}
return data;
}
private ProcessInstanceStatsData getProcessInstanceStatsInstance(Long processInstanceId) {
ProcessInstanceStatsData data = this.processInstanceStats.get(processInstanceId);
if (data == null) {
data = new ProcessInstanceStatsData();
this.processInstanceStats.put(processInstanceId, data);
}
return data;
}
public void afterProcessStarted(ProcessStartedEvent event) {
this.consolidated.processInstancesStarted.incrementAndGet();
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processInstancesStarted.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processStarted = new Date();
}
public void afterProcessCompleted(ProcessCompletedEvent event) {
this.consolidated.processInstancesCompleted.incrementAndGet();
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processInstancesCompleted.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processCompleted = new Date();
}
public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
ProcessStatsData data = getProcessStatsInstance(event.getProcessInstance().getProcessId());
data.processNodesTriggered.incrementAndGet();
ProcessInstanceStatsData dataI = getProcessInstanceStatsInstance(event.getProcessInstance().getId());
dataI.processNodesTriggered++;
}
public void afterNodeLeft(ProcessNodeLeftEvent event) {
// TODO Auto-generated method stub
}
public void beforeNodeLeft(ProcessNodeLeftEvent event) {
// TODO Auto-generated method stub
}
public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
// TODO Auto-generated method stub
}
public void beforeProcessCompleted(ProcessCompletedEvent event) {
// TODO Auto-generated method stub
}
public void beforeProcessStarted(ProcessStartedEvent event) {
// TODO Auto-generated method stub
}
public void afterVariableChanged(ProcessVariableChangedEvent event) {
// TODO Auto-generated method stub
}
public void beforeVariableChanged(ProcessVariableChangedEvent event) {
// TODO Auto-generated method stub
}
public static class GlobalProcessStatsData {
public AtomicLong processInstancesStarted;
public AtomicLong processInstancesCompleted;
public AtomicReference<Date> lastReset;
public GlobalProcessStatsData() {
this.processInstancesStarted = new AtomicLong(0);
this.processInstancesCompleted = new AtomicLong(0);
this.lastReset = new AtomicReference<Date>(new Date());
}
public void reset() {
this.processInstancesStarted.set( 0 );
this.processInstancesCompleted.set( 0 );
this.lastReset.set( new Date() );
}
public String toString() {
return "processInstancesStarted=" + processInstancesStarted.get()
+ " processInstancesCompleted=" + processInstancesCompleted.get();
}
}
public static class ProcessStatsData extends GlobalProcessStatsData {
public AtomicLong processNodesTriggered;
public ProcessStatsData() {
this.processNodesTriggered = new AtomicLong(0);
}
public void reset() {
super.reset();
this.processNodesTriggered.set( 0 );
}
public String toString() {
return super.toString() + " processNodesTriggered=" + processNodesTriggered.get();
}
}
public static class ProcessInstanceStatsData {
// no need for synch, because one process instance cannot be executed concurrently
public Date processStarted;
public Date processCompleted;
public long processNodesTriggered;
public ProcessInstanceStatsData() {
this.processNodesTriggered = 0;
}
public void reset() {
this.processNodesTriggered = 0;
}
public String toString() {
return
(processStarted != null ? "processStarted=" + processStarted + " ": "") +
(processCompleted != null ? "processCompleted=" + processCompleted + " ": "") +
"processNodesTriggered=" + processNodesTriggered;
}
}
}
}
|
JBRULES-2835: fixing missing long sessionId
|
drools-core/src/main/java/org/drools/management/KnowledgeSessionMonitoring.java
|
JBRULES-2835: fixing missing long sessionId
|
|
Java
|
apache-2.0
|
6c46ebebf5c6462e1c693439d469a1b622b22381
| 0
|
nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,trombonehero/Footlights
|
package me.footlights.core.crypto;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.annotations.VisibleForTesting;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import me.footlights.HasBytes;
import me.footlights.core.Config;
import me.footlights.core.ConfigurationError;
/** A fingerprint for a number of bytes. */
public class Fingerprint
{
public static Fingerprint decode(String name)
throws Base64DecodingException, NoSuchAlgorithmException
{
String parts[] = name.replaceAll("\\+", "/").split(":");
MessageDigest algorithm = MessageDigest.getInstance(parts[0]);
return new Fingerprint(algorithm, ByteBuffer.wrap(Base64.decode(parts[1])));
}
public static Builder newBuilder() { return new Builder(); }
public String encode()
{
StringBuffer sb = new StringBuffer();
sb.append(algorithm.getAlgorithm().toLowerCase());
sb.append(":");
sb.append(Base64.encode(bytes.array()).replaceAll("/", "+"));
return sb.toString();
}
public MessageDigest getAlgorithm() { return algorithm; }
public boolean matches(ByteBuffer b) { return (0 == bytes.compareTo(b)); }
public boolean matches(byte[] b) { return matches(ByteBuffer.wrap(b)); }
public ByteBuffer getBytes() { return bytes.asReadOnlyBuffer(); }
public byte[] copyBytes()
{
byte[] copy = new byte[bytes.remaining()];
bytes.get(copy);
return copy;
}
public static class Builder
{
public Fingerprint build()
{
ByteBuffer hash = ByteBuffer.wrap(algorithm.digest(bytes));
return new Fingerprint(algorithm, hash);
}
public Builder setAlgorithm(String a) throws NoSuchAlgorithmException
{
algorithm = MessageDigest.getInstance(a);
return this;
}
public Builder setContent(byte[] b) { bytes = b; return this; }
public Builder setContent(HasBytes h) { return setContent(h.getBytes()); }
public Builder setContent(ByteBuffer b)
{
if (b.isReadOnly())
{
bytes = new byte[b.remaining()];
b.get(bytes);
}
else bytes = b.array();
return this;
}
private Builder()
{
try
{
algorithm = MessageDigest.getInstance(
Config.getInstance().get("crypto.hash.algorithm"));
}
catch (NoSuchAlgorithmException e)
{
throw new ConfigurationError("Invalid hash algorithm: " + e);
}
}
private MessageDigest algorithm;
private byte[] bytes;
}
@Override public boolean equals(Object o)
{
if (!(o instanceof Fingerprint)) return false;
Fingerprint f = (Fingerprint) o;
if (!algorithm.getAlgorithm().equals(f.algorithm.getAlgorithm())) return false;
if (bytes.compareTo(f.bytes) != 0) return false;
return true;
}
@VisibleForTesting String hex() { return Hex.encodeHexString(bytes.array()); }
private Fingerprint(MessageDigest hashAlgorithm, ByteBuffer fingerprintBytes)
{
this.algorithm = hashAlgorithm;
this.bytes = fingerprintBytes;
}
private MessageDigest algorithm;
private ByteBuffer bytes;
}
|
Client/Core/src/main/java/me/footlights/core/crypto/Fingerprint.java
|
package me.footlights.core.crypto;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.annotations.VisibleForTesting;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import me.footlights.HasBytes;
import me.footlights.core.Config;
import me.footlights.core.ConfigurationError;
/** A fingerprint for a number of bytes. */
public class Fingerprint
{
public static Fingerprint decode(String name)
throws Base64DecodingException, NoSuchAlgorithmException
{
String parts[] = name.replaceAll("\\+", "/").split(":");
MessageDigest algorithm = MessageDigest.getInstance(parts[0]);
return new Fingerprint(algorithm, ByteBuffer.wrap(Base64.decode(parts[1])));
}
public static Builder newBuilder() { return new Builder(); }
public String encode()
{
StringBuffer sb = new StringBuffer();
sb.append(algorithm.getAlgorithm().toLowerCase());
sb.append(":");
sb.append(Base64.encode(bytes.array()).replaceAll("/", "+"));
return sb.toString();
}
public MessageDigest getAlgorithm() { return algorithm; }
public boolean matches(ByteBuffer b) { return (0 == bytes.compareTo(b)); }
public boolean matches(byte[] b) { return matches(ByteBuffer.wrap(b)); }
public ByteBuffer getBytes() { return bytes.asReadOnlyBuffer(); }
public static class Builder
{
public Fingerprint build()
{
ByteBuffer hash = ByteBuffer.wrap(algorithm.digest(bytes));
return new Fingerprint(algorithm, hash);
}
public Builder setAlgorithm(String a) throws NoSuchAlgorithmException
{
algorithm = MessageDigest.getInstance(a);
return this;
}
public Builder setContent(byte[] b) { bytes = b; return this; }
public Builder setContent(HasBytes h) { return setContent(h.getBytes()); }
public Builder setContent(ByteBuffer b)
{
if (b.isReadOnly())
{
bytes = new byte[b.remaining()];
b.get(bytes);
}
else bytes = b.array();
return this;
}
private Builder()
{
try
{
algorithm = MessageDigest.getInstance(
Config.getInstance().get("crypto.hash.algorithm"));
}
catch (NoSuchAlgorithmException e)
{
throw new ConfigurationError("Invalid hash algorithm: " + e);
}
}
private MessageDigest algorithm;
private byte[] bytes;
}
@Override public boolean equals(Object o)
{
if (!(o instanceof Fingerprint)) return false;
Fingerprint f = (Fingerprint) o;
if (!algorithm.getAlgorithm().equals(f.algorithm.getAlgorithm())) return false;
if (bytes.compareTo(f.bytes) != 0) return false;
return true;
}
@VisibleForTesting String hex() { return Hex.encodeHexString(bytes.array()); }
private Fingerprint(MessageDigest hashAlgorithm, ByteBuffer fingerprintBytes)
{
this.algorithm = hashAlgorithm;
this.bytes = fingerprintBytes;
}
private MessageDigest algorithm;
private ByteBuffer bytes;
}
|
Add Fingerprint.copyBytes().
|
Client/Core/src/main/java/me/footlights/core/crypto/Fingerprint.java
|
Add Fingerprint.copyBytes().
|
|
Java
|
apache-2.0
|
d7cc4a0597f29c202cc12226dd754737f44ef029
| 0
|
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.graphgeckos.dashboard.storage;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.DatastoreOptions.DefaultDatastoreFactory;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.StructuredQuery.OrderBy;
import com.google.graphgeckos.dashboard.datatypes.BuildBotData;
import com.google.graphgeckos.dashboard.datatypes.BuildInfo;
import com.google.graphgeckos.dashboard.datatypes.GitHubData;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import org.springframework.cloud.gcp.data.datastore.core.DatastoreTemplate;
import org.springframework.cloud.gcp.data.datastore.core.convert.DatastoreServiceObjectToKeyFactory;
import org.springframework.cloud.gcp.data.datastore.core.convert.DefaultDatastoreEntityConverter;
import org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
/**
* A DataRepository implementation backed up by Google Datastore.
* Each database entry is modeled by the {@link #BuildInfo BuildInfo} class.
* The relevant fields for the database are:
* - Kind: "revision"
* - Key: commit hash
*
* Useful links:
* - https://googleapis.dev/java/google-cloud-datastore/latest/index.html
* - https://googleapis.dev/java/spring-cloud-gcp/1.2.2.RELEASE/index.html
* - https://cloud.google.com/datastore/docs/concepts/
* - https://spring.io/projects/spring-cloud-gcp#overview
*/
@Repository
public class DatastoreRepository implements DataRepository {
private DatastoreTemplate storage;
public DatastoreRepository(@NonNull Datastore underlyingStorage) {
Objects.requireNonNull(underlyingStorage);
Supplier<Datastore> supplier = () -> underlyingStorage;
DatastoreMappingContext mappingContext = new DatastoreMappingContext();
DatastoreServiceObjectToKeyFactory objectToKeyFactory =
new DatastoreServiceObjectToKeyFactory(supplier);
DefaultDatastoreEntityConverter entityConverter =
new DefaultDatastoreEntityConverter(mappingContext, objectToKeyFactory);
storage = new DatastoreTemplate(supplier, entityConverter, mappingContext, objectToKeyFactory);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code entryData} is null.
*/
@Override
public boolean createRevisionEntry(@NonNull GitHubData entryData) {
Objects.requireNonNull(entryData);
if (getRevisionEntry(entryData.getCommitHash()) != null) {
return false;
}
try {
storage.save(new BuildInfo(entryData));
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code updateData} is null.
*/
@Override
public boolean updateRevisionEntry(@NonNull BuildBotData updateData) {
Objects.requireNonNull(updateData);
BuildInfo associatedEntity = getRevisionEntry(updateData.getCommitHash());
if (associatedEntity == null) {
return false;
}
try {
storage.save(associatedEntity);
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code commitHash} is null.
*/
@Override
public boolean deleteRevisionEntry(@NonNull String commitHash) {
Objects.requireNonNull(commitHash);
BuildInfo toBeDeleted = getRevisionEntry(commitHash);
if (toBeDeleted == null) {
return true;
}
try {
storage.delete(toBeDeleted);
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public List<BuildInfo> getLastRevisionEntries(int number, int offset)
throws IllegalArgumentException {
if (number < 0 || offset < 0) {
throw new IllegalArgumentException("Both number and offset must be >= 0");
}
Query<Entity> query = Query.newEntityQueryBuilder()
.setKind("revision")
.setOrderBy(OrderBy.desc("timestamp"))
.setOffset(offset)
.setLimit(number)
.build();
List<BuildInfo> toBeReturned = new ArrayList<>();
storage.query(query, BuildInfo.class).getIterable().forEach(toBeReturned::add);
return toBeReturned;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code commitHash} is null.
*/
@Override
public BuildInfo getRevisionEntry(@NonNull String commitHash) {
Objects.requireNonNull(commitHash);
return storage.findById(commitHash, BuildInfo.class);
}
}
@Configuration
class DatastoreRepositoryConfig {
DefaultDatastoreFactory datastoreFactory = new DefaultDatastoreFactory();
@Bean
DatastoreRepository datastoreRepository() {
return new DatastoreRepository(datastoreFactory.create(DatastoreOptions.getDefaultInstance()));
}
}
|
src/main/java/com/google/graphgeckos/dashboard/storage/DatastoreRepository.java
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.graphgeckos.dashboard.storage;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.StructuredQuery.OrderBy;
import com.google.graphgeckos.dashboard.datatypes.BuildBotData;
import com.google.graphgeckos.dashboard.datatypes.BuildInfo;
import com.google.graphgeckos.dashboard.datatypes.GitHubData;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import org.springframework.cloud.gcp.data.datastore.core.DatastoreTemplate;
import org.springframework.cloud.gcp.data.datastore.core.convert.DatastoreServiceObjectToKeyFactory;
import org.springframework.cloud.gcp.data.datastore.core.convert.DefaultDatastoreEntityConverter;
import org.springframework.cloud.gcp.data.datastore.core.mapping.DatastoreMappingContext;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Repository;
/**
* A DataRepository implementation backed up by Google Datastore.
* Each database entry is modeled by the {@link #BuildInfo BuildInfo} class.
* The relevant fields for the database are:
* - Kind: "revision"
* - Key: commit hash
*
* Useful links:
* - https://googleapis.dev/java/google-cloud-datastore/latest/index.html
* - https://googleapis.dev/java/spring-cloud-gcp/1.2.2.RELEASE/index.html
* - https://cloud.google.com/datastore/docs/concepts/
* - https://spring.io/projects/spring-cloud-gcp#overview
*/
@Repository
public class DatastoreRepository implements DataRepository {
private DatastoreTemplate storage;
public DatastoreRepository(@NonNull Datastore underlyingStorage) {
Objects.requireNonNull(underlyingStorage);
Supplier<Datastore> supplier = () -> underlyingStorage;
DatastoreMappingContext mappingContext = new DatastoreMappingContext();
DatastoreServiceObjectToKeyFactory objectToKeyFactory =
new DatastoreServiceObjectToKeyFactory(supplier);
DefaultDatastoreEntityConverter entityConverter =
new DefaultDatastoreEntityConverter(mappingContext, objectToKeyFactory);
storage = new DatastoreTemplate(supplier, entityConverter, mappingContext, objectToKeyFactory);
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code entryData} is null.
*/
@Override
public boolean createRevisionEntry(@NonNull GitHubData entryData) {
Objects.requireNonNull(entryData);
if (getRevisionEntry(entryData.getCommitHash()) != null) {
return false;
}
try {
storage.save(new BuildInfo(entryData));
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code updateData} is null.
*/
@Override
public boolean updateRevisionEntry(@NonNull BuildBotData updateData) {
Objects.requireNonNull(updateData);
BuildInfo associatedEntity = getRevisionEntry(updateData.getCommitHash());
if (associatedEntity == null) {
return false;
}
try {
storage.save(associatedEntity);
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code commitHash} is null.
*/
@Override
public boolean deleteRevisionEntry(@NonNull String commitHash) {
Objects.requireNonNull(commitHash);
BuildInfo toBeDeleted = getRevisionEntry(commitHash);
if (toBeDeleted == null) {
return true;
}
try {
storage.delete(toBeDeleted);
} catch (DatastoreException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public List<BuildInfo> getLastRevisionEntries(int number, int offset)
throws IllegalArgumentException {
if (number < 0 || offset < 0) {
throw new IllegalArgumentException("Both number and offset must be >= 0");
}
Query<Entity> query = Query.newEntityQueryBuilder()
.setKind("revision")
.setOrderBy(OrderBy.desc("timestamp"))
.setOffset(offset)
.setLimit(number)
.build();
List<BuildInfo> toBeReturned = new ArrayList<>();
storage.query(query, BuildInfo.class).getIterable().forEach(toBeReturned::add);
return toBeReturned;
}
/**
* {@inheritDoc}
*
* @throws NullPointerException if the {@code commitHash} is null.
*/
@Override
public BuildInfo getRevisionEntry(@NonNull String commitHash) {
Objects.requireNonNull(commitHash);
return storage.findById(commitHash, BuildInfo.class);
}
}
|
add config class
|
src/main/java/com/google/graphgeckos/dashboard/storage/DatastoreRepository.java
|
add config class
|
|
Java
|
apache-2.0
|
cfce68cf8f4d4a4f0f5d0579e514b388fda58f04
| 0
|
phambryan/dropwizard,dropwizard/dropwizard,phambryan/dropwizard,dropwizard/dropwizard,dropwizard/dropwizard,phambryan/dropwizard
|
package io.dropwizard.client;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.client.ssl.TlsConfiguration;
import io.dropwizard.setup.Environment;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.util.Duration;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.glassfish.jersey.client.ClientResponse;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.security.Security;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
@ExtendWith(DropwizardExtensionsSupport.class)
public class DropwizardSSLConnectionSocketFactoryTest {
private TlsConfiguration tlsConfiguration;
private JerseyClientConfiguration jerseyClientConfiguration;
@Path("/")
public static class TestResource {
@GET
public Response respondOk() {
return Response.ok().build();
}
}
public static class TlsTestApplication extends Application<Configuration> {
public static void main(String[] args) throws Exception {
new TlsTestApplication().run(args);
}
@Override
public void run(Configuration configuration, Environment environment) {
environment.jersey().register(TestResource.class);
}
}
static {
Security.addProvider(new BouncyCastleProvider());
}
@AfterAll
static void classTearDown() {
Security.removeProvider(PROVIDER_NAME);
}
private static final DropwizardAppExtension<Configuration> TLS_APP_RULE = new DropwizardAppExtension<>(TlsTestApplication.class,
ResourceHelpers.resourceFilePath("yaml/ssl_connection_socket_factory_test.yml"),
"tls",
ConfigOverride.config("tls", "server.applicationConnectors[0].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[1].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/self_sign_keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[2].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[2].trustStorePath", ResourceHelpers.resourceFilePath("stores/server/ca_truststore.ts")),
ConfigOverride.config("tls", "server.applicationConnectors[2].wantClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[2].needClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[2].validatePeers", "false"),
ConfigOverride.config("tls", "server.applicationConnectors[2].trustStorePassword", "password"),
ConfigOverride.config("tls", "server.applicationConnectors[3].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/bad_host_keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[4].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[4].supportedProtocols", "SSLv1,SSLv2,SSLv3"),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/acme-weak.keystore.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStorePath", ResourceHelpers.resourceFilePath("stores/server/acme-weak.truststore.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[5].wantClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].needClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].validatePeers", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStorePassword", "acme2"),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStorePassword", "acme2"),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStoreProvider", PROVIDER_NAME),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStoreProvider", PROVIDER_NAME));
@BeforeEach
void setUp() {
tlsConfiguration = new TlsConfiguration();
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/ca_truststore.ts")));
tlsConfiguration.setTrustStorePassword("password");
jerseyClientConfiguration = new JerseyClientConfiguration();
jerseyClientConfiguration.setTlsConfiguration(tlsConfiguration);
jerseyClientConfiguration.setConnectionTimeout(Duration.milliseconds(2000));
jerseyClientConfiguration.setTimeout(Duration.milliseconds(5000));
}
@Test
void configOnlyConstructorShouldSetNullCustomVerifier() {
assertThat(new DropwizardSSLConnectionSocketFactory(tlsConfiguration).verifier).isNull();
}
@Test
void shouldReturn200IfServerCertInTruststore() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("tls_working_client");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfServerCertNotFoundInTruststore() {
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/other_cert_truststore.ts")));
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("tls_broken_client");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get())
.withCauseInstanceOf(SSLHandshakeException.class);
}
@Test
void shouldNotErrorIfServerCertSelfSignedAndSelfSignedCertsAllowed() {
tlsConfiguration.setTrustSelfSignedCertificates(true);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("self_sign_permitted");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getTestSupport().getPort(1))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfServerCertSelfSignedAndSelfSignedCertsNotAllowed() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("self_sign_failure");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(1))).request().get(ClientResponse.class))
.withCauseInstanceOf(SSLHandshakeException.class);
}
@Test
void shouldReturn200IfAbleToClientAuth() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/keycert.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfClientAuthFails() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/self_sign_keycert.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldReturn200IfAbleToClientAuthSpecifyingCertAliasForGoodCert() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("1");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_cert_alias_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfTryToClientAuthSpecifyingCertAliasForBadCert() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("2");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_cert_alias_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldErrorIfTryToClientAuthSpecifyingUnknownCertAlias() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("unknown");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_unknown_cert_alias_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldErrorIfHostnameVerificationOnAndServerHostnameDoesntMatch() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("bad_host_broken");
final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get());
assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class);
assertThat(exn.getCause()).hasMessage("Certificate for <localhost> doesn't match any of the subject alternative names: []");
}
@Test
void shouldErrorIfHostnameVerificationOnAndServerHostnameMatchesAndFailVerifierSpecified() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new FailVerifier()).build("bad_host_broken_fail_verifier");
final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get());
assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class);
assertThat(exn.getCause()).hasMessage("Certificate for <localhost> doesn't match any of the subject alternative names: []");
}
@Test
void shouldBeOkIfHostnameVerificationOnAndServerHostnameDoesntMatchAndNoopVerifierSpecified() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new NoopHostnameVerifier()).build("bad_host_noop_verifier_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldBeOkIfHostnameVerificationOffAndServerHostnameDoesntMatch() {
tlsConfiguration.setVerifyHostname(false);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("bad_host_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldBeOkIfHostnameVerificationOffAndServerHostnameMatchesAndFailVerfierSpecified() {
tlsConfiguration.setVerifyHostname(false);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new FailVerifier()).build("bad_host_fail_verifier_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldRejectNonSupportedProtocols() {
tlsConfiguration.setSupportedProtocols(Collections.singletonList("TLSv1.2"));
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("reject_non_supported");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(4))).request().get())
.withRootCauseInstanceOf(IOException.class);
}
@Test
void shouldSucceedWithBcProvider() {
// switching host verifier off for simplicity
tlsConfiguration.setVerifyHostname(false);
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/acme-weak.keystore.p12")));
tlsConfiguration.setKeyStorePassword("acme2");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setKeyStoreProvider(PROVIDER_NAME);
tlsConfiguration.setCertAlias("acme-weak");
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/acme-weak.truststore.p12")));
tlsConfiguration.setTrustStorePassword("acme2");
tlsConfiguration.setTrustStoreType("PKCS12");
tlsConfiguration.setTrustStoreProvider(PROVIDER_NAME);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("custom_jce_supported");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(5))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
private static class FailVerifier implements HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return false;
}
}
}
|
dropwizard-client/src/test/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactoryTest.java
|
package io.dropwizard.client;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.client.ssl.TlsConfiguration;
import io.dropwizard.setup.Environment;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit5.DropwizardAppExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.util.Duration;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLInitializationException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.glassfish.jersey.client.ClientResponse;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.security.Security;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME;
@ExtendWith(DropwizardExtensionsSupport.class)
public class DropwizardSSLConnectionSocketFactoryTest {
private TlsConfiguration tlsConfiguration;
private JerseyClientConfiguration jerseyClientConfiguration;
@Path("/")
public static class TestResource {
@GET
public Response respondOk() {
return Response.ok().build();
}
}
public static class TlsTestApplication extends Application<Configuration> {
public static void main(String[] args) throws Exception {
new TlsTestApplication().run(args);
}
@Override
public void run(Configuration configuration, Environment environment) {
environment.jersey().register(TestResource.class);
}
}
static {
Security.addProvider(new BouncyCastleProvider());
}
@AfterAll
static void classTearDown() {
Security.removeProvider(PROVIDER_NAME);
}
private static final DropwizardAppExtension<Configuration> TLS_APP_RULE = new DropwizardAppExtension<>(TlsTestApplication.class,
ResourceHelpers.resourceFilePath("yaml/ssl_connection_socket_factory_test.yml"),
"tls",
ConfigOverride.config("tls", "server.applicationConnectors[0].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[1].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/self_sign_keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[2].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[2].trustStorePath", ResourceHelpers.resourceFilePath("stores/server/ca_truststore.ts")),
ConfigOverride.config("tls", "server.applicationConnectors[2].wantClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[2].needClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[2].validatePeers", "false"),
ConfigOverride.config("tls", "server.applicationConnectors[2].trustStorePassword", "password"),
ConfigOverride.config("tls", "server.applicationConnectors[3].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/bad_host_keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[4].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/keycert.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[4].supportedProtocols", "SSLv1,SSLv2,SSLv3"),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStorePath", ResourceHelpers.resourceFilePath("stores/server/acme-weak.keystore.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStorePath", ResourceHelpers.resourceFilePath("stores/server/acme-weak.truststore.p12")),
ConfigOverride.config("tls", "server.applicationConnectors[5].wantClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].needClientAuth", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].validatePeers", "true"),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStorePassword", "acme2"),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStorePassword", "acme2"),
ConfigOverride.config("tls", "server.applicationConnectors[5].trustStoreProvider", PROVIDER_NAME),
ConfigOverride.config("tls", "server.applicationConnectors[5].keyStoreProvider", PROVIDER_NAME));
@BeforeEach
void setUp() {
tlsConfiguration = new TlsConfiguration();
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/ca_truststore.ts")));
tlsConfiguration.setTrustStorePassword("password");
jerseyClientConfiguration = new JerseyClientConfiguration();
jerseyClientConfiguration.setTlsConfiguration(tlsConfiguration);
jerseyClientConfiguration.setConnectionTimeout(Duration.milliseconds(2000));
jerseyClientConfiguration.setTimeout(Duration.milliseconds(5000));
}
@Test
void configOnlyConstructorShouldSetNullCustomVerifier() {
assertThat(new DropwizardSSLConnectionSocketFactory(tlsConfiguration).verifier).isNull();
}
@Test
void shouldReturn200IfServerCertInTruststore() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("tls_working_client");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfServerCertNotFoundInTruststore() {
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/other_cert_truststore.ts")));
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("tls_broken_client");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get())
.withCauseInstanceOf(SSLHandshakeException.class);
}
@Test
void shouldNotErrorIfServerCertSelfSignedAndSelfSignedCertsAllowed() {
tlsConfiguration.setTrustSelfSignedCertificates(true);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("self_sign_permitted");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getTestSupport().getPort(1))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfServerCertSelfSignedAndSelfSignedCertsNotAllowed() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("self_sign_failure");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(1))).request().get(ClientResponse.class))
.withCauseInstanceOf(SSLHandshakeException.class);
}
@Test
void shouldReturn200IfAbleToClientAuth() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/keycert.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfClientAuthFails() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/self_sign_keycert.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldReturn200IfAbleToClientAuthSpecifyingCertAliasForGoodCert() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("1");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_cert_alias_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldErrorIfTryToClientAuthSpecifyingCertAliasForBadCert() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("2");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_cert_alias_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldErrorIfTryToClientAuthSpecifyingUnknownCertAlias() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/twokeys.p12")));
tlsConfiguration.setKeyStorePassword("password");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("unknown");
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_using_unknown_cert_alias_broken");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get())
.satisfies(e -> assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class, SSLException.class));
}
@Test
void shouldErrorIfHostnameVerificationOnAndServerHostnameDoesntMatch() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("bad_host_broken");
final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get());
assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class);
assertThat(exn.getCause()).hasMessage("Certificate for <localhost> doesn't match any of the subject alternative names: []");
}
@Test
void shouldErrorIfHostnameVerificationOnAndServerHostnameMatchesAndFailVerifierSpecified() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new FailVerifier()).build("bad_host_broken_fail_verifier");
final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get());
assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class);
assertThat(exn.getCause()).hasMessage("Certificate for <localhost> doesn't match any of the subject alternative names: []");
}
@Test
void shouldBeOkIfHostnameVerificationOnAndServerHostnameDoesntMatchAndNoopVerifierSpecified() {
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new NoopHostnameVerifier()).build("bad_host_noop_verifier_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldBeOkIfHostnameVerificationOffAndServerHostnameDoesntMatch() {
tlsConfiguration.setVerifyHostname(false);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("bad_host_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldBeOkIfHostnameVerificationOffAndServerHostnameMatchesAndFailVerfierSpecified() {
tlsConfiguration.setVerifyHostname(false);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new FailVerifier()).build("bad_host_fail_verifier_working");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
void shouldRejectNonSupportedProtocols() {
tlsConfiguration.setSupportedProtocols(Collections.singletonList("TLSv1.2"));
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("reject_non_supported");
assertThatExceptionOfType(ProcessingException.class)
.isThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(4))).request().get())
.withRootCauseInstanceOf(IOException.class);
}
@Test
@EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11})
void shouldFailDueDefaultProviderInsufficiency() {
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/acme-weak.keystore.p12")));
tlsConfiguration.setKeyStorePassword("acme2");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setCertAlias("acme-weak");
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/acme-weak.truststore.p12")));
tlsConfiguration.setTrustStorePassword("acme2");
tlsConfiguration.setTrustStoreType("PKCS12");
assertThatExceptionOfType(SSLInitializationException.class).isThrownBy(() -> new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(
jerseyClientConfiguration).build("reject_provider_non_supported"));
}
@Test
void shouldSucceedWithBcProvider() {
// switching host verifier off for simplicity
tlsConfiguration.setVerifyHostname(false);
tlsConfiguration.setKeyStorePath(new File(ResourceHelpers.resourceFilePath("stores/client/acme-weak.keystore.p12")));
tlsConfiguration.setKeyStorePassword("acme2");
tlsConfiguration.setKeyStoreType("PKCS12");
tlsConfiguration.setKeyStoreProvider(PROVIDER_NAME);
tlsConfiguration.setCertAlias("acme-weak");
tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/acme-weak.truststore.p12")));
tlsConfiguration.setTrustStorePassword("acme2");
tlsConfiguration.setTrustStoreType("PKCS12");
tlsConfiguration.setTrustStoreProvider(PROVIDER_NAME);
final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("custom_jce_supported");
final Response response = client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(5))).request().get();
assertThat(response.getStatus()).isEqualTo(200);
}
private static class FailVerifier implements HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return false;
}
}
}
|
Fix DropwizardSSLConnectionSocketFactoryTest
Java 8u301 and 11.0.12 upgrade the default PKCS12 encryption/MAC algorithms so that `DropwizardSSLConnectionSocketFactoryTest#shouldFailDueDefaultProviderInsufficiency()` wasn't failing anymore.
https://bugs.openjdk.java.net/browse/JDK-8228481
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8153005
|
dropwizard-client/src/test/java/io/dropwizard/client/DropwizardSSLConnectionSocketFactoryTest.java
|
Fix DropwizardSSLConnectionSocketFactoryTest
|
|
Java
|
apache-2.0
|
eca487eae2d78a82191017cfe3a602f69d4a2bdf
| 0
|
tufangorel/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,lmjacksoniii/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,juanavelez/hazelcast,tombujok/hazelcast,mdogan/hazelcast,tkountis/hazelcast,mdogan/hazelcast,mdogan/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,tufangorel/hazelcast,lmjacksoniii/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast
|
/*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.hazelcast.nio.serialization;
import com.hazelcast.internal.serialization.SerializationService;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class AbstractSerializationCompatibilityTest {
protected SerializationService serializationService;
@Test
public void testSampleEncodeDecode() throws IOException {
SerializationV1Dataserializable testData = SerializationV1Dataserializable.createInstanceWithNonNullFields();
Data data = serializationService.toData(testData);
SerializationV1Dataserializable testDataFromSerializer = serializationService.toObject(data);
assertTrue(testData.equals(testDataFromSerializer));
}
@Test
public void testSampleEncodeDecode_with_null_arrays() throws IOException {
SerializationV1Dataserializable testData = new SerializationV1Dataserializable();
Data data = serializationService.toData(testData);
SerializationV1Dataserializable testDataFromSerializer = serializationService.toObject(data);
assertEquals(testData, testDataFromSerializer);
}
@Test
public void testSamplePortableEncodeDecode() throws IOException {
SerializationV1Portable testData = SerializationV1Portable.createInstanceWithNonNullFields();
Data data = serializationService.toData(testData);
SerializationV1Portable testDataFromSerializer = serializationService.toObject(data);
assertTrue(testData.equals(testDataFromSerializer));
}
@Test
public void testSamplePortableEncodeDecode_with_null_arrays() throws IOException {
SerializationV1Portable testDataw = SerializationV1Portable.createInstanceWithNonNullFields();
serializationService.toData(testDataw);
SerializationV1Portable testData = new SerializationV1Portable();
Data data = serializationService.toData(testData);
SerializationV1Portable testDataFromSerializer = serializationService.toObject(data);
assertEquals(testData, testDataFromSerializer);
}
}
|
hazelcast/src/test/java/com/hazelcast/nio/serialization/AbstractSerializationCompatibilityTest.java
|
/*
* Copyright (c) 2014, Oracle America, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Oracle nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.hazelcast.nio.serialization;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class AbstractSerializationCompatibilityTest {
protected SerializationService serializationService;
@Test
public void testSampleEncodeDecode() throws IOException {
SerializationV1Dataserializable testData = SerializationV1Dataserializable.createInstanceWithNonNullFields();
Data data = serializationService.toData(testData);
SerializationV1Dataserializable testDataFromSerializer = serializationService.toObject(data);
assertTrue(testData.equals(testDataFromSerializer));
}
@Test
public void testSampleEncodeDecode_with_null_arrays() throws IOException {
SerializationV1Dataserializable testData = new SerializationV1Dataserializable();
Data data = serializationService.toData(testData);
SerializationV1Dataserializable testDataFromSerializer = serializationService.toObject(data);
assertEquals(testData, testDataFromSerializer);
}
@Test
public void testSamplePortableEncodeDecode() throws IOException {
SerializationV1Portable testData = SerializationV1Portable.createInstanceWithNonNullFields();
Data data = serializationService.toData(testData);
SerializationV1Portable testDataFromSerializer = serializationService.toObject(data);
assertTrue(testData.equals(testDataFromSerializer));
}
@Test
public void testSamplePortableEncodeDecode_with_null_arrays() throws IOException {
SerializationV1Portable testDataw = SerializationV1Portable.createInstanceWithNonNullFields();
serializationService.toData(testDataw);
SerializationV1Portable testData = new SerializationV1Portable();
Data data = serializationService.toData(testData);
SerializationV1Portable testDataFromSerializer = serializationService.toObject(data);
assertEquals(testData, testDataFromSerializer);
}
}
|
Made AbstractSerializationCompatibilityTest abstract, so it is not executed when running all tests via IntelliJ.
|
hazelcast/src/test/java/com/hazelcast/nio/serialization/AbstractSerializationCompatibilityTest.java
|
Made AbstractSerializationCompatibilityTest abstract, so it is not executed when running all tests via IntelliJ.
|
|
Java
|
apache-2.0
|
6b7f5703ef55deff14c5551b25e35d3c6e2ceecc
| 0
|
jvf/scalaris,caijieming-baidu/scalaris,jvf/scalaris,caijieming-baidu/scalaris,scalaris-team/scalaris,scalaris-team/scalaris,scalaris-team/scalaris,scalaris-team/scalaris,jvf/scalaris,caijieming-baidu/scalaris,scalaris-team/scalaris,caijieming-baidu/scalaris,caijieming-baidu/scalaris,jvf/scalaris,caijieming-baidu/scalaris,scalaris-team/scalaris,jvf/scalaris,jvf/scalaris,scalaris-team/scalaris,scalaris-team/scalaris,caijieming-baidu/scalaris,jvf/scalaris
|
/**
* Copyright 2007-2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.data.xml;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import de.zib.scalaris.examples.wikipedia.bliki.MyNamespace;
import de.zib.scalaris.examples.wikipedia.bliki.MyParsingWikiModel;
import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel;
import de.zib.scalaris.examples.wikipedia.data.Page;
import de.zib.scalaris.examples.wikipedia.data.SiteInfo;
/**
* Provides abilities to read an xml wiki dump file and create a category (and
* template) tree.
*
* @author Nico Kruber, kruber@zib.de
*/
public class WikiDumpGetCategoryTreeHandler extends WikiDumpHandler {
private static final int PRINT_PAGES_EVERY = 400;
protected String dbFileName;
protected SQLiteConnection db = null;
protected SQLiteStatement stWritePages = null;
protected SQLiteStatement stWriteCategories = null;
protected SQLiteStatement stWriteTemplates = null;
protected SQLiteStatement stWriteIncludes = null;
protected SQLiteStatement stWriteRedirects = null;
protected SQLiteStatement stWriteLinks = null;
protected Map<String, Integer> pages = new HashMap<String, Integer>();
/**
* Sets up a SAX XmlHandler extracting all categories from all pages except
* the ones in a blacklist to stdout.
*
* @param blacklist
* a number of page titles to ignore
* @param maxTime
* maximum time a revision should have (newer revisions are
* omitted) - <tt>null/tt> imports all revisions
* (useful to create dumps of a wiki at a specific point in time)
* @param dbFileName
* the name of the directory to write categories, templates,
* inclusions etc to
*
* @throws RuntimeException
* if the creation of the SQLite DB fails
*/
public WikiDumpGetCategoryTreeHandler(Set<String> blacklist,
Calendar maxTime, String dbFileName) throws RuntimeException {
super(blacklist, null, 1, maxTime);
this.dbFileName = dbFileName;
}
static SQLiteStatement createReadCategoriesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT category FROM categories WHERE title == ?;");
}
static SQLiteStatement createReadTemplatesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT template FROM templates WHERE title == ?;");
}
static SQLiteStatement createReadIncludesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT include FROM includes WHERE title == ?;");
}
static SQLiteStatement createReadRedirectsStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT redirect FROM redirects WHERE title == ?;");
}
static SQLiteStatement createReadLinksStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT link FROM links WHERE title == ?;");
}
static Set<String> readValues(SQLiteStatement stmt, String key)
throws RuntimeException {
try {
try {
HashSet<String> results = new HashSet<String>();
stmt.bind(1, key);
while (stmt.step()) {
results.add(stmt.columnString(1));
}
return results;
} finally {
stmt.reset();
}
} catch (SQLiteException e) {
System.err.println("read of " + key + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
protected void writeValue(SQLiteStatement stmt, String key, String value)
throws RuntimeException {
writeValues(stmt, key, Arrays.asList(value));
}
protected void writeValues(SQLiteStatement stmt, String key, Collection<? extends String> values)
throws RuntimeException {
Integer key_id = pageToId(key);
LinkedList<Integer> values_id = new LinkedList<Integer>();
for (String value : values) {
values_id.add(pageToId(value));
}
try {
try {
stmt.bind(1, key_id);
for (Integer value_id : values_id) {
stmt.bind(2, value_id).stepThrough().reset(false);
}
} finally {
stmt.reset();
}
} catch (SQLiteException e) {
System.err.println("write of " + key + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
protected Integer pageToId(String pageTitle) throws RuntimeException {
try {
Integer id = pages.get(pageTitle);
if (id == null) {
id = pages.size();
pages.put(pageTitle, id);
try {
stWritePages.bind(1, id).bind(2, pageTitle).stepThrough();
} finally {
stWritePages.reset();
}
}
return id;
} catch (SQLiteException e) {
System.err.println("write of " + pageTitle + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
static void writeSiteInfo(SQLiteConnection db, SiteInfo siteInfo)
throws RuntimeException {
SQLiteStatement stmt = null;
try {
stmt = db.prepare("REPLACE INTO properties (key, value) VALUES (?, ?);");
WikiDumpPrepareSQLiteForScalarisHandler.writeObject(stmt, "siteinfo", siteInfo);
} catch (SQLiteException e) {
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
}
}
static SiteInfo readSiteInfo(SQLiteConnection db) throws RuntimeException {
SQLiteStatement stmt = null;
try {
stmt = db.prepare("SELECT value FROM properties WHERE key == ?");
return WikiDumpPrepareSQLiteForScalarisHandler.readObject(stmt, "siteinfo");
} catch (SQLiteException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
}
}
protected static void updateMap(Map<String, Set<String>> map, String key, String addToValue) {
Set<String> oldValue = map.get(key);
if (oldValue == null) {
oldValue = new HashSet<String>();
map.put(key, oldValue);
}
oldValue.add(addToValue);
}
protected static void updateMap(Map<String, Set<String>> map, String key, Collection<? extends String> addToValues) {
Set<String> oldValue = map.get(key);
if (oldValue == null) {
oldValue = new HashSet<String>(addToValues);
map.put(key, oldValue);
} else {
oldValue.addAll(addToValues);
}
}
/**
* Exports the given siteinfo (nothing to do here).
*
* @param revisions
* the siteinfo to export
*/
@Override
protected void export(XmlSiteInfo siteinfo_xml) {
writeSiteInfo(db, siteinfo_xml.getSiteInfo());
}
/**
* Builds the category tree.
*
* @param page_xml
* the page object extracted from XML
*/
@Override
protected void export(XmlPage page_xml) {
Page page = page_xml.getPage();
if (page.getCurRev() != null && wikiModel != null) {
wikiModel.setUp();
final String pageTitle = page.getTitle();
wikiModel.setPageName(pageTitle);
wikiModel.render(null, page.getCurRev().getText());
// categories:
do {
final Set<String> pageCategories_raw = wikiModel.getCategories().keySet();
ArrayList<String> pageCategories = new ArrayList<String>(pageCategories_raw.size());
for (String cat_raw: pageCategories_raw) {
String category = (wikiModel.getCategoryNamespace() + ":" + cat_raw);
pageCategories.add(category);
}
writeValues(stWriteCategories, pageTitle, pageCategories);
} while(false);
// templates:
do {
final Set<String> pageTemplates_raw = wikiModel.getTemplates();
ArrayList<String> pageTemplates = new ArrayList<String>(pageTemplates_raw.size());
for (String tpl_raw: pageTemplates_raw) {
String template = (wikiModel.getTemplateNamespace() + ":" + tpl_raw);
pageTemplates.add(template);
}
writeValues(stWriteTemplates, pageTitle, pageTemplates);
} while (false);
// includes:
do {
Set<String> pageIncludes = wikiModel.getIncludes();
if (!pageIncludes.isEmpty()) {
writeValues(stWriteIncludes, pageTitle, pageIncludes);
}
} while (false);
// redirections:
do {
String pageRedirLink = wikiModel.getRedirectLink();
if (pageRedirLink != null) {
writeValue(stWriteRedirects, pageTitle, pageRedirLink);
}
} while(false);
// links:
do {
Set<String> pageLinks = wikiModel.getLinks();
if (!pageLinks.isEmpty()) {
writeValues(stWriteLinks, pageTitle, pageLinks);
}
} while(false);
wikiModel.tearDown();
}
++pageCount;
// only export page list every UPDATE_PAGELIST_EVERY pages:
if ((pageCount % PRINT_PAGES_EVERY) == 0) {
msgOut.println("processed pages: " + pageCount);
}
}
/* (non-Javadoc)
* @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#tearDown()
*/
@Override
public void tearDown() {
super.tearDown();
if (db != null) {
db.dispose();
}
importEnd();
}
/**
* Gets all sub categories that belong to a given root category
* (recursively).
*
* @param tree
* the tree of categories or templates as created by
* {@link #readTrees(String, Map, Map, Map, Map)}
* @param root
* a root category or template
*
* @return a set of all sub categories/templates; also includes the root
*/
public static Set<String> getAllChildren(Map<String, Set<String>> tree, String root) {
return getAllChildren(tree, new LinkedList<String>(Arrays.asList(root)));
}
/**
* Gets all sub categories that belong to any of the given root categories
* (recursively).
*
* @param tree
* the tree of categories or templates as created by
* {@link #readTrees(String, Map, Map, Map, Map)}
* @param roots
* a list of root categories or templates
*
* @return a set of all sub categories; also includes the rootCats
*/
public static Set<String> getAllChildren(Map<String, Set<String>> tree, List<String> roots) {
HashSet<String> allChildren = new HashSet<String>(roots);
while (!roots.isEmpty()) {
String curChild = roots.remove(0);
Set<String> subChilds = tree.get(curChild);
if (subChilds != null) {
// only add new categories to the root categories
// (remove already processed ones)
// -> prevents endless loops in circles
Set<String> newCats = new HashSet<String>(subChilds);
newCats.removeAll(allChildren);
allChildren.addAll(subChilds);
roots.addAll(newCats);
}
}
return allChildren;
}
/* (non-Javadoc)
* @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#setUp()
*/
@Override
public void setUp() {
super.setUp();
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
db.exec("CREATE TABLE pages(id INTEGER PRIMARY KEY ASC, title STRING);");
db.exec("CREATE INDEX page_titles ON pages(title);");
db.exec("CREATE TABLE categories(title INTEGER, category INTEGER);");
db.exec("CREATE INDEX cat_titles ON categories(title);");
db.exec("CREATE TABLE templates(title INTEGER, template INTEGER);");
db.exec("CREATE INDEX tpl_titles ON templates(title);");
db.exec("CREATE TABLE includes(title INTEGER, include INTEGER);");
db.exec("CREATE INDEX incl_titles ON includes(title);");
db.exec("CREATE TABLE redirects(title INTEGER, redirect INTEGER);");
db.exec("CREATE INDEX redir_titles ON redirects(title);");
db.exec("CREATE TABLE links(title INTEGER, link INTEGER);");
db.exec("CREATE INDEX lnk_titles ON links(title);");
db.exec("CREATE TABLE properties(key STRING PRIMARY KEY ASC, value);");
stWritePages = db.prepare("INSERT INTO pages (id, title) VALUES (?, ?);");
stWriteCategories = db.prepare("INSERT INTO categories (title, category) VALUES (?, ?);");
stWriteTemplates = db.prepare("INSERT INTO templates (title, template) VALUES (?, ?);");
stWriteIncludes = db.prepare("INSERT INTO includes (title, include) VALUES (?, ?);");
stWriteRedirects = db.prepare("INSERT INTO redirects (title, redirect) VALUES (?, ?);");
stWriteLinks = db.prepare("INSERT INTO links (title, link) VALUES (?, ?);");
} catch (SQLiteException e) {
throw new RuntimeException(e);
}
}
/**
* Reads the given parameter trees from the DB file.
*
* @param dbFileName
* name of the DB file
* @param categoryTree
* information about the categories and their dependencies
* @param templateTree
* information about the templates and their dependencies
* @param includeTree
* information about page includes
* @param referenceTree
* information about references to a page
*
* @throws RuntimeException if any error occurs
*/
public static void readTrees(
String dbFileName,
Map<String, Set<String>> categoryTree,
Map<String, Set<String>> templateTree,
Map<String, Set<String>> includeTree,
Map<String, Set<String>> referenceTree)
throws RuntimeException {
SQLiteConnection db = null;
SQLiteStatement stmt = null;
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
SiteInfo siteInfo = readSiteInfo(db);
MyParsingWikiModel wikiModel = new MyParsingWikiModel("", "", new MyNamespace(siteInfo));
stmt = db
.prepare("SELECT page.title, cat.title FROM " +
"categories INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN pages AS cat ON categories.category == cat.id " +
"WHERE page.title LIKE '" + wikiModel.getCategoryNamespace() + ":%';");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String category = stmt.columnString(1).intern();
updateMap(categoryTree, category, pageTitle);
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, tpl.title FROM " +
"templates INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id " +
"WHERE page.title LIKE '" + wikiModel.getCategoryNamespace() + ":%' OR "
+ "page.title LIKE '" + wikiModel.getTemplateNamespace() + ":%';");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String template = stmt.columnString(1).intern();
final String namespace = MyWikiModel.getNamespace(pageTitle);
updateMap(categoryTree, template, pageTitle);
if (wikiModel.isTemplateNamespace(namespace)) {
updateMap(templateTree, pageTitle, template);
}
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, incl.title FROM " +
"includes INNER JOIN pages AS page ON includes.title == page.id " +
"INNER JOIN pages AS incl ON includes.include == incl.id;");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String include = stmt.columnString(1).intern();
updateMap(includeTree, pageTitle, include);
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, redir.title FROM " +
"redirects INNER JOIN pages AS page ON redirects.title == page.id " +
"INNER JOIN pages AS redir ON redirects.redirect == redir.id;");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String redirect = stmt.columnString(1).intern();
updateMap(referenceTree, redirect, pageTitle);
}
} catch (SQLiteException e) {
System.err.println("read of category tree failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
if (db != null) {
db.dispose();
}
}
}
/**
* Extracts all pages in the given categories from the given DB.
*
* @param dbFileName
* name of the DB file
* @param allowedCats
* include all pages in these categories
* @param allowedPages
* a number of pages to include (also parses these pages for more
* links)
* @param depth
* follow links this deep
* @param templateTree
* information about the templates and their dependencies
* @param includeTree
* information about page includes
* @param referenceTree
* information about references to a page
*
* @return full list of allowed pages
*
* @throws RuntimeException
* if any error occurs
*/
public static Set<String> getPagesInCategories(String dbFileName,
Set<String> allowedCats, Set<String> allowedPages, int depth,
Map<String, Set<String>> templateTree,
Map<String, Set<String>> includeTree,
Map<String, Set<String>> referenceTree) throws RuntimeException {
Set<String> pages = new HashSet<String>();
Set<String> pageLinks = new HashSet<String>();
SQLiteConnection db = null;
SQLiteStatement stmt = null;
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
Set<String> currentPages = new HashSet<String>(allowedPages);
currentPages.addAll(allowedCats);
// note: allowedCats can contain categories or templates
if (!allowedCats.isEmpty()) {
// select all pages belonging to any of the allowed categories:
stmt = db
.prepare("SELECT page.title, cat.title FROM " +
"categories INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN pages AS cat ON categories.category == cat.id;");
while (stmt.step()) {
String pageTitle = stmt.columnString(0);
String pageCategory = stmt.columnString(1);
if (allowedCats.contains(pageCategory)) {
currentPages.add(pageTitle);
}
}
stmt.dispose();
// select all pages belonging to any of the allowed templates:
stmt = db
.prepare("SELECT page.title, tpl.title FROM " +
"templates INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id;");
while (stmt.step()) {
String pageTitle = stmt.columnString(0);
String pageTemplate = stmt.columnString(1);
if (allowedCats.contains(pageTemplate)) {
currentPages.add(pageTitle);
}
}
stmt.dispose();
}
pageLinks = new HashSet<String>();
Set<String> newPages = new HashSet<String>();
while(depth >= 0) {
System.out.println("recursion level: " + depth);
System.out.println("adding " + currentPages.size() + " pages");
do {
db.exec("DROP TABLE IF EXISTS currentPages;");
db.exec("CREATE TEMPORARY TABLE currentPages(title STRING PRIMARY KEY);");
stmt = db.prepare("INSERT INTO currentPages (title) VALUES (?);");
for (String pageTitle : currentPages) {
pages.add(pageTitle);
addToPages(pages, newPages, pageTitle, includeTree, referenceTree);
stmt.bind(1, pageTitle).stepThrough().reset();
}
System.out.println(" adding categories of " + currentPages.size() + " pages");
// add all categories the page belongs to
stmt = db
.prepare("SELECT cat.title FROM categories " +
"INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS cat ON categories.category == cat.id;");
while (stmt.step()) {
String pageCategory = stmt.columnString(0);
addToPages(pages, newPages, pageCategory, includeTree, referenceTree);
}
stmt.reset();
System.out.println(" adding templates of " + currentPages.size() + " pages");
// add all templates (and their requirements) of the pages
stmt = db
.prepare("SELECT tpl.title FROM templates " +
"INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id;");
while (stmt.step()) {
String pageTemplate = stmt.columnString(0);
Set<String> tplChildren = WikiDumpGetCategoryTreeHandler.getAllChildren(templateTree, pageTemplate);
addToPages(pages, newPages, tplChildren, includeTree, referenceTree);
}
stmt.reset();
System.out.println(" adding links of " + currentPages.size() + " pages");
// add all links of the pages for further processing
stmt = db
.prepare("SELECT lnk.title FROM links " +
"INNER JOIN pages AS page ON links.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS lnk ON links.link == lnk.id;");
while (stmt.step()) {
String pageLink = stmt.columnString(0);
if (!pageLink.isEmpty()) { // there may be empty links
pageLinks.add(pageLink);
}
}
stmt.reset();
if (newPages.isEmpty()) {
break;
} else {
System.out.println("adding " + newPages.size() + " dependencies");
currentPages = newPages;
newPages = new HashSet<String>();
}
} while (true);
// for the next recursion:
currentPages = pageLinks;
pageLinks = new HashSet<String>();
--depth;
}
db.dispose();
return pages;
} catch (SQLiteException e) {
System.err.println("read of category tree failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
if (db != null) {
db.dispose();
}
}
}
static protected void addToPages(Set<String> pages, Set<String> newPages, String title, Map<String, Set<String>> includeTree, Map<String, Set<String>> referenceTree) {
if (!pages.contains(title) && newPages.add(title)) {
// title not yet in pages -> add includes, redirects and pages redirecting to this page
addToPages(pages, newPages, WikiDumpGetCategoryTreeHandler.getAllChildren(includeTree, title), includeTree, referenceTree); // also has redirects
addToPages(pages, newPages, WikiDumpGetCategoryTreeHandler.getAllChildren(referenceTree, title), includeTree, referenceTree);
}
}
static protected void addToPages(Set<String> pages, Set<String> newPages, Collection<? extends String> titles, Map<String, Set<String>> includeTree, Map<String, Set<String>> referenceTree) {
for (String title : titles) {
addToPages(pages, newPages, title, includeTree, referenceTree);
}
}
}
|
contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/WikiDumpGetCategoryTreeHandler.java
|
/**
* Copyright 2007-2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.data.xml;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import de.zib.scalaris.examples.wikipedia.bliki.MyNamespace;
import de.zib.scalaris.examples.wikipedia.bliki.MyParsingWikiModel;
import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel;
import de.zib.scalaris.examples.wikipedia.data.Page;
import de.zib.scalaris.examples.wikipedia.data.SiteInfo;
/**
* Provides abilities to read an xml wiki dump file and create a category (and
* template) tree.
*
* @author Nico Kruber, kruber@zib.de
*/
public class WikiDumpGetCategoryTreeHandler extends WikiDumpHandler {
private static final int PRINT_PAGES_EVERY = 400;
protected String dbFileName;
protected SQLiteConnection db = null;
protected SQLiteStatement stWritePages = null;
protected SQLiteStatement stWriteCategories = null;
protected SQLiteStatement stWriteTemplates = null;
protected SQLiteStatement stWriteIncludes = null;
protected SQLiteStatement stWriteRedirects = null;
protected SQLiteStatement stWriteLinks = null;
protected Map<String, Integer> pages = new HashMap<String, Integer>();
/**
* Sets up a SAX XmlHandler extracting all categories from all pages except
* the ones in a blacklist to stdout.
*
* @param blacklist
* a number of page titles to ignore
* @param maxTime
* maximum time a revision should have (newer revisions are
* omitted) - <tt>null/tt> imports all revisions
* (useful to create dumps of a wiki at a specific point in time)
* @param dbFileName
* the name of the directory to write categories, templates,
* inclusions etc to
*
* @throws RuntimeException
* if the creation of the SQLite DB fails
*/
public WikiDumpGetCategoryTreeHandler(Set<String> blacklist,
Calendar maxTime, String dbFileName) throws RuntimeException {
super(blacklist, null, 1, maxTime);
this.dbFileName = dbFileName;
}
static SQLiteStatement createReadCategoriesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT category FROM categories WHERE title == ?");
}
static SQLiteStatement createReadTemplatesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT template FROM templates WHERE title == ?");
}
static SQLiteStatement createReadIncludesStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT include FROM includes WHERE title == ?");
}
static SQLiteStatement createReadRedirectsStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT redirect FROM redirects WHERE title == ?");
}
static SQLiteStatement createReadLinksStmt(SQLiteConnection db) throws SQLiteException {
return db.prepare("SELECT link FROM links WHERE title == ?");
}
static Set<String> readValues(SQLiteStatement stmt, String key)
throws RuntimeException {
try {
try {
HashSet<String> results = new HashSet<String>();
stmt.bind(1, key);
while (stmt.step()) {
results.add(stmt.columnString(1));
}
return results;
} finally {
stmt.reset();
}
} catch (SQLiteException e) {
System.err.println("read of " + key + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
protected void writeValue(SQLiteStatement stmt, String key, String value)
throws RuntimeException {
writeValues(stmt, key, Arrays.asList(value));
}
protected void writeValues(SQLiteStatement stmt, String key, Collection<? extends String> values)
throws RuntimeException {
Integer key_id = pageToId(key);
LinkedList<Integer> values_id = new LinkedList<Integer>();
for (String value : values) {
values_id.add(pageToId(value));
}
try {
try {
stmt.bind(1, key_id);
for (Integer value_id : values_id) {
stmt.bind(2, value_id).stepThrough().reset(false);
}
} finally {
stmt.reset();
}
} catch (SQLiteException e) {
System.err.println("write of " + key + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
protected Integer pageToId(String pageTitle) throws RuntimeException {
try {
Integer id = pages.get(pageTitle);
if (id == null) {
id = pages.size();
pages.put(pageTitle, id);
try {
stWritePages.bind(1, id).bind(2, pageTitle).stepThrough();
} finally {
stWritePages.reset();
}
}
return id;
} catch (SQLiteException e) {
System.err.println("write of " + pageTitle + " failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
}
}
static void writeSiteInfo(SQLiteConnection db, SiteInfo siteInfo)
throws RuntimeException {
SQLiteStatement stmt = null;
try {
stmt = db.prepare("REPLACE INTO properties (key, value) VALUES (?, ?);");
WikiDumpPrepareSQLiteForScalarisHandler.writeObject(stmt, "siteinfo", siteInfo);
} catch (SQLiteException e) {
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
}
}
static SiteInfo readSiteInfo(SQLiteConnection db) throws RuntimeException {
SQLiteStatement stmt = null;
try {
stmt = db.prepare("SELECT value FROM properties WHERE key == ?");
return WikiDumpPrepareSQLiteForScalarisHandler.readObject(stmt, "siteinfo");
} catch (SQLiteException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
}
}
protected static void updateMap(Map<String, Set<String>> map, String key, String addToValue) {
Set<String> oldValue = map.get(key);
if (oldValue == null) {
oldValue = new HashSet<String>();
map.put(key, oldValue);
}
oldValue.add(addToValue);
}
protected static void updateMap(Map<String, Set<String>> map, String key, Collection<? extends String> addToValues) {
Set<String> oldValue = map.get(key);
if (oldValue == null) {
oldValue = new HashSet<String>(addToValues);
map.put(key, oldValue);
} else {
oldValue.addAll(addToValues);
}
}
/**
* Exports the given siteinfo (nothing to do here).
*
* @param revisions
* the siteinfo to export
*/
@Override
protected void export(XmlSiteInfo siteinfo_xml) {
writeSiteInfo(db, siteinfo_xml.getSiteInfo());
}
/**
* Builds the category tree.
*
* @param page_xml
* the page object extracted from XML
*/
@Override
protected void export(XmlPage page_xml) {
Page page = page_xml.getPage();
if (page.getCurRev() != null && wikiModel != null) {
wikiModel.setUp();
final String pageTitle = page.getTitle();
wikiModel.setPageName(pageTitle);
wikiModel.render(null, page.getCurRev().getText());
// categories:
do {
final Set<String> pageCategories_raw = wikiModel.getCategories().keySet();
ArrayList<String> pageCategories = new ArrayList<String>(pageCategories_raw.size());
for (String cat_raw: pageCategories_raw) {
String category = (wikiModel.getCategoryNamespace() + ":" + cat_raw);
pageCategories.add(category);
}
writeValues(stWriteCategories, pageTitle, pageCategories);
} while(false);
// templates:
do {
final Set<String> pageTemplates_raw = wikiModel.getTemplates();
ArrayList<String> pageTemplates = new ArrayList<String>(pageTemplates_raw.size());
for (String tpl_raw: pageTemplates_raw) {
String template = (wikiModel.getTemplateNamespace() + ":" + tpl_raw);
pageTemplates.add(template);
}
writeValues(stWriteTemplates, pageTitle, pageTemplates);
} while (false);
// includes:
do {
Set<String> pageIncludes = wikiModel.getIncludes();
if (!pageIncludes.isEmpty()) {
writeValues(stWriteIncludes, pageTitle, pageIncludes);
}
} while (false);
// redirections:
do {
String pageRedirLink = wikiModel.getRedirectLink();
if (pageRedirLink != null) {
writeValue(stWriteRedirects, pageTitle, pageRedirLink);
}
} while(false);
// links:
do {
Set<String> pageLinks = wikiModel.getLinks();
if (!pageLinks.isEmpty()) {
writeValues(stWriteLinks, pageTitle, pageLinks);
}
} while(false);
wikiModel.tearDown();
}
++pageCount;
// only export page list every UPDATE_PAGELIST_EVERY pages:
if ((pageCount % PRINT_PAGES_EVERY) == 0) {
msgOut.println("processed pages: " + pageCount);
}
}
/* (non-Javadoc)
* @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#tearDown()
*/
@Override
public void tearDown() {
super.tearDown();
if (db != null) {
db.dispose();
}
importEnd();
}
/**
* Gets all sub categories that belong to a given root category
* (recursively).
*
* @param tree
* the tree of categories or templates as created by
* {@link #readTrees(String, Map, Map, Map, Map)}
* @param root
* a root category or template
*
* @return a set of all sub categories/templates; also includes the root
*/
public static Set<String> getAllChildren(Map<String, Set<String>> tree, String root) {
return getAllChildren(tree, new LinkedList<String>(Arrays.asList(root)));
}
/**
* Gets all sub categories that belong to any of the given root categories
* (recursively).
*
* @param tree
* the tree of categories or templates as created by
* {@link #readTrees(String, Map, Map, Map, Map)}
* @param roots
* a list of root categories or templates
*
* @return a set of all sub categories; also includes the rootCats
*/
public static Set<String> getAllChildren(Map<String, Set<String>> tree, List<String> roots) {
HashSet<String> allChildren = new HashSet<String>(roots);
while (!roots.isEmpty()) {
String curChild = roots.remove(0);
Set<String> subChilds = tree.get(curChild);
if (subChilds != null) {
// only add new categories to the root categories
// (remove already processed ones)
// -> prevents endless loops in circles
Set<String> newCats = new HashSet<String>(subChilds);
newCats.removeAll(allChildren);
allChildren.addAll(subChilds);
roots.addAll(newCats);
}
}
return allChildren;
}
/* (non-Javadoc)
* @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#setUp()
*/
@Override
public void setUp() {
super.setUp();
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
db.exec("CREATE TABLE pages(id INTEGER PRIMARY KEY ASC, title STRING);");
db.exec("CREATE INDEX page_titles ON pages(title);");
db.exec("CREATE TABLE categories(title INTEGER, category INTEGER);");
db.exec("CREATE INDEX cat_titles ON categories(title);");
db.exec("CREATE TABLE templates(title INTEGER, template INTEGER);");
db.exec("CREATE INDEX tpl_titles ON templates(title);");
db.exec("CREATE TABLE includes(title INTEGER, include INTEGER);");
db.exec("CREATE INDEX incl_titles ON includes(title);");
db.exec("CREATE TABLE redirects(title INTEGER, redirect INTEGER);");
db.exec("CREATE INDEX redir_titles ON redirects(title);");
db.exec("CREATE TABLE links(title INTEGER, link INTEGER);");
db.exec("CREATE INDEX lnk_titles ON links(title);");
db.exec("CREATE TABLE properties(key STRING PRIMARY KEY ASC, value);");
stWritePages = db.prepare("INSERT INTO pages (id, title) VALUES (?, ?);");
stWriteCategories = db.prepare("INSERT INTO categories (title, category) VALUES (?, ?);");
stWriteTemplates = db.prepare("INSERT INTO templates (title, template) VALUES (?, ?);");
stWriteIncludes = db.prepare("INSERT INTO includes (title, include) VALUES (?, ?);");
stWriteRedirects = db.prepare("INSERT INTO redirects (title, redirect) VALUES (?, ?);");
stWriteLinks = db.prepare("INSERT INTO links (title, link) VALUES (?, ?);");
} catch (SQLiteException e) {
throw new RuntimeException(e);
}
}
/**
* Reads the given parameter trees from the DB file.
*
* @param dbFileName
* name of the DB file
* @param categoryTree
* information about the categories and their dependencies
* @param templateTree
* information about the templates and their dependencies
* @param includeTree
* information about page includes
* @param referenceTree
* information about references to a page
*
* @throws RuntimeException if any error occurs
*/
public static void readTrees(
String dbFileName,
Map<String, Set<String>> categoryTree,
Map<String, Set<String>> templateTree,
Map<String, Set<String>> includeTree,
Map<String, Set<String>> referenceTree)
throws RuntimeException {
SQLiteConnection db = null;
SQLiteStatement stmt = null;
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
SiteInfo siteInfo = readSiteInfo(db);
MyParsingWikiModel wikiModel = new MyParsingWikiModel("", "", new MyNamespace(siteInfo));
stmt = db
.prepare("SELECT page.title, cat.title FROM " +
"categories INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN pages AS cat ON categories.category == cat.id " +
"WHERE page.title LIKE '" + wikiModel.getCategoryNamespace() + ":%'");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String category = stmt.columnString(1).intern();
updateMap(categoryTree, category, pageTitle);
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, tpl.title FROM " +
"templates INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id " +
"WHERE page.title LIKE '" + wikiModel.getCategoryNamespace() + ":%' OR "
+ "page.title LIKE '" + wikiModel.getTemplateNamespace() + ":%'");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String template = stmt.columnString(1).intern();
final String namespace = MyWikiModel.getNamespace(pageTitle);
updateMap(categoryTree, template, pageTitle);
if (wikiModel.isTemplateNamespace(namespace)) {
updateMap(templateTree, pageTitle, template);
}
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, incl.title FROM " +
"includes INNER JOIN pages AS page ON includes.title == page.id " +
"INNER JOIN pages AS incl ON includes.include == incl.id");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String include = stmt.columnString(1).intern();
updateMap(includeTree, pageTitle, include);
}
stmt.dispose();
stmt = db
.prepare("SELECT page.title, redir.title FROM " +
"redirects INNER JOIN pages AS page ON redirects.title == page.id " +
"INNER JOIN pages AS redir ON redirects.redirect == redir.id");
while (stmt.step()) {
String pageTitle = stmt.columnString(0).intern();
String redirect = stmt.columnString(1).intern();
updateMap(referenceTree, redirect, pageTitle);
}
} catch (SQLiteException e) {
System.err.println("read of category tree failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
if (db != null) {
db.dispose();
}
}
}
/**
* Extracts all pages in the given categories from the given DB.
*
* @param dbFileName
* name of the DB file
* @param allowedCats
* include all pages in these categories
* @param allowedPages
* a number of pages to include (also parses these pages for more
* links)
* @param depth
* follow links this deep
* @param templateTree
* information about the templates and their dependencies
* @param includeTree
* information about page includes
* @param referenceTree
* information about references to a page
*
* @return full list of allowed pages
*
* @throws RuntimeException
* if any error occurs
*/
public static Set<String> getPagesInCategories(String dbFileName,
Set<String> allowedCats, Set<String> allowedPages, int depth,
Map<String, Set<String>> templateTree,
Map<String, Set<String>> includeTree,
Map<String, Set<String>> referenceTree) throws RuntimeException {
Set<String> pages = new HashSet<String>();
Set<String> pageLinks = new HashSet<String>();
SQLiteConnection db = null;
SQLiteStatement stmt = null;
try {
db = WikiDumpPrepareSQLiteForScalarisHandler.openDB(dbFileName);
Set<String> currentPages = new HashSet<String>(allowedPages);
currentPages.addAll(allowedCats);
// note: allowedCats can contain categories or templates
if (!allowedCats.isEmpty()) {
// select all pages belonging to any of the allowed categories:
stmt = db
.prepare("SELECT page.title, cat.title FROM " +
"categories INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN pages AS cat ON categories.category == cat.id");
while (stmt.step()) {
String pageTitle = stmt.columnString(0);
String pageCategory = stmt.columnString(1);
if (allowedCats.contains(pageCategory)) {
currentPages.add(pageTitle);
}
}
stmt.dispose();
// select all pages belonging to any of the allowed templates:
stmt = db
.prepare("SELECT page.title, tpl.title FROM " +
"templates INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id");
while (stmt.step()) {
String pageTitle = stmt.columnString(0);
String pageTemplate = stmt.columnString(1);
if (allowedCats.contains(pageTemplate)) {
currentPages.add(pageTitle);
}
}
stmt.dispose();
}
pageLinks = new HashSet<String>();
Set<String> newPages = new HashSet<String>();
while(depth >= 0) {
System.out.println("recursion level: " + depth);
System.out.println("adding " + currentPages.size() + " pages");
do {
db.exec("DROP TABLE IF EXISTS currentPages");
db.exec("CREATE TEMPORARY TABLE currentPages(title STRING PRIMARY KEY);");
stmt = db.prepare("INSERT INTO currentPages (title) VALUES (?);");
for (String pageTitle : currentPages) {
pages.add(pageTitle);
addToPages(pages, newPages, pageTitle, includeTree, referenceTree);
stmt.bind(1, pageTitle).stepThrough().reset();
}
System.out.println(" adding categories of " + currentPages.size() + " pages");
// add all categories the page belongs to
stmt = db
.prepare("SELECT cat.title FROM categories " +
"INNER JOIN pages AS page ON categories.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS cat ON categories.category == cat.id");
while (stmt.step()) {
String pageCategory = stmt.columnString(0);
addToPages(pages, newPages, pageCategory, includeTree, referenceTree);
}
stmt.reset();
System.out.println(" adding templates of " + currentPages.size() + " pages");
// add all templates (and their requirements) of the pages
stmt = db
.prepare("SELECT tpl.title FROM templates " +
"INNER JOIN pages AS page ON templates.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS tpl ON templates.template == tpl.id");
while (stmt.step()) {
String pageTemplate = stmt.columnString(0);
Set<String> tplChildren = WikiDumpGetCategoryTreeHandler.getAllChildren(templateTree, pageTemplate);
addToPages(pages, newPages, tplChildren, includeTree, referenceTree);
}
stmt.reset();
System.out.println(" adding links of " + currentPages.size() + " pages");
// add all links of the pages for further processing
stmt = db
.prepare("SELECT lnk.title FROM links " +
"INNER JOIN pages AS page ON links.title == page.id " +
"INNER JOIN currentPages AS cp ON page.title == cp.title " +
"INNER JOIN pages AS lnk ON links.link == lnk.id");
while (stmt.step()) {
String pageLink = stmt.columnString(0);
if (!pageLink.isEmpty()) { // there may be empty links
pageLinks.add(pageLink);
}
}
stmt.reset();
if (newPages.isEmpty()) {
break;
} else {
System.out.println("adding " + newPages.size() + " dependencies");
currentPages = newPages;
newPages = new HashSet<String>();
}
} while (true);
// for the next recursion:
currentPages = pageLinks;
pageLinks = new HashSet<String>();
--depth;
}
db.dispose();
return pages;
} catch (SQLiteException e) {
System.err.println("read of category tree failed (sqlite error: " + e.toString() + ")");
throw new RuntimeException(e);
} finally {
if (stmt != null) {
stmt.dispose();
}
if (db != null) {
db.dispose();
}
}
}
static protected void addToPages(Set<String> pages, Set<String> newPages, String title, Map<String, Set<String>> includeTree, Map<String, Set<String>> referenceTree) {
if (!pages.contains(title) && newPages.add(title)) {
// title not yet in pages -> add includes, redirects and pages redirecting to this page
addToPages(pages, newPages, WikiDumpGetCategoryTreeHandler.getAllChildren(includeTree, title), includeTree, referenceTree); // also has redirects
addToPages(pages, newPages, WikiDumpGetCategoryTreeHandler.getAllChildren(referenceTree, title), includeTree, referenceTree);
}
}
static protected void addToPages(Set<String> pages, Set<String> newPages, Collection<? extends String> titles, Map<String, Set<String>> includeTree, Map<String, Set<String>> referenceTree) {
for (String title : titles) {
addToPages(pages, newPages, title, includeTree, referenceTree);
}
}
}
|
- Wiki on Scalaris - filtering: properly end all SQL statements with ';'
|
contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/WikiDumpGetCategoryTreeHandler.java
|
- Wiki on Scalaris - filtering: properly end all SQL statements with ';'
|
|
Java
|
apache-2.0
|
8d3e1c27417d2aa1edb11d0e1fbe16886dc90632
| 0
|
AxonFramework/AxonFramework
|
/* Copyright (c) 2010-2018. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.integrationtests.commandhandling;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.deadline.DeadlineManager;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.*;
import org.axonframework.spring.stereotype.Aggregate;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Test whether aggregate member annotated collections of the same generic type be able to forward command.
*
* @author Somrak Monpengpinij
*/
public class AbstractAggregateMemberTest {
private FixtureConfiguration<FactoryAggregate> fixture;
private String factoryId = "factoryId";
@BeforeEach
public void setUp(){
fixture = new AggregateTestFixture(FactoryAggregate.class);
}
@Test
public void testInitializingFactoryAggregate_ShouldHandleBeAbleToInitialize(){
fixture.givenNoPriorActivity()
.when(new CreateFactoryCommand(factoryId))
.expectEvents(new FactoryCreatedEvent(factoryId));
}
@Test
public void testForwardingCommandToAggregateMemberWithTheSameGenericType_ShouldForwardCommandToEmployeeAggregate(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "employeeId"))
.expectEvents(new EmployeeTaskCreatedEvent(factoryId, "employeeId"));
}
@Test
public void testForwardingCommandToAggregateMemberWithTheSameGenericType_ShouldForwardCommandToManagerAggregate(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "managerId"))
.expectEvents(new ManagerTaskCreatedEvent(factoryId, "managerId"));
}
@Test
public void testSendCommandToNoneExistEntity_ShouldThrowAggregateEntityNotFoundException(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "none-exist-id"))
.expectException(AggregateEntityNotFoundException.class);
}
private static abstract class Person {
@EntityId
public String personId;
}
private static class Employee extends Person {
public Employee(){
}
public Employee(String personId){
this.personId = personId;
}
@CommandHandler
public void handle(CreateTaskCommand cmd){
AggregateLifecycle.apply(new EmployeeTaskCreatedEvent(
cmd.getFactoryId(),
cmd.getPersonId()
));
}
@EventSourcingHandler
public void on(EmployeeTaskCreatedEvent event){
}
public String getPersonId(){
return personId;
}
@Override
public int hashCode(){
return this.personId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Employee){
Employee manager = (Employee) o;
return manager.personId == this.personId;
}
return false;
}
}
private static class Manager extends Person {
public Manager(){
}
public Manager(String personId){
this.personId = personId;
}
@CommandHandler
public void handle(CreateTaskCommand cmd){
AggregateLifecycle.apply(new ManagerTaskCreatedEvent(
cmd.getFactoryId(),
cmd.getPersonId()
));
}
@EventSourcingHandler
public void on(ManagerTaskCreatedEvent event){
}
public String getPersonId(){
return personId;
}
@Override
public int hashCode(){
return this.personId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Manager){
Manager manager = (Manager) o;
return manager.personId == this.personId;
}
return false;
}
}
@Aggregate
private static class FactoryAggregate {
@AggregateIdentifier
public String factoryId;
public List<Person> persons = new ArrayList<>();
@AggregateMember(type = Employee.class)
public List<Person> employees(){
return persons.stream()
.filter(p -> p instanceof Employee)
.collect(Collectors.toList());
}
@AggregateMember(type = Manager.class)
public List<Person> managers(){
return persons.stream()
.filter(p -> p instanceof Manager)
.collect(Collectors.toList());
}
public String getFactoryId(){
return factoryId;
}
public FactoryAggregate(){
}
@CommandHandler
public FactoryAggregate(CreateFactoryCommand cmd){
AggregateLifecycle.apply(new FactoryCreatedEvent(
cmd.getFactoryId()
));
}
@EventSourcingHandler
public void on(FactoryCreatedEvent event){
this.factoryId = event.getFactoryId();
this.persons.add(new Employee(
"employeeId"
));
this.persons.add(new Manager(
"managerId"
));
}
@Override
public int hashCode(){
return this.factoryId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof FactoryAggregate){
FactoryAggregate manager = (FactoryAggregate) o;
return manager.factoryId == this.factoryId;
}
return false;
}
}
private static class CreateTaskCommand {
@TargetAggregateIdentifier
public String factoryId;
public String personId;
public CreateTaskCommand(){}
public CreateTaskCommand(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
public String getFactoryId(){
return factoryId;
}
public String getPersonId(){
return personId;
}
}
private static class EmployeeTaskCreatedEvent {
String factoryId;
String personId;
public EmployeeTaskCreatedEvent(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
}
private static class ManagerTaskCreatedEvent {
String factoryId;
String personId;
public ManagerTaskCreatedEvent(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
}
private static class CreateFactoryCommand {
@TargetAggregateIdentifier
public String factoryId;
public CreateFactoryCommand(String factoryId){
this.factoryId = factoryId;
}
public String getFactoryId(){
return factoryId;
}
}
private static class FactoryCreatedEvent {
public String factoryId;
public FactoryCreatedEvent(String factoryId){
this.factoryId = factoryId;
}
public String getFactoryId(){
return factoryId;
}
}
}
|
integrationtests/src/test/java/org/axonframework/integrationtests/commandhandling/AbstractAggregateMemberTest.java
|
/* Copyright (c) 2010-2018. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.integrationtests.commandhandling;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.deadline.DeadlineManager;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.*;
import org.axonframework.spring.stereotype.Aggregate;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Test whether aggregate member annotated collections of the same generic type be able to handle command.
*
* @author Somrak Monpengpinij
*/
public class AbstractAggregateMemberTest {
private FixtureConfiguration<FactoryAggregate> fixture;
private String factoryId = "factoryId";
@BeforeEach
public void setUp(){
fixture = new AggregateTestFixture(FactoryAggregate.class);
}
@Test
public void testInitFactoryAggregate_ShouldHandleCommandNormally(){
fixture.givenNoPriorActivity()
.when(new CreateFactoryCommand(factoryId))
.expectEvents(new FactoryCreatedEvent(factoryId));
}
@Test
public void testEmployeesAggregateMember_ShouldBeAbleToHandleCommand(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "employeeId"))
.expectEvents(new EmployeeTaskCreatedEvent(factoryId, "employeeId"));
}
@Test
public void testManagersAggregateMember_ShouldBeAbleToHandleCommand(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "managerId"))
.expectEvents(new ManagerTaskCreatedEvent(factoryId, "managerId"));
}
@Test
public void testSendCommandToNoneExistEntity_ShouldThrowAggregateEntityNotFoundException(){
fixture.givenCommands(new CreateFactoryCommand(factoryId))
.when(new CreateTaskCommand(factoryId, "none-exist-id"))
.expectException(AggregateEntityNotFoundException.class);
}
private static abstract class Person {
@EntityId
public String personId;
}
private static class Employee extends Person {
public Employee(){
}
public Employee(String personId){
this.personId = personId;
}
@CommandHandler
public void handle(CreateTaskCommand cmd){
AggregateLifecycle.apply(new EmployeeTaskCreatedEvent(
cmd.getFactoryId(),
cmd.getPersonId()
));
}
@EventSourcingHandler
public void on(EmployeeTaskCreatedEvent event){
}
public String getPersonId(){
return personId;
}
@Override
public int hashCode(){
return this.personId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Employee){
Employee manager = (Employee) o;
return manager.personId == this.personId;
}
return false;
}
}
private static class Manager extends Person {
public Manager(){
}
public Manager(String personId){
this.personId = personId;
}
@CommandHandler
public void handle(CreateTaskCommand cmd){
AggregateLifecycle.apply(new ManagerTaskCreatedEvent(
cmd.getFactoryId(),
cmd.getPersonId()
));
}
@EventSourcingHandler
public void on(ManagerTaskCreatedEvent event){
}
public String getPersonId(){
return personId;
}
@Override
public int hashCode(){
return this.personId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Manager){
Manager manager = (Manager) o;
return manager.personId == this.personId;
}
return false;
}
}
@Aggregate
private static class FactoryAggregate {
@AggregateIdentifier
public String factoryId;
public List<Person> persons = new ArrayList<>();
@AggregateMember(type = Employee.class)
public List<Person> employees(){
return persons.stream()
.filter(p -> p instanceof Employee)
.collect(Collectors.toList());
}
@AggregateMember(type = Manager.class)
public List<Person> managers(){
return persons.stream()
.filter(p -> p instanceof Manager)
.collect(Collectors.toList());
}
public String getFactoryId(){
return factoryId;
}
public FactoryAggregate(){
}
@CommandHandler
public FactoryAggregate(CreateFactoryCommand cmd){
AggregateLifecycle.apply(new FactoryCreatedEvent(
cmd.getFactoryId()
));
}
@EventSourcingHandler
public void on(FactoryCreatedEvent event){
this.factoryId = event.getFactoryId();
this.persons.add(new Employee(
"employeeId"
));
this.persons.add(new Manager(
"managerId"
));
}
@Override
public int hashCode(){
return this.factoryId.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof FactoryAggregate){
FactoryAggregate manager = (FactoryAggregate) o;
return manager.factoryId == this.factoryId;
}
return false;
}
}
private static class CreateTaskCommand {
@TargetAggregateIdentifier
public String factoryId;
public String personId;
public CreateTaskCommand(){}
public CreateTaskCommand(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
public String getFactoryId(){
return factoryId;
}
public String getPersonId(){
return personId;
}
}
private static class EmployeeTaskCreatedEvent {
String factoryId;
String personId;
public EmployeeTaskCreatedEvent(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
}
private static class ManagerTaskCreatedEvent {
String factoryId;
String personId;
public ManagerTaskCreatedEvent(String factoryId, String personId){
this.factoryId = factoryId;
this.personId = personId;
}
}
private static class CreateFactoryCommand {
@TargetAggregateIdentifier
public String factoryId;
public CreateFactoryCommand(String factoryId){
this.factoryId = factoryId;
}
public String getFactoryId(){
return factoryId;
}
}
private static class FactoryCreatedEvent {
public String factoryId;
public FactoryCreatedEvent(String factoryId){
this.factoryId = factoryId;
}
public String getFactoryId(){
return factoryId;
}
}
}
|
refactor more meaningful test name
|
integrationtests/src/test/java/org/axonframework/integrationtests/commandhandling/AbstractAggregateMemberTest.java
|
refactor more meaningful test name
|
|
Java
|
apache-2.0
|
4bd38de1d0cb8617ffbf892f83f8e30f750ceff1
| 0
|
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
|
/*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.event.model;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.Immutable;
import io.spine.server.entity.model.StateClass;
import io.spine.server.event.EventReceiver;
import io.spine.server.model.HandlerMap;
import io.spine.server.model.HandlerMethod;
import io.spine.server.model.MethodSignature;
import io.spine.server.model.ModelClass;
import io.spine.server.type.EventClass;
import io.spine.type.MessageClass;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
/**
* Helper object for storing information about methods and handlers of an
* {@linkplain EventReceiverClass event receiving class}.
*
* @param <T>
* the type of target objects that handle messages
* @param <P>
* the type of message classes produced by handler methods
* @param <M>
* the type of handler method objects
*/
@Immutable(containerOf = "M")
public class EventReceivingClassDelegate<T extends EventReceiver,
P extends MessageClass<?>,
M extends HandlerMethod<?, EventClass, ?, P>>
extends ModelClass<T> {
private static final long serialVersionUID = 0L;
private final HandlerMap<EventClass, P, M> handlers;
private final ImmutableSet<EventClass> events;
private final ImmutableSet<EventClass> domesticEvents;
private final ImmutableSet<EventClass> externalEvents;
private final ImmutableSet<StateClass> domesticStates;
private final ImmutableSet<StateClass> externalStates;
/**
* Creates new instance for the passed raw class with methods obtained
* through the passed factory.
*/
public EventReceivingClassDelegate(Class<T> delegatingClass, MethodSignature<M, ?> signature) {
super(delegatingClass);
this.handlers = HandlerMap.create(delegatingClass, signature);
this.events = handlers.messageClasses();
this.domesticEvents = handlers.messageClasses((h) -> !h.isExternal());
this.externalEvents = handlers.messageClasses(HandlerMethod::isExternal);
this.domesticStates = extractStates(false);
this.externalStates = extractStates(true);
}
public boolean contains(EventClass eventClass) {
return handlers.containsClass(eventClass);
}
/**
* Obtains all event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> events() {
return events;
}
/**
* Obtains domestic event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> domesticEvents() {
return domesticEvents;
}
/**
* Obtains external event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> externalEvents() {
return externalEvents;
}
/**
* Obtains domestic entity states to which the delegating class is subscribed.
*/
public ImmutableSet<StateClass> domesticStates() {
return domesticStates;
}
/**
* Obtains external entity states to which the delegating class is subscribed.
*/
public ImmutableSet<StateClass> externalStates() {
return externalStates;
}
/**
* Obtains the classes of messages produced by handler methods of this class.
*/
public ImmutableSet<P> producedTypes() {
return handlers.producedTypes();
}
/**
* Obtains the method which handles the passed event class.
*/
public ImmutableSet<M> handlersOf(EventClass eventClass, MessageClass<?> originClass) {
return handlers.handlersOf(eventClass, originClass);
}
/**
* Obtains the method which handles the passed event class.
*
* @throws IllegalStateException
* if there is no such method in the class
*/
public M handlerOf(EventClass eventClass, MessageClass<?> originClass) {
return handlers.handlerOf(eventClass, originClass);
}
/**
* Obtains the classes of entity state messages from the passed handlers.
*/
private ImmutableSet<StateClass> extractStates(boolean external) {
EventClass updateEvent = StateClass.updateEvent();
if (!handlers.containsClass(updateEvent)) {
return ImmutableSet.of();
}
ImmutableSet<M> stateHandlers = handlers.handlersOf(updateEvent);
ImmutableSet<StateClass> result =
stateHandlers
.stream()
.filter(StateSubscriberMethod.class::isInstance)
.map(StateSubscriberMethod.class::cast)
.filter(external ? HandlerMethod::isExternal : HandlerMethod::isDomestic)
.map(StateSubscriberMethod::stateType)
.map(StateClass::from)
.collect(toImmutableSet());
return result;
}
}
|
server/src/main/java/io/spine/server/event/model/EventReceivingClassDelegate.java
|
/*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.event.model;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.Immutable;
import io.spine.server.entity.model.StateClass;
import io.spine.server.event.EventReceiver;
import io.spine.server.model.HandlerMap;
import io.spine.server.model.HandlerMethod;
import io.spine.server.model.MethodSignature;
import io.spine.server.model.ModelClass;
import io.spine.server.type.EventClass;
import io.spine.type.MessageClass;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
/**
* Helper object for storing information about methods and handlers of an
* {@linkplain EventReceiverClass event receiving class}.
*
* @param <T>
* the type of target objects that handle messages
* @param <P>
* the type of message classes produced by handler methods
* @param <M>
* the type of handler method objects
*/
@Immutable(containerOf = "M")
public class EventReceivingClassDelegate<T extends EventReceiver,
P extends MessageClass<?>,
M extends HandlerMethod<?, EventClass, ?, P>>
extends ModelClass<T> {
private static final long serialVersionUID = 0L;
private final HandlerMap<EventClass, P, M> handlers;
private final ImmutableSet<EventClass> events;
private final ImmutableSet<EventClass> domesticEvents;
private final ImmutableSet<EventClass> externalEvents;
private final ImmutableSet<StateClass> domesticStates;
private final ImmutableSet<StateClass> externalStates;
/**
* Creates new instance for the passed raw class with methods obtained
* through the passed factory.
*/
public EventReceivingClassDelegate(Class<T> delegatingClass, MethodSignature<M, ?> signature) {
super(delegatingClass);
this.handlers = HandlerMap.create(delegatingClass, signature);
this.events = handlers.messageClasses();
this.domesticEvents = handlers.messageClasses((h) -> !h.isExternal());
this.externalEvents = handlers.messageClasses(HandlerMethod::isExternal);
this.domesticStates = extractStates(false);
this.externalStates = extractStates(true);
}
public boolean contains(EventClass eventClass) {
return handlers.containsClass(eventClass);
}
/**
* Obtains all event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> events() {
return events;
}
/**
* Obtains domestic event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> domesticEvents() {
return domesticEvents;
}
/**
* Obtains external event classes handled by the delegating class.
*/
public ImmutableSet<EventClass> externalEvents() {
return externalEvents;
}
/**
* Obtains domestic entity states to which the delegating class is subscribed.
*/
public ImmutableSet<StateClass> domesticStates() {
return domesticStates;
}
/**
* Obtains external entity states to which the delegating class is subscribed.
*/
public ImmutableSet<StateClass> externalStates() {
return externalStates;
}
/**
* Obtains the classes of messages produced by handler methods of this class.
*/
public ImmutableSet<P> producedTypes() {
return handlers.producedTypes();
}
/**
* Obtains the method which handles the passed event class.
*/
public ImmutableSet<M> handlersOf(EventClass eventClass, MessageClass<?> originClass) {
return handlers.handlersOf(eventClass, originClass);
}
/**
* Obtains the method which handles the passed event class.
*
* @throws IllegalStateException
* if there is no such method in the class
*/
public M handlerOf(EventClass eventClass, MessageClass<?> originClass) {
return handlers.handlerOf(eventClass, originClass);
}
/**
* Obtains the classes of entity state messages from the passed handlers.
*/
private ImmutableSet<StateClass> extractStates(boolean external) {
EventClass updateEvent = StateClass.updateEvent();
if (!handlers.containsClass(updateEvent)) {
return ImmutableSet.of();
}
ImmutableSet<M> stateHandlers = handlers.handlersOf(updateEvent);
ImmutableSet<StateClass> result =
stateHandlers.stream()
.filter(StateSubscriberMethod.class::isInstance)
.map(StateSubscriberMethod.class::cast)
.filter(external ? HandlerMethod::isExternal : HandlerMethod::isDomestic)
.map(StateSubscriberMethod::stateType)
.map(StateClass::from)
.collect(toImmutableSet());
return result;
}
}
|
Move the `.stream` call to the next line.
|
server/src/main/java/io/spine/server/event/model/EventReceivingClassDelegate.java
|
Move the `.stream` call to the next line.
|
|
Java
|
apache-2.0
|
5bf2544539f0b9f3356c0e4a6d2f433409d958be
| 0
|
colczr/sakai,introp-software/sakai,bkirschn/sakai,wfuedu/sakai,conder/sakai,joserabal/sakai,kwedoff1/sakai,OpenCollabZA/sakai,willkara/sakai,wfuedu/sakai,kingmook/sakai,zqian/sakai,ktakacs/sakai,ouit0408/sakai,lorenamgUMU/sakai,ktakacs/sakai,puramshetty/sakai,clhedrick/sakai,rodriguezdevera/sakai,pushyamig/sakai,frasese/sakai,introp-software/sakai,kingmook/sakai,clhedrick/sakai,frasese/sakai,kingmook/sakai,liubo404/sakai,whumph/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,clhedrick/sakai,bzhouduke123/sakai,hackbuteer59/sakai,lorenamgUMU/sakai,frasese/sakai,kwedoff1/sakai,hackbuteer59/sakai,zqian/sakai,willkara/sakai,surya-janani/sakai,whumph/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,Fudan-University/sakai,ktakacs/sakai,whumph/sakai,conder/sakai,joserabal/sakai,liubo404/sakai,puramshetty/sakai,bkirschn/sakai,willkara/sakai,introp-software/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,frasese/sakai,joserabal/sakai,wfuedu/sakai,Fudan-University/sakai,OpenCollabZA/sakai,Fudan-University/sakai,joserabal/sakai,ktakacs/sakai,Fudan-University/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,zqian/sakai,introp-software/sakai,kingmook/sakai,lorenamgUMU/sakai,ouit0408/sakai,frasese/sakai,bkirschn/sakai,OpenCollabZA/sakai,udayg/sakai,buckett/sakai-gitflow,noondaysun/sakai,hackbuteer59/sakai,bzhouduke123/sakai,wfuedu/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,udayg/sakai,liubo404/sakai,introp-software/sakai,noondaysun/sakai,hackbuteer59/sakai,buckett/sakai-gitflow,ktakacs/sakai,ktakacs/sakai,surya-janani/sakai,zqian/sakai,ouit0408/sakai,puramshetty/sakai,zqian/sakai,pushyamig/sakai,surya-janani/sakai,ouit0408/sakai,udayg/sakai,bzhouduke123/sakai,kwedoff1/sakai,liubo404/sakai,hackbuteer59/sakai,kingmook/sakai,OpenCollabZA/sakai,udayg/sakai,whumph/sakai,ouit0408/sakai,Fudan-University/sakai,willkara/sakai,noondaysun/sakai,conder/sakai,noondaysun/sakai,kwedoff1/sakai,ouit0408/sakai,zqian/sakai,hackbuteer59/sakai,surya-janani/sakai,pushyamig/sakai,liubo404/sakai,noondaysun/sakai,puramshetty/sakai,buckett/sakai-gitflow,udayg/sakai,clhedrick/sakai,kingmook/sakai,bzhouduke123/sakai,Fudan-University/sakai,bkirschn/sakai,pushyamig/sakai,colczr/sakai,OpenCollabZA/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,ouit0408/sakai,conder/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,bkirschn/sakai,bkirschn/sakai,willkara/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,liubo404/sakai,hackbuteer59/sakai,bzhouduke123/sakai,kingmook/sakai,colczr/sakai,ouit0408/sakai,rodriguezdevera/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,whumph/sakai,Fudan-University/sakai,lorenamgUMU/sakai,colczr/sakai,willkara/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,wfuedu/sakai,lorenamgUMU/sakai,udayg/sakai,kwedoff1/sakai,clhedrick/sakai,surya-janani/sakai,colczr/sakai,conder/sakai,joserabal/sakai,kwedoff1/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,rodriguezdevera/sakai,bkirschn/sakai,lorenamgUMU/sakai,puramshetty/sakai,bzhouduke123/sakai,joserabal/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,introp-software/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,willkara/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,udayg/sakai,zqian/sakai,noondaysun/sakai,surya-janani/sakai,conder/sakai,pushyamig/sakai,kingmook/sakai,whumph/sakai,surya-janani/sakai,clhedrick/sakai,introp-software/sakai,joserabal/sakai,colczr/sakai,conder/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,liubo404/sakai,frasese/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,puramshetty/sakai,Fudan-University/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,bkirschn/sakai,buckett/sakai-gitflow,puramshetty/sakai,zqian/sakai,colczr/sakai,colczr/sakai,ktakacs/sakai,conder/sakai,surya-janani/sakai,joserabal/sakai,introp-software/sakai,whumph/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,clhedrick/sakai,udayg/sakai,pushyamig/sakai,wfuedu/sakai,willkara/sakai,liubo404/sakai
|
package org.sakaiproject.component.app.scheduler.jobs;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.db.cover.SqlService;
public class SakaiEventArchiveJob implements Job {
private static final Log LOG = LogFactory.getLog(SakaiEventArchiveJob.class);
// default is to move any events older than 24 hours
private static final boolean ARCHIVE_ENABLED = true;
private static final String DEFAULT_ARCHIVE_LENGTH = "86400000";
public void execute(JobExecutionContext arg0) throws JobExecutionException {
boolean archiveEnabled = ServerConfigurationService.getBoolean("scheduler.event.archive.enabled", ARCHIVE_ENABLED);
long archiveLength = Long.parseLong(
ServerConfigurationService.getString("scheduler.event.archive.length", DEFAULT_ARCHIVE_LENGTH));
Connection sakaiConnection = null;
PreparedStatement sakaiStatement = null;
String sql;
Timestamp archiveDate = new Timestamp(System.currentTimeMillis()- archiveLength);
LOG.info("archiveDate="+archiveDate.toString());
// TODO: checkToSeeIfArchiveTablesExist();
// Make separate statements for HSQL, MySQL, Oracle
try {
sakaiConnection = SqlService.borrowConnection();
sakaiConnection.setAutoCommit(false);
// move session entries older than <date> to archive table
sql = "INSERT INTO SAKAI_SESSION_ARCHIVE (SELECT * FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?)";
LOG.info("sql="+sql);
sakaiStatement = sakaiConnection.prepareStatement(sql);
sakaiStatement.setTimestamp(1, archiveDate);
sakaiStatement.execute(sql);
sql = "DELETE FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?";
LOG.info("sql="+sql);
//sakaiStatement = sakaiConnection.prepareStatement(sql);
//sakaiStatement.setTimestamp(1, archiveDate);
//sakaiStatement.execute(sql);
sakaiConnection.commit();
// move events older than <date> to archive table
sql = "INSERT INTO SAKAI_EVENT_ARCHIVE (SELECT * FROM SAKAI_EVENT WHERE EVENT_DATE < ?)";
LOG.info("sql="+sql);
sakaiStatement = sakaiConnection.prepareStatement(sql);
sakaiStatement.setTimestamp(1, archiveDate);
sakaiStatement.execute(sql);
sql = "DELETE FROM SAKAI_EVENT WHERE EVENT_DATE < ?";
LOG.info("sql="+sql);
//sakaiStatement = sakaiConnection.prepareStatement(sql);
//sakaiStatement.setTimestamp(1, archiveDate);
//sakaiStatement.execute(sql);
sakaiConnection.commit();
} catch (SQLException e) {
LOG.error("SQLException: " +e);
} finally {
try {
if(sakaiStatement != null) sakaiStatement.close();
} catch (SQLException e) {
LOG.error("SQLException in finally block: " +e);
}
if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection);
}
}
}
|
jobscheduler/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java
|
package org.sakaiproject.component.app.scheduler.jobs;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.db.cover.SqlService;
public class SakaiEventArchiveJob implements Job {
private static final Log LOG = LogFactory.getLog(SakaiEventArchiveJob.class);
// default is to move any events older than 24 hours
private static final boolean ARCHIVE_ENABLED = true;
private static final String DEFAULT_ARCHIVE_LENGTH = "86400000";
public void execute(JobExecutionContext arg0) throws JobExecutionException {
boolean archiveEnabled = ServerConfigurationService.getBoolean("scheduler.event.archive.enabled", ARCHIVE_ENABLED);
long archiveLength = Long.parseLong(
ServerConfigurationService.getString("scheduler.event.archive.length", DEFAULT_ARCHIVE_LENGTH));
Connection sakaiConnection = null;
PreparedStatement sakaiStatement = null;
String sql;
Timestamp archiveDate = new Timestamp(System.currentTimeMillis()- archiveLength);
LOG.info("archiveDate="+archiveDate.toString());
// TODO: checkToSeeIfArchiveTablesExist();
// Make separate statements for HSQL, MySQL, Oracle
try {
sakaiConnection = SqlService.borrowConnection();
sakaiConnection.setAutoCommit(false);
// move session entries older than <date> to archive table
sql = "INSERT INTO SAKAI_SESSION_ARCHIVE (SELECT * FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?)";
LOG.info("sql="+sql);
sakaiStatement = sakaiConnection.prepareStatement(sql);
sakaiStatement.setTimestamp(1, archiveDate);
sakaiStatement.execute(sql);
sql = "DELETE FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?";
LOG.info("sql="+sql);
//sakaiStatement = sakaiConnection.prepareStatement(sql);
//sakaiStatement.setTimestamp(1, archiveDate);
//sakaiStatement.execute(sql);
sakaiConnection.commit();
// move events older than <date> to archive table
sql = "INSERT INTO SAKAI_EVENT_ARCHIVE (SELECT * FROM SAKAI_EVENT WHERE EVENT_DATE < ?)";
LOG.info("sql="+sql);
sakaiStatement = sakaiConnection.prepareStatement(sql);
sakaiStatement.setTimestamp(1, archiveDate);
sakaiStatement.execute(sql);
sql = "DELETE FROM SAKAI_EVENT WHERE EVENT_DATE < ?";
LOG.info("sql="+sql);
//sakaiStatement = sakaiConnection.prepareStatement(sql);
//sakaiStatement.setTimestamp(1, archiveDate);
//sakaiStatement.execute(sql);
sakaiConnection.commit();
} catch (SQLException e) {
LOG.error("SQLException: " +e);
} finally {
try {
if(sakaiStatement != null) sakaiStatement.close();
} catch (SQLException e) {
LOG.error("SQLException in finally block: " +e);
}
try {
if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection);
} catch (SQLException e) {
LOG.error("SQLException in finally block: " +e);
}
}
}
}
|
http://bugs.sakaiproject.org/jira/browse/SAK-14386
Fixed extra try catch
NO: 31,140
http://qa1-nl.sakaiproject.org/codereview/trunk/api/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java.html#55
Personally, bad practice if's in finally
May fail to returnConnection if fails to close sakaiStatement
try {
89 if(sakaiStatement != null) sakaiStatement.close();
90 if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection);
91 } catch (SQLException e) {
92 LOG.error("SQLException in finally block: " +e);
93 }
94 }
git-svn-id: 9006cb4c7e0a229d7b5ec939397f19f8c5ab4cf9@52711 66ffb92e-73f9-0310-93c1-f5514f145a0a
|
jobscheduler/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java
|
http://bugs.sakaiproject.org/jira/browse/SAK-14386 Fixed extra try catch NO: 31,140 http://qa1-nl.sakaiproject.org/codereview/trunk/api/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java.html#55 Personally, bad practice if's in finally May fail to returnConnection if fails to close sakaiStatement
|
|
Java
|
apache-2.0
|
ff75bc6f2f60a0f0f1fbe01bafe5644d86fd596d
| 0
|
venicegeo/pz-servicecontroller,venicegeo/pz-servicecontroller,venicegeo/pz-servicecontroller
|
package org.venice.piazza.serviceregistry.controller.messaging.handlers;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor;
import org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandler;
import org.venice.piazza.servicecontroller.util.CoreServiceProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.data.DataType;
import model.data.type.BodyDataType;
import model.data.type.TextDataType;
import model.data.type.URLParameterDataType;
import model.job.metadata.ResourceMetadata;
import model.service.metadata.ExecuteServiceData;
import model.service.metadata.Format;
import model.service.metadata.MetadataType;
import model.service.metadata.ParamDataItem;
import model.service.metadata.Service;
import util.PiazzaLogger;
@RunWith(PowerMockRunner.class)
public class ExecuteServiceHandlerTest {
ResourceMetadata rm = null;
Service service = null;
RestTemplate template = null;
@Before
public void setup() {
template = mock(RestTemplate.class);
try {
whenNew(RestTemplate.class).withNoArguments().thenReturn(template);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rm = new ResourceMetadata();
rm.name = "toUpper Params";
rm.description = "Service to convert string to uppercase";
rm.method = "POST";
service = new Service();
service.setResourceMetadata(rm);
service.setServiceId("8");
service.setUrl("http://localhost:8082/string/toUpper");
}
@PrepareForTest({ExecuteServiceHandler.class})
//@Test
public void testHandleWithNoInputs() {
String upperServiceDef = "{ \"name\":\"toUpper Params\"," +
"\"description\":\"Service to convert string to uppercase\"," +
"\"url\":\"http://localhost:8082/string/toUpper\"," +
"\"method\":\"POST\"," +
"\"params\": [\"aString\"]," +
"\"mimeType\":\"application/json\"" +
"}";
ExecuteServiceData edata = new ExecuteServiceData();
//edata.resourceId = "8";
edata.setServiceId("a842aae2-bd74-4c4b-9a65-c45e8cd9060f");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
String istring = "The rain in Spain falls mainly in the plain";
BodyDataType body = new BodyDataType();
body.content = istring;
dataInputs.put("Body", body);
edata.setDataInputs(dataInputs);
URI uri = URI.create("http://localhost:8085//string/toUpper");
when(template.postForEntity(Mockito.eq(uri),Mockito.any(Object.class),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("8")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
//@PrepareForTest({ExecuteServiceHandler.class})
//@Test
public void testHandleWithMapInputsPost() {
ExecuteServiceData edata = new ExecuteServiceData();
edata.setServiceId("8");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
TextDataType tdt = new TextDataType();
tdt.content = "My name is Marge";
dataInputs.put("name",tdt);
edata.setDataInputs(dataInputs);
rm.method = "POST";
URI uri = URI.create("http://localhost:8082/string/toUpper");
when(template.postForEntity(Mockito.eq(uri),Mockito.any(Object.class),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("8")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
@PrepareForTest({ExecuteServiceHandler.class})
@Test
public void testHandleWithMapInputsGet() {
ExecuteServiceData edata = new ExecuteServiceData();
edata.setServiceId("a842aae2-bd74-4c4b-9a65-c45e8cd9060f");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
URLParameterDataType tdt = new URLParameterDataType();
tdt.content = "The rain in Spain";
dataInputs.put("aString",tdt);
edata.setDataInputs(dataInputs);
ObjectMapper mapper = new ObjectMapper();
try {
String tsvc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(edata);
System.out.println(tsvc);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rm.method = "GET";
URI uri = URI.create("http://localhost:8082/string/toUpper?aString=The%20rain%20in%20Spain");
when(template.getForEntity(Mockito.eq(uri),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("a842aae2-bd74-4c4b-9a65-c45e8cd9060f")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
}
|
mainServiceController/src/test/java/org/venice/piazza/serviceregistry/controller/messaging/handlers/ExecuteServiceHandlerTest.java
|
package org.venice.piazza.serviceregistry.controller.messaging.handlers;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor;
import org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandler;
import org.venice.piazza.servicecontroller.util.CoreServiceProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.data.DataType;
import model.data.type.BodyDataType;
import model.data.type.TextDataType;
import model.data.type.URLParameterDataType;
import model.job.metadata.ResourceMetadata;
import model.service.metadata.ExecuteServiceData;
import model.service.metadata.Format;
import model.service.metadata.MetadataType;
import model.service.metadata.ParamDataItem;
import model.service.metadata.Service;
import util.PiazzaLogger;
@RunWith(PowerMockRunner.class)
public class ExecuteServiceHandlerTest {
ResourceMetadata rm = null;
Service service = null;
RestTemplate template = null;
@Before
public void setup() {
template = mock(RestTemplate.class);
try {
whenNew(RestTemplate.class).withNoArguments().thenReturn(template);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rm = new ResourceMetadata();
rm.name = "toUpper Params";
rm.description = "Service to convert string to uppercase";
rm.method = "POST";
service = new Service();
service.setResourceMetadata(rm);
service.setServiceId("8");
}
@PrepareForTest({ExecuteServiceHandler.class})
//@Test
public void testHandleWithNoInputs() {
String upperServiceDef = "{ \"name\":\"toUpper Params\"," +
"\"description\":\"Service to convert string to uppercase\"," +
"\"url\":\"http://localhost:8082/string/toUpper\"," +
"\"method\":\"POST\"," +
"\"params\": [\"aString\"]," +
"\"mimeType\":\"application/json\"" +
"}";
ExecuteServiceData edata = new ExecuteServiceData();
//edata.resourceId = "8";
edata.setServiceId("a842aae2-bd74-4c4b-9a65-c45e8cd9060f");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
String istring = "The rain in Spain falls mainly in the plain";
BodyDataType body = new BodyDataType();
body.content = istring;
dataInputs.put("Body", body);
edata.setDataInputs(dataInputs);
URI uri = URI.create("http://localhost:8085//string/toUpper");
when(template.postForEntity(Mockito.eq(uri),Mockito.any(Object.class),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("8")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
//@PrepareForTest({ExecuteServiceHandler.class})
//@Test
public void testHandleWithMapInputsPost() {
ExecuteServiceData edata = new ExecuteServiceData();
edata.setServiceId("8");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
TextDataType tdt = new TextDataType();
tdt.content = "My name is Marge";
dataInputs.put("name",tdt);
edata.setDataInputs(dataInputs);
rm.method = "POST";
URI uri = URI.create("http://localhost:8082/string/toUpper");
when(template.postForEntity(Mockito.eq(uri),Mockito.any(Object.class),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("8")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
@PrepareForTest({ExecuteServiceHandler.class})
@Test
public void testHandleWithMapInputsGet() {
ExecuteServiceData edata = new ExecuteServiceData();
edata.setServiceId("a842aae2-bd74-4c4b-9a65-c45e8cd9060f");
HashMap<String,DataType> dataInputs = new HashMap<String,DataType>();
URLParameterDataType tdt = new URLParameterDataType();
tdt.content = "The rain in Spain";
dataInputs.put("aString",tdt);
edata.setDataInputs(dataInputs);
ObjectMapper mapper = new ObjectMapper();
try {
String tsvc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(edata);
System.out.println(tsvc);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rm.method = "GET";
URI uri = URI.create("http://localhost:8085/string/toUpper?aString=The%20rain%20in%20Spain");
when(template.getForEntity(Mockito.eq(uri),Mockito.eq(String.class))).thenReturn(new ResponseEntity<String>("testExecuteService",HttpStatus.FOUND));
MongoAccessor mockMongo = mock(MongoAccessor.class);
when(mockMongo.getServiceById("a842aae2-bd74-4c4b-9a65-c45e8cd9060f")).thenReturn(service);
CoreServiceProperties props = mock(CoreServiceProperties.class);
PiazzaLogger logger = mock(PiazzaLogger.class);
ExecuteServiceHandler handler = new ExecuteServiceHandler(mockMongo,props,logger);
ResponseEntity<String> retVal = handler.handle(edata);
assertTrue(retVal.getBody().contains("testExecuteService"));
}
}
|
Corrected 2 unit tests
|
mainServiceController/src/test/java/org/venice/piazza/serviceregistry/controller/messaging/handlers/ExecuteServiceHandlerTest.java
|
Corrected 2 unit tests
|
|
Java
|
apache-2.0
|
cfcf67d345abc14f7de77d0cf629c41d5668f794
| 0
|
wso2-extensions/identity-inbound-auth-saml,wso2-extensions/identity-inbound-auth-saml
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.sso.saml.ui.client;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.identity.sso.saml.stub.types.SAMLSSOServiceProviderDTO;
import org.wso2.carbon.identity.sso.saml.ui.SAMLSSOUIConstants;
import org.wso2.carbon.ui.CarbonUIMessage;
import org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor;
import org.wso2.carbon.utils.FileItemData;
import org.wso2.carbon.utils.ServerConstants;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SamlSPMetadataUploadExecutor extends AbstractFileUploadExecutor {
private static final String[] ALLOWED_FILE_EXTENSIONS = new String[]{".xml"};
private static final String APPLICATION_SP_NAME_KEY = "application-sp-name";
private String errorRedirectionPage;
@Override
public boolean execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws CarbonException, IOException {
log.info("Uploading");
String webContext = (String) httpServletRequest.getAttribute(CarbonConstants.WEB_CONTEXT);
String serverURL = (String) httpServletRequest.getAttribute(CarbonConstants.SERVER_URL);
String cookie = (String) httpServletRequest.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
String spName = getFormFieldsMap().get(APPLICATION_SP_NAME_KEY).get(0);
log.info(spName);
errorRedirectionPage = getContextRoot(httpServletRequest) + "/" + webContext
+ "/sso-saml/add_service_provider.jsp?spName=" + spName;
Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
if (fileItemsMap == null || fileItemsMap.isEmpty()) {
String msg = "File uploading failed. No files are specified.";
log.error(msg);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
return false;
}
SAMLSSOConfigServiceClient client =
new SAMLSSOConfigServiceClient(cookie, serverURL, configurationContext);
List<FileItemData> fileItems = fileItemsMap.get("metadataFromFileSystem");
String msg;
try {
SAMLSSOServiceProviderDTO serviceProviderDTO = null;
for (FileItemData fileItem : fileItems) {
String filename = getFileName(fileItem.getFileItem().getName());
checkServiceFileExtensionValidity(filename, ALLOWED_FILE_EXTENSIONS);
if (!filename.endsWith(".xml")) {
throw new CarbonException("File with extension " +
getFileName(fileItem.getFileItem().getName()) + " is not supported!");
} else {
StringBuilder policyContent = new StringBuilder();
try (InputStreamReader ir = new InputStreamReader(fileItem.getDataHandler().getInputStream());
BufferedReader br = new BufferedReader(ir)) {
String temp;
while ((temp = br.readLine()) != null) {
policyContent.append(temp);
}
}
if (StringUtils.isNotEmpty(policyContent.toString())) {
serviceProviderDTO = client.uploadServiceProvider(policyContent.toString());
}
}
}
if (serviceProviderDTO != null) {
httpServletResponse.setContentType("text/html; charset=utf-8");
msg = "Metadata have been uploaded successfully.";
String attributeConsumingServiceIndex = "";
if (serviceProviderDTO.getAttributeConsumingServiceIndex() != null) {
attributeConsumingServiceIndex = serviceProviderDTO.getAttributeConsumingServiceIndex();
}
// Store the certificate contained inside the metadata file, in the session.
// This will be used by service provider update operation to know the certificate came inside SAML
// metadata file.
httpServletRequest.getSession().setAttribute(SAMLSSOUIConstants
.SESSION_ATTRIBUTE_NAME_APPLICATION_CERTIFICATE,
serviceProviderDTO.getCertificateContent());
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, httpServletRequest,
httpServletResponse, getContextRoot(httpServletRequest)
+ "/" + webContext + "/application/configure-service-provider" +
".jsp?action=update&display=samlIssuer&spName=" + spName + "&samlIssuer=" +
serviceProviderDTO.getIssuer() + "&attrConServIndex=" + attributeConsumingServiceIndex);
return true;
} else {
msg = "Metadata uploading failed. ";
log.error(msg);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
}
} catch (Exception e) {
msg = "Metadata uploading failed. " + e.getMessage();
log.error(msg, e);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
}
return false;
}
@Override
protected String getErrorRedirectionPage() {
return errorRedirectionPage;
}
}
|
components/org.wso2.carbon.identity.sso.saml.ui/src/main/java/org/wso2/carbon/identity/sso/saml/ui/client/SamlSPMetadataUploadExecutor.java
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.sso.saml.ui.client;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.identity.sso.saml.stub.types.SAMLSSOServiceProviderDTO;
import org.wso2.carbon.identity.sso.saml.ui.SAMLSSOUIConstants;
import org.wso2.carbon.ui.CarbonUIMessage;
import org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor;
import org.wso2.carbon.utils.FileItemData;
import org.wso2.carbon.utils.ServerConstants;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SamlSPMetadataUploadExecutor extends AbstractFileUploadExecutor {
private static final String[] ALLOWED_FILE_EXTENSIONS = new String[]{".xml"};
private String errorRedirectionPage;
@Override
public boolean execute(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws CarbonException, IOException {
log.info("Uploading");
String webContext = (String) httpServletRequest.getAttribute(CarbonConstants.WEB_CONTEXT);
String serverURL = (String) httpServletRequest.getAttribute(CarbonConstants.SERVER_URL);
String cookie = (String) httpServletRequest.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
String spName = getFormFieldsMap().get("application-sp-name").get(0);
log.info(spName);
errorRedirectionPage = getContextRoot(httpServletRequest) + "/" + webContext
+ "/sso-saml/add_service_provider.jsp?spName=" + spName;
Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
if (fileItemsMap == null || fileItemsMap.isEmpty()) {
String msg = "File uploading failed. No files are specified.";
log.error(msg);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
return false;
}
SAMLSSOConfigServiceClient client =
new SAMLSSOConfigServiceClient(cookie, serverURL, configurationContext);
List<FileItemData> fileItems = fileItemsMap.get("metadataFromFileSystem");
String msg;
try {
SAMLSSOServiceProviderDTO serviceProviderDTO = null;
for (FileItemData fileItem : fileItems) {
String filename = getFileName(fileItem.getFileItem().getName());
checkServiceFileExtensionValidity(filename, ALLOWED_FILE_EXTENSIONS);
if (!filename.endsWith(".xml")) {
throw new CarbonException("File with extension " +
getFileName(fileItem.getFileItem().getName()) + " is not supported!");
} else {
StringBuilder policyContent = new StringBuilder();
try (InputStreamReader ir = new InputStreamReader(fileItem.getDataHandler().getInputStream());
BufferedReader br = new BufferedReader(ir)) {
String temp;
while ((temp = br.readLine()) != null) {
policyContent.append(temp);
}
}
if (StringUtils.isNotEmpty(policyContent.toString())) {
serviceProviderDTO = client.uploadServiceProvider(policyContent.toString());
}
}
}
if (serviceProviderDTO != null) {
httpServletResponse.setContentType("text/html; charset=utf-8");
msg = "Metadata have been uploaded successfully.";
String attributeConsumingServiceIndex = "";
if (serviceProviderDTO.getAttributeConsumingServiceIndex() != null) {
attributeConsumingServiceIndex = serviceProviderDTO.getAttributeConsumingServiceIndex();
}
// Store the certificate contained inside the metadata file, in the session.
// This will be used by service provider update operation to know the certificate came inside SAML
// metadata file.
httpServletRequest.getSession().setAttribute(SAMLSSOUIConstants
.SESSION_ATTRIBUTE_NAME_APPLICATION_CERTIFICATE,
serviceProviderDTO.getCertificateContent());
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, httpServletRequest,
httpServletResponse, getContextRoot(httpServletRequest)
+ "/" + webContext + "/application/configure-service-provider" +
".jsp?action=update&display=samlIssuer&spName=" + spName + "&samlIssuer=" +
serviceProviderDTO.getIssuer() + "&attrConServIndex=" + attributeConsumingServiceIndex);
return true;
} else {
msg = "Metadata uploading failed. ";
log.error(msg);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
}
} catch (Exception e) {
msg = "Metadata uploading failed. " + e.getMessage();
log.error(msg, e);
CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.ERROR, httpServletRequest,
httpServletResponse, errorRedirectionPage);
}
return false;
}
@Override
protected String getErrorRedirectionPage() {
return errorRedirectionPage;
}
}
|
Added constant for application sp name key and reformat code.
|
components/org.wso2.carbon.identity.sso.saml.ui/src/main/java/org/wso2/carbon/identity/sso/saml/ui/client/SamlSPMetadataUploadExecutor.java
|
Added constant for application sp name key and reformat code.
|
|
Java
|
apache-2.0
|
30b4e7b02aa300449327b53c2f39f1bb39879ca7
| 0
|
somas/spring-security-oauth,jmnarloch/spring-security-oauth,pawans-optimus/spring-security-oauth,xiangzhuyuan/spring-security-oauth,gharizanov92/spring-security-oauth,xueyumusic/spring-security-oauth,michaelwoodson/spring-security-oauth,KeesKoffeman/spring-security-oauth,efenderbosch/spring-security-oauth,280455936/spring-security-oauth,mostgreat/spring-security-oauth,SupengCai/spring-security-oauth,yuanqixun/spring-security-oauth,marcosbarbero/spring-security-oauth,rodrijuarez/spring-security-oauth,rangakg/spring-security-oauth,karteek-salumuri/spring-security-oauth,niravmak/spring-security-oauth,voronaam/spring-security-oauth,vivekkiran/spring-security-oauth,ollie314/spring-security-oauth,ssxxue/spring-security-oauth,spring-projects/spring-security-oauth,Peter32/spring-security-oauth,Fitzoh/spring-security-oauth,offbye/spring-security-oauth,pkdevbox/spring-security-oauth,K-Tom/spring-security-oauth,reypader/spring-security-oauth,eddiejaoude/spring-security-oauth,adrianoschmidt/spring-security-oauth,latte1855/spring-security-oauth,jramal/spring-security-oauth,tkrille/spring-security-oauth,dviron27/spring-security-oauth,raoghuge/spring-security-oauth,ahmadOwais/spring-security-oauth,hongyang070/spring-security-oauth,cruiser/spring-security-oauth,gharizanov92/spring-security-oauth,ractive/spring-security-oauth,Fitzoh/spring-security-oauth,ollie314/spring-security-oauth,jgrandja/spring-security-oauth,NorthStation/spring-security-oauth
|
package org.springframework.security.oauth2.client.token.grant.client;
import java.util.Iterator;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* Provider for obtaining an oauth2 access token by using client credentials.
*
* @author Dave Syer
*/
public class ClientCredentialsAccessTokenProvider extends OAuth2AccessTokenSupport implements AccessTokenProvider {
public boolean supportsResource(OAuth2ProtectedResourceDetails resource) {
return resource instanceof ClientCredentialsResourceDetails
&& "client_credentials".equals(resource.getGrantType());
}
public boolean supportsRefresh(OAuth2ProtectedResourceDetails resource) {
return false;
}
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource,
OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
return null;
}
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
throws UserRedirectRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
ClientCredentialsResourceDetails resource = (ClientCredentialsResourceDetails) details;
return retrieveToken(getParametersForTokenRequest(resource), new HttpHeaders(), resource);
}
private MultiValueMap<String, String> getParametersForTokenRequest(ClientCredentialsResourceDetails resource) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("grant_type", "client_credentials");
if (resource.isScoped()) {
StringBuilder builder = new StringBuilder();
List<String> scope = resource.getScope();
if (scope != null) {
Iterator<String> scopeIt = scope.iterator();
while (scopeIt.hasNext()) {
builder.append(scopeIt.next());
if (scopeIt.hasNext()) {
builder.append(' ');
}
}
}
form.set("scope", builder.toString());
}
return form;
}
}
|
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/client/token/grant/client/ClientCredentialsAccessTokenProvider.java
|
package org.springframework.security.oauth2.client.token.grant.client;
import java.util.Iterator;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* Provider for obtaining an oauth2 access token by using client credentials.
*
* @author Dave Syer
*/
public class ClientCredentialsAccessTokenProvider extends OAuth2AccessTokenSupport implements AccessTokenProvider {
public boolean supportsResource(OAuth2ProtectedResourceDetails resource) {
return resource instanceof ClientCredentialsResourceDetails
&& "client_credentials".equals(resource.getGrantType());
}
public boolean supportsRefresh(OAuth2ProtectedResourceDetails resource) {
return false;
}
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource,
OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
return null;
}
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
throws UserRedirectRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
ClientCredentialsResourceDetails resource = (ClientCredentialsResourceDetails) details;
return retrieveToken(getParametersForTokenRequest(resource), new HttpHeaders(), resource);
}
private MultiValueMap<String, String> getParametersForTokenRequest(ClientCredentialsResourceDetails resource) {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("grant_type", "client_credentials");
form.set("client_id", resource.getClientId());
if (resource.isScoped()) {
StringBuilder builder = new StringBuilder();
List<String> scope = resource.getScope();
if (scope != null) {
Iterator<String> scopeIt = scope.iterator();
while (scopeIt.hasNext()) {
builder.append(scopeIt.next());
if (scopeIt.hasNext()) {
builder.append(' ');
}
}
}
form.set("scope", builder.toString());
}
return form;
}
}
|
Fix for client_id in req parm and auth header
|
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/client/token/grant/client/ClientCredentialsAccessTokenProvider.java
|
Fix for client_id in req parm and auth header
|
|
Java
|
bsd-3-clause
|
b1909d94380c322b1ec9fb514afbcc2035dffa1a
| 0
|
softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass,softappeal/yass
|
package ch.softappeal.yass.tutorial.datagram;
import ch.softappeal.yass.remote.*;
import ch.softappeal.yass.serialize.*;
import ch.softappeal.yass.transport.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import static ch.softappeal.yass.serialize.ReaderKt.*;
import static ch.softappeal.yass.serialize.WriterKt.*;
public final class DatagramTransport {
private DatagramTransport() {
// disable
}
private static void checkOneWay(final MethodMapping methodMapping, final Request request) {
if (!methodMapping.getOneWay()) {
throw new IllegalArgumentException(
"transport not allowed for rpc method (serviceId " + request.getServiceId() +
", methodId " + request.getMethodId() + ')'
);
}
}
public static Client client(
final Serializer messageSerializer, final DatagramChannel channel, final SocketAddress target
) {
Objects.requireNonNull(messageSerializer);
Objects.requireNonNull(channel);
Objects.requireNonNull(target);
return new Client() {
@Override
public void invoke(final ClientInvocation invocation) {
invocation.invoke(true, request -> {
checkOneWay(invocation.getMethodMapping(), request);
final ByteBufferOutputStream out = new ByteBufferOutputStream(128);
try {
messageSerializer.write(writer(out), request);
channel.send(out.toByteBuffer(), target);
} catch (final Exception e) {
throw new RuntimeException(e);
}
return null;
});
}
};
}
public static void invoke(
final ServerTransport setup, final DatagramChannel channel, final int maxRequestBytes
) throws Exception {
final ByteBuffer in = ByteBuffer.allocate(maxRequestBytes);
channel.receive(in);
in.flip();
final Request request = setup.read(reader(in));
if (in.hasRemaining()) {
throw new RuntimeException("input buffer is not empty");
}
final ServerInvocation invocation = setup.invocation(true, request);
checkOneWay(invocation.getMethodMapping(), request);
invocation.invoke(reply -> null);
}
}
|
kotlin/tutorial/main/ch/softappeal/yass/tutorial/datagram/DatagramTransport.java
|
package ch.softappeal.yass.tutorial.datagram;
import ch.softappeal.yass.remote.*;
import ch.softappeal.yass.serialize.*;
import ch.softappeal.yass.transport.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import static ch.softappeal.yass.serialize.ReaderKt.*;
import static ch.softappeal.yass.serialize.WriterKt.*;
public final class DatagramTransport {
private DatagramTransport() {
// disable
}
private static void checkOneWay(final MethodMapping methodMapping, final Request request) {
if (!methodMapping.getOneWay()) {
throw new IllegalArgumentException(
"transport not allowed for rpc method (serviceId " + request.getServiceId() +
", methodId " + request.getMethodId() + ')'
);
}
}
public static Client client(
final Serializer messageSerializer, final DatagramChannel channel, final SocketAddress target
) {
Objects.requireNonNull(messageSerializer);
Objects.requireNonNull(channel);
Objects.requireNonNull(target);
return new Client() {
@Override
public void invoke(final ClientInvocation invocation) {
invocation.invoke(false, request -> {
checkOneWay(invocation.getMethodMapping(), request);
final ByteBufferOutputStream out = new ByteBufferOutputStream(128);
try {
messageSerializer.write(writer(out), request);
channel.send(out.toByteBuffer(), target);
} catch (final Exception e) {
throw new RuntimeException(e);
}
return null;
});
}
};
}
public static void invoke(
final ServerTransport setup, final DatagramChannel channel, final int maxRequestBytes
) throws Exception {
final ByteBuffer in = ByteBuffer.allocate(maxRequestBytes);
channel.receive(in);
in.flip();
final Request request = setup.read(reader(in));
if (in.hasRemaining()) {
throw new RuntimeException("input buffer is not empty");
}
final ServerInvocation invocation = setup.invocation(true, request);
checkOneWay(invocation.getMethodMapping(), request);
invocation.invoke(reply -> null);
}
}
|
cosmetic
|
kotlin/tutorial/main/ch/softappeal/yass/tutorial/datagram/DatagramTransport.java
|
cosmetic
|
|
Java
|
bsd-3-clause
|
1b5e0774c4383520746c0fb5a5d9ed882f9988e9
| 0
|
motech-implementations/mim,ngraczewski/mim,ngraczewski/mim,motech-implementations/mim,motech-implementations/mim,motech-implementations/mim,ngraczewski/mim
|
package org.motechproject.nms.testing.it.kilkari;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createDistrict;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthBlock;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthFacility;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthFacilityType;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createState;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createTaluka;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createVillage;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.nms.csv.exception.CsvImportDataException;
import org.motechproject.nms.kilkari.domain.DeactivationReason;
import org.motechproject.nms.kilkari.domain.Subscriber;
import org.motechproject.nms.kilkari.domain.Subscription;
import org.motechproject.nms.kilkari.domain.SubscriptionError;
import org.motechproject.nms.kilkari.domain.SubscriptionOrigin;
import org.motechproject.nms.kilkari.domain.SubscriptionPackType;
import org.motechproject.nms.kilkari.domain.SubscriptionRejectionReason;
import org.motechproject.nms.kilkari.repository.SubscriberDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionErrorDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionPackDataService;
import org.motechproject.nms.kilkari.service.MctsBeneficiaryImportService;
import org.motechproject.nms.kilkari.service.SubscriberService;
import org.motechproject.nms.kilkari.service.SubscriptionService;
import org.motechproject.nms.region.domain.District;
import org.motechproject.nms.region.domain.HealthBlock;
import org.motechproject.nms.region.domain.HealthFacility;
import org.motechproject.nms.region.domain.HealthFacilityType;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.region.domain.Taluka;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.repository.CircleDataService;
import org.motechproject.nms.region.repository.DistrictDataService;
import org.motechproject.nms.region.repository.LanguageDataService;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.testing.it.utils.SubscriptionHelper;
import org.motechproject.nms.testing.service.TestingService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class MctsBeneficiaryImportServiceBundleIT extends BasePaxIT {
@Inject
private TestingService testingService;
@Inject
private LanguageDataService languageDataService;
@Inject
private StateDataService stateDataService;
@Inject
private DistrictDataService districtDataService;
@Inject
private CircleDataService circleDataService;
@Inject
private SubscriberDataService subscriberDataService;
@Inject
private SubscriptionService subscriptionService;
@Inject
private SubscriptionPackDataService subscriptionPackDataService;
@Inject
private MctsBeneficiaryImportService mctsBeneficiaryImportService;
@Inject
private SubscriptionErrorDataService subscriptionErrorDataService;
@Inject
private SubscriberService subscriberService;
@Before
public void setUp() {
testingService.clearDatabase();
createLocationData();
SubscriptionHelper subscriptionHelper = new SubscriptionHelper(subscriptionService, subscriberDataService,
subscriptionPackDataService, languageDataService, circleDataService,
stateDataService, districtDataService);
subscriptionHelper.pregnancyPack();
subscriptionHelper.childPack();
}
private void createLocationData() {
// specific locations from the mother and child data files:
State state21 = createState(21L, "State 21");
District district2 = createDistrict(state21, 2L, "Jharsuguda");
District district3 = createDistrict(state21, 3L, "Sambalpur");
District district4 = createDistrict(state21, 4L, "Debagarh");
state21.getDistricts().addAll(Arrays.asList(district2, district3, district4));
Taluka taluka24 = createTaluka(district2, "0024", "Laikera P.S.", 24);
district2.getTalukas().add(taluka24);
Taluka taluka26 = createTaluka(district3, "0026", "Govindpur P.S.", 26);
district3.getTalukas().add(taluka26);
Taluka taluka46 = createTaluka(district4, "0046", "Debagarh P.S.", 46);
district4.getTalukas().add(taluka46);
HealthBlock healthBlock259 = createHealthBlock(taluka24, 259L, "Laikera", "hq");
taluka24.getHealthBlocks().add(healthBlock259);
HealthBlock healthBlock453 = createHealthBlock(taluka26, 453L, "Bamara", "hq");
taluka26.getHealthBlocks().add(healthBlock453);
HealthBlock healthBlock153 = createHealthBlock(taluka46, 153L, "Tileibani", "hq");
taluka46.getHealthBlocks().add(healthBlock153);
HealthFacilityType facilityType635 = createHealthFacilityType("Mundrajore CHC", 635L);
HealthFacility healthFacility635 = createHealthFacility(healthBlock259, 635L, "Mundrajore CHC", facilityType635);
healthBlock259.getHealthFacilities().add(healthFacility635);
HealthFacilityType facilityType41 = createHealthFacilityType("Garposh CHC", 41L);
HealthFacility healthFacility41 = createHealthFacility(healthBlock453, 41L, "Garposh CHC", facilityType41);
healthBlock453.getHealthFacilities().add(healthFacility41);
HealthFacilityType facilityType114 = createHealthFacilityType("CHC Tileibani", 114L);
HealthFacility healthFacility114 = createHealthFacility(healthBlock153, 114L, "CHC Tileibani", facilityType114);
healthBlock153.getHealthFacilities().add(healthFacility114);
Village village10004693 = createVillage(taluka24, 10004693L, null, "Khairdihi");
Village village10004691 = createVillage(taluka24, 10004691L, null, "Gambhariguda");
Village village1509 = createVillage(taluka24, null, 1509L, "Mundrajore");
Village village1505 = createVillage(taluka24, null, 1505L, "Kulemura");
Village village10004690 = createVillage(taluka24, 10004690L, null, "Ampada");
Village village10004697 = createVillage(taluka24, 10004697L, null, "Saletikra");
taluka24.getVillages().addAll(Arrays.asList(village10004693, village10004691, village1509, village1505,
village10004690, village10004697));
Village village3089 = createVillage(taluka46, null, 3089L, "Podapara");
taluka46.getVillages().add(village3089);
stateDataService.create(state21);
}
@Test
public void testImportMotherNewSubscriber() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals("Shanti Ekka", subscriber.getMother().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(SubscriptionOrigin.MCTS_IMPORT, subscription.getOrigin());
}
@Test
public void testImportMotherAlternateDateFormat() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = lmp.toString("dd/MM/yyyy");
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
}
@Test
public void testImportMotherWhoAlreadyExistsUpdateLmp() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals("Shanti Ekka", subscriber.getMother().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(90, Days.daysBetween(lmp.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
DateTime newLmp = DateTime.now().minusDays(150);
String newLmpString = getDateString(newLmp);
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + newLmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(newLmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(90, Days.daysBetween(newLmp.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
}
@Test(expected = CsvImportDataException.class)
public void testImportMotherInvalidState() throws Exception {
Reader reader = createMotherDataReaderWithHeaders("9\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t22-11-2014");
mctsBeneficiaryImportService.importMotherData(reader);
}
@Test
public void testImportChildNewSubscriberNoMotherId() throws Exception {
DateTime dob = DateTime.now().minusDays(100);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
assertEquals("Baby1 of Lilima Kua", subscriber.getChild().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(SubscriptionOrigin.MCTS_IMPORT, subscription.getOrigin());
assertEquals(SubscriptionPackType.CHILD, subscription.getSubscriptionPack().getType());
}
@Test
public void testImportMotherAndChildSameMsisdn() throws Exception {
// import mother
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
Set<Subscription> subscriptions = subscriber.getActiveSubscriptions();
assertEquals(1, subscriptions.size());
// import child with same MSISDN and matching MotherID
DateTime dob = DateTime.now().minusDays(200);
String dobString = getDateString(dob);
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t9876543210\tBaby1 of Shanti Ekka\t1234567890\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
subscriptions = subscriber.getActiveSubscriptions();
Subscription childSubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.CHILD);
Subscription pregnancySubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.PREGNANCY);
// the pregnancy subscription should have been deactivated
assertEquals(1, subscriptions.size());
assertNotNull(childSubscription);
assertNull(pregnancySubscription);
}
@Test
public void testImportMotherDataFromSampleFile() throws Exception {
mctsBeneficiaryImportService.importMotherData(read("csv/mother.txt"));
State expectedState = stateDataService.findByCode(21L);
District expectedDistrict = districtDataService.findByCode(3L);
Subscriber subscriber1 = subscriberDataService.findByCallingNumber(9439986187L);
assertMother(subscriber1, "210302604211400029", getDateTime("22/11/2014"), "Shanti Ekka", expectedState,
expectedDistrict);
Subscriber subscriber2 = subscriberDataService.findByCallingNumber(7894221701L);
assertMother(subscriber2, "210302604611400023", getDateTime("15/6/2014"), "Damayanti Khadia", expectedState,
expectedDistrict);
// although our MCTS data file contains 10 mothers, we only create 3 subscribers due to duplicate phone numbers
assertEquals(3, subscriberDataService.count());
}
@Test
public void testImportChildDataFromSampleFile() throws Exception {
mctsBeneficiaryImportService.importChildData(read("csv/child.txt"));
State expectedState = stateDataService.findByCode(21L);
District expectedDistrict2 = districtDataService.findByCode(2L);
District expectedDistrict4 = districtDataService.findByCode(4L);
Subscriber subscriber1 = subscriberDataService.findByCallingNumber(9439998253L);
assertChild(subscriber1, "210404600521400116", getDateTime("2/12/2014"), "Baby1 of PANI HEMRAM", expectedState,
expectedDistrict4);
// although our MCTS data file contains 10 children, we only create 8 subscribers due to duplicate phone numbers
assertEquals(8, subscriberDataService.count());
}
private void assertMother(Subscriber subscriber, String motherId, DateTime lmp, String name, State state, District district) {
assertNotNull(subscriber);
assertNotNull(subscriber.getMother());
assertEquals(motherId, subscriber.getMother().getBeneficiaryId());
assertEquals(name, subscriber.getMother().getName());
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals(state, subscriber.getMother().getState());
assertEquals(district, subscriber.getMother().getDistrict());
}
private void assertChild(Subscriber subscriber, String childId, DateTime dob, String name, State state, District district) {
assertNotNull(subscriber);
assertNotNull(subscriber.getChild());
assertEquals(childId, subscriber.getChild().getBeneficiaryId());
assertEquals(name, subscriber.getChild().getName());
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
assertEquals(state, subscriber.getChild().getState());
assertEquals(district, subscriber.getChild().getDistrict());
}
private String getDateString(DateTime date) {
return date.toString("dd-MM-yyyy");
}
private DateTime getDateTime(String dateString) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
return DateTime.parse(dateString, formatter);
}
private Reader createChildDataReaderWithHeaders(String... lines) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("State Name : State 1").append("\n");
builder.append("\n");
builder.append("StateID\tDistrict_ID\tTaluka_ID\tHealthBlock_ID\tPHC_ID\tVillage_ID\tID_No\tName\tMother_ID\tWhom_PhoneNo\tBirthdate");
builder.append("\n");
for (String line : lines) {
builder.append(line).append("\n");
}
return new StringReader(builder.toString());
}
private Reader createMotherDataReaderWithHeaders(String... lines) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("State Name : State 1").append("\n");
builder.append("\n");
builder.append("StateID\tDistrict_ID\tTaluka_ID\tHealthBlock_ID\tPHC_ID\tVillage_ID\tID_No\tName\tWhom_PhoneNo\tLMP_Date");
builder.append("\n");
for (String line : lines) {
builder.append(line).append("\n");
}
return new StringReader(builder.toString());
}
private Reader read(String resource) {
return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(resource));
}
/*
* To verify mother subscription is rejected when future LMP is provided
*/
@Test
public void verifyFT282() throws Exception {
DateTime lmp = DateTime.now().plusDays(1);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.INVALID_LMP);
}
/*
* To verify child subscriber is rejected when future DOB is provided.
*/
@Test
public void verifyFT283() throws Exception {
DateTime dob = DateTime.now().plusDays(1);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.INVALID_DOB);
}
/*
* To verify mother subscription is rejected when LMP provided is 72 weeks back.
*/
@Test
public void verifyFT284() throws Exception {
DateTime lmp = DateTime.now().minusDays(7*72+90);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.INVALID_LMP);
}
/*
* To verify child subscription is rejected when DOB provided is 48 weeks back.
*/
@Test
public void verifyFT285() throws Exception {
DateTime dob = DateTime.now().minusDays(7*48);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.INVALID_DOB);
}
/*
* To verify MCTS upload is rejected when MSISDN number already exist
* for subscriber with new mctsid(beneficiary id).
*/
@Test
public void verifyFT287() throws Exception {
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
// create subscriber and subscription
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
// attempt to create subscriber with same msisdn but different mcts.
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567891\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.ALREADY_SUBSCRIBED);
}
/*
* To verify MCTS upload is rejected when MCTS doesn’t contain DOB.
*
* https://applab.atlassian.net/browse/NMS-206
*/
@Test
@Ignore
public void verifyFT288_1() throws Exception {
//DOB is missing
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t");
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.MISSING_DOB);
}
/*
* To verify MCTS upload is rejected when MCTS doesn’t contain LMP.
*
* https://applab.atlassian.net/browse/NMS-206
*/
@Test
@Ignore
public void verifyFT288_2() throws Exception {
//LMP is missing
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t");
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.MISSING_LMP);
}
private void assertSubscriptionError(SubscriptionError susbError, SubscriptionPackType packType,
SubscriptionRejectionReason rejectionReason) {
assertNotNull(susbError);
assertEquals(packType, susbError.getPackType());
assertEquals(rejectionReason, susbError.getRejectionReason());
}
/*
* NMS_FT_289:: To verify new subscription is created successfully when subscription
* already exist having status as "Completed" for same MSISDN.
* NMS_FT_306:: To verify LMP is changed successfully via CSV when subscription
* already exist for pregnancyPack having status as "Completed"
*/
@Test
public void verifyFT289() throws Exception {
DateTime lmp = DateTime.now();
String lmpString = getDateString(lmp);
// create subscriber and subscription
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
//Make subscription completed
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
subscriber.setLastMenstrualPeriod(lmp.minusDays(650));
subscriberService.update(subscriber);
//create a new subscription for subscriber whose subscription is completed.
lmpString = getDateString(lmp.minus(200));
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(lmpString, getDateString(subscriber.getLastMenstrualPeriod()));
}
/*
* NMS_FT_290:: To verify new subscription is created successfully when subscription
* already exist having status as "Deactivated" for same MSISDN.
* NMS_FT_305:: To verify LMP is changed successfully via CSV when subscription
* already exist for pregnancyPack having status as "Deactivated"
*/
@Test
public void verifyFT290() throws Exception {
DateTime lmp = DateTime.now().minus(100);
String lmpString = getDateString(lmp);
// create subscriber and subscription
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
//Mark subscription deactivate
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
Subscription subscription =subscriber.getActiveSubscriptions().iterator().next();
subscriptionService.deactivateSubscription(subscription, DeactivationReason.MISCARRIAGE_OR_ABORTION);
//create a new subscription for subscriber whose subscription is deactivated.
lmpString = getDateString(lmp.minus(200));
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(lmpString, getDateString(subscriber.getLastMenstrualPeriod()));
}
/*
* To verify MCTS upload is rejected when location information is incorrect.
*
* https://applab.atlassian.net/browse/NMS-208
*/
@Test(expected = CsvImportDataException.class)
@Ignore
public void verifyFT286() throws Exception {
State state31 = createState(31L, "State 31");
stateDataService.create(state31);
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
//attempt to create subscriber and subscription with wrong state-district combination. it should be rejected
Reader reader = createChildDataReaderWithHeaders("31\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
}
/*
* To verify DOB is changed successfully via CSV when subscription
* already exist for childPack having status as "Deactivated"
*/
@Test
public void verifyFT309() throws Exception {
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
//Mark subscription deactivate
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
Subscription subscription =subscriber.getActiveSubscriptions().iterator().next();
subscriptionService.deactivateSubscription(subscription, DeactivationReason.STILL_BIRTH);
//create a new subscription for subscriber whose subscription is deactivated.
dobString = getDateString(dob.minus(50));
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(dobString, getDateString(subscriber.getDateOfBirth()));
}
/*
* To verify DOB is changed successfully via CSV when subscription
* already exist for childPack having status as "Deactivated"
*/
@Test
public void verifyFT310() throws Exception {
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
//Make subscription completed
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
subscriber.setDateOfBirth(dob.minusDays(500));
subscriberService.update(subscriber);
//create a new subscription for subscriber whose subscription is deactivated.
dobString = getDateString(dob.minus(50));
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(dobString, getDateString(subscriber.getDateOfBirth()));
}
/*
* To verify DOB is changed successfully via CSV when subscription
* already exist for childPack having status as "Active"
*/
@Test
public void verifyFT311() throws Exception {
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
assertEquals("Baby1 of Lilima Kua", subscriber.getChild().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(0, Days.daysBetween(dob.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
// attempt to update dob through mcts upload
DateTime newDob = DateTime.now().minusDays(150);
String newDobString = getDateString(newDob);
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + newDobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(newDob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(0, Days.daysBetween(newDob.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
}
/*
* To verify that NMS shall deactivate pregancyPack if childPack uploads
* for updation which contains motherId for an active mother beneficiary.
*
* https://applab.atlassian.net/browse/NMS-207
*/
@Test
@Ignore
public void verifyFT322() throws Exception {
// import mother
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
Set<Subscription> subscriptions = subscriber.getActiveSubscriptions();
assertEquals(1, subscriptions.size());
// import child with same MSISDN and no MotherID
DateTime dob = DateTime.now().minusDays(200);
String dobString = getDateString(dob);
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t9876543210\tBaby1 of Shanti Ekka\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
subscriptions = subscriber.getActiveSubscriptions();
Subscription childSubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.CHILD);
Subscription pregnancySubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.PREGNANCY);
// both subscription should have been activated
assertEquals(2, subscriptions.size());
assertNotNull(childSubscription);
assertNotNull(pregnancySubscription);
// import child with same MSISDN and above MotherID --> child should be updated and mother be deactivated
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t9876543210\tBaby1 of Shanti Ekka\t1234567890\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
subscriptions = subscriber.getActiveSubscriptions();
childSubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.CHILD);
pregnancySubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.PREGNANCY);
//only child subscription should be activated
assertEquals(1, subscriptions.size());
assertNotNull(childSubscription);
assertNull(pregnancySubscription);
}
}
|
testing/src/test/java/org/motechproject/nms/testing/it/kilkari/MctsBeneficiaryImportServiceBundleIT.java
|
package org.motechproject.nms.testing.it.kilkari;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createDistrict;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthBlock;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthFacility;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createHealthFacilityType;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createState;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createTaluka;
import static org.motechproject.nms.testing.it.utils.RegionHelper.createVillage;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.nms.csv.exception.CsvImportDataException;
import org.motechproject.nms.kilkari.domain.DeactivationReason;
import org.motechproject.nms.kilkari.domain.Subscriber;
import org.motechproject.nms.kilkari.domain.Subscription;
import org.motechproject.nms.kilkari.domain.SubscriptionError;
import org.motechproject.nms.kilkari.domain.SubscriptionOrigin;
import org.motechproject.nms.kilkari.domain.SubscriptionPackType;
import org.motechproject.nms.kilkari.domain.SubscriptionRejectionReason;
import org.motechproject.nms.kilkari.repository.SubscriberDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionErrorDataService;
import org.motechproject.nms.kilkari.repository.SubscriptionPackDataService;
import org.motechproject.nms.kilkari.service.MctsBeneficiaryImportService;
import org.motechproject.nms.kilkari.service.SubscriberService;
import org.motechproject.nms.kilkari.service.SubscriptionService;
import org.motechproject.nms.region.domain.District;
import org.motechproject.nms.region.domain.HealthBlock;
import org.motechproject.nms.region.domain.HealthFacility;
import org.motechproject.nms.region.domain.HealthFacilityType;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.region.domain.Taluka;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.repository.CircleDataService;
import org.motechproject.nms.region.repository.DistrictDataService;
import org.motechproject.nms.region.repository.LanguageDataService;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.testing.it.utils.SubscriptionHelper;
import org.motechproject.nms.testing.service.TestingService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class MctsBeneficiaryImportServiceBundleIT extends BasePaxIT {
@Inject
private TestingService testingService;
@Inject
private LanguageDataService languageDataService;
@Inject
private StateDataService stateDataService;
@Inject
private DistrictDataService districtDataService;
@Inject
private CircleDataService circleDataService;
@Inject
private SubscriberDataService subscriberDataService;
@Inject
private SubscriptionService subscriptionService;
@Inject
private SubscriptionPackDataService subscriptionPackDataService;
@Inject
private MctsBeneficiaryImportService mctsBeneficiaryImportService;
@Inject
private SubscriptionErrorDataService subscriptionErrorDataService;
@Inject
private SubscriberService subscriberService;
@Before
public void setUp() {
testingService.clearDatabase();
createLocationData();
SubscriptionHelper subscriptionHelper = new SubscriptionHelper(subscriptionService, subscriberDataService,
subscriptionPackDataService, languageDataService, circleDataService,
stateDataService, districtDataService);
subscriptionHelper.pregnancyPack();
subscriptionHelper.childPack();
}
private void createLocationData() {
// specific locations from the mother and child data files:
State state21 = createState(21L, "State 21");
District district2 = createDistrict(state21, 2L, "Jharsuguda");
District district3 = createDistrict(state21, 3L, "Sambalpur");
District district4 = createDistrict(state21, 4L, "Debagarh");
state21.getDistricts().addAll(Arrays.asList(district2, district3, district4));
Taluka taluka24 = createTaluka(district2, "0024", "Laikera P.S.", 24);
district2.getTalukas().add(taluka24);
Taluka taluka26 = createTaluka(district3, "0026", "Govindpur P.S.", 26);
district3.getTalukas().add(taluka26);
Taluka taluka46 = createTaluka(district4, "0046", "Debagarh P.S.", 46);
district4.getTalukas().add(taluka46);
HealthBlock healthBlock259 = createHealthBlock(taluka24, 259L, "Laikera", "hq");
taluka24.getHealthBlocks().add(healthBlock259);
HealthBlock healthBlock453 = createHealthBlock(taluka26, 453L, "Bamara", "hq");
taluka26.getHealthBlocks().add(healthBlock453);
HealthBlock healthBlock153 = createHealthBlock(taluka46, 153L, "Tileibani", "hq");
taluka46.getHealthBlocks().add(healthBlock153);
HealthFacilityType facilityType635 = createHealthFacilityType("Mundrajore CHC", 635L);
HealthFacility healthFacility635 = createHealthFacility(healthBlock259, 635L, "Mundrajore CHC", facilityType635);
healthBlock259.getHealthFacilities().add(healthFacility635);
HealthFacilityType facilityType41 = createHealthFacilityType("Garposh CHC", 41L);
HealthFacility healthFacility41 = createHealthFacility(healthBlock453, 41L, "Garposh CHC", facilityType41);
healthBlock453.getHealthFacilities().add(healthFacility41);
HealthFacilityType facilityType114 = createHealthFacilityType("CHC Tileibani", 114L);
HealthFacility healthFacility114 = createHealthFacility(healthBlock153, 114L, "CHC Tileibani", facilityType114);
healthBlock153.getHealthFacilities().add(healthFacility114);
Village village10004693 = createVillage(taluka24, 10004693L, null, "Khairdihi");
Village village10004691 = createVillage(taluka24, 10004691L, null, "Gambhariguda");
Village village1509 = createVillage(taluka24, null, 1509L, "Mundrajore");
Village village1505 = createVillage(taluka24, null, 1505L, "Kulemura");
Village village10004690 = createVillage(taluka24, 10004690L, null, "Ampada");
Village village10004697 = createVillage(taluka24, 10004697L, null, "Saletikra");
taluka24.getVillages().addAll(Arrays.asList(village10004693, village10004691, village1509, village1505,
village10004690, village10004697));
Village village3089 = createVillage(taluka46, null, 3089L, "Podapara");
taluka46.getVillages().add(village3089);
stateDataService.create(state21);
}
@Test
public void testImportMotherNewSubscriber() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals("Shanti Ekka", subscriber.getMother().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(SubscriptionOrigin.MCTS_IMPORT, subscription.getOrigin());
}
@Test
public void testImportMotherAlternateDateFormat() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = lmp.toString("dd/MM/yyyy");
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
}
@Test
public void testImportMotherWhoAlreadyExistsUpdateLmp() throws Exception {
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals("Shanti Ekka", subscriber.getMother().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(90, Days.daysBetween(lmp.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
DateTime newLmp = DateTime.now().minusDays(150);
String newLmpString = getDateString(newLmp);
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + newLmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(newLmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(90, Days.daysBetween(newLmp.toLocalDate(), subscription.getStartDate().toLocalDate()).getDays());
}
@Test(expected = CsvImportDataException.class)
public void testImportMotherInvalidState() throws Exception {
Reader reader = createMotherDataReaderWithHeaders("9\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t22-11-2014");
mctsBeneficiaryImportService.importMotherData(reader);
}
@Test
public void testImportChildNewSubscriberNoMotherId() throws Exception {
DateTime dob = DateTime.now().minusDays(100);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
assertEquals("Baby1 of Lilima Kua", subscriber.getChild().getName());
Subscription subscription = subscriber.getActiveSubscriptions().iterator().next();
assertEquals(SubscriptionOrigin.MCTS_IMPORT, subscription.getOrigin());
assertEquals(SubscriptionPackType.CHILD, subscription.getSubscriptionPack().getType());
}
@Test
public void testImportMotherAndChildSameMsisdn() throws Exception {
// import mother
DateTime lmp = DateTime.now().minusDays(100);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
Set<Subscription> subscriptions = subscriber.getActiveSubscriptions();
assertEquals(1, subscriptions.size());
// import child with same MSISDN and matching MotherID
DateTime dob = DateTime.now().minusDays(200);
String dobString = getDateString(dob);
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t9876543210\tBaby1 of Shanti Ekka\t1234567890\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
subscriptions = subscriber.getActiveSubscriptions();
Subscription childSubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.CHILD);
Subscription pregnancySubscription = subscriptionService.getActiveSubscription(subscriber, SubscriptionPackType.PREGNANCY);
// the pregnancy subscription should have been deactivated
assertEquals(1, subscriptions.size());
assertNotNull(childSubscription);
assertNull(pregnancySubscription);
}
@Test
public void testImportMotherDataFromSampleFile() throws Exception {
mctsBeneficiaryImportService.importMotherData(read("csv/mother.txt"));
State expectedState = stateDataService.findByCode(21L);
District expectedDistrict = districtDataService.findByCode(3L);
Subscriber subscriber1 = subscriberDataService.findByCallingNumber(9439986187L);
assertMother(subscriber1, "210302604211400029", getDateTime("22/11/2014"), "Shanti Ekka", expectedState,
expectedDistrict);
Subscriber subscriber2 = subscriberDataService.findByCallingNumber(7894221701L);
assertMother(subscriber2, "210302604611400023", getDateTime("15/6/2014"), "Damayanti Khadia", expectedState,
expectedDistrict);
// although our MCTS data file contains 10 mothers, we only create 3 subscribers due to duplicate phone numbers
assertEquals(3, subscriberDataService.count());
}
@Test
public void testImportChildDataFromSampleFile() throws Exception {
mctsBeneficiaryImportService.importChildData(read("csv/child.txt"));
State expectedState = stateDataService.findByCode(21L);
District expectedDistrict2 = districtDataService.findByCode(2L);
District expectedDistrict4 = districtDataService.findByCode(4L);
Subscriber subscriber1 = subscriberDataService.findByCallingNumber(9439998253L);
assertChild(subscriber1, "210404600521400116", getDateTime("2/12/2014"), "Baby1 of PANI HEMRAM", expectedState,
expectedDistrict4);
// although our MCTS data file contains 10 children, we only create 8 subscribers due to duplicate phone numbers
assertEquals(8, subscriberDataService.count());
}
private void assertMother(Subscriber subscriber, String motherId, DateTime lmp, String name, State state, District district) {
assertNotNull(subscriber);
assertNotNull(subscriber.getMother());
assertEquals(motherId, subscriber.getMother().getBeneficiaryId());
assertEquals(name, subscriber.getMother().getName());
assertEquals(lmp.toLocalDate(), subscriber.getLastMenstrualPeriod().toLocalDate());
assertEquals(state, subscriber.getMother().getState());
assertEquals(district, subscriber.getMother().getDistrict());
}
private void assertChild(Subscriber subscriber, String childId, DateTime dob, String name, State state, District district) {
assertNotNull(subscriber);
assertNotNull(subscriber.getChild());
assertEquals(childId, subscriber.getChild().getBeneficiaryId());
assertEquals(name, subscriber.getChild().getName());
assertEquals(dob.toLocalDate(), subscriber.getDateOfBirth().toLocalDate());
assertEquals(state, subscriber.getChild().getState());
assertEquals(district, subscriber.getChild().getDistrict());
}
private String getDateString(DateTime date) {
return date.toString("dd-MM-yyyy");
}
private DateTime getDateTime(String dateString) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
return DateTime.parse(dateString, formatter);
}
private Reader createChildDataReaderWithHeaders(String... lines) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("State Name : State 1").append("\n");
builder.append("\n");
builder.append("StateID\tDistrict_ID\tTaluka_ID\tHealthBlock_ID\tPHC_ID\tVillage_ID\tID_No\tName\tMother_ID\tWhom_PhoneNo\tBirthdate");
builder.append("\n");
for (String line : lines) {
builder.append(line).append("\n");
}
return new StringReader(builder.toString());
}
private Reader createMotherDataReaderWithHeaders(String... lines) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append("State Name : State 1").append("\n");
builder.append("\n");
builder.append("StateID\tDistrict_ID\tTaluka_ID\tHealthBlock_ID\tPHC_ID\tVillage_ID\tID_No\tName\tWhom_PhoneNo\tLMP_Date");
builder.append("\n");
for (String line : lines) {
builder.append(line).append("\n");
}
return new StringReader(builder.toString());
}
private Reader read(String resource) {
return new InputStreamReader(getClass().getClassLoader().getResourceAsStream(resource));
}
/*
* To verify mother subscription is rejected when future LMP is provided
*/
@Test
public void verifyFT282() throws Exception {
DateTime lmp = DateTime.now().plusDays(1);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.INVALID_LMP);
}
/*
* To verify child subscriber is rejected when future DOB is provided.
*/
@Test
public void verifyFT283() throws Exception {
DateTime dob = DateTime.now().plusDays(1);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.INVALID_DOB);
}
/*
* To verify mother subscription is rejected when LMP provided is 72 weeks back.
*/
@Test
public void verifyFT284() throws Exception {
DateTime lmp = DateTime.now().minusDays(7*72+90);
String lmpString = getDateString(lmp);
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.INVALID_LMP);
}
/*
* To verify child subscription is rejected when DOB provided is 48 weeks back.
*/
@Test
public void verifyFT285() throws Exception {
DateTime dob = DateTime.now().minusDays(7*48);
String dobString = getDateString(dob);
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.INVALID_DOB);
}
/*
* To verify MCTS upload is rejected when MSISDN number already exist
* for subscriber with new mctsid(beneficiary id).
*/
@Test
public void verifyFT287() throws Exception {
DateTime dob = DateTime.now();
String dobString = getDateString(dob);
// create subscriber and subscription
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
// attempt to create subscriber with same msisdn but different mcts.
reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567891\tBaby1 of Lilima Kua\t\t9439986187\t" + dobString);
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNotNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.ALREADY_SUBSCRIBED);
}
/*
* To verify MCTS upload is rejected when MCTS doesn’t contain DOB.
*
* https://applab.atlassian.net/browse/NMS-206
*/
@Test
@Ignore
public void verifyFT288_1() throws Exception {
//DOB is missing
Reader reader = createChildDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tBaby1 of Lilima Kua\t\t9439986187\t");
mctsBeneficiaryImportService.importChildData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.CHILD, SubscriptionRejectionReason.MISSING_DOB);
}
/*
* To verify MCTS upload is rejected when MCTS doesn’t contain LMP.
*
* https://applab.atlassian.net/browse/NMS-206
*/
@Test
@Ignore
public void verifyFT288_2() throws Exception {
//LMP is missing
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t");
mctsBeneficiaryImportService.importMotherData(reader);
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertNull(subscriber);
List<SubscriptionError> susbErrors = subscriptionErrorDataService.findByContactNumber(9439986187L);
SubscriptionError susbError = susbErrors.iterator().next();
assertSubscriptionError(susbError, SubscriptionPackType.PREGNANCY, SubscriptionRejectionReason.MISSING_LMP);
}
private void assertSubscriptionError(SubscriptionError susbError, SubscriptionPackType packType,
SubscriptionRejectionReason rejectionReason) {
assertNotNull(susbError);
assertEquals(packType, susbError.getPackType());
assertEquals(rejectionReason, susbError.getRejectionReason());
}
/*
* NMS_FT_289:: To verify new subscription is created successfully when subscription
* already exist having status as "Completed" for same MSISDN.
* NMS_FT_306:: To verify LMP is changed successfully via CSV when subscription
* already exist for pregnancyPack having status as "Completed"
*/
@Test
public void verifyFT289() throws Exception {
DateTime lmp = DateTime.now();
String lmpString = getDateString(lmp);
// create subscriber and subscription
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
//Make subscription completed
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
subscriber.setLastMenstrualPeriod(lmp.minusDays(650));
subscriberService.update(subscriber);
//create a new subscription for subscriber whose subscription is completed.
lmpString = getDateString(lmp.minus(200));
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(lmpString, getDateString(subscriber.getLastMenstrualPeriod()));
}
/*
* NMS_FT_290:: To verify new subscription is created successfully when subscription
* already exist having status as "Deactivated" for same MSISDN.
* NMS_FT_305:: To verify LMP is changed successfully via CSV when subscription
* already exist for pregnancyPack having status as "Deactivated"
*/
@Test
public void verifyFT290() throws Exception {
DateTime lmp = DateTime.now().minus(100);
String lmpString = getDateString(lmp);
// create subscriber and subscription
Reader reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
//Mark subscription deactivate
Subscriber subscriber = subscriberDataService.findByCallingNumber(9439986187L);
Subscription subscription =subscriber.getActiveSubscriptions().iterator().next();
subscriptionService.deactivateSubscription(subscription, DeactivationReason.MISCARRIAGE_OR_ABORTION);
//create a new subscription for subscriber whose subscription is deactivated.
lmpString = getDateString(lmp.minus(200));
reader = createMotherDataReaderWithHeaders("21\t3\t\t\t\t\t1234567890\tShanti Ekka\t9439986187\t" + lmpString);
mctsBeneficiaryImportService.importMotherData(reader);
subscriber = subscriberDataService.findByCallingNumber(9439986187L);
assertEquals(2, subscriber.getAllSubscriptions().size());
assertEquals(1, subscriber.getActiveSubscriptions().size());
assertEquals(lmpString, getDateString(subscriber.getLastMenstrualPeriod()));
}
}
|
Edited jira issue
|
testing/src/test/java/org/motechproject/nms/testing/it/kilkari/MctsBeneficiaryImportServiceBundleIT.java
|
Edited jira issue
|
|
Java
|
mit
|
58208b9c06f6d38029ac88278d6a0c117a83fd0c
| 0
|
sys1yagi/swipe-android,sys1yagi/swipe-android
|
package com.sys1yagi.swipe.core.tool;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sys1yagi.swipe.core.entity.index.Index;
import com.sys1yagi.swipe.core.entity.swipe.SwipeDocument;
import org.hjson.JsonValue;
public class SwipeEntityDecoder {
private final static String KEY_TYPE = "type";
private final static String TYPE_INDEX = "net.swipe.list";
//TODO remove it
private String hjson(String jsonString) {
return JsonValue.readHjson(jsonString).asObject().toString();
}
public Index decodeToIndex(Gson gson, String jsonString) {
JsonObject json = new JsonParser().parse(hjson(jsonString)).getAsJsonObject();
if (!json.has(KEY_TYPE)) {
throw new IllegalArgumentException("Invalid index swipe file. data:" + jsonString);
}
if (!TYPE_INDEX.equals(json.get(KEY_TYPE).getAsString())) {
throw new IllegalArgumentException("Invalid index swipe file. data:" + jsonString);
}
return gson.fromJson(json, Index.class);
}
public SwipeDocument decodeToSwipe(Gson gson, String jsonString) {
JsonObject json = new JsonParser().parse(hjson(jsonString)).getAsJsonObject();
if (json.has(KEY_TYPE) && TYPE_INDEX.equals(json.get(KEY_TYPE).getAsString())) {
throw new IllegalArgumentException("Invalid contents swipe file. data:" + jsonString);
}
return gson.fromJson(json, SwipeDocument.class);
}
}
|
core/src/main/java/com/sys1yagi/swipe/core/tool/SwipeEntityDecoder.java
|
package com.sys1yagi.swipe.core.tool;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sys1yagi.swipe.core.entity.index.Index;
import com.sys1yagi.swipe.core.entity.swipe.SwipeDocument;
public class SwipeEntityDecoder {
private final static String KEY_TYPE = "type";
private final static String TYPE_INDEX = "net.swipe.list";
public Index decodeToIndex(Gson gson, String jsonString) {
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
if (!json.has(KEY_TYPE)) {
throw new IllegalArgumentException("Invalid index swipe file. data:" + jsonString);
}
if (!TYPE_INDEX.equals(json.get(KEY_TYPE).getAsString())) {
throw new IllegalArgumentException("Invalid index swipe file. data:" + jsonString);
}
return gson.fromJson(json, Index.class);
}
public SwipeDocument decodeToSwipe(Gson gson, String jsonString) {
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
if (json.has(KEY_TYPE) && TYPE_INDEX.equals(json.get(KEY_TYPE).getAsString())) {
throw new IllegalArgumentException("Invalid contents swipe file. data:" + jsonString);
}
return gson.fromJson(json, SwipeDocument.class);
}
}
|
Use hjson on SwipeEntityDecoder.
|
core/src/main/java/com/sys1yagi/swipe/core/tool/SwipeEntityDecoder.java
|
Use hjson on SwipeEntityDecoder.
|
|
Java
|
mit
|
a9afdb5e2a8872eb6a193efc0dd6b429bcfed967
| 0
|
maillouxc/git-rekt
|
package com.gitrekt.resort.controller;
import com.gitrekt.resort.model.entities.GuestFeedback;
import com.gitrekt.resort.model.services.GuestFeedbackService;
import com.gitrekt.resort.view.GuestFeedbackListItem;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
/**
* Handles the functionality of FeedbackReportScreen.fxml
*/
public class FeedbackReportScreenController
implements Initializable {
@FXML
private Button backButton;
@FXML
private ListView<GuestFeedback> guestFeedbackListView;
private ObservableList<GuestFeedback> guestFeedbackList;
private GuestFeedbackService guestFeedbackService;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
guestFeedbackList = FXCollections.observableArrayList();
guestFeedbackListView.setItems(guestFeedbackList);
guestFeedbackListView.setCellFactory(
param -> new GuestFeedbackListItem(this)
);
guestFeedbackListView.setPlaceholder(
new Label("No unresolved feedback")
);
this.guestFeedbackService = new GuestFeedbackService();
loadFeedback();
}
/**
* @param item The data item to hide from the screen.
*/
public void hideItem(GuestFeedback item) {
guestFeedbackList.remove(item);
}
@FXML
private void onBackButtonClicked() throws IOException {
ScreenManager.getInstance().switchToScreen(
"/fxml/ReportsHomeScreen.fxml"
);
}
@FXML
private void onRefreshButtonClicked() {
loadFeedback();
}
private void loadFeedback() {
// Clear any existing items from the list
guestFeedbackList.clear();
// Retrieve new items
guestFeedbackList.addAll(
guestFeedbackService.getUnresolvedGuestFeedback()
);
}
}
|
src/main/java/com/gitrekt/resort/controller/FeedbackReportScreenController.java
|
package com.gitrekt.resort.controller;
import com.gitrekt.resort.model.entities.GuestFeedback;
import com.gitrekt.resort.model.services.GuestFeedbackService;
import com.gitrekt.resort.view.GuestFeedbackListItem;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
/**
* Handles the functionality of FeedbackReportScreen.fxml
*/
public class FeedbackReportScreenController
implements Initializable {
@FXML
private Button backButton;
@FXML
private ListView<GuestFeedback> guestFeedbackListView;
private ObservableList<GuestFeedback> guestFeedbackList;
private GuestFeedbackService guestFeedbackService;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
guestFeedbackList = FXCollections.observableArrayList();
guestFeedbackListView.setItems(guestFeedbackList);
guestFeedbackListView.setCellFactory(
param -> new GuestFeedbackListItem(this)
);
this.guestFeedbackService = new GuestFeedbackService();
loadFeedback();
}
/**
* @param item The data item to hide from the screen.
*/
public void hideItem(GuestFeedback item) {
guestFeedbackList.remove(item);
}
@FXML
private void onBackButtonClicked() throws IOException {
ScreenManager.getInstance().switchToScreen(
"/fxml/ReportsHomeScreen.fxml"
);
}
@FXML
private void onRefreshButtonClicked() {
loadFeedback();
}
private void loadFeedback() {
// Clear any existing items from the list
guestFeedbackList.clear();
// Retrieve new items
guestFeedbackList.addAll(
guestFeedbackService.getUnresolvedGuestFeedback()
);
}
}
|
Add placeholder to empty guest feedback list
|
src/main/java/com/gitrekt/resort/controller/FeedbackReportScreenController.java
|
Add placeholder to empty guest feedback list
|
|
Java
|
mit
|
7ba06573feb6561c6fc857cd5b53ff1449808da9
| 0
|
outofcoffee/testcontainers-java,rnorth/test-containers,testcontainers/testcontainers-java,outofcoffee/testcontainers-java,rnorth/test-containers,outofcoffee/testcontainers-java,testcontainers/testcontainers-java,rnorth/test-containers,testcontainers/testcontainers-java
|
package org.testcontainers.utility;
import com.google.common.annotations.VisibleForTesting;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.UnstableAPI;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
/**
* Provides a mechanism for fetching configuration/defaults from the classpath.
*/
@Data
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class TestcontainersConfiguration {
private static String PROPERTIES_FILE_NAME = "testcontainers.properties";
private static File ENVIRONMENT_CONFIG_FILE = new File(System.getProperty("user.home"), "." + PROPERTIES_FILE_NAME);
@Getter(lazy = true)
private static final TestcontainersConfiguration instance = loadConfiguration();;
@SuppressWarnings({"ConstantConditions", "unchecked", "rawtypes"})
@VisibleForTesting
static AtomicReference<TestcontainersConfiguration> getInstanceField() {
// Lazy Getter from Lombok changes the field's type to AtomicReference
return (AtomicReference) (Object) instance;
}
@Getter(AccessLevel.NONE)
private final Properties environmentProperties;
private final Properties properties = new Properties();
TestcontainersConfiguration(Properties environmentProperties, Properties classpathProperties) {
this.environmentProperties = environmentProperties;
this.properties.putAll(classpathProperties);
this.properties.putAll(environmentProperties);
}
@Deprecated
public String getAmbassadorContainerImage() {
return (String) properties.getOrDefault("ambassador.container.image", "richnorth/ambassador:latest");
}
public String getSocatContainerImage() {
return (String) properties.getOrDefault("socat.container.image", "alpine/socat:latest");
}
public String getVncRecordedContainerImage() {
return (String) properties.getOrDefault("vncrecorder.container.image", "testcontainers/vnc-recorder:1.1.0");
}
public String getDockerComposeContainerImage() {
return (String) properties.getOrDefault("compose.container.image", "docker/compose:1.24.1");
}
public String getTinyImage() {
return (String) properties.getOrDefault("tinyimage.container.image", "alpine:3.5");
}
public boolean isRyukPrivileged() {
return Boolean.parseBoolean((String) properties.getOrDefault("ryuk.container.privileged", "false"));
}
public String getRyukImage() {
return (String) properties.getOrDefault("ryuk.container.image", "testcontainers/ryuk:0.3.0");
}
public String getSSHdImage() {
return (String) properties.getOrDefault("sshd.container.image", "testcontainers/sshd:1.0.0");
}
public Integer getRyukTimeout() {
return Integer.parseInt((String) properties.getOrDefault("ryuk.container.timeout", "30"));
}
public String getKafkaImage() {
return (String) properties.getOrDefault("kafka.container.image", "confluentinc/cp-kafka");
}
public String getPulsarImage() {
return (String) properties.getOrDefault("pulsar.container.image", "apachepulsar/pulsar");
}
public String getLocalStackImage() {
return (String) properties.getOrDefault("localstack.container.image", "localstack/localstack");
}
public boolean isDisableChecks() {
return Boolean.parseBoolean((String) environmentProperties.getOrDefault("checks.disable", "false"));
}
@UnstableAPI
public boolean environmentSupportsReuse() {
return Boolean.parseBoolean((String) environmentProperties.getOrDefault("testcontainers.reuse.enable", "false"));
}
public String getDockerClientStrategyClassName() {
return (String) environmentProperties.get("docker.client.strategy");
}
/**
*
* @deprecated we no longer have different transport types
*/
@Deprecated
public String getTransportType() {
return properties.getProperty("transport.type", "okhttp");
}
public Integer getImagePullPauseTimeout() {
return Integer.parseInt((String) properties.getOrDefault("pull.pause.timeout", "30"));
}
@Synchronized
public boolean updateGlobalConfig(@NonNull String prop, @NonNull String value) {
try {
if (value.equals(environmentProperties.get(prop))) {
return false;
}
environmentProperties.setProperty(prop, value);
ENVIRONMENT_CONFIG_FILE.createNewFile();
try (OutputStream outputStream = new FileOutputStream(ENVIRONMENT_CONFIG_FILE)) {
environmentProperties.store(outputStream, "Modified by Testcontainers");
}
// Update internal state only if environment config was successfully updated
properties.setProperty(prop, value);
return true;
} catch (Exception e) {
log.debug("Can't store environment property {} in {}", prop, ENVIRONMENT_CONFIG_FILE);
return false;
}
}
@SneakyThrows(MalformedURLException.class)
private static TestcontainersConfiguration loadConfiguration() {
return new TestcontainersConfiguration(
readProperties(ENVIRONMENT_CONFIG_FILE.toURI().toURL()),
Stream
.of(
TestcontainersConfiguration.class.getClassLoader(),
Thread.currentThread().getContextClassLoader()
)
.map(it -> it.getResource(PROPERTIES_FILE_NAME))
.filter(Objects::nonNull)
.map(TestcontainersConfiguration::readProperties)
.reduce(new Properties(), (a, b) -> {
a.putAll(b);
return a;
})
);
}
private static Properties readProperties(URL url) {
log.debug("Testcontainers configuration overrides will be loaded from {}", url);
Properties properties = new Properties();
try (InputStream inputStream = url.openStream()) {
properties.load(inputStream);
} catch (FileNotFoundException e) {
log.trace("Testcontainers config override was found on {} but the file was not found", url, e);
} catch (IOException e) {
log.warn("Testcontainers config override was found on {} but could not be loaded", url, e);
}
return properties;
}
}
|
core/src/main/java/org/testcontainers/utility/TestcontainersConfiguration.java
|
package org.testcontainers.utility;
import com.google.common.annotations.VisibleForTesting;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.testcontainers.UnstableAPI;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
/**
* Provides a mechanism for fetching configuration/defaults from the classpath.
*/
@Data
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class TestcontainersConfiguration {
private static String PROPERTIES_FILE_NAME = "testcontainers.properties";
private static File ENVIRONMENT_CONFIG_FILE = new File(System.getProperty("user.home"), "." + PROPERTIES_FILE_NAME);
@Getter(lazy = true)
private static final TestcontainersConfiguration instance = loadConfiguration();;
@SuppressWarnings({"ConstantConditions", "unchecked", "rawtypes"})
@VisibleForTesting
static AtomicReference<TestcontainersConfiguration> getInstanceField() {
// Lazy Getter from Lombok changes the field's type to AtomicReference
return (AtomicReference) (Object) instance;
}
@Getter(AccessLevel.NONE)
private final Properties environmentProperties;
private final Properties properties = new Properties();
TestcontainersConfiguration(Properties environmentProperties, Properties classpathProperties) {
this.environmentProperties = environmentProperties;
this.properties.putAll(classpathProperties);
this.properties.putAll(environmentProperties);
}
public String getAmbassadorContainerImage() {
return (String) properties.getOrDefault("ambassador.container.image", "richnorth/ambassador:latest");
}
public String getSocatContainerImage() {
return (String) properties.getOrDefault("socat.container.image", "alpine/socat:latest");
}
public String getVncRecordedContainerImage() {
return (String) properties.getOrDefault("vncrecorder.container.image", "testcontainersofficial/vnc-recorder:1.1.0");
}
public String getDockerComposeContainerImage() {
return (String) properties.getOrDefault("compose.container.image", "docker/compose:1.24.1");
}
public String getTinyImage() {
return (String) properties.getOrDefault("tinyimage.container.image", "alpine:3.5");
}
public boolean isRyukPrivileged() {
return Boolean.parseBoolean((String) properties.getOrDefault("ryuk.container.privileged", "false"));
}
public String getRyukImage() {
return (String) properties.getOrDefault("ryuk.container.image", "testcontainersofficial/ryuk:0.3.0");
}
public String getSSHdImage() {
return (String) properties.getOrDefault("sshd.container.image", "testcontainersofficial/sshd:1.0.0");
}
public Integer getRyukTimeout() {
return Integer.parseInt((String) properties.getOrDefault("ryuk.container.timeout", "30"));
}
public String getKafkaImage() {
return (String) properties.getOrDefault("kafka.container.image", "confluentinc/cp-kafka");
}
public String getPulsarImage() {
return (String) properties.getOrDefault("pulsar.container.image", "apachepulsar/pulsar");
}
public String getLocalStackImage() {
return (String) properties.getOrDefault("localstack.container.image", "localstack/localstack");
}
public boolean isDisableChecks() {
return Boolean.parseBoolean((String) environmentProperties.getOrDefault("checks.disable", "false"));
}
@UnstableAPI
public boolean environmentSupportsReuse() {
return Boolean.parseBoolean((String) environmentProperties.getOrDefault("testcontainers.reuse.enable", "false"));
}
public String getDockerClientStrategyClassName() {
return (String) environmentProperties.get("docker.client.strategy");
}
/**
*
* @deprecated we no longer have different transport types
*/
@Deprecated
public String getTransportType() {
return properties.getProperty("transport.type", "okhttp");
}
public Integer getImagePullPauseTimeout() {
return Integer.parseInt((String) properties.getOrDefault("pull.pause.timeout", "30"));
}
@Synchronized
public boolean updateGlobalConfig(@NonNull String prop, @NonNull String value) {
try {
if (value.equals(environmentProperties.get(prop))) {
return false;
}
environmentProperties.setProperty(prop, value);
ENVIRONMENT_CONFIG_FILE.createNewFile();
try (OutputStream outputStream = new FileOutputStream(ENVIRONMENT_CONFIG_FILE)) {
environmentProperties.store(outputStream, "Modified by Testcontainers");
}
// Update internal state only if environment config was successfully updated
properties.setProperty(prop, value);
return true;
} catch (Exception e) {
log.debug("Can't store environment property {} in {}", prop, ENVIRONMENT_CONFIG_FILE);
return false;
}
}
@SneakyThrows(MalformedURLException.class)
private static TestcontainersConfiguration loadConfiguration() {
return new TestcontainersConfiguration(
readProperties(ENVIRONMENT_CONFIG_FILE.toURI().toURL()),
Stream
.of(
TestcontainersConfiguration.class.getClassLoader(),
Thread.currentThread().getContextClassLoader()
)
.map(it -> it.getResource(PROPERTIES_FILE_NAME))
.filter(Objects::nonNull)
.map(TestcontainersConfiguration::readProperties)
.reduce(new Properties(), (a, b) -> {
a.putAll(b);
return a;
})
);
}
private static Properties readProperties(URL url) {
log.debug("Testcontainers configuration overrides will be loaded from {}", url);
Properties properties = new Properties();
try (InputStream inputStream = url.openStream()) {
properties.load(inputStream);
} catch (FileNotFoundException e) {
log.trace("Testcontainers config override was found on {} but the file was not found", url, e);
} catch (IOException e) {
log.warn("Testcontainers config override was found on {} but could not be loaded", url, e);
}
return properties;
}
}
|
Use testcontainers/* Docker Hub images (#2850)
|
core/src/main/java/org/testcontainers/utility/TestcontainersConfiguration.java
|
Use testcontainers/* Docker Hub images (#2850)
|
|
Java
|
epl-1.0
|
0c96152ed9769751f38e91f0459f8b81ca787288
| 0
|
Mixajlo/smarthome,phxql/smarthome,S0urceror/smarthome,sja/smarthome,marinmitev/smarthome,fatihboy/smarthome,Snickermicker/smarthome,adimova/smarthome,fatihboy/smarthome,digitaldan/smarthome,Snickermicker/smarthome,chrisschauer/smarthome,cdjackson/smarthome,paphko/smarthome,adimova/smarthome,phxql/smarthome,paphko/smarthome,GradyD/smarthome,kgoderis/smarthome,S0urceror/smarthome,CrackerStealth/smarthome,cdjackson/smarthome,plamen-peev/smarthome,Stratehm/smarthome,vkolotov/smarthome,AchimHentschel/smarthome,phxql/smarthome,AchimHentschel/smarthome,marinmitev/smarthome,peuter/smarthome,AchimHentschel/smarthome,ArchibaldLeMagnifique/smarthome,vilchev/eclipse-smarthome,vkolotov/smarthome,chrisschauer/smarthome,Mixajlo/smarthome,sja/smarthome,CrackerStealth/smarthome,plamen-peev/smarthome,Stratehm/smarthome,Mixajlo/smarthome,shry15harsh/smarthome,phxql/smarthome,neverend92/smarthome,ArchibaldLeMagnifique/smarthome,peuter/smarthome,cdjackson/smarthome,vilchev/eclipse-smarthome,kdavis-mozilla/smarthome,paphko/smarthome,vilchev/eclipse-smarthome,sja/smarthome,chaton78/smarthome,vkolotov/smarthome,kceiw/smarthome,BenediktNiehues/smarthome,marinmitev/smarthome,fatihboy/smarthome,chaton78/smarthome,peuter/smarthome,philomatic/smarthome,CrackerStealth/smarthome,digitaldan/smarthome,kgoderis/smarthome,sja/smarthome,BenediktNiehues/smarthome,shry15harsh/smarthome,ArchibaldLeMagnifique/smarthome,BenediktNiehues/smarthome,resetnow/smarthome,chaton78/smarthome,plamen-peev/smarthome,Stratehm/smarthome,kgoderis/smarthome,dvanherbergen/smarthome,Snickermicker/smarthome,chaton78/smarthome,Snickermicker/smarthome,S0urceror/smarthome,kgoderis/smarthome,neverend92/smarthome,fatihboy/smarthome,shry15harsh/smarthome,kdavis-mozilla/smarthome,dvanherbergen/smarthome,vilchev/eclipse-smarthome,kceiw/smarthome,BenediktNiehues/smarthome,marinmitev/smarthome,GradyD/smarthome,resetnow/smarthome,GradyD/smarthome,kdavis-mozilla/smarthome,kceiw/smarthome,kdavis-mozilla/smarthome,kceiw/smarthome,Stratehm/smarthome,adimova/smarthome,Mixajlo/smarthome,digitaldan/smarthome,dvanherbergen/smarthome,resetnow/smarthome,resetnow/smarthome,shry15harsh/smarthome,philomatic/smarthome,neverend92/smarthome,vkolotov/smarthome,chrisschauer/smarthome,philomatic/smarthome,digitaldan/smarthome,S0urceror/smarthome,philomatic/smarthome,GradyD/smarthome,dvanherbergen/smarthome,AchimHentschel/smarthome,cdjackson/smarthome,paphko/smarthome,plamen-peev/smarthome,neverend92/smarthome,adimova/smarthome,peuter/smarthome,chrisschauer/smarthome,CrackerStealth/smarthome
|
/**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.io.transport.mdns.internal;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import javax.jmdns.ServiceInfo;
import org.eclipse.smarthome.io.transport.mdns.MDNSClient;
import org.eclipse.smarthome.io.transport.mdns.MDNSService;
import org.eclipse.smarthome.io.transport.mdns.ServiceDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class starts the JmDNS and implements interface to register and
* unregister services.
*
* @author Victor Belov
*
*/
public class MDNSServiceImpl implements MDNSService {
private final Logger logger = LoggerFactory.getLogger(MDNSServiceImpl.class);
private MDNSClient mdnsClient;
private Set<ServiceInfo> servicesToRegisterQueue = new CopyOnWriteArraySet<>();
public MDNSServiceImpl() {
}
public void setMDNSClient(MDNSClient client) {
this.mdnsClient = client;
// register queued services
if (servicesToRegisterQueue.size() > 0) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (ServiceInfo serviceInfo : servicesToRegisterQueue) {
try {
logger.debug("Registering new service " + serviceInfo.getType() + " at port "
+ String.valueOf(serviceInfo.getPort()));
mdnsClient.getClient().registerService(serviceInfo);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
servicesToRegisterQueue.clear();
}
};
Executors.newSingleThreadExecutor().execute(runnable);
}
}
public void unsetMDNSClient(MDNSClient mdnsClient) {
this.mdnsClient = null;
}
/**
* @{inheritDoc
*/
@Override
public void registerService(final ServiceDescription description) {
if (mdnsClient == null) {
// queue the service to register it as soon as the mDNS client is
// available
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
servicesToRegisterQueue.add(serviceInfo);
} else {
Runnable runnable = new Runnable() {
@Override
public void run() {
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
try {
logger.debug("Registering new service " + description.serviceType + " at port "
+ String.valueOf(description.servicePort));
mdnsClient.getClient().registerService(serviceInfo);
} catch (IOException e) {
logger.error(e.getMessage());
} catch (IllegalStateException e) {
logger.debug("Not registering service, because service is already deactivated!");
}
}
};
Executors.newSingleThreadExecutor().execute(runnable);
}
}
/**
* @{inheritDoc
*/
@Override
public void unregisterService(ServiceDescription description) {
if (mdnsClient == null) {
return;
}
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
logger.debug("Unregistering service " + description.serviceType + " at port "
+ String.valueOf(description.servicePort));
mdnsClient.getClient().unregisterService(serviceInfo);
}
/**
* This method unregisters all services from Bonjour/MDNS
*/
protected void unregisterAllServices() {
if (mdnsClient != null) {
mdnsClient.getClient().unregisterAllServices();
}
}
public void activate() {
}
public void deactivate() {
unregisterAllServices();
try {
if (mdnsClient != null) {
mdnsClient.getClient().close();
logger.debug("mDNS service has been stopped");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
|
bundles/io/org.eclipse.smarthome.io.transport.mdns/src/main/java/org/eclipse/smarthome/io/transport/mdns/internal/MDNSServiceImpl.java
|
/**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.io.transport.mdns.internal;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import javax.jmdns.ServiceInfo;
import org.eclipse.smarthome.io.transport.mdns.MDNSClient;
import org.eclipse.smarthome.io.transport.mdns.MDNSService;
import org.eclipse.smarthome.io.transport.mdns.ServiceDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class starts the JmDNS and implements interface to register and
* unregister services.
*
* @author Victor Belov
*
*/
public class MDNSServiceImpl implements MDNSService {
private final Logger logger = LoggerFactory.getLogger(MDNSServiceImpl.class);
private MDNSClient mdnsClient;
private Set<ServiceInfo> servicesToRegisterQueue = new CopyOnWriteArraySet<>();
public MDNSServiceImpl() {
}
public void setMDNSClient(MDNSClient client) {
this.mdnsClient = client;
// register queued services
if (servicesToRegisterQueue.size() > 0) {
Runnable runnable = new Runnable() {
@Override
public void run() {
for (ServiceInfo serviceInfo : servicesToRegisterQueue) {
try {
logger.debug("Registering new service " + serviceInfo.getType() + " at port "
+ String.valueOf(serviceInfo.getPort()));
mdnsClient.getClient().registerService(serviceInfo);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
servicesToRegisterQueue.clear();
}
};
Executors.newSingleThreadExecutor().execute(runnable);
}
}
public void unsetMDNSClient(MDNSClient mdnsClient) {
this.mdnsClient = null;
}
/**
* @{inheritDoc
*/
@Override
public void registerService(final ServiceDescription description) {
if (mdnsClient == null) {
// queue the service to register it as soon as the mDNS client is
// available
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
servicesToRegisterQueue.add(serviceInfo);
} else {
Runnable runnable = new Runnable() {
@Override
public void run() {
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
try {
logger.debug("Registering new service " + description.serviceType + " at port "
+ String.valueOf(description.servicePort));
mdnsClient.getClient().registerService(serviceInfo);
} catch (IOException e) {
logger.error(e.getMessage());
}
}
};
Executors.newSingleThreadExecutor().execute(runnable);
}
}
/**
* @{inheritDoc
*/
@Override
public void unregisterService(ServiceDescription description) {
if (mdnsClient == null)
return;
ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName,
description.servicePort, 0, 0, description.serviceProperties);
logger.debug("Unregistering service " + description.serviceType + " at port "
+ String.valueOf(description.servicePort));
mdnsClient.getClient().unregisterService(serviceInfo);
}
/**
* This method unregisters all services from Bonjour/MDNS
*/
protected void unregisterAllServices() {
if (mdnsClient != null)
mdnsClient.getClient().unregisterAllServices();
}
public void activate() {
}
public void deactivate() {
unregisterAllServices();
try {
if (mdnsClient != null) {
mdnsClient.getClient().close();
logger.debug("mDNS service has been stopped");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
|
catching exception when mdns service is already closed
Signed-off-by: Kai Kreuzer <31ea678c44dc4e8e22ccfd165592dd71a30e46ae@openhab.org>
|
bundles/io/org.eclipse.smarthome.io.transport.mdns/src/main/java/org/eclipse/smarthome/io/transport/mdns/internal/MDNSServiceImpl.java
|
catching exception when mdns service is already closed
|
|
Java
|
agpl-3.0
|
f4d56d15a5398259ff02311cc0c89d536791d75b
| 0
|
kkronenb/kfs,kuali/kfs,smith750/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,smith750/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,kuali/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork
|
/*
* Copyright 2007-2008 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.purap.fixture;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants.TaxParameters;
import org.kuali.kfs.module.purap.businessobject.RequisitionItem;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.module.purap.fixture.TaxFixture.TaxTestCaseFixture;
import org.kuali.kfs.sys.context.TestUtils;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.kfs.vnd.fixture.CommodityCodeFixture;
import org.kuali.rice.kns.util.KualiDecimal;
public enum RequisitionDocumentFixture {
REQ_ONLY_REQUIRED_FIELDS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_TWO_ITEMS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1,
RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_2 } // requisitionItemMultiFixtures
),
REQ_ONLY_REQUIRED_FIELDS_MULTIPLE_ACCOUNTS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_3 } // requisitionItemMultiFixtures
),
REQ_WITH_NEGATIVE_AMOUNT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_ITEM_NEGATIVE_AMOUNT } // requisitionItemMultiFixtures
),
REQ_VALID_NO_APO_OVER_LIMIT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] {RequisitionItemFixture.REQ_ITEM_NO_APO} // requisitionItemMultiFixtures
),
REQ_VALID_NO_APO_RESTRICTED_ITEM(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] {RequisitionItemFixture.REQ_ITEM_NO_APO_RESTRICTED_ITEM} // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO } // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID_2(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO } // requisitionItemMultiFixtures
),
REQ_APO_VALID(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_MULTI_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_MULTI_QUANTITY, // purapDocumentFixture
PurchasingDocumentFixture.REQ_MULTI, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_MULTI_ITEM_QUANTITY } // requisitionItemMultiFixtures
),
REQ_MULTI_NON_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_MULTI_NON_QUANTITY, // purapDocumentFixture
PurchasingDocumentFixture.REQ_MULTI, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_MULTI_ITEM_NON_QUANTITY } // requisitionItemMultiFixtures
),
REQ_ALTERNATE_APO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ALTERNATE_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1, RequisitionItemFixture.REQ_SERVICE_APO_ITEM_1, RequisitionItemFixture.REQ_FREIGHT_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_ALTERNATE_VENDOR_NAMES(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
"NFL Shop", // alternate1VendorName
"Dicks Sporting Goods", // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_TOTAL_NOT_GREATER_THAN_ZERO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_TOTAL_NOT_GREATER_THAN_ZERO } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_CONTAINS_RESTRICTED_ITEM (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_CONTAIN_RESTRICTED_ITEM } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_ERROR_RETRIEVING_VENDOR_FROM_DATABASE (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_VENDOR_NOT_IN_DATABASE, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_WITH_RESTRICTED_VENDOR (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_RESTRICTED_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_PAYMENT_TYPE_RECURRING(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_PO_TOTAL_LIMIT_NON_ZERO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_PO_TOTAL_LIMIT_NON_ZERO, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_FAILS_CAPITAL_ASSET_RULE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_INVALID_CAPITAL_ASSET } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_APPROVAL_OUTSIDE_ALLOWED_DATE_RANGE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_VALID_VENDOR_FAX_NUMBER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_VALID_VENDOR_FAX_NUMBER, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_DEBARRED_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_DEBARRED_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_INACTIVE_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INACTIVE_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_DV_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_DV_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_PO_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR_NO_TOTAL_LIMIT, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_B2B_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_INVALID_VENDOR_FAX_NUMBER_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_INVALID_VENDOR_FAX_NUMBER_CONTAINS_LETTER, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_INVALID_VENDOR_FAX_NUMBER_BAD_FORMAT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_INVALID_VENDOR_FAX_NUMBER_BAD_FORMAT, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_BAD_FORMAT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_BAD_FORMAT, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_NON_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_NON_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_VALID_US_VENDOR_ZIP_CODE_WITH_4_TRAILING_NUMBERS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_VALID_US_VENDOR_ZIP_CODE_WITH_4_TRAILING_NUMBERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_AFTER_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_BEGIN_DATE_AFTER_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_NO_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_BEGIN_DATE_NO_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_END_DATE_NO_BEGIN_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_END_DATE_NO_BEGIN_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_AND_END_DATE_NO_RECURRING_PAYMENT_TYPE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_BEGIN_AND_END_DATE_WITHOUT_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_RECURRING_PAYMENT_TYPE_WITHOUT_BEGIN_NOR_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_RECURRING_PAYMENT_TYPE_BEGIN_AND_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE_BEGIN_AND_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID_WITH_BASIC_ACTIVE_COMMODITY_CODE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_BASIC_ACTIVE_COMMODITY_CODE } // requisitionItemMultiFixtures
),
REQ_INVALID_ITEM_QUANTITY_BASED_NO_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_INVALID_QUANTITY_BASED_NO_QUANTITY } // requisitionItemMultiFixtures
),
REQ_TAX(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_TAX, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PERFORMANCE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PERFORMANCE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
} // requisitionItemMultiFixtures
),
;
public final String requisitionOrganizationReference1Text;
public final String requisitionOrganizationReference2Text;
public final String requisitionOrganizationReference3Text;
public final String alternate1VendorName;
public final String alternate2VendorName;
public final String alternate3VendorName;
public final String alternate4VendorName;
public final String alternate5VendorName;
public final KualiDecimal organizationAutomaticPurchaseOrderLimit;
private PurchasingAccountsPayableDocumentFixture purapDocumentFixture;
private PurchasingDocumentFixture purchasingDocumentFixture;
private RequisitionItemFixture[] requisitionItemFixtures;
private RequisitionDocumentFixture(String requisitionOrganizationReference1Text, String requisitionOrganizationReference2Text, String requisitionOrganizationReference3Text, String alternate1VendorName, String alternate2VendorName, String alternate3VendorName, String alternate4VendorName, String alternate5VendorName, KualiDecimal organizationAutomaticPurchaseOrderLimit, PurchasingAccountsPayableDocumentFixture purapDocumentFixture, PurchasingDocumentFixture purchasingDocumentFixture, RequisitionItemFixture[] requisitionItemFixtures) {
this.requisitionOrganizationReference1Text = requisitionOrganizationReference1Text;
this.requisitionOrganizationReference2Text = requisitionOrganizationReference2Text;
this.requisitionOrganizationReference3Text = requisitionOrganizationReference3Text;
this.alternate1VendorName = alternate1VendorName;
this.alternate2VendorName = alternate2VendorName;
this.alternate3VendorName = alternate3VendorName;
this.alternate4VendorName = alternate4VendorName;
this.alternate5VendorName = alternate5VendorName;
this.organizationAutomaticPurchaseOrderLimit = organizationAutomaticPurchaseOrderLimit;
this.purapDocumentFixture = purapDocumentFixture;
this.purchasingDocumentFixture = purchasingDocumentFixture;
this.requisitionItemFixtures = requisitionItemFixtures;
}
public RequisitionDocument createRequisitionDocument() {
RequisitionDocument doc = purchasingDocumentFixture.createRequisitionDocument(purapDocumentFixture);
doc.setRequisitionOrganizationReference1Text(this.requisitionOrganizationReference1Text);
doc.setRequisitionOrganizationReference2Text(this.requisitionOrganizationReference2Text);
doc.setRequisitionOrganizationReference3Text(this.requisitionOrganizationReference3Text);
doc.setAlternate1VendorName(this.alternate1VendorName);
doc.setAlternate2VendorName(this.alternate2VendorName);
doc.setAlternate3VendorName(this.alternate3VendorName);
doc.setAlternate4VendorName(this.alternate4VendorName);
doc.setAlternate5VendorName(this.alternate5VendorName);
doc.setOrganizationAutomaticPurchaseOrderLimit(this.organizationAutomaticPurchaseOrderLimit);
for (RequisitionItemFixture requisitionItemFixture : requisitionItemFixtures) {
requisitionItemFixture.addTo(doc);
}
doc.fixItemReferences();
doc.setAccountDistributionMethod("S");
return doc;
}
public RequisitionDocument createRequisitionDocumentForTax(TaxTestCaseFixture taxTestCaseFixture) {
RequisitionDocument doc = createRequisitionDocument();
doc.getItem(0).getItemType().setTaxableIndicator(taxTestCaseFixture.isItemTypeTaxable());
doc.setDeliveryStateCode("IN");
if (taxTestCaseFixture.isItemTaxAmountNull()){
doc.getItem(0).setItemTaxAmount(null);
}else{
doc.getItem(0).setItemTaxAmount(new KualiDecimal(100));
}
doc.setUseTaxIndicator(taxTestCaseFixture.isUseTax());
if (taxTestCaseFixture.iscommodityCodeNull()){
((RequisitionItem)doc.getItem(0)).setPurchasingCommodityCode(null);
((RequisitionItem)doc.getItem(0)).setCommodityCode(null);
}else{
((RequisitionItem)doc.getItem(0)).setCommodityCode(CommodityCodeFixture.COMMODITY_CODE_BASIC_ACTIVE.createCommodityCode());
}
String INVALID_VALUE = "XX";
String fundGroupCode = doc.getItem(0).getSourceAccountingLines().get(0).getAccount().getSubFundGroup().getFundGroupCode();
String subFundGroupCode = doc.getItem(0).getSourceAccountingLines().get(0).getAccount().getSubFundGroup().getSubFundGroupCode();
String objectLevelCode = doc.getItem(0).getSourceAccountingLines().get(0).getObjectCode().getFinancialObjectLevelCode();
String consolidationObjectCode = doc.getItem(0).getSourceAccountingLines().get(0).getObjectCode().getFinancialObjectLevel().getFinancialConsolidationObjectCode();
String parameterSuffix;
if (taxTestCaseFixture.isDeliveryStateTaxable()){
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, TaxParameters.TAXABLE_DELIVERY_STATES, doc.getDeliveryStateCode());
parameterSuffix = "FOR_TAXABLE_STATES";
} else {
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, TaxParameters.TAXABLE_DELIVERY_STATES, INVALID_VALUE);
parameterSuffix = "FOR_NON_TAXABLE_STATES";
}
if (taxTestCaseFixture.isFundGroupCodeTaxable()){
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_FUND_GROUPS_" + parameterSuffix, fundGroupCode);
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_SUB_FUND_GROUPS_" + parameterSuffix, subFundGroupCode);
}else{
//Just put some invalid value
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_FUND_GROUPS_" + parameterSuffix, INVALID_VALUE);
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_SUB_FUND_GROUPS_" + parameterSuffix, INVALID_VALUE);
}
if (taxTestCaseFixture.isObjectCodeTaxable()){
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_LEVELS_" + parameterSuffix, objectLevelCode);
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_CONSOLIDATIONS_" + parameterSuffix, consolidationObjectCode);
}else{
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_LEVELS_" + parameterSuffix, INVALID_VALUE);
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_CONSOLIDATIONS_" + parameterSuffix, INVALID_VALUE);
}
if (taxTestCaseFixture.isSalesTaxEnabled()){
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND,"Y");
}else{
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND,"N");
}
return doc;
}
public String toString() {
return new ToStringBuilder(this).append("requisitionOrganizationReference1Text", requisitionOrganizationReference1Text).append("requisitionOrganizationReference2Text", requisitionOrganizationReference2Text).append("requisitionOrganizationReference3Text", requisitionOrganizationReference3Text).append("alternate1VendorName", alternate1VendorName).append("alternate2VendorName", alternate2VendorName).append("alternate3VendorName", alternate3VendorName)
.append("alternate4VendorName", alternate4VendorName).append("alternate5VendorName", alternate5VendorName).append("organizationAutomaticPurchaseOrderLimit", organizationAutomaticPurchaseOrderLimit).append("purapDocumentFixture", purapDocumentFixture).append("purchasingDocumentFixture", purchasingDocumentFixture).append("requisitionItemFixtures", requisitionItemFixtures).toString();
}
}
|
test/unit/src/org/kuali/kfs/module/purap/fixture/RequisitionDocumentFixture.java
|
/*
* Copyright 2007-2008 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.purap.fixture;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapParameterConstants.TaxParameters;
import org.kuali.kfs.module.purap.businessobject.RequisitionItem;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.module.purap.fixture.TaxFixture.TaxTestCaseFixture;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.context.TestUtils;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.kfs.vnd.fixture.CommodityCodeFixture;
import org.kuali.rice.kns.service.ParameterService;
import org.kuali.rice.kns.util.KualiDecimal;
public enum RequisitionDocumentFixture {
REQ_ONLY_REQUIRED_FIELDS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_TWO_ITEMS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1,
RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_2 } // requisitionItemMultiFixtures
),
REQ_ONLY_REQUIRED_FIELDS_MULTIPLE_ACCOUNTS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_3 } // requisitionItemMultiFixtures
),
REQ_WITH_NEGATIVE_AMOUNT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_ITEM_NEGATIVE_AMOUNT } // requisitionItemMultiFixtures
),
REQ_VALID_NO_APO_OVER_LIMIT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] {RequisitionItemFixture.REQ_ITEM_NO_APO} // requisitionItemMultiFixtures
),
REQ_VALID_NO_APO_RESTRICTED_ITEM(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] {RequisitionItemFixture.REQ_ITEM_NO_APO_RESTRICTED_ITEM} // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO } // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID_2(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO } // requisitionItemMultiFixtures
),
REQ_APO_VALID(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_MULTI_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_MULTI_QUANTITY, // purapDocumentFixture
PurchasingDocumentFixture.REQ_MULTI, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_MULTI_ITEM_QUANTITY } // requisitionItemMultiFixtures
),
REQ_MULTI_NON_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_MULTI_NON_QUANTITY, // purapDocumentFixture
PurchasingDocumentFixture.REQ_MULTI, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_MULTI_ITEM_NON_QUANTITY } // requisitionItemMultiFixtures
),
REQ_ALTERNATE_APO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ALTERNATE_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1, RequisitionItemFixture.REQ_SERVICE_APO_ITEM_1, RequisitionItemFixture.REQ_FREIGHT_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_ALTERNATE_VENDOR_NAMES(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
"NFL Shop", // alternate1VendorName
"Dicks Sporting Goods", // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_TOTAL_NOT_GREATER_THAN_ZERO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_TOTAL_NOT_GREATER_THAN_ZERO } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_CONTAINS_RESTRICTED_ITEM (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_CONTAIN_RESTRICTED_ITEM } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_ERROR_RETRIEVING_VENDOR_FROM_DATABASE (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_VENDOR_NOT_IN_DATABASE, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_WITH_RESTRICTED_VENDOR (null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_RESTRICTED_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_PAYMENT_TYPE_RECURRING(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_PO_TOTAL_LIMIT_NON_ZERO(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_PO_TOTAL_LIMIT_NON_ZERO, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_FAILS_CAPITAL_ASSET_RULE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_INVALID_CAPITAL_ASSET } // requisitionItemMultiFixtures
),
REQ_APO_INVALID_APPROVAL_OUTSIDE_ALLOWED_DATE_RANGE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_VALID_VENDOR_FAX_NUMBER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_VALID_VENDOR_FAX_NUMBER, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_DEBARRED_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_DEBARRED_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_INACTIVE_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INACTIVE_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_DV_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_DV_VENDOR, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_B2B_WITH_PO_VENDOR(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_B2B_VENDOR_NO_TOTAL_LIMIT, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_B2B_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_INVALID_VENDOR_FAX_NUMBER_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_INVALID_VENDOR_FAX_NUMBER_CONTAINS_LETTER, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_INVALID_VENDOR_FAX_NUMBER_BAD_FORMAT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_INVALID_VENDOR_FAX_NUMBER_BAD_FORMAT, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_BAD_FORMAT(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_US_VENDOR_ZIP_CODE_BAD_FORMAT, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_INVALID_NON_US_VENDOR_ZIP_CODE_CONTAINS_LETTER(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_INVALID_NON_US_VENDOR_ZIP_CODE_CONTAINS_LETTERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_VALID_US_VENDOR_ZIP_CODE_WITH_4_TRAILING_NUMBERS(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_WITH_VALID_US_VENDOR_ZIP_CODE_WITH_4_TRAILING_NUMBERS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_AFTER_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_BEGIN_DATE_AFTER_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_NO_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_BEGIN_DATE_NO_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_END_DATE_NO_BEGIN_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PO_END_DATE_NO_BEGIN_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PO_BEGIN_DATE_AND_END_DATE_NO_RECURRING_PAYMENT_TYPE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_BEGIN_AND_END_DATE_WITHOUT_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_RECURRING_PAYMENT_TYPE_WITHOUT_BEGIN_NOR_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_WITH_RECURRING_PAYMENT_TYPE_BEGIN_AND_END_DATE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_WITH_RECURRING_PAYMENT_TYPE_BEGIN_AND_END_DATE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_APO_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_NO_APO_VALID_WITH_BASIC_ACTIVE_COMMODITY_CODE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_VALID_APO, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_NO_APO_BASIC_ACTIVE_COMMODITY_CODE } // requisitionItemMultiFixtures
),
REQ_INVALID_ITEM_QUANTITY_BASED_NO_QUANTITY(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_INVALID_QUANTITY_BASED_NO_QUANTITY } // requisitionItemMultiFixtures
),
REQ_TAX(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_TAX, // purapDocumentFixture
PurchasingDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_QTY_UNRESTRICTED_ITEM_1 } // requisitionItemMultiFixtures
),
REQ_PERFORMANCE(null, // requisitionOrganizationReference1Text
null, // requisitionOrganizationReference2Text
null, // requisitionOrganizationReference3Text
null, // alternate1VendorName
null, // alternate2VendorName
null, // alternate3VendorName
null, // alternate4VendorName
null, // alternate5VendorName
null, // organizationAutomaticPurchaseOrderLimit
PurchasingAccountsPayableDocumentFixture.REQ_ONLY_REQUIRED_FIELDS, // purapDocumentFixture
PurchasingDocumentFixture.REQ_PERFORMANCE, // purchasingDocumentFixture
new RequisitionItemFixture[] { RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
RequisitionItemFixture.REQ_ITEM_PERFORMANCE,
} // requisitionItemMultiFixtures
),
;
public final String requisitionOrganizationReference1Text;
public final String requisitionOrganizationReference2Text;
public final String requisitionOrganizationReference3Text;
public final String alternate1VendorName;
public final String alternate2VendorName;
public final String alternate3VendorName;
public final String alternate4VendorName;
public final String alternate5VendorName;
public final KualiDecimal organizationAutomaticPurchaseOrderLimit;
private PurchasingAccountsPayableDocumentFixture purapDocumentFixture;
private PurchasingDocumentFixture purchasingDocumentFixture;
private RequisitionItemFixture[] requisitionItemFixtures;
private RequisitionDocumentFixture(String requisitionOrganizationReference1Text, String requisitionOrganizationReference2Text, String requisitionOrganizationReference3Text, String alternate1VendorName, String alternate2VendorName, String alternate3VendorName, String alternate4VendorName, String alternate5VendorName, KualiDecimal organizationAutomaticPurchaseOrderLimit, PurchasingAccountsPayableDocumentFixture purapDocumentFixture, PurchasingDocumentFixture purchasingDocumentFixture, RequisitionItemFixture[] requisitionItemFixtures) {
this.requisitionOrganizationReference1Text = requisitionOrganizationReference1Text;
this.requisitionOrganizationReference2Text = requisitionOrganizationReference2Text;
this.requisitionOrganizationReference3Text = requisitionOrganizationReference3Text;
this.alternate1VendorName = alternate1VendorName;
this.alternate2VendorName = alternate2VendorName;
this.alternate3VendorName = alternate3VendorName;
this.alternate4VendorName = alternate4VendorName;
this.alternate5VendorName = alternate5VendorName;
this.organizationAutomaticPurchaseOrderLimit = organizationAutomaticPurchaseOrderLimit;
this.purapDocumentFixture = purapDocumentFixture;
this.purchasingDocumentFixture = purchasingDocumentFixture;
this.requisitionItemFixtures = requisitionItemFixtures;
}
public RequisitionDocument createRequisitionDocument() {
RequisitionDocument doc = purchasingDocumentFixture.createRequisitionDocument(purapDocumentFixture);
doc.setRequisitionOrganizationReference1Text(this.requisitionOrganizationReference1Text);
doc.setRequisitionOrganizationReference2Text(this.requisitionOrganizationReference2Text);
doc.setRequisitionOrganizationReference3Text(this.requisitionOrganizationReference3Text);
doc.setAlternate1VendorName(this.alternate1VendorName);
doc.setAlternate2VendorName(this.alternate2VendorName);
doc.setAlternate3VendorName(this.alternate3VendorName);
doc.setAlternate4VendorName(this.alternate4VendorName);
doc.setAlternate5VendorName(this.alternate5VendorName);
doc.setOrganizationAutomaticPurchaseOrderLimit(this.organizationAutomaticPurchaseOrderLimit);
for (RequisitionItemFixture requisitionItemFixture : requisitionItemFixtures) {
requisitionItemFixture.addTo(doc);
}
doc.fixItemReferences();
doc.setAccountDistributionMethod("S");
return doc;
}
public RequisitionDocument createRequisitionDocumentForTax(TaxTestCaseFixture taxTestCaseFixture) {
RequisitionDocument doc = createRequisitionDocument();
doc.getItem(0).getItemType().setTaxableIndicator(taxTestCaseFixture.isItemTypeTaxable());
doc.setDeliveryStateCode("IN");
if (taxTestCaseFixture.isItemTaxAmountNull()){
doc.getItem(0).setItemTaxAmount(null);
}else{
doc.getItem(0).setItemTaxAmount(new KualiDecimal(100));
}
doc.setUseTaxIndicator(taxTestCaseFixture.isUseTax());
if (taxTestCaseFixture.iscommodityCodeNull()){
((RequisitionItem)doc.getItem(0)).setPurchasingCommodityCode(null);
((RequisitionItem)doc.getItem(0)).setCommodityCode(null);
}else{
((RequisitionItem)doc.getItem(0)).setCommodityCode(CommodityCodeFixture.COMMODITY_CODE_BASIC_ACTIVE.createCommodityCode());
}
String INVALID_VALUE = "XX";
String fundGroupCode = doc.getItem(0).getSourceAccountingLines().get(0).getAccount().getSubFundGroup().getFundGroupCode();
String subFundGroupCode = doc.getItem(0).getSourceAccountingLines().get(0).getAccount().getSubFundGroup().getSubFundGroupCode();
String objectLevelCode = doc.getItem(0).getSourceAccountingLines().get(0).getObjectCode().getFinancialObjectLevelCode();
String consolidationObjectCode = doc.getItem(0).getSourceAccountingLines().get(0).getObjectCode().getFinancialObjectLevel().getFinancialConsolidationObjectCode();
String parameterSuffix;
if (taxTestCaseFixture.isDeliveryStateTaxable()){
ParameterService paramSrv = SpringContext.getBean(ParameterService.class);
TestUtils.setSystemParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, TaxParameters.TAXABLE_DELIVERY_STATES, doc.getDeliveryStateCode());
parameterSuffix = "FOR_TAXABLE_STATES";
} else {
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, TaxParameters.TAXABLE_DELIVERY_STATES, INVALID_VALUE);
parameterSuffix = "FOR_NON_TAXABLE_STATES";
}
if (taxTestCaseFixture.isFundGroupCodeTaxable()){
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_FUND_GROUPS_" + parameterSuffix, fundGroupCode);
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_SUB_FUND_GROUPS_" + parameterSuffix, subFundGroupCode);
}else{
//Just put some invalid value
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_FUND_GROUPS_" + parameterSuffix, INVALID_VALUE);
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_SUB_FUND_GROUPS_" + parameterSuffix, INVALID_VALUE);
}
if (taxTestCaseFixture.isObjectCodeTaxable()){
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_LEVELS_" + parameterSuffix, objectLevelCode);
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_CONSOLIDATIONS_" + parameterSuffix, consolidationObjectCode);
}else{
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_LEVELS_" + parameterSuffix, INVALID_VALUE);
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, "TAXABLE_OBJECT_CONSOLIDATIONS_" + parameterSuffix, INVALID_VALUE);
}
if (taxTestCaseFixture.isSalesTaxEnabled()){
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND,"Y");
}else{
SpringContext.getBean(ParameterService.class).setParameterForTesting(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND,"N");
}
return doc;
}
public String toString() {
return new ToStringBuilder(this).append("requisitionOrganizationReference1Text", requisitionOrganizationReference1Text).append("requisitionOrganizationReference2Text", requisitionOrganizationReference2Text).append("requisitionOrganizationReference3Text", requisitionOrganizationReference3Text).append("alternate1VendorName", alternate1VendorName).append("alternate2VendorName", alternate2VendorName).append("alternate3VendorName", alternate3VendorName)
.append("alternate4VendorName", alternate4VendorName).append("alternate5VendorName", alternate5VendorName).append("organizationAutomaticPurchaseOrderLimit", organizationAutomaticPurchaseOrderLimit).append("purapDocumentFixture", purapDocumentFixture).append("purchasingDocumentFixture", purchasingDocumentFixture).append("requisitionItemFixtures", requisitionItemFixtures).toString();
}
}
|
KFSMI-6663 : pre Rice 2.0 cleanup
|
test/unit/src/org/kuali/kfs/module/purap/fixture/RequisitionDocumentFixture.java
|
KFSMI-6663 : pre Rice 2.0 cleanup
|
|
Java
|
lgpl-2.1
|
cab1f4b8045a31fcc301c999b800a4ea44482783
| 0
|
JordanReiter/railo,getrailo/railo,getrailo/railo,modius/railo,getrailo/railo,modius/railo,JordanReiter/railo
|
package railo.runtime.listener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.Cookie;
import railo.commons.io.DevNullOutputStream;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.commons.lang.types.RefBoolean;
import railo.commons.lang.types.RefBooleanImpl;
import railo.runtime.CFMLFactory;
import railo.runtime.Component;
import railo.runtime.ComponentPage;
import railo.runtime.PageContext;
import railo.runtime.PageContextImpl;
import railo.runtime.PageSource;
import railo.runtime.component.ComponentLoader;
import railo.runtime.component.Member;
import railo.runtime.config.Constants;
import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.exp.Abort;
import railo.runtime.exp.MissingIncludeException;
import railo.runtime.exp.PageException;
import railo.runtime.interpreter.JSONExpressionInterpreter;
import railo.runtime.net.http.HttpServletRequestDummy;
import railo.runtime.net.http.HttpServletResponseDummy;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.orm.ORMUtil;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.cfc.ComponentAccess;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.StructUtil;
public class ModernAppListener extends AppListenerSupport {
private static final Collection.Key ON_REQUEST_START = KeyImpl.intern("onRequestStart");
private static final Collection.Key ON_CFCREQUEST = KeyImpl.intern("onCFCRequest");
private static final Collection.Key ON_REQUEST = KeyImpl.intern("onRequest");
private static final Collection.Key ON_REQUEST_END = KeyImpl.intern("onRequestEnd");
private static final Collection.Key ON_ABORT = KeyImpl.intern("onAbort");
private static final Collection.Key ON_APPLICATION_START = KeyImpl.intern("onApplicationStart");
private static final Collection.Key ON_APPLICATION_END = KeyImpl.intern("onApplicationEnd");
private static final Collection.Key ON_SESSION_START = KeyImpl.intern("onSessionStart");
private static final Collection.Key ON_SESSION_END = KeyImpl.intern("onSessionEnd");
private static final Collection.Key ON_DEBUG = KeyImpl.intern("onDebug");
private static final Collection.Key ON_ERROR = KeyImpl.intern("onError");
private static final Collection.Key ON_MISSING_TEMPLATE = KeyImpl.intern("onMissingTemplate");
//private ComponentImpl app;
private Map apps=new HashMap();
protected int mode=MODE_CURRENT2ROOT;
private String type;
//private ApplicationContextImpl appContext;
//private long cfcCompileTime;
/**
*
* @throws PageException
* @see railo.runtime.listener.ApplicationListener#onRequest(railo.runtime.PageContext, railo.runtime.PageSource)
*/
public void onRequest(PageContext pc, PageSource requestedPage) throws PageException {
// on requestStart
PageSource appPS=//pc.isCFCRequest()?null:
AppListenerUtil.getApplicationPageSource(pc,requestedPage,Constants.APP_CFC,mode);
_onRequest(pc, requestedPage, appPS);
}
protected void _onRequest(PageContext pc, PageSource requestedPage,PageSource appPS) throws PageException {
PageContextImpl pci = (PageContextImpl)pc;
if(appPS!=null) {
String callPath=appPS.getComponentName();
ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,true);
String targetPage=requestedPage.getFullRealpath();
// init
initApplicationContext(pci,app);
apps.put(pc.getApplicationContext().getName(), app);
if(!pci.initApplicationContext()) return;
boolean doOnRequestEnd=true;
// onRequestStart
if(app.contains(pc,ON_REQUEST_START)) {
Object rtn=call(app,pci, ON_REQUEST_START, new Object[]{targetPage});
if(!Caster.toBooleanValue(rtn,true))
return;
}
// onRequest
boolean isCFC=ResourceUtil.getExtension(targetPage,"").equalsIgnoreCase(pc.getConfig().getCFCExtension());
Object method;
if(isCFC && app.contains(pc,ON_CFCREQUEST) && (method=pc.urlFormScope().get(ComponentPage.METHOD,null))!=null) {
Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
url.removeEL(KeyImpl.FIELD_NAMES);
url.removeEL(ComponentPage.METHOD);
Object args=url.get(KeyImpl.ARGUMENT_COLLECTION,null);
Object returnFormat=url.removeEL(KeyImpl.RETURN_FORMAT);
Object queryFormat=url.removeEL(ComponentPage.QUERY_FORMAT);
if(args==null){
args=pc.getHttpServletRequest().getAttribute("argumentCollection");
}
if(args instanceof String){
args=new JSONExpressionInterpreter().interpret(pc, (String)args);
}
if(args!=null) {
if(Decision.isCastableToStruct(args)){
Struct sct = Caster.toStruct(args,false);
//Key[] keys = url.keys();
Iterator<Entry<Key, Object>> it = url.entryIterator();
Entry<Key, Object> e;
while(it.hasNext()){
e = it.next();
sct.setEL(e.getKey(),e.getValue());
}
args=sct;
}
else if(Decision.isCastableToArray(args)){
args = Caster.toArray(args);
}
else {
Array arr = new ArrayImpl();
arr.appendEL(args);
args=arr;
}
}
else
args=url;
//print.out("c:"+requestedPage.getComponentName());
//print.out("c:"+requestedPage.getComponentName());
Object rtn = call(app,pci, ON_CFCREQUEST, new Object[]{requestedPage.getComponentName(),method,args});
if(rtn!=null){
if(pc.getHttpServletRequest().getHeader("AMF-Forward")!=null) {
pc.variablesScope().setEL("AMF-Forward", rtn);
//ThreadLocalWDDXResult.set(rtn);
}
else {
try {
pc.forceWrite(ComponentPage.convertResult(pc,app,method.toString(),returnFormat,queryFormat,rtn));
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
}
else if(!isCFC && app.contains(pc,ON_REQUEST)) {
call(app,pci, ON_REQUEST, new Object[]{targetPage});
}
else {
// TODO impl die nicht so generisch ist
try{
pci.doInclude(requestedPage);
}
catch(PageException pe){
if(!Abort.isSilentAbort(pe)) {
if(pe instanceof MissingIncludeException){
if(((MissingIncludeException) pe).getPageSource().equals(requestedPage)){
if(app.contains(pc,ON_MISSING_TEMPLATE)) {
if(!Caster.toBooleanValue(call(app,pci, ON_MISSING_TEMPLATE, new Object[]{targetPage}),true))
throw pe;
}
else throw pe;
}
else throw pe;
}
else throw pe;
}
else {
doOnRequestEnd=false;
if(app.contains(pc,ON_ABORT))
call(app,pci, ON_ABORT, new Object[]{targetPage});
}
}
}
// onRequestEnd
if(doOnRequestEnd && app.contains(pc,ON_REQUEST_END)) {
call(app,pci, ON_REQUEST_END, new Object[]{targetPage});
}
}
else {
apps.put(pc.getApplicationContext().getName(), null);
pc.doInclude(requestedPage);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onApplicationStart(railo.runtime.PageContext)
*/
public boolean onApplicationStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_APPLICATION_START)) {
Object rtn = call(app,pc, ON_APPLICATION_START, ArrayUtil.OBJECT_EMPTY);
return Caster.toBooleanValue(rtn,true);
}
return true;
}
public void onApplicationEnd(CFMLFactory factory, String applicationName) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_APPLICATION_END)) return;
PageContextImpl pc=(PageContextImpl) ThreadLocalPageContext.get();
boolean createPc=pc==null;
try {
if(createPc)pc = createPageContext(factory,app,applicationName,null,ON_APPLICATION_END);
call(app,pc, ON_APPLICATION_END, new Object[]{pc.applicationScope()});
}
finally {
if(createPc && pc!=null){
factory.releasePageContext(pc);
}
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionStart(railo.runtime.PageContext)
*/
public void onSessionStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(hasOnSessionStart(pc,app)) {
call(app,pc, ON_SESSION_START, ArrayUtil.OBJECT_EMPTY);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionEnd(railo.runtime.CFMLFactory, java.lang.String, java.lang.String)
*/
public void onSessionEnd(CFMLFactory factory, String applicationName, String cfid) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_SESSION_END)) return;
PageContextImpl pc=null;
try {
pc = createPageContext(factory,app,applicationName,cfid,ON_SESSION_END);
call(app,pc, ON_SESSION_END, new Object[]{pc.sessionScope(false),pc.applicationScope()});
}
finally {
if(pc!=null){
factory.releasePageContext(pc);
}
}
}
private PageContextImpl createPageContext(CFMLFactory factory, ComponentAccess app, String applicationName, String cfid,Collection.Key methodName) throws PageException {
Resource root = factory.getConfig().getRootDirectory();
String path = app.getPageSource().getFullRealpath();
// Request
HttpServletRequestDummy req = new HttpServletRequestDummy(root,"localhost",path,"",null,null,null,null,null);
if(!StringUtil.isEmpty(cfid))req.setCookies(new Cookie[]{new Cookie("cfid",cfid),new Cookie("cftoken","0")});
// Response
OutputStream os=DevNullOutputStream.DEV_NULL_OUTPUT_STREAM;
try {
Resource out = factory.getConfig().getConfigDir().getRealResource("output/"+methodName.getString()+".out");
out.getParentResource().mkdirs();
os = out.getOutputStream(false);
}
catch (IOException e) {
e.printStackTrace();
// TODO was passiert hier
}
HttpServletResponseDummy rsp = new HttpServletResponseDummy(os);
// PageContext
PageContextImpl pc = (PageContextImpl) factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false);
// ApplicationContext
ClassicApplicationContext ap = new ClassicApplicationContext(factory.getConfig(),applicationName,false,app==null?null:ResourceUtil.getResource(pc,app.getPageSource(),null));
initApplicationContext(pc, app);
ap.setName(applicationName);
ap.setSetSessionManagement(true);
//if(!ap.hasName())ap.setName("Controler")
// Base
pc.setBase(app.getPageSource());
return pc;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onDebug(railo.runtime.PageContext)
*/
public void onDebug(PageContext pc) throws PageException {
if(((PageContextImpl)pc).isGatewayContext()) return;
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_DEBUG)) {
call(app,pc, ON_DEBUG, new Object[]{pc.getDebugger().getDebuggingData(pc)});
return;
}
try {
pc.getDebugger().writeOut(pc);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onError(railo.runtime.PageContext, railo.runtime.exp.PageException)
*/
public void onError(PageContext pc, PageException pe) {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.containsKey(ON_ERROR) && !Abort.isSilentAbort(pe)) {
try {
String eventName="";
if(pe instanceof ModernAppListenerException) eventName= ((ModernAppListenerException)pe).getEventName();
if(eventName==null)eventName="";
call(app,pc, ON_ERROR, new Object[]{pe.getCatchBlock(pc),eventName});
return;
}
catch(PageException _pe) {
pe=_pe;
}
}
pc.handlePageException(pe);
}
private Object call(Component app, PageContext pc, Collection.Key eventName, Object[] args) throws ModernAppListenerException {
try {
return app.call(pc, eventName, args);
}
catch (PageException pe) {
if(Abort.isSilentAbort(pe)) return Boolean.FALSE;
throw new ModernAppListenerException(pe,eventName.getString());
}
}
private void initApplicationContext(PageContextImpl pc, ComponentAccess app) throws PageException {
// use existing app context
RefBoolean throwsErrorWhileInit=new RefBooleanImpl(false);
ModernApplicationContext appContext = new ModernApplicationContext(pc,app,throwsErrorWhileInit);
pc.setApplicationContext(appContext);
if(appContext.isORMEnabled()) {
boolean hasError=throwsErrorWhileInit.toBooleanValue();
if(hasError)pc.addPageSource(app.getPageSource(), true);
try{
ORMUtil.resetEngine(pc,false);
}
finally {
if(hasError)pc.removeLastPageSource(true);
}
}
}
private static Object get(ComponentAccess app, Key name,String defaultValue) {
Member mem = app.getMember(Component.ACCESS_PRIVATE, name, true, false);
if(mem==null) return defaultValue;
return mem.getValue();
}
/**
*
* @see railo.runtime.listener.ApplicationListener#setMode(int)
*/
public void setMode(int mode) {
this.mode=mode;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#getMode()
*/
public int getMode() {
return mode;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @see railo.runtime.listener.AppListenerSupport#hasOnSessionStart(railo.runtime.PageContext)
*/
public boolean hasOnSessionStart(PageContext pc) {
return hasOnSessionStart(pc,(ComponentAccess) apps.get(pc.getApplicationContext().getName()));
}
private boolean hasOnSessionStart(PageContext pc,ComponentAccess app) {
return app!=null && app.contains(pc,ON_SESSION_START);
}
}
|
railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java
|
package railo.runtime.listener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.Cookie;
import railo.commons.io.DevNullOutputStream;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.commons.lang.types.RefBoolean;
import railo.commons.lang.types.RefBooleanImpl;
import railo.runtime.CFMLFactory;
import railo.runtime.Component;
import railo.runtime.ComponentPage;
import railo.runtime.PageContext;
import railo.runtime.PageContextImpl;
import railo.runtime.PageSource;
import railo.runtime.component.ComponentLoader;
import railo.runtime.component.Member;
import railo.runtime.config.Constants;
import railo.runtime.engine.ThreadLocalPageContext;
import railo.runtime.exp.Abort;
import railo.runtime.exp.MissingIncludeException;
import railo.runtime.exp.PageException;
import railo.runtime.interpreter.JSONExpressionInterpreter;
import railo.runtime.net.http.HttpServletRequestDummy;
import railo.runtime.net.http.HttpServletResponseDummy;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.orm.ORMUtil;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.cfc.ComponentAccess;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.StructUtil;
public class ModernAppListener extends AppListenerSupport {
private static final Collection.Key ON_REQUEST_START = KeyImpl.intern("onRequestStart");
private static final Collection.Key ON_CFCREQUEST = KeyImpl.intern("onCFCRequest");
private static final Collection.Key ON_REQUEST = KeyImpl.intern("onRequest");
private static final Collection.Key ON_REQUEST_END = KeyImpl.intern("onRequestEnd");
private static final Collection.Key ON_APPLICATION_START = KeyImpl.intern("onApplicationStart");
private static final Collection.Key ON_APPLICATION_END = KeyImpl.intern("onApplicationEnd");
private static final Collection.Key ON_SESSION_START = KeyImpl.intern("onSessionStart");
private static final Collection.Key ON_SESSION_END = KeyImpl.intern("onSessionEnd");
private static final Collection.Key ON_DEBUG = KeyImpl.intern("onDebug");
private static final Collection.Key ON_ERROR = KeyImpl.intern("onError");
private static final Collection.Key ON_MISSING_TEMPLATE = KeyImpl.intern("onMissingTemplate");
//private ComponentImpl app;
private Map apps=new HashMap();
protected int mode=MODE_CURRENT2ROOT;
private String type;
//private ApplicationContextImpl appContext;
//private long cfcCompileTime;
/**
*
* @throws PageException
* @see railo.runtime.listener.ApplicationListener#onRequest(railo.runtime.PageContext, railo.runtime.PageSource)
*/
public void onRequest(PageContext pc, PageSource requestedPage) throws PageException {
// on requestStart
PageSource appPS=//pc.isCFCRequest()?null:
AppListenerUtil.getApplicationPageSource(pc,requestedPage,Constants.APP_CFC,mode);
_onRequest(pc, requestedPage, appPS);
}
protected void _onRequest(PageContext pc, PageSource requestedPage,PageSource appPS) throws PageException {
PageContextImpl pci = (PageContextImpl)pc;
if(appPS!=null) {
String callPath=appPS.getComponentName();
ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,true);
String targetPage=requestedPage.getFullRealpath();
// init
initApplicationContext(pci,app);
apps.put(pc.getApplicationContext().getName(), app);
if(!pci.initApplicationContext()) return;
// onRequestStart
if(app.contains(pc,ON_REQUEST_START)) {
Object rtn=call(app,pci, ON_REQUEST_START, new Object[]{targetPage});
if(!Caster.toBooleanValue(rtn,true))
return;
}
// onRequest
boolean isCFC=ResourceUtil.getExtension(targetPage,"").equalsIgnoreCase(pc.getConfig().getCFCExtension());
Object method;
if(isCFC && app.contains(pc,ON_CFCREQUEST) && (method=pc.urlFormScope().get(ComponentPage.METHOD,null))!=null) {
Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
url.removeEL(KeyImpl.FIELD_NAMES);
url.removeEL(ComponentPage.METHOD);
Object args=url.get(KeyImpl.ARGUMENT_COLLECTION,null);
Object returnFormat=url.removeEL(KeyImpl.RETURN_FORMAT);
Object queryFormat=url.removeEL(ComponentPage.QUERY_FORMAT);
if(args==null){
args=pc.getHttpServletRequest().getAttribute("argumentCollection");
}
if(args instanceof String){
args=new JSONExpressionInterpreter().interpret(pc, (String)args);
}
if(args!=null) {
if(Decision.isCastableToStruct(args)){
Struct sct = Caster.toStruct(args,false);
//Key[] keys = url.keys();
Iterator<Entry<Key, Object>> it = url.entryIterator();
Entry<Key, Object> e;
while(it.hasNext()){
e = it.next();
sct.setEL(e.getKey(),e.getValue());
}
args=sct;
}
else if(Decision.isCastableToArray(args)){
args = Caster.toArray(args);
}
else {
Array arr = new ArrayImpl();
arr.appendEL(args);
args=arr;
}
}
else
args=url;
//print.out("c:"+requestedPage.getComponentName());
//print.out("c:"+requestedPage.getComponentName());
Object rtn = call(app,pci, ON_CFCREQUEST, new Object[]{requestedPage.getComponentName(),method,args});
if(rtn!=null){
if(pc.getHttpServletRequest().getHeader("AMF-Forward")!=null) {
pc.variablesScope().setEL("AMF-Forward", rtn);
//ThreadLocalWDDXResult.set(rtn);
}
else {
try {
pc.forceWrite(ComponentPage.convertResult(pc,app,method.toString(),returnFormat,queryFormat,rtn));
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
}
else if(!isCFC && app.contains(pc,ON_REQUEST)) {
call(app,pci, ON_REQUEST, new Object[]{targetPage});
}
else {
// TODO impl die nicht so generisch ist
try{
pci.doInclude(requestedPage);
}
catch(PageException pe){
if(!Abort.isSilentAbort(pe)) {
if(pe instanceof MissingIncludeException){
if(((MissingIncludeException) pe).getPageSource().equals(requestedPage)){
if(app.contains(pc,ON_MISSING_TEMPLATE)) {
if(!Caster.toBooleanValue(call(app,pci, ON_MISSING_TEMPLATE, new Object[]{targetPage}),true))
throw pe;
}
else throw pe;
}
else throw pe;
}
else throw pe;
}
}
}
// onRequestEnd
if(app.contains(pc,ON_REQUEST_END)) {
call(app,pci, ON_REQUEST_END, new Object[]{targetPage});
}
}
else {
apps.put(pc.getApplicationContext().getName(), null);
pc.doInclude(requestedPage);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onApplicationStart(railo.runtime.PageContext)
*/
public boolean onApplicationStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_APPLICATION_START)) {
Object rtn = call(app,pc, ON_APPLICATION_START, ArrayUtil.OBJECT_EMPTY);
return Caster.toBooleanValue(rtn,true);
}
return true;
}
public void onApplicationEnd(CFMLFactory factory, String applicationName) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_APPLICATION_END)) return;
PageContextImpl pc=(PageContextImpl) ThreadLocalPageContext.get();
boolean createPc=pc==null;
try {
if(createPc)pc = createPageContext(factory,app,applicationName,null,ON_APPLICATION_END);
call(app,pc, ON_APPLICATION_END, new Object[]{pc.applicationScope()});
}
finally {
if(createPc && pc!=null){
factory.releasePageContext(pc);
}
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionStart(railo.runtime.PageContext)
*/
public void onSessionStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(hasOnSessionStart(pc,app)) {
call(app,pc, ON_SESSION_START, ArrayUtil.OBJECT_EMPTY);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionEnd(railo.runtime.CFMLFactory, java.lang.String, java.lang.String)
*/
public void onSessionEnd(CFMLFactory factory, String applicationName, String cfid) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_SESSION_END)) return;
PageContextImpl pc=null;
try {
pc = createPageContext(factory,app,applicationName,cfid,ON_SESSION_END);
call(app,pc, ON_SESSION_END, new Object[]{pc.sessionScope(false),pc.applicationScope()});
}
finally {
if(pc!=null){
factory.releasePageContext(pc);
}
}
}
private PageContextImpl createPageContext(CFMLFactory factory, ComponentAccess app, String applicationName, String cfid,Collection.Key methodName) throws PageException {
Resource root = factory.getConfig().getRootDirectory();
String path = app.getPageSource().getFullRealpath();
// Request
HttpServletRequestDummy req = new HttpServletRequestDummy(root,"localhost",path,"",null,null,null,null,null);
if(!StringUtil.isEmpty(cfid))req.setCookies(new Cookie[]{new Cookie("cfid",cfid),new Cookie("cftoken","0")});
// Response
OutputStream os=DevNullOutputStream.DEV_NULL_OUTPUT_STREAM;
try {
Resource out = factory.getConfig().getConfigDir().getRealResource("output/"+methodName.getString()+".out");
out.getParentResource().mkdirs();
os = out.getOutputStream(false);
}
catch (IOException e) {
e.printStackTrace();
// TODO was passiert hier
}
HttpServletResponseDummy rsp = new HttpServletResponseDummy(os);
// PageContext
PageContextImpl pc = (PageContextImpl) factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false);
// ApplicationContext
ClassicApplicationContext ap = new ClassicApplicationContext(factory.getConfig(),applicationName,false,app==null?null:ResourceUtil.getResource(pc,app.getPageSource(),null));
initApplicationContext(pc, app);
ap.setName(applicationName);
ap.setSetSessionManagement(true);
//if(!ap.hasName())ap.setName("Controler")
// Base
pc.setBase(app.getPageSource());
return pc;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onDebug(railo.runtime.PageContext)
*/
public void onDebug(PageContext pc) throws PageException {
if(((PageContextImpl)pc).isGatewayContext()) return;
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_DEBUG)) {
call(app,pc, ON_DEBUG, new Object[]{pc.getDebugger().getDebuggingData(pc)});
return;
}
try {
pc.getDebugger().writeOut(pc);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onError(railo.runtime.PageContext, railo.runtime.exp.PageException)
*/
public void onError(PageContext pc, PageException pe) {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.containsKey(ON_ERROR) && !Abort.isSilentAbort(pe)) {
try {
String eventName="";
if(pe instanceof ModernAppListenerException) eventName= ((ModernAppListenerException)pe).getEventName();
if(eventName==null)eventName="";
call(app,pc, ON_ERROR, new Object[]{pe.getCatchBlock(pc),eventName});
return;
}
catch(PageException _pe) {
pe=_pe;
}
}
pc.handlePageException(pe);
}
private Object call(Component app, PageContext pc, Collection.Key eventName, Object[] args) throws ModernAppListenerException {
try {
return app.call(pc, eventName, args);
}
catch (PageException pe) {
if(Abort.isSilentAbort(pe)) return Boolean.FALSE;
throw new ModernAppListenerException(pe,eventName.getString());
}
}
private void initApplicationContext(PageContextImpl pc, ComponentAccess app) throws PageException {
// use existing app context
RefBoolean throwsErrorWhileInit=new RefBooleanImpl(false);
ModernApplicationContext appContext = new ModernApplicationContext(pc,app,throwsErrorWhileInit);
pc.setApplicationContext(appContext);
if(appContext.isORMEnabled()) {
boolean hasError=throwsErrorWhileInit.toBooleanValue();
if(hasError)pc.addPageSource(app.getPageSource(), true);
try{
ORMUtil.resetEngine(pc,false);
}
finally {
if(hasError)pc.removeLastPageSource(true);
}
}
}
private static Object get(ComponentAccess app, Key name,String defaultValue) {
Member mem = app.getMember(Component.ACCESS_PRIVATE, name, true, false);
if(mem==null) return defaultValue;
return mem.getValue();
}
/**
*
* @see railo.runtime.listener.ApplicationListener#setMode(int)
*/
public void setMode(int mode) {
this.mode=mode;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#getMode()
*/
public int getMode() {
return mode;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @see railo.runtime.listener.AppListenerSupport#hasOnSessionStart(railo.runtime.PageContext)
*/
public boolean hasOnSessionStart(PageContext pc) {
return hasOnSessionStart(pc,(ComponentAccess) apps.get(pc.getApplicationContext().getName()));
}
private boolean hasOnSessionStart(PageContext pc,ComponentAccess app) {
return app!=null && app.contains(pc,ON_SESSION_START);
}
}
|
solved ticket https://issues.jboss.org/browse/RAILO-1867
|
railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java
|
solved ticket https://issues.jboss.org/browse/RAILO-1867
|
|
Java
|
apache-2.0
|
b32f28ed31b17d33553337639ab366f809b0d9dd
| 0
|
metaborg/spoofax,metaborg/spoofax,metaborg/spoofax,metaborg/spoofax
|
package org.metaborg.spoofax.core.analysis.constraint;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.analysis.AnalysisException;
import org.metaborg.core.context.IContext;
import org.metaborg.core.language.FacetContribution;
import org.metaborg.core.language.ILanguageCache;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.messages.MessageFactory;
import org.metaborg.core.messages.MessageSeverity;
import org.metaborg.core.resource.IResourceService;
import org.metaborg.core.source.ISourceRegion;
import org.metaborg.meta.nabl2.constraints.messages.IMessageInfo;
import org.metaborg.meta.nabl2.solver.messages.IMessages;
import org.metaborg.meta.nabl2.solver.solvers.CallExternal;
import org.metaborg.meta.nabl2.spoofax.TermSimplifier;
import org.metaborg.meta.nabl2.stratego.ConstraintTerms;
import org.metaborg.meta.nabl2.stratego.StrategoTerms;
import org.metaborg.meta.nabl2.stratego.TermOrigin;
import org.metaborg.meta.nabl2.terms.ITerm;
import org.metaborg.meta.nabl2.terms.unification.IUnifier;
import org.metaborg.meta.nabl2.terms.unification.PersistentUnifier;
import org.metaborg.meta.nabl2.util.collections.IRelation3;
import org.metaborg.spoofax.core.analysis.AnalysisCommon;
import org.metaborg.spoofax.core.analysis.AnalysisFacet;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResult;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer;
import org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResult;
import org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.context.scopegraph.ISpoofaxScopeGraphContext;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService;
import org.metaborg.spoofax.core.syntax.JSGLRSourceRegionFactory;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.util.iterators.Iterables2;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.metaborg.util.resource.ResourceUtils;
import org.metaborg.util.task.ICancel;
import org.metaborg.util.task.IProgress;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.ParseError;
import org.strategoxt.HybridInterpreter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import meta.flowspec.java.solver.ParseException;
import meta.flowspec.java.solver.TFFileInfo;
abstract class AbstractConstraintAnalyzer<C extends ISpoofaxScopeGraphContext<?>>
implements ISpoofaxAnalyzer, ILanguageCache {
private static final ILogger logger = LoggerUtils.logger(AbstractConstraintAnalyzer.class);
private static final String PP_STRATEGY = "pp-NaBL2-objlangterm";
private static final String TRANSFER_FUNCTIONS_FILE = "target/metaborg/transfer-functions.aterm";
protected final AnalysisCommon analysisCommon;
protected final IResourceService resourceService;
protected final IStrategoRuntimeService runtimeService;
protected final IStrategoCommon strategoCommon;
protected final ISpoofaxTracingService tracingService;
protected final ITermFactory termFactory;
protected final StrategoTerms strategoTerms;
protected final Map<ILanguageComponent, TFFileInfo> flowSpecTransferFunctionCache = new HashMap<>();
public AbstractConstraintAnalyzer(final AnalysisCommon analysisCommon, final IResourceService resourceService,
final IStrategoRuntimeService runtimeService, final IStrategoCommon strategoCommon,
final ITermFactoryService termFactoryService, final ISpoofaxTracingService tracingService) {
this.analysisCommon = analysisCommon;
this.resourceService = resourceService;
this.runtimeService = runtimeService;
this.strategoCommon = strategoCommon;
this.tracingService = tracingService;
this.termFactory = termFactoryService.getGeneric();
this.strategoTerms = new StrategoTerms(termFactory);
}
@Override public ISpoofaxAnalyzeResult analyze(ISpoofaxParseUnit input, IContext genericContext, IProgress progress,
ICancel cancel) throws AnalysisException {
if(!input.valid()) {
final String message = logger.format("Parse input for {} is invalid, cannot analyze", input.source());
throw new AnalysisException(genericContext, message);
}
final ISpoofaxAnalyzeResults results =
analyzeAll(Iterables2.singleton(input), genericContext, progress, cancel);
if(results.results().isEmpty()) {
throw new AnalysisException(genericContext, "Analysis failed.");
}
return new SpoofaxAnalyzeResult(Iterables.getOnlyElement(results.results()), results.updates(),
results.context());
}
@SuppressWarnings("unchecked") @Override public ISpoofaxAnalyzeResults
analyzeAll(Iterable<ISpoofaxParseUnit> inputs, IContext genericContext, IProgress progress, ICancel cancel)
throws AnalysisException {
C context;
try {
context = (C) genericContext;
} catch(ClassCastException ex) {
throw new AnalysisException(genericContext, "Scope graph context required for constraint analysis.", ex);
}
final ILanguageImpl langImpl = context.language();
final FacetContribution<AnalysisFacet> facetContribution = langImpl.facetContribution(AnalysisFacet.class);
if(facetContribution == null) {
logger.debug("No analysis required for {}", langImpl);
return new SpoofaxAnalyzeResults(context);
}
final AnalysisFacet facet = facetContribution.facet;
final HybridInterpreter runtime;
try {
runtime = runtimeService.runtime(facetContribution.contributor, context, false);
} catch(MetaborgException e) {
throw new AnalysisException(context, "Failed to get Stratego runtime", e);
}
Map<String, ISpoofaxParseUnit> changed = Maps.newHashMap();
Set<String> removed = Sets.newHashSet();
for(ISpoofaxParseUnit input : inputs) {
final String source;
if(input.detached()) {
source = "detached-" + UUID.randomUUID().toString();
} else {
source = resource(input.source(), context);
}
if(!input.valid() || isEmptyAST(input.ast())) {
removed.add(source);
} else {
changed.put(source, input);
}
}
return analyzeAll(changed, removed, context, runtime, facet.strategyName, progress, cancel);
}
@Override
public void invalidateCache(ILanguageComponent component) {
logger.debug("Removing cached flowspec transfer functions for {}", component);
flowSpecTransferFunctionCache.remove(component);
}
@Override
public void invalidateCache(ILanguageImpl impl) {
logger.debug("Removing cached flowspec transfer functions for {}", impl);
for (ILanguageComponent component : impl.components()) {
flowSpecTransferFunctionCache.remove(component);
}
}
protected String resource(FileObject resource, C context) {
return ResourceUtils.relativeName(resource.getName(), context.location().getName(), true);
}
protected FileObject resource(String resource, C context) {
return resourceService.resolve(context.location(), resource);
}
private boolean isEmptyAST(IStrategoTerm ast) {
return Tools.isTermTuple(ast) && ast.getSubtermCount() == 0;
}
protected Optional<TFFileInfo> getFlowSpecTransferFunctions(ILanguageComponent component) {
TFFileInfo transferFunctions = flowSpecTransferFunctionCache.get(component);
if (transferFunctions != null) {
return Optional.of(transferFunctions);
}
FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE);
try {
IStrategoTerm sTerm = termFactory.parseFromString(
IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8));
ITerm term = strategoTerms.fromStratego(sTerm);
transferFunctions = TFFileInfo.match().match(term, PersistentUnifier.Immutable.of()).orElseThrow(() -> new ParseException("Parse error on reading the transfer function file"));
} catch (ParseError | ParseException | IOException e) {
logger.error("Could not read transfer functions file for {}", component);
return Optional.empty();
}
logger.debug("Caching flowspec transfer functions for language {}", component);
flowSpecTransferFunctionCache.put(component, transferFunctions);
return Optional.of(transferFunctions);
}
protected TFFileInfo getFlowSpecTransferFunctions(ILanguageImpl impl) {
Optional<TFFileInfo> result = Optional.empty();
for (ILanguageComponent comp : impl.components()) {
Optional<TFFileInfo> tfs = getFlowSpecTransferFunctions(comp);
if (tfs.isPresent()) {
if (!result.isPresent()) {
result = tfs;
} else {
result = Optional.of(result.get().addAll(tfs.get()));
}
}
}
if (!result.isPresent()) {
logger.error("No flowspec transfer functions found for {}", impl);
return TFFileInfo.of();
}
return result.get();
}
protected abstract ISpoofaxAnalyzeResults analyzeAll(Map<String, ISpoofaxParseUnit> changed, Set<String> removed,
C context, HybridInterpreter runtime, String strategy, IProgress progress, ICancel cancel)
throws AnalysisException;
// this function does not handle specialization and explication, which is left to the analysis input and output
// matchers and builders
protected Optional<ITerm> doAction(String strategy, ITerm action, C context, HybridInterpreter runtime)
throws AnalysisException {
try {
return Optional
.ofNullable(strategoCommon.invoke(runtime,
strategoTerms.toStratego(ConstraintTerms.explicate(action)), strategy))
.map(strategoTerms::fromStratego);
} catch(MetaborgException ex) {
final String message = "Analysis failed.\n" + ex.getMessage();
throw new AnalysisException(context, message, ex);
}
}
protected Optional<ITerm> doCustomAction(String strategy, ITerm action, C context, HybridInterpreter runtime)
throws AnalysisException {
try {
return Optional
.ofNullable(strategoCommon.invoke(runtime,
strategoTerms.toStratego(ConstraintTerms.explicate(action)), strategy))
.map(strategoTerms::fromStratego);
} catch(Exception ex) {
final String message = "Custom analysis failed.\n" + ex.getMessage();
throw new AnalysisException(context, message, ex);
}
}
protected CallExternal callExternal(HybridInterpreter runtime) {
return (name, args) -> {
final IStrategoTerm[] sargs = Iterables2.stream(args).map(strategoTerms::toStratego)
.collect(Collectors.toList()).toArray(new IStrategoTerm[0]);
final IStrategoTerm sarg = sargs.length == 1 ? sargs[0] : termFactory.makeTuple(sargs);
try {
final IStrategoTerm sresult = strategoCommon.invoke(runtime, sarg, name);
return Optional.ofNullable(sresult).map(strategoTerms::fromStratego).map(ConstraintTerms::specialize);
} catch(Exception ex) {
logger.warn("External call to '{}' failed.", name);
return Optional.empty();
}
};
}
protected void messagesByFile(Iterable<IMessage> messages,
IRelation3.Transient<String, MessageSeverity, IMessage> fmessages, C context) {
for(IMessage message : messages) {
fmessages.put(resource(message.source(), context), message.severity(), message);
}
}
protected void countMessages(IMessages messages, AtomicInteger numErrors, AtomicInteger numWarnings,
AtomicInteger numNotes) {
numErrors.addAndGet(messages.getErrors().size());
numWarnings.addAndGet(messages.getWarnings().size());
numNotes.addAndGet(messages.getNotes().size());
}
protected Set<IMessage> messages(Iterable<IMessageInfo> messages, IUnifier unifier, C context,
FileObject defaultLocation) {
return Iterables2.stream(messages).map(m -> message(m, unifier, context, defaultLocation))
.collect(Collectors.toSet());
}
private IMessage message(IMessageInfo message, IUnifier unifier, C context, FileObject defaultLocation) {
final MessageSeverity severity;
switch(message.getKind()) {
default:
case ERROR:
severity = MessageSeverity.ERROR;
break;
case WARNING:
severity = MessageSeverity.WARNING;
break;
case NOTE:
severity = MessageSeverity.NOTE;
break;
}
return message(message.getOriginTerm(), message, severity, unifier, context, defaultLocation);
}
private IMessage message(ITerm originatingTerm, IMessageInfo messageInfo, MessageSeverity severity,
IUnifier unifier, C context, FileObject defaultLocation) {
Optional<TermOrigin> maybeOrigin = TermOrigin.get(originatingTerm);
if(maybeOrigin.isPresent()) {
TermOrigin origin = maybeOrigin.get();
ISourceRegion region = JSGLRSourceRegionFactory.fromTokens(origin.getLeftToken(), origin.getRightToken());
FileObject resource = resourceService.resolve(context.location(), origin.getResource());
String message = messageInfo.getContent().apply(unifier::findRecursive)
.toString(prettyprint(context, resource(resource, context)));
return MessageFactory.newAnalysisMessage(resource, region, message, severity, null);
} else {
String message =
messageInfo.getContent().apply(unifier::findRecursive).toString(prettyprint(context, null));
return MessageFactory.newAnalysisMessageAtTop(defaultLocation, message, severity, null);
}
}
protected Function<ITerm, String> prettyprint(C context, @Nullable String resource) {
return term -> {
final ITerm simpleTerm = ConstraintTerms.explicate(TermSimplifier.focus(resource, term));
final IStrategoTerm sterm = strategoTerms.toStratego(simpleTerm);
String text;
try {
text = Optional.ofNullable(strategoCommon.invoke(context.language(), context, sterm, PP_STRATEGY))
.map(Tools::asJavaString).orElseGet(() -> simpleTerm.toString());
} catch(MetaborgException ex) {
logger.warn("Pretty-printing failed on {}, using simple term representation.", ex, simpleTerm);
text = simpleTerm.toString();
}
return text;
};
}
}
|
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/analysis/constraint/AbstractConstraintAnalyzer.java
|
package org.metaborg.spoofax.core.analysis.constraint;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.vfs2.FileObject;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.analysis.AnalysisException;
import org.metaborg.core.context.IContext;
import org.metaborg.core.language.FacetContribution;
import org.metaborg.core.language.ILanguageCache;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.messages.MessageFactory;
import org.metaborg.core.messages.MessageSeverity;
import org.metaborg.core.resource.IResourceService;
import org.metaborg.core.source.ISourceRegion;
import org.metaborg.meta.nabl2.constraints.messages.IMessageInfo;
import org.metaborg.meta.nabl2.solver.messages.IMessages;
import org.metaborg.meta.nabl2.solver.solvers.CallExternal;
import org.metaborg.meta.nabl2.spoofax.TermSimplifier;
import org.metaborg.meta.nabl2.stratego.ConstraintTerms;
import org.metaborg.meta.nabl2.stratego.StrategoTerms;
import org.metaborg.meta.nabl2.stratego.TermOrigin;
import org.metaborg.meta.nabl2.terms.ITerm;
import org.metaborg.meta.nabl2.terms.unification.IUnifier;
import org.metaborg.meta.nabl2.util.collections.IRelation3;
import org.metaborg.spoofax.core.analysis.AnalysisCommon;
import org.metaborg.spoofax.core.analysis.AnalysisFacet;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResult;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer;
import org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResult;
import org.metaborg.spoofax.core.analysis.SpoofaxAnalyzeResults;
import org.metaborg.spoofax.core.context.scopegraph.ISpoofaxScopeGraphContext;
import org.metaborg.spoofax.core.stratego.IStrategoCommon;
import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService;
import org.metaborg.spoofax.core.syntax.JSGLRSourceRegionFactory;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.spoofax.core.tracing.ISpoofaxTracingService;
import org.metaborg.spoofax.core.unit.ISpoofaxParseUnit;
import org.metaborg.util.iterators.Iterables2;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.metaborg.util.resource.ResourceUtils;
import org.metaborg.util.task.ICancel;
import org.metaborg.util.task.IProgress;
import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.ParseError;
import org.strategoxt.HybridInterpreter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import meta.flowspec.java.solver.ParseException;
import meta.flowspec.java.solver.TFFileInfo;
abstract class AbstractConstraintAnalyzer<C extends ISpoofaxScopeGraphContext<?>>
implements ISpoofaxAnalyzer, ILanguageCache {
private static final ILogger logger = LoggerUtils.logger(AbstractConstraintAnalyzer.class);
private static final String PP_STRATEGY = "pp-NaBL2-objlangterm";
private static final String TRANSFER_FUNCTIONS_FILE = "target/metaborg/transfer-functions.aterm";
protected final AnalysisCommon analysisCommon;
protected final IResourceService resourceService;
protected final IStrategoRuntimeService runtimeService;
protected final IStrategoCommon strategoCommon;
protected final ISpoofaxTracingService tracingService;
protected final ITermFactory termFactory;
protected final StrategoTerms strategoTerms;
protected final Map<ILanguageComponent, TFFileInfo> flowSpecTransferFunctionCache = new HashMap<>();
public AbstractConstraintAnalyzer(final AnalysisCommon analysisCommon, final IResourceService resourceService,
final IStrategoRuntimeService runtimeService, final IStrategoCommon strategoCommon,
final ITermFactoryService termFactoryService, final ISpoofaxTracingService tracingService) {
this.analysisCommon = analysisCommon;
this.resourceService = resourceService;
this.runtimeService = runtimeService;
this.strategoCommon = strategoCommon;
this.tracingService = tracingService;
this.termFactory = termFactoryService.getGeneric();
this.strategoTerms = new StrategoTerms(termFactory);
}
@Override public ISpoofaxAnalyzeResult analyze(ISpoofaxParseUnit input, IContext genericContext, IProgress progress,
ICancel cancel) throws AnalysisException {
if(!input.valid()) {
final String message = logger.format("Parse input for {} is invalid, cannot analyze", input.source());
throw new AnalysisException(genericContext, message);
}
final ISpoofaxAnalyzeResults results =
analyzeAll(Iterables2.singleton(input), genericContext, progress, cancel);
if(results.results().isEmpty()) {
throw new AnalysisException(genericContext, "Analysis failed.");
}
return new SpoofaxAnalyzeResult(Iterables.getOnlyElement(results.results()), results.updates(),
results.context());
}
@SuppressWarnings("unchecked") @Override public ISpoofaxAnalyzeResults
analyzeAll(Iterable<ISpoofaxParseUnit> inputs, IContext genericContext, IProgress progress, ICancel cancel)
throws AnalysisException {
C context;
try {
context = (C) genericContext;
} catch(ClassCastException ex) {
throw new AnalysisException(genericContext, "Scope graph context required for constraint analysis.", ex);
}
final ILanguageImpl langImpl = context.language();
final FacetContribution<AnalysisFacet> facetContribution = langImpl.facetContribution(AnalysisFacet.class);
if(facetContribution == null) {
logger.debug("No analysis required for {}", langImpl);
return new SpoofaxAnalyzeResults(context);
}
final AnalysisFacet facet = facetContribution.facet;
final HybridInterpreter runtime;
try {
runtime = runtimeService.runtime(facetContribution.contributor, context, false);
} catch(MetaborgException e) {
throw new AnalysisException(context, "Failed to get Stratego runtime", e);
}
Map<String, ISpoofaxParseUnit> changed = Maps.newHashMap();
Set<String> removed = Sets.newHashSet();
for(ISpoofaxParseUnit input : inputs) {
final String source;
if(input.detached()) {
source = "detached-" + UUID.randomUUID().toString();
} else {
source = resource(input.source(), context);
}
if(!input.valid() || isEmptyAST(input.ast())) {
removed.add(source);
} else {
changed.put(source, input);
}
}
return analyzeAll(changed, removed, context, runtime, facet.strategyName, progress, cancel);
}
@Override
public void invalidateCache(ILanguageComponent component) {
logger.debug("Removing cached flowspec transfer functions for {}", component);
flowSpecTransferFunctionCache.remove(component);
}
@Override
public void invalidateCache(ILanguageImpl impl) {
logger.debug("Removing cached flowspec transfer functions for {}", impl);
for (ILanguageComponent component : impl.components()) {
flowSpecTransferFunctionCache.remove(component);
}
}
protected String resource(FileObject resource, C context) {
return ResourceUtils.relativeName(resource.getName(), context.location().getName(), true);
}
protected FileObject resource(String resource, C context) {
return resourceService.resolve(context.location(), resource);
}
private boolean isEmptyAST(IStrategoTerm ast) {
return Tools.isTermTuple(ast) && ast.getSubtermCount() == 0;
}
protected Optional<TFFileInfo> getFlowSpecTransferFunctions(ILanguageComponent component) {
TFFileInfo transferFunctions = flowSpecTransferFunctionCache.get(component);
if (transferFunctions != null) {
return Optional.of(transferFunctions);
}
FileObject tfs = resourceService.resolve(component.location(), TRANSFER_FUNCTIONS_FILE);
try {
IStrategoTerm sTerm = termFactory.parseFromString(
IOUtils.toString(tfs.getContent().getInputStream(), StandardCharsets.UTF_8));
ITerm term = strategoTerms.fromStratego(sTerm);
transferFunctions = TFFileInfo.match().match(term).orElseThrow(() -> new ParseException("Parse error on reading the transfer function file"));
} catch (ParseError | ParseException | IOException e) {
logger.error("Could not read transfer functions file for {}", component);
return Optional.empty();
}
logger.debug("Caching flowspec transfer functions for language {}", component);
flowSpecTransferFunctionCache.put(component, transferFunctions);
return Optional.of(transferFunctions);
}
protected TFFileInfo getFlowSpecTransferFunctions(ILanguageImpl impl) {
Optional<TFFileInfo> result = Optional.empty();
for (ILanguageComponent comp : impl.components()) {
Optional<TFFileInfo> tfs = getFlowSpecTransferFunctions(comp);
if (tfs.isPresent()) {
if (!result.isPresent()) {
result = tfs;
} else {
result = Optional.of(result.get().addAll(tfs.get()));
}
}
}
if (!result.isPresent()) {
logger.error("No flowspec transfer functions found for {}", impl);
return TFFileInfo.of();
}
return result.get();
}
protected abstract ISpoofaxAnalyzeResults analyzeAll(Map<String, ISpoofaxParseUnit> changed, Set<String> removed,
C context, HybridInterpreter runtime, String strategy, IProgress progress, ICancel cancel)
throws AnalysisException;
// this function does not handle specialization and explication, which is left to the analysis input and output
// matchers and builders
protected Optional<ITerm> doAction(String strategy, ITerm action, C context, HybridInterpreter runtime)
throws AnalysisException {
try {
return Optional
.ofNullable(strategoCommon.invoke(runtime,
strategoTerms.toStratego(ConstraintTerms.explicate(action)), strategy))
.map(strategoTerms::fromStratego);
} catch(MetaborgException ex) {
final String message = "Analysis failed.\n" + ex.getMessage();
throw new AnalysisException(context, message, ex);
}
}
protected Optional<ITerm> doCustomAction(String strategy, ITerm action, C context, HybridInterpreter runtime)
throws AnalysisException {
try {
return Optional
.ofNullable(strategoCommon.invoke(runtime,
strategoTerms.toStratego(ConstraintTerms.explicate(action)), strategy))
.map(strategoTerms::fromStratego);
} catch(Exception ex) {
final String message = "Custom analysis failed.\n" + ex.getMessage();
throw new AnalysisException(context, message, ex);
}
}
protected CallExternal callExternal(HybridInterpreter runtime) {
return (name, args) -> {
final IStrategoTerm[] sargs = Iterables2.stream(args).map(strategoTerms::toStratego)
.collect(Collectors.toList()).toArray(new IStrategoTerm[0]);
final IStrategoTerm sarg = sargs.length == 1 ? sargs[0] : termFactory.makeTuple(sargs);
try {
final IStrategoTerm sresult = strategoCommon.invoke(runtime, sarg, name);
return Optional.ofNullable(sresult).map(strategoTerms::fromStratego).map(ConstraintTerms::specialize);
} catch(Exception ex) {
logger.warn("External call to '{}' failed.", name);
return Optional.empty();
}
};
}
protected void messagesByFile(Iterable<IMessage> messages,
IRelation3.Transient<String, MessageSeverity, IMessage> fmessages, C context) {
for(IMessage message : messages) {
fmessages.put(resource(message.source(), context), message.severity(), message);
}
}
protected void countMessages(IMessages messages, AtomicInteger numErrors, AtomicInteger numWarnings,
AtomicInteger numNotes) {
numErrors.addAndGet(messages.getErrors().size());
numWarnings.addAndGet(messages.getWarnings().size());
numNotes.addAndGet(messages.getNotes().size());
}
protected Set<IMessage> messages(Iterable<IMessageInfo> messages, IUnifier unifier, C context,
FileObject defaultLocation) {
return Iterables2.stream(messages).map(m -> message(m, unifier, context, defaultLocation))
.collect(Collectors.toSet());
}
private IMessage message(IMessageInfo message, IUnifier unifier, C context, FileObject defaultLocation) {
final MessageSeverity severity;
switch(message.getKind()) {
default:
case ERROR:
severity = MessageSeverity.ERROR;
break;
case WARNING:
severity = MessageSeverity.WARNING;
break;
case NOTE:
severity = MessageSeverity.NOTE;
break;
}
return message(message.getOriginTerm(), message, severity, unifier, context, defaultLocation);
}
private IMessage message(ITerm originatingTerm, IMessageInfo messageInfo, MessageSeverity severity,
IUnifier unifier, C context, FileObject defaultLocation) {
Optional<TermOrigin> maybeOrigin = TermOrigin.get(originatingTerm);
if(maybeOrigin.isPresent()) {
TermOrigin origin = maybeOrigin.get();
ISourceRegion region = JSGLRSourceRegionFactory.fromTokens(origin.getLeftToken(), origin.getRightToken());
FileObject resource = resourceService.resolve(context.location(), origin.getResource());
String message = messageInfo.getContent().apply(unifier::findRecursive)
.toString(prettyprint(context, resource(resource, context)));
return MessageFactory.newAnalysisMessage(resource, region, message, severity, null);
} else {
String message =
messageInfo.getContent().apply(unifier::findRecursive).toString(prettyprint(context, null));
return MessageFactory.newAnalysisMessageAtTop(defaultLocation, message, severity, null);
}
}
protected Function<ITerm, String> prettyprint(C context, @Nullable String resource) {
return term -> {
final ITerm simpleTerm = ConstraintTerms.explicate(TermSimplifier.focus(resource, term));
final IStrategoTerm sterm = strategoTerms.toStratego(simpleTerm);
String text;
try {
text = Optional.ofNullable(strategoCommon.invoke(context.language(), context, sterm, PP_STRATEGY))
.map(Tools::asJavaString).orElseGet(() -> simpleTerm.toString());
} catch(MetaborgException ex) {
logger.warn("Pretty-printing failed on {}, using simple term representation.", ex, simpleTerm);
text = simpleTerm.toString();
}
return text;
};
}
}
|
Get rid of deprecated match construct
|
org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/analysis/constraint/AbstractConstraintAnalyzer.java
|
Get rid of deprecated match construct
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.