answer
stringlengths 17
10.2M
|
|---|
package org.opencb.hpg_pore;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.HashMap;
import org.jfree.chart.JFreeChart;
import org.opencb.hpg_pore.commandline.SignalCommandLine;
import com.beust.jcommander.JCommander;
public class SignalCmd {
public static String outDir;
// S Q U I G G L E C O M M A N D //
public static void run(String[] args) throws Exception {
SignalCommandLine cmdLine = new SignalCommandLine();
JCommander cmd = new JCommander(cmdLine);
cmd.setProgramName(Main.BINARY_NAME + " signal");
try {
cmd.parse(args);
} catch (Exception e) {
cmd.usage();
System.exit(-1);
}
if (cmdLine.isHadoop()) {
runHadoopSignalCmd(cmdLine.getIn(), cmdLine.getFast5name(), cmdLine.getOut(), cmdLine.getMin(), cmdLine.getMax());
} else {
runLocalSignalCmd(cmdLine.getIn(), cmdLine.getOut(), cmdLine.getMin(), cmdLine.getMax());
}
}
// local squiggle command //
private static void runLocalSignalCmd(String in, String out, int min, int max) throws IOException {
File inFile = new File(in);
if (!inFile.exists()) {
System.out.println("Error: Local directory " + in + " does not exist!");
System.exit(-1);
}
NativePoreSupport.loadLibrary();
int width = 1024;
int height = 480;
NumberFormat nf = NumberFormat.getInstance();
String events = null;
events = new NativePoreSupport().getEvents(Utils.read(inFile), "template", min, max);
//System.out.println(events);
if(events != null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[] lineas = events.split("\n");
//read the first and get the start time
//linea = lineas[1].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
//double starttime = Double.parseDouble(linea[0]);
for (int i = 1 ; i< lineas.length; i++){
//for (int i = 1 ; i< 200; i++){
//System.out.println("linea numero " + i);
linea = lineas[i].split("\t");
//System.out.println("linea[1]: " + linea[1] + " linea[0]: " + linea[0]);
//if((Double.parseDouble(linea[0])- starttime) < max )
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for template", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/template_signal.jpg");
}else{
System.out.println("There is no template event type");
}
events = null;
events = new NativePoreSupport().getEvents(Utils.read(inFile), "complement", min, max);
if(events!= null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[]lineas = events.split("\n");
for (int i = 1 ; i< lineas.length; i++){
//for (int i = 1 ; i< 200; i++){
linea = lineas[i].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for Complement", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/complement_signal.jpg");
}else{
System.out.println("There is no complement event type");
}
events = null;
events = new NativePoreSupport().getEvents(Utils.read(inFile), "2D", min, max);
if(events !=null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[] lineas = events.split("\n");
for (int i = 1 ; i< lineas.length; i++){
//for (int i = 1 ; i< 200; i++){
linea = lineas[i].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for 2D", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/2D_signal.jpg");
}else{
System.out.println("There is no 2D event type");
}
}
// hadoop squiggle command //
private static void runHadoopSignalCmd(String in, String nameFile, String out, int min, int max) throws Exception {
NativePoreSupport.loadLibrary();
int width = 1024;
int height = 480;
NumberFormat nf = NumberFormat.getInstance();
String events = null;
events = new NativePoreSupport().getEvents(Utils.readHadoop(in, nameFile), "template", min, max);
if(events != null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[] lineas = events.split("\n");
for (int i = 1 ; i< lineas.length; i++){
linea = lineas[i].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for template", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/template_signal.jpg");
}else{
System.out.println("There is no template event type");
}
events = null;
events = new NativePoreSupport().getEvents(Utils.readHadoop(in, nameFile), "complement", min, max);
if(events!= null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[]lineas = events.split("\n");
for (int i = 1 ; i< lineas.length; i++){
linea = lineas[i].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for Complement", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/complement_signal.jpg");
}else{
System.out.println("There is no complement event type");
}
events = null;
events = new NativePoreSupport().getEvents(Utils.readHadoop(in, nameFile), "2D", min, max);
if(events !=null){
HashMap<Double, Double> map = new HashMap<Double, Double>();
String[] linea;
String[] lineas = events.split("\n");
for (int i = 1 ; i< lineas.length; i++){
linea = lineas[i].split("\t");
//map.put(Double.parseDouble(linea[1]),Double.parseDouble(linea[0]));
try {
map.put(nf.parse(linea[1]).doubleValue(), nf.parse(linea[0]).doubleValue());
} catch (Exception e) {
}
}
JFreeChart chart = Utils.plotSignalChart(map, "Signal for 2D", "measured signal", "time");
Utils.saveChart(chart, width, height, out + "/2D_signal.jpg");
}else{
System.out.println("There is no 2D event type");
}
}
}
|
package taskDo;
import org.joda.time.DateTime;
/*
* @author Paing Zin Oo(Jack)
*/
public class Task implements Comparable<Task>{
private final int INCREMENT = 1;
private static int lastTaskId = 0;
private int id;
private String category;
private String title;
private String note;
private boolean important;
private DateTime dueDate;
private DateTime startDate;
private boolean completed;
private TaskType type;
public Task( String category, String description,
boolean important, DateTime dueDate, DateTime startDate,
boolean completed) {
super();
lastTaskId++;
this.id = lastTaskId+INCREMENT;
this.category = category;
this.title = description;
this.important = important;
this.dueDate = dueDate;
this.startDate = startDate;
this.completed = completed;
}
public Task(){
lastTaskId++;
this.id = lastTaskId+INCREMENT;
this.title = "";
this.type = TaskType.TODO;
this.category = "Others";
this.note = "";
}
public Task(String description){
this.title = description;
}
public static int getLastTaskId(){
return lastTaskId;
}
//for testing only
public Task (DateTime dueDate){
this.id=lastTaskId+1;
lastTaskId++;
this.dueDate = dueDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isImportant() {
return important;
}
public void setImportant(boolean important) {
this.important = important;
}
public DateTime getDueDate() {
return dueDate;
}
public void setDueDate(DateTime dueDate) {
this.dueDate = dueDate;
}
public DateTime getStartDate() {
return startDate;
}
public void setStartDate(DateTime startDate) {
this.startDate = startDate;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public TaskType getTaskType() {
return this.type;
}
public void setTaskType(TaskType taskType) {
this.type = taskType;
}
public String getNote() {
return this.note;
}
public void setNote(String taskNote) {
this.note = taskNote;
}
public String toString() {
return "ID" + this.id + "[Catogory: "+ this.getCategory()+ " Task:"
+this.getTitle();
}
@Override
public int compareTo(Task task) {
if (getDueDate() == null || task.getDueDate() == null){
return -1;
}
return getDueDate().compareTo(task.getDueDate());
}
}
|
package org.scijava.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptException;
import org.scijava.Context;
import org.scijava.Contextual;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.NullContextException;
import org.scijava.command.Command;
import org.scijava.log.LogService;
import org.scijava.module.AbstractModuleInfo;
import org.scijava.module.DefaultMutableModuleItem;
import org.scijava.module.ModuleException;
import org.scijava.plugin.Parameter;
import org.scijava.util.ConversionUtils;
/**
* Metadata about a script.
* <p>
* This class is responsible for parsing the script for parameters. See
* {@link #parseParameters()} for details.
* </p>
*
* @author Curtis Rueden
* @author Johannes Schindelin
*/
public class ScriptInfo extends AbstractModuleInfo implements Contextual {
private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-)
private final String path;
private final BufferedReader reader;
@Parameter
private Context context;
@Parameter
private LogService log;
@Parameter
private ScriptService scriptService;
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param file The script file.
*/
public ScriptInfo(final Context context, final File file) {
this(context, file.getPath());
}
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param path Path to the script file.
*/
public ScriptInfo(final Context context, final String path) {
this(context, path, null);
}
/**
* Creates a script metadata object which describes a script provided by the
* given {@link Reader}.
*
* @param context The ImageJ application context to use when populating
* service inputs.
* @param path Pseudo-path to the script file. This file does not actually
* need to exist, but rather provides a name for the script with file
* extension.
* @param reader Reader which provides the script itself (i.e., its contents).
*/
public ScriptInfo(final Context context, final String path,
final Reader reader)
{
setContext(context);
this.path = path;
this.reader =
reader == null ? null : new BufferedReader(reader, PARAM_CHAR_MAX);
}
// -- ScriptInfo methods --
/**
* Gets the path to the script on disk.
* <p>
* If the path doesn't actually exist on disk, then this is a pseudo-path
* merely for the purpose of naming the script with a file extension, and the
* actual script content is delivered by the {@link BufferedReader} given by
* {@link #getReader()}.
* </p>
*/
public String getPath() {
return path;
}
/**
* Gets the reader which delivers the script's content.
* <p>
* This might be null, in which case the content is stored in a file on disk
* given by {@link #getPath()}.
* </p>
*/
public BufferedReader getReader() {
return reader;
}
/**
* Parses the script's input and output parameters from the script header.
* <p>
* This method is called automatically the first time any parameter accessor
* method is called ({@link #getInput}, {@link #getOutput}, {@link #inputs()},
* {@link #outputs()}, etc.). Subsequent calls will reparse the parameters.
* <p>
* ImageJ's scripting framework supports specifying @{@link Parameter}-style
* inputs and outputs in a preamble. The format is a simplified version of the
* Java @{@link Parameter} annotation syntax. The following syntaxes are
* supported:
* </p>
* <ul>
* <li>{@code // @<type> <varName>}</li>
* <li>{@code // @<type>(<attr1>=<value1>, ..., <attrN>=<valueN>) <varName>}</li>
* <li>{@code // @<IOType> <type> <varName>}</li>
* <li>
* {@code // @<IOType>(<attr1>=<value1>, ..., <attrN>=<valueN>) <type> <varName>}
* </li>
* </ul>
* <p>
* Where:
* </p>
* <ul>
* <li>{@code //} = the comment style of the scripting language, so that the
* parameter line is ignored by the script engine itself.</li>
* <li>{@code <IOType>} = one of {@code INPUT}, {@code OUTPUT}, or
* {@code BOTH}.</li>
* <li>{@code <varName>} = the name of the input or output variable.</li>
* <li>{@code <type>} = the Java {@link Class} of the variable.</li>
* <li>{@code <attr*>} = an attribute key.</li>
* <li>{@code <value*>} = an attribute value.</li>
* </ul>
* <p>
* See the @{@link Parameter} annotation for a list of valid attributes.
* </p>
* <p>
* Here are a few examples:
* </p>
* <ul>
* <li>{@code // @Dataset dataset}</li>
* <li>{@code // @double(type=OUTPUT) result}</li>
* <li>{@code // @BOTH ImageDisplay display}</li>
* <li>{@code // @INPUT(persist=false, visibility=INVISIBLE) boolean verbose}</li>
* parameters will be parsed and filled just like @{@link Parameter}
* -annotated fields in {@link Command}s.
* </ul>
*/
// NB: Widened visibility from AbstractModuleInfo.
@Override
public void parseParameters() {
clearParameters();
try {
final BufferedReader in;
if (reader == null) {
in = new BufferedReader(new FileReader(getPath()));
}
else {
in = reader;
in.mark(PARAM_CHAR_MAX);
}
while (true) {
final String line = in.readLine();
if (line == null) break;
// scan for lines containing an '@' stopping at the first line
// containing at least one alphameric character but no '@'.
final int at = line.indexOf('@');
if (at >= 0) parseParam(line.substring(at + 1));
else if (line.matches(".*\\w.*")) break;
}
if (reader == null) in.close();
else in.reset();
addReturnValue();
}
catch (final IOException exc) {
log.error("Error reading script: " + path, exc);
}
catch (final ScriptException exc) {
log.error("Invalid parameter syntax for script: " + path, exc);
}
}
// -- ModuleInfo methods --
@Override
public String getDelegateClassName() {
return ScriptModule.class.getName();
}
@Override
public Class<?> loadDelegateClass() {
return ScriptModule.class;
}
@Override
public ScriptModule createModule() throws ModuleException {
return new ScriptModule(this);
}
// -- Contextual methods --
@Override
public Context context() {
if (context == null) throw new NullContextException();
return context;
}
@Override
public Context getContext() {
return context;
}
@Override
public void setContext(final Context context) {
context.inject(this);
}
// -- Identifiable methods --
@Override
public String getIdentifier() {
return "script:" + path;
}
// -- Helper methods --
private void parseParam(final String param) throws ScriptException {
final int lParen = param.indexOf("(");
final int rParen = param.lastIndexOf(")");
if (rParen < lParen) {
throw new ScriptException("Invalid parameter: " + param);
}
if (lParen < 0) parseParam(param, parseAttrs(""));
else {
final String cutParam =
param.substring(0, lParen) + param.substring(rParen + 1);
final String attrs = param.substring(lParen + 1, rParen);
parseParam(cutParam, parseAttrs(attrs));
}
}
private void parseParam(final String param,
final HashMap<String, String> attrs) throws ScriptException
{
final String[] tokens = param.trim().split("[ \t\n]+");
checkValid(tokens.length >= 1, param);
final String typeName, varName;
if (isIOType(tokens[0])) {
// assume syntax: <IOType> <type> <varName>
checkValid(tokens.length >= 3, param);
attrs.put("type", tokens[0]);
typeName = tokens[1];
varName = tokens[2];
}
else {
// assume syntax: <type> <varName>
checkValid(tokens.length >= 2, param);
typeName = tokens[0];
varName = tokens[1];
}
final Class<?> type = scriptService.lookupClass(typeName);
addItem(varName, type, attrs);
}
/** Parses a comma-delimited list of {@code key=value} pairs into a map. */
private HashMap<String, String> parseAttrs(final String attrs)
throws ScriptException
{
// TODO: We probably want to use a real CSV parser.
final HashMap<String, String> attrsMap = new HashMap<String, String>();
for (final String token : attrs.split(",")) {
if (token.isEmpty()) continue;
final int equals = token.indexOf("=");
if (equals < 0) throw new ScriptException("Invalid attribute: " + token);
final String key = token.substring(0, equals).trim();
String value = token.substring(equals + 1).trim();
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
attrsMap.put(key, value);
}
return attrsMap;
}
private boolean isIOType(final String token) {
return ConversionUtils.convert(token, ItemIO.class) != null;
}
private void checkValid(final boolean valid, final String param)
throws ScriptException
{
if (!valid) throw new ScriptException("Invalid parameter: " + param);
}
/** Adds an output for the value returned by the script itself. */
private void addReturnValue() throws ScriptException {
final HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("type", "OUTPUT");
addItem(ScriptModule.RETURN_VALUE, Object.class, attrs);
}
private <T> void addItem(final String name, final Class<T> type,
final Map<String, String> attrs) throws ScriptException
{
final DefaultMutableModuleItem<T> item =
new DefaultMutableModuleItem<T>(this, name, type);
for (final String key : attrs.keySet()) {
final String value = attrs.get(key);
assignAttribute(item, key, value);
}
if (item.isInput()) registerInput(item);
if (item.isOutput()) registerOutput(item);
}
private <T> void assignAttribute(final DefaultMutableModuleItem<T> item,
final String key, final String value) throws ScriptException
{
// CTR: There must be an easier way to do this.
// Just compile the thing using javac? Or parse via javascript, maybe?
if ("callback".equalsIgnoreCase(key)) {
item.setCallback(value);
}
else if ("choices".equalsIgnoreCase(key)) {
// FIXME: Regex above won't handle {a,b,c} syntax.
// item.setChoices(choices);
}
else if ("columns".equalsIgnoreCase(key)) {
item.setColumnCount(ConversionUtils.convert(value, int.class));
}
else if ("description".equalsIgnoreCase(key)) {
item.setDescription(value);
}
else if ("initializer".equalsIgnoreCase(key)) {
item.setInitializer(value);
}
else if ("type".equalsIgnoreCase(key)) {
item.setIOType(ConversionUtils.convert(value, ItemIO.class));
}
else if ("label".equalsIgnoreCase(key)) {
item.setLabel(value);
}
else if ("max".equalsIgnoreCase(key)) {
item.setMaximumValue(ConversionUtils.convert(value, item.getType()));
}
else if ("min".equalsIgnoreCase(key)) {
item.setMinimumValue(ConversionUtils.convert(value, item.getType()));
}
else if ("name".equalsIgnoreCase(key)) {
item.setName(value);
}
else if ("persist".equalsIgnoreCase(key)) {
item.setPersisted(ConversionUtils.convert(value, boolean.class));
}
else if ("persistKey".equalsIgnoreCase(key)) {
item.setPersistKey(value);
}
else if ("required".equalsIgnoreCase(key)) {
item.setRequired(ConversionUtils.convert(value, boolean.class));
}
else if ("softMax".equalsIgnoreCase(key)) {
item.setSoftMaximum(ConversionUtils.convert(value, item.getType()));
}
else if ("softMin".equalsIgnoreCase(key)) {
item.setSoftMinimum(ConversionUtils.convert(value, item.getType()));
}
else if ("stepSize".equalsIgnoreCase(key)) {
// FIXME
item.setStepSize(ConversionUtils.convert(value, Number.class));
}
else if ("visibility".equalsIgnoreCase(key)) {
item.setVisibility(ConversionUtils.convert(value, ItemVisibility.class));
}
else if ("value".equalsIgnoreCase(key)) {
item.setWidgetStyle(value);
}
else {
throw new ScriptException("Invalid attribute name: " + key);
}
}
}
|
package seedu.doit.model;
import java.util.Set;
import java.util.logging.Logger;
import javafx.collections.transformation.FilteredList;
import seedu.doit.commons.core.ComponentManager;
import seedu.doit.commons.core.LogsCenter;
import seedu.doit.commons.core.UnmodifiableObservableList;
import seedu.doit.commons.events.model.TaskManagerChangedEvent;
import seedu.doit.commons.exceptions.EmptyTaskManagerStackException;
import seedu.doit.commons.util.CollectionUtil;
import seedu.doit.commons.util.StringUtil;
import seedu.doit.model.item.ReadOnlyTask;
import seedu.doit.model.item.Task;
import seedu.doit.model.item.UniqueTaskList;
import seedu.doit.model.item.UniqueTaskList.DuplicateTaskException;
import seedu.doit.model.item.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the task manager data. All changes to any
* model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private TaskManager taskManager;
private FilteredList<ReadOnlyTask> filteredTasks;
private static TaskManagerStack taskManagerStack;
/**
* Initializes a ModelManager with the given taskManager and userPrefs.
*/
public ModelManager(ReadOnlyItemManager taskManager, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(taskManager, userPrefs);
logger.fine("Initializing with task manager: " + taskManager + " and user prefs " + userPrefs);
this.taskManager = new TaskManager(taskManager);
taskManagerStack = TaskManagerStack.getInstance();
updateFilteredTasks();
}
/**
* Updates the filteredTasks after the taskmanager have changed
*/
public void updateFilteredTasks() {
this.filteredTasks = new FilteredList<ReadOnlyTask>(this.taskManager.getTaskList());
}
public ModelManager() {
this(new TaskManager(), new UserPrefs());
}
@Override
public void resetData(ReadOnlyItemManager newData) {
this.taskManager.resetData(newData);
indicateTaskManagerChanged();
}
@Override
public ReadOnlyItemManager getTaskManager() {
return this.taskManager;
}
/**
* Raises an event to indicate the model has changed
*/
private void indicateTaskManagerChanged() {
raise(new TaskManagerChangedEvent(this.taskManager));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
logger.info("delete task in model manager");
TaskManagerStack.addToUndoStack(this.getTaskManager());
this.taskManager.removeTask(target);
updateFilteredListToShowAll();
indicateTaskManagerChanged();
}
@Override
public synchronized void addTask(Task task) throws DuplicateTaskException {
logger.info("add task in model manager");
TaskManagerStack.addToUndoStack(this.getTaskManager());
this.taskManager.addTask(task);
updateFilteredListToShowAll();
indicateTaskManagerChanged();
}
@Override
public synchronized void markTask(int taskIndex, ReadOnlyTask taskToDone)
throws UniqueTaskList.TaskNotFoundException, DuplicateTaskException {
this.taskManager.markTask(taskIndex, taskToDone);
indicateTaskManagerChanged();
}
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) throws DuplicateTaskException {
assert editedTask != null;
logger.info("update task in model manager");
TaskManagerStack.addToUndoStack(this.getTaskManager());
int taskManagerIndex = this.filteredTasks.getSourceIndex(filteredTaskListIndex);
this.taskManager.updateTask(taskManagerIndex, editedTask);
indicateTaskManagerChanged();
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(this.filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
this.filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskList(Set<String> nameKeywords, Set<String> priorityKeywords,
Set<String> descriptionKeywords) {
if (!nameKeywords.isEmpty()) {
updateFilteredTaskList(new PredicateExpression(new NameQualifier(nameKeywords)));
}
if (!priorityKeywords.isEmpty()) {
updateFilteredTaskList(new PredicateExpression(new PriorityQualifier(priorityKeywords)));
}
if (!descriptionKeywords.isEmpty()) {
updateFilteredTaskList(new PredicateExpression(new DescriptionQualifier(descriptionKeywords)));
}
}
private void updateFilteredTaskList(Expression expression) {
this.filteredTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
@Override
String toString();
}
interface Qualifier {
boolean run(ReadOnlyTask task);
@Override
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return this.qualifier.run(task);
}
@Override
public String toString() {
return this.qualifier.toString();
}
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return this.nameKeyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword)).findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", this.nameKeyWords);
}
}
@Override
public void undo() throws EmptyTaskManagerStackException {
this.taskManager.resetData(taskManagerStack.loadOlderTaskManager(this.getTaskManager()));
updateFilteredTasks();
indicateTaskManagerChanged();
}
@Override
public void redo() throws EmptyTaskManagerStackException {
this.taskManager.resetData(taskManagerStack.loadNewerTaskManager(this.getTaskManager()));
updateFilteredTasks();
indicateTaskManagerChanged();
}
private class PriorityQualifier implements Qualifier {
private Set<String> priorityKeywords;
PriorityQualifier(Set<String> priorityKeywords) {
this.priorityKeywords = priorityKeywords;
}
@Override
public boolean run(ReadOnlyTask task) {
return this.priorityKeywords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getPriority().value, keyword)).findAny()
.isPresent();
}
@Override
public String toString() {
return "priority=" + String.join(", ", this.priorityKeywords);
}
}
private class DescriptionQualifier implements Qualifier {
private Set<String> descriptionKeywords;
DescriptionQualifier(Set<String> descriptionKeywords) {
this.descriptionKeywords = descriptionKeywords;
}
@Override
public boolean run(ReadOnlyTask task) {
return this.descriptionKeywords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getDescription().value, keyword))
.findAny().isPresent();
}
@Override
public String toString() {
return "description=" + String.join(", ", this.descriptionKeywords);
}
}
}
|
package seedu.typed.model;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javafx.collections.ObservableList;
import seedu.typed.commons.core.UnmodifiableObservableList;
import seedu.typed.commons.exceptions.IllegalValueException;
import seedu.typed.model.tag.Tag;
import seedu.typed.model.tag.UniqueTagList;
import seedu.typed.model.task.ReadOnlyTask;
import seedu.typed.model.task.Task;
import seedu.typed.model.task.TaskBuilder;
import seedu.typed.model.task.UniqueTaskList;
import seedu.typed.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.typed.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Wraps all data at the task-manager level. Duplicates are not allowed (by
* .equals comparison)
*/
public class TaskManager implements ReadOnlyTaskManager {
private static final String DUPLICATE_TASK_WARNING = "Task Manager should not have duplicate tasks";
private final UniqueTaskList tasks;
private final UniqueTagList tags;
{
tasks = new UniqueTaskList();
tags = new UniqueTagList();
}
public TaskManager() {
}
public TaskManager(ReadOnlyTaskManager toBeCopied) throws IllegalValueException {
this();
resetData(toBeCopied);
}
//// list overwrite operations
public void setTasks(List<? extends ReadOnlyTask> tasks)
throws DuplicateTaskException, IllegalValueException {
this.tasks.setTasks(tasks);
}
public void setTags(Collection<Tag> tags) throws UniqueTagList.DuplicateTagException {
this.tags.setTags(tags);
}
//@@author A0143853A
public void copyData(ReadOnlyTaskManager newData) {
assert newData != null;
try {
ObservableList<ReadOnlyTask> tasksToCopy = newData.getTaskList();
Iterator<ReadOnlyTask> iterator = tasksToCopy.iterator();
while (iterator.hasNext()) {
ReadOnlyTask toCopy = iterator.next();
addTask((Task) toCopy);
}
} catch (UniqueTaskList.DuplicateTaskException e) {
;
}
try {
ObservableList<Tag> tagsToCopy = newData.getTagList();
Iterator<Tag> iterator = tagsToCopy.iterator();
while (iterator.hasNext()) {
Tag toCopy = iterator.next();
addTag(toCopy);
}
} catch (UniqueTagList.DuplicateTagException e) {
;
}
syncMasterTagListWith(tasks);
}
//@@author
public void resetData(ReadOnlyTaskManager newData) throws IllegalValueException {
assert newData != null;
try {
setTasks(newData.getTaskList());
} catch (UniqueTaskList.DuplicateTaskException e) {
assert false : DUPLICATE_TASK_WARNING;
}
try {
setTags(newData.getTagList());
} catch (UniqueTagList.DuplicateTagException e) {
assert false : DUPLICATE_TASK_WARNING;
}
syncMasterTagListWith(tasks);
}
@Override
public void printData() {
for (int i = 0; i < tasks.size(); i++) {
System.out.println("tasks: " + i + " " + tasks.getTaskAt(i).toString());
}
System.out.println("Number of Deadline Tasks : " + this.getNumberDeadlines());
System.out.println("Number of Floating Tasks : " + this.getNumberFloatingTasks());
System.out.println("Number of Event Tasks : " + this.getNumberEvents());
System.out.println("Number of Uncompleted Deadline : " + this.getNumberUncompletedDeadlines());
System.out.println("Number of Uncompleted Floating : " + this.getNumberUncompletedFloatingTasks());
System.out.println("Number of Uncompleted Event : " + this.getNumberUncompletedEvents());
}
//// task-level operations
/**
* Adds a task to the task manager. Also checks the new task's tags and
* updates {@link #tags} with any new tags found, and updates the Tag
* objects in the task to point to those in {@link #tags}.
*
* @throws UniqueTaskList.DuplicateTaskException
* if an equivalent task already exists.
*/
public void addTask(Task task) throws DuplicateTaskException {
syncMasterTagListWith(task);
tasks.add(task);
}
//@@author A0143853A
public void addTask(int index, Task task) throws DuplicateTaskException {
syncMasterTagListWith(task);
tasks.add(index, task);
}
//@@author
//@@author A0143853A
public int getIndexOf(Task task) throws TaskNotFoundException {
return tasks.indexOf(task);
}
//@@author
//@@author A0143853A
public Task getTaskAt(int index) {
return tasks.getTaskAt(index);
}
//@@author
/**
* Updates the task in the list at position {@code index} with
* {@code editedReadOnlyTask}. {@code TaskManager}'s tag list will be
* updated with the tags of {@code editedReadOnlyTask}.
*
* @see #syncMasterTagListWith(Task)
* @throws DuplicateTaskException
* if updating the task's details causes the task to be
* equivalent to another existing task in the list.
* @throws IndexOutOfBoundsException
* if {@code index} < 0 or >= the size of the list.
*/
public void updateTask(int index, ReadOnlyTask editedReadOnlyTask)
throws DuplicateTaskException, IllegalValueException {
assert editedReadOnlyTask != null;
Task editedTask = new TaskBuilder(editedReadOnlyTask).build();
tasks.updateTask(index, editedTask);
syncMasterTagListWith(editedTask);
}
/**
* Ensures that every tag in this task: - exists in the master list
* {@link #tags} - points to a Tag object in the master list
*/
private void syncMasterTagListWith(Task task) {
final UniqueTagList taskTags = task.getTags();
tags.mergeFrom(taskTags);
// Create map with values = tag object references in the master list
// used for checking task tag references
final Map<Tag, Tag> masterTagObjects = new HashMap<>();
tags.forEach(tag -> masterTagObjects.put(tag, tag));
// Rebuild the list of task tags to point to the relevant tags in the
// master
// tag list.
final Set<Tag> correctTagReferences = new HashSet<>();
taskTags.forEach(tag -> correctTagReferences.add(masterTagObjects.get(tag)));
task.setTags(new UniqueTagList(correctTagReferences));
}
/**
* Ensures that every tag in these tasks: - exists in the master list
* {@link #tags} - points to a Tag object in the master list
*
* @see #syncMasterTagListWith(Task)
*/
private void syncMasterTagListWith(UniqueTaskList tasks) {
tasks.forEach(this::syncMasterTagListWith);
}
public boolean removeTask(ReadOnlyTask key) throws TaskNotFoundException {
if (tasks.remove(key)) {
return true;
} else {
throw new TaskNotFoundException();
}
}
public void removeTaskAt(int index) {
tasks.remove(index);
}
//// tag-level operations
public void addTag(Tag tag) throws UniqueTagList.DuplicateTagException {
tags.add(tag);
}
//// util methods
@Override
public String toString() {
return tasks.asObservableList().size() + " tasks, " + tags.asObservableList().size() + " tags";
// TODO: refine later
}
@Override
public ObservableList<ReadOnlyTask> getTaskList() {
return new UnmodifiableObservableList<>(tasks.asObservableList());
}
@Override
public ObservableList<Tag> getTagList() {
return new UnmodifiableObservableList<>(tags.asObservableList());
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TaskManager // instanceof handles nulls
&& this.tasks.equals(((TaskManager) other).tasks)
&& this.tags.equalsOrderInsensitive(((TaskManager) other).tags));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing
// your
// own
return Objects.hash(tasks, tags);
}
public void completeTaskAt(int taskManagerIndex) throws DuplicateTaskException {
tasks.completeTaskAt(taskManagerIndex);
}
//@@author A0143853A
public void uncompleteTaskAt(int taskManagerIndex) throws DuplicateTaskException {
tasks.uncompleteTaskAt(taskManagerIndex);
}
//@@author
public int getNumberCompletedTasks() {
int num = 0;
int total = tasks.size();
for (int i = 0; i < total; i++) {
if (tasks.getTaskAt(i).getIsCompleted()) {
num++;
}
}
return num;
}
public int getNumberUncompletedTasks() {
return tasks.size() - getNumberCompletedTasks();
}
public int getNumberFloatingTasks() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
if (tasks.getTaskAt(i).isFloating()) {
count++;
}
}
return count;
}
public int getNumberUncompletedFloatingTasks() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
Task task = tasks.getTaskAt(i);
if (task.isFloating() && !task.getIsCompleted()) {
count++;
}
}
return count;
}
public int getNumberEvents() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
if (tasks.getTaskAt(i).isEvent()) {
count++;
}
}
return count;
}
public int getNumberUncompletedEvents() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
Task task = tasks.getTaskAt(i);
if (task.isEvent() && !task.getIsCompleted()) {
count++;
}
}
return count;
}
public int getNumberDeadlines() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
if (tasks.getTaskAt(i).isDeadline()) {
count++;
}
}
return count;
}
public int getNumberUncompletedDeadlines() {
int size = tasks.size();
int count = 0;
for (int i = 0; i < size; i++) {
Task task = tasks.getTaskAt(i);
if (task.isDeadline() && !task.getIsCompleted()) {
count++;
}
}
return count;
}
}
|
package sg.ncl.testbed_interface;
/**
*
* Team model
* @author yeoteye
*
*/
public class Team {
private long id;
private String name;
private String description;
private String website;
private String organizationType;
private boolean isApproved;
public Team() {
id = 0;
}
public Team(long id, String name, String description, String website, String organizationType, boolean isApproved) {
this.id = id;
this.name = name;
this.description = description;
this.website = website;
this.organizationType = organizationType;
this.isApproved = isApproved;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getOrganizationType() {
return organizationType;
}
public void setOrganizationType(String organizationType) {
this.organizationType = organizationType;
}
public boolean getIsApproved() {
return isApproved;
}
public void setIsApproved(boolean isApproved) {
this.isApproved = isApproved;
}
@Override
public String toString() {
return "Team {" +
"id=" + id +
", name=" + name +
", description=" + description +
", website=" + website +
", organizationType=" + organizationType +
", isApproved=" + isApproved;
}
}
|
package yanagishima.util;
import static org.apache.commons.csv.CSVFormat.EXCEL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import lombok.experimental.UtilityClass;
@UtilityClass
public final class DownloadUtil {
private static final byte[] BOM = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf };
public static void downloadTsv(HttpServletResponse response, String fileName, String datasource,
String queryId, String encode, boolean showHeader, boolean showBOM) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
download(response, datasource, queryId, encode, showHeader, showBOM, '\t');
}
public static void downloadCsv(HttpServletResponse response, String fileName, String datasource,
String queryId, String encode, boolean showHeader, boolean showBOM) {
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
download(response, datasource, queryId, encode, showHeader, showBOM, ',');
}
private static void download(HttpServletResponse response, String datasource, String queryId,
String encode, boolean showHeader, boolean showBOM, char delimiter) {
Path filePath = PathUtil.getResultFilePath(datasource, queryId, false);
if (!filePath.toFile().exists()) {
throw new RuntimeException(filePath.toFile().getName());
}
CSVFormat format = EXCEL.withDelimiter(delimiter).withRecordSeparator(System.getProperty("line.separator"));
try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), encode));
BufferedReader reader = Files.newBufferedReader(filePath);
CSVPrinter printer = new CSVPrinter(writer, format);
CSVParser parser = EXCEL.withDelimiter('\t').withNullString("\\N").parse(reader)) {
if (showBOM) {
response.getOutputStream().write(BOM);
}
int rowNumber = 0;
for (CSVRecord record : parser) {
List<String> columns = new ArrayList<>();
record.forEach(columns::add);
if (showHeader || rowNumber > 0) {
printer.printRecord(columns);
}
rowNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
package org.commcare.tasks;
import android.content.Context;
import android.content.Intent;
import android.support.v4.util.Pair;
import net.sqlcipher.database.SQLiteDatabase;
import org.commcare.CommCareApplication;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.database.user.models.ACase;
import org.commcare.cases.ledger.Ledger;
import org.commcare.core.encryption.CryptUtil;
import org.commcare.core.network.AuthenticationInterceptor;
import org.commcare.core.network.bitcache.BitCache;
import org.commcare.data.xml.DataModelPullParser;
import org.commcare.engine.cases.CaseUtils;
import org.commcare.google.services.analytics.AnalyticsParamValue;
import org.commcare.interfaces.CommcareRequestEndpoints;
import org.commcare.models.database.SqlStorage;
import org.commcare.models.database.user.models.AndroidCaseIndexTable;
import org.commcare.models.database.user.models.EntityStorageCache;
import org.commcare.models.encryption.ByteEncrypter;
import org.commcare.modern.models.RecordTooLargeException;
import org.commcare.network.DataPullRequester;
import org.commcare.network.RemoteDataPullResponse;
import org.commcare.preferences.ServerUrls;
import org.commcare.preferences.HiddenPreferences;
import org.commcare.resources.model.CommCareOTARestoreListener;
import org.commcare.services.CommCareSessionService;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.util.LogTypes;
import org.commcare.utils.FormSaveUtil;
import org.commcare.utils.SessionUnavailableException;
import org.commcare.utils.SyncDetailCalculations;
import org.commcare.utils.UnknownSyncError;
import org.commcare.xml.AndroidTransactionParserFactory;
import org.javarosa.core.model.User;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.xml.util.ActionableInvalidStructureException;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import javax.crypto.SecretKey;
/**
* @author ctsims
*/
public abstract class DataPullTask<R>
extends CommCareTask<Void, Integer, ResultAndError<DataPullTask.PullTaskResult>, R>
implements CommCareOTARestoreListener {
private final String server;
private final String username;
private final String password;
protected final Context context;
private int mCurrentProgress;
private int mTotalItems;
private long mSyncStartTime;
public static final int DATA_PULL_TASK_ID = 10;
public static final int PROGRESS_STARTED = 0;
public static final int PROGRESS_CLEANED = 1;
public static final int PROGRESS_AUTHED = 2;
private static final int PROGRESS_DONE = 4;
public static final int PROGRESS_RECOVERY_NEEDED = 8;
public static final int PROGRESS_RECOVERY_STARTED = 16;
private static final int PROGRESS_RECOVERY_FAIL_SAFE = 32;
private static final int PROGRESS_RECOVERY_FAIL_BAD = 64;
public static final int PROGRESS_PROCESSING = 128;
public static final int PROGRESS_DOWNLOADING = 256;
public static final int PROGRESS_DOWNLOADING_COMPLETE = 512;
public static final int PROGRESS_SERVER_PROCESSING = 1024;
private final DataPullRequester dataPullRequester;
private final AsyncRestoreHelper asyncRestoreHelper;
private final boolean blockRemoteKeyManagement;
private boolean loginNeeded;
private UserKeyRecord ukrForLogin;
private boolean wasKeyLoggedIn;
public DataPullTask(String username, String password, String userId,
String server, Context context, DataPullRequester dataPullRequester,
boolean blockRemoteKeyManagement) {
this.server = server;
this.username = username;
this.password = password;
this.context = context;
this.taskId = DATA_PULL_TASK_ID;
this.dataPullRequester = dataPullRequester;
this.requestor = dataPullRequester.getHttpGenerator(username, password, userId);
this.asyncRestoreHelper = new AsyncRestoreHelper(this);
this.blockRemoteKeyManagement = blockRemoteKeyManagement;
TAG = DataPullTask.class.getSimpleName();
}
public DataPullTask(String username, String password, String userId,
String server, Context context) {
this(username, password, userId, server, context, CommCareApplication.instance().getDataPullRequester(),
false);
}
// TODO PLM: once this task is refactored into manageable components, it should use the
// ManagedAsyncTask pattern of checking for isCancelled() and aborting at safe places.
@Override
protected void onCancelled() {
super.onCancelled();
wipeLoginIfItOccurred();
}
private final CommcareRequestEndpoints requestor;
@Override
protected ResultAndError<PullTaskResult> doTaskBackground(Void... params) {
if (!CommCareSessionService.sessionAliveLock.tryLock()) {
// Don't try to sync if logging out is occurring
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE,
"Cannot sync while a logout is in process");
}
try {
return doTaskBackgroundHelper();
} finally {
CommCareSessionService.sessionAliveLock.unlock();
}
}
private ResultAndError<PullTaskResult> doTaskBackgroundHelper() {
publishProgress(PROGRESS_STARTED);
recordSyncAttempt();
Logger.log(LogTypes.TYPE_USER, "Starting Sync");
determineIfLoginNeeded();
AndroidTransactionParserFactory factory = getTransactionParserFactory();
byte[] wrappedEncryptionKey = getEncryptionKey();
if (wrappedEncryptionKey == null) {
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE,
"Unable to get or generate encryption key");
}
factory.initUserParser(wrappedEncryptionKey);
if (!loginNeeded) {
//Only purge cases if we already had a logged in user. Otherwise we probably can't read the DB.
CaseUtils.purgeCases();
}
return getRequestResultOrRetry(factory);
}
private void determineIfLoginNeeded() {
try {
loginNeeded = !CommCareApplication.instance().getSession().isActive();
} catch (SessionUnavailableException sue) {
// expected if we aren't initialized.
loginNeeded = true;
}
}
private AndroidTransactionParserFactory getTransactionParserFactory() {
return new AndroidTransactionParserFactory(context, requestor) {
boolean publishedAuth = false;
@Override
public void reportProgress(int progress) {
if (!publishedAuth) {
DataPullTask.this.publishProgress(PROGRESS_AUTHED, progress);
publishedAuth = true;
}
}
};
}
private byte[] getEncryptionKey() {
byte[] key;
if (loginNeeded) {
initUKRForLogin();
if (ukrForLogin == null) {
return null;
}
key = ukrForLogin.getEncryptedKey();
} else {
key = CommCareApplication.instance().getSession().getLoggedInUser().getWrappedKey();
}
this.publishProgress(PROGRESS_CLEANED); // Either way, we don't want to do this step again
return key;
}
private void initUKRForLogin() {
if (blockRemoteKeyManagement || shouldGenerateFirstKey()) {
SecretKey newKey = CryptUtil.generateSemiRandomKey();
if (newKey == null) {
return;
}
String sandboxId = PropertyUtils.genUUID().replace("-", "");
ukrForLogin = new UserKeyRecord(username, UserKeyRecord.generatePwdHash(password),
ByteEncrypter.wrapByteArrayWithString(newKey.getEncoded(), password),
new Date(), new Date(Long.MAX_VALUE), sandboxId);
} else {
ukrForLogin = UserKeyRecord.getCurrentValidRecordByPassword(
CommCareApplication.instance().getCurrentApp(), username, password, true);
if (ukrForLogin == null) {
Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
"Shouldn't be able to not have a valid key record when OTA restoring with a key server");
}
}
}
private static boolean shouldGenerateFirstKey() {
String keyServer = ServerUrls.getKeyServer();
return keyServer == null || keyServer.equals("");
}
private ResultAndError<PullTaskResult> getRequestResultOrRetry(AndroidTransactionParserFactory factory) {
while (asyncRestoreHelper.retryWaitPeriodInProgress()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
if (isCancelled()) {
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE);
}
}
PullTaskResult responseError = PullTaskResult.UNKNOWN_FAILURE;
asyncRestoreHelper.retryAtTime = -1;
try {
ResultAndError<PullTaskResult> result = makeRequestAndHandleResponse(factory);
if (PullTaskResult.RETRY_NEEDED.equals(result.data)) {
asyncRestoreHelper.startReportingServerProgress();
return getRequestResultOrRetry(factory);
} else {
return result;
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Timed out listening to receive data during sync");
responseError = PullTaskResult.CONNECTION_TIMEOUT;
} catch (UnknownHostException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to bad network");
responseError = PullTaskResult.UNREACHABLE_HOST;
} catch (AuthenticationInterceptor.PlainTextPasswordException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE, "Encountered PlainTextPasswordException during sync: Sending password over HTTP");
responseError = PullTaskResult.AUTH_OVER_HTTP;
} catch (IOException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to IO Error|" + e.getMessage());
} catch (UnknownSyncError e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Couldn't sync due to Unknown Error|" + e.getMessage());
}
wipeLoginIfItOccurred();
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(responseError);
}
/**
* @return the proper result, or null if we have not yet been able to determine the result to
* return
*/
private ResultAndError<PullTaskResult> makeRequestAndHandleResponse(AndroidTransactionParserFactory factory)
throws IOException, UnknownSyncError {
RemoteDataPullResponse pullResponse =
dataPullRequester.makeDataPullRequest(this, requestor, server, !loginNeeded);
int responseCode = pullResponse.responseCode;
Logger.log(LogTypes.TYPE_USER,
"Request opened. Response code: " + responseCode);
if (responseCode == 401) {
return handleAuthFailed();
} else if (responseCode >= 200 && responseCode < 300) {
if (responseCode == 202) {
return asyncRestoreHelper.handleRetryResponseCode(pullResponse);
} else {
return handleSuccessResponseCode(pullResponse, factory);
}
} else if (responseCode == 412) {
return handleBadLocalState(factory);
} else if (responseCode == 406) {
return processErrorResponseWithMessage(pullResponse);
} else if (responseCode == 500) {
return handleServerError();
} else {
throw new UnknownSyncError();
}
}
private ResultAndError<PullTaskResult> processErrorResponseWithMessage(RemoteDataPullResponse pullResponse) throws IOException {
String message;
try {
JSONObject errorKeyAndDefault = new JSONObject(pullResponse.getErrorBody());
message = Localization.getWithDefault(
errorKeyAndDefault.getString("error"),
errorKeyAndDefault.getString("default_response"));
} catch (JSONException e) {
message = "Unknown issue";
}
return new ResultAndError<>(PullTaskResult.ACTIONABLE_FAILURE, message);
}
private ResultAndError<PullTaskResult> handleAuthFailed() {
wipeLoginIfItOccurred();
Logger.log(LogTypes.TYPE_USER, "Bad Auth Request for user!|" + username);
return new ResultAndError<>(PullTaskResult.AUTH_FAILED);
}
/**
* @return the proper result, or null if we have not yet been able to determine the result to
* return
* @throws IOException
*/
private ResultAndError<PullTaskResult> handleSuccessResponseCode(
RemoteDataPullResponse pullResponse, AndroidTransactionParserFactory factory)
throws IOException, UnknownSyncError {
asyncRestoreHelper.completeServerProgressBarIfShowing();
handleLoginNeededOnSuccess();
this.publishProgress(PROGRESS_AUTHED, 0);
if (isCancelled()) {
// About to enter data commit phase; last chance to finish early if cancelled.
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE);
}
this.publishProgress(PROGRESS_DOWNLOADING_COMPLETE, 0);
Logger.log(LogTypes.TYPE_USER, "Remote Auth Successful|" + username);
try {
BitCache cache = pullResponse.writeResponseToCache(context);
String syncToken = readInput(cache.retrieveCache(), factory);
updateUserSyncToken(syncToken);
onSuccessfulSync();
return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
} catch (XmlPullParserException e) {
wipeLoginIfItOccurred();
e.printStackTrace();
Logger.log(LogTypes.TYPE_USER,
"User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
} catch (ActionableInvalidStructureException e) {
wipeLoginIfItOccurred();
e.printStackTrace();
Logger.log(LogTypes.TYPE_USER,
"User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA_REQUIRES_INTERVENTION,
e.getLocalizedMessage());
} catch (InvalidStructureException e) {
wipeLoginIfItOccurred();
e.printStackTrace();
Logger.log(LogTypes.TYPE_USER,
"User Sync failed due to bad payload|" + e.getMessage());
return new ResultAndError<>(PullTaskResult.BAD_DATA, e.getMessage());
} catch (UnfullfilledRequirementsException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
"User sync failed oddly, unfulfilled reqs |" + e.getMessage());
throw new UnknownSyncError();
} catch (IllegalStateException e) {
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
"User sync failed oddly, ISE |" + e.getMessage());
throw new UnknownSyncError();
} catch (RecordTooLargeException e) {
wipeLoginIfItOccurred();
e.printStackTrace();
Logger.log(LogTypes.TYPE_ERROR_ASSERTION,
"Storage Full during user sync |" + e.getMessage());
return new ResultAndError<>(PullTaskResult.STORAGE_FULL);
}
}
private void handleLoginNeededOnSuccess() {
if (loginNeeded) {
// This is currently necessary to make sure that data is encoded, but there is
// probably a better way to do it
CommCareApplication.instance().startUserSession(
ByteEncrypter.unwrapByteArrayWithString(ukrForLogin.getEncryptedKey(), password),
ukrForLogin, false);
wasKeyLoggedIn = true;
}
}
/**
* @return the proper result, or null if we have not yet been able to determine the result to
* return
*/
private ResultAndError<PullTaskResult> handleBadLocalState(AndroidTransactionParserFactory factory)
throws UnknownSyncError {
this.publishProgress(PROGRESS_RECOVERY_NEEDED);
Logger.log(LogTypes.TYPE_USER, "Sync Recovery Triggered");
Pair<Integer, String> returnCodeAndMessageFromRecovery = recover(requestor, factory);
int returnCode = returnCodeAndMessageFromRecovery.first;
String failureReason = returnCodeAndMessageFromRecovery.second;
if (returnCode == PROGRESS_DONE) {
// Recovery was successful
onSuccessfulSync();
return new ResultAndError<>(PullTaskResult.DOWNLOAD_SUCCESS);
} else if (returnCode == PROGRESS_RECOVERY_FAIL_SAFE || returnCode == PROGRESS_RECOVERY_FAIL_BAD) {
wipeLoginIfItOccurred();
this.publishProgress(PROGRESS_DONE);
return new ResultAndError<>(PullTaskResult.UNKNOWN_FAILURE, failureReason);
} else {
throw new UnknownSyncError();
}
}
private void onSuccessfulSync() {
recordSuccessfulSyncTime(username);
Intent i = new Intent("org.commcare.dalvik.api.action.data.update");
this.context.sendBroadcast(i);
if (loginNeeded) {
CommCareApplication.instance().getAppStorage(UserKeyRecord.class).write(ukrForLogin);
}
Logger.log(LogTypes.TYPE_USER, "User Sync Successful|" + username);
updateCurrentUser(password);
this.publishProgress(PROGRESS_DONE);
}
private ResultAndError<PullTaskResult> handleServerError() {
wipeLoginIfItOccurred();
Logger.log(LogTypes.TYPE_USER, "500 Server Error|" + username);
return new ResultAndError<>(PullTaskResult.SERVER_ERROR);
}
private void wipeLoginIfItOccurred() {
if (wasKeyLoggedIn) {
CommCareApplication.instance().releaseUserResourcesAndServices();
}
}
@Override
public void tryAbort() {
if (requestor != null) {
requestor.abortCurrentRequest();
}
}
private static void recordSyncAttempt() {
//TODO: This should be per _user_, not per app
CommCareApplication.instance().getCurrentApp().getAppPreferences().edit()
.putLong(HiddenPreferences.LAST_SYNC_ATTEMPT, new Date().getTime()).apply();
HiddenPreferences.setPostUpdateSyncNeeded(false);
}
private static void recordSuccessfulSyncTime(String username) {
CommCareApplication.instance().getCurrentApp().getAppPreferences().edit()
.putLong(SyncDetailCalculations.getLastSyncKey(username), new Date().getTime()).apply();
}
//TODO: This and the normal sync share a ton of code. It's hard to really... figure out the right way to
private Pair<Integer, String> recover(CommcareRequestEndpoints requestor, AndroidTransactionParserFactory factory) {
while (asyncRestoreHelper.retryWaitPeriodInProgress()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
if (isCancelled()) {
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
"Task was cancelled during recovery sync");
}
}
// This chunk is the safe field of operations which can all fail in IO in such a way that
// we can just report back that things didn't work and don't need to attempt any recovery
// or additional work
BitCache cache;
try {
// Make a new request without all of the flags
RemoteDataPullResponse pullResponse =
dataPullRequester.makeDataPullRequest(this, requestor, server, false);
if (!(pullResponse.responseCode >= 200 && pullResponse.responseCode < 300)) {
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
"Received a non-success response during recovery sync");
} else if (pullResponse.responseCode == 202) {
ResultAndError<PullTaskResult> result =
asyncRestoreHelper.handleRetryResponseCode(pullResponse);
if (PullTaskResult.RETRY_NEEDED.equals(result.data)) {
asyncRestoreHelper.startReportingServerProgress();
return recover(requestor, factory);
} else {
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE,
"Retry response during recovery sync was improperly formed");
}
}
// Grab a cache. The plan is to download the incoming data, wipe (move) the existing
// db, and then restore fresh from the downloaded file
cache = pullResponse.writeResponseToCache(context);
} catch (IOException e) {
e.printStackTrace();
//Ok, well, we're bailing here, but we didn't make any changes
Logger.log(LogTypes.TYPE_USER, "Sync Recovery Failed due to IOException|" + e.getMessage());
return new Pair<>(PROGRESS_RECOVERY_FAIL_SAFE, "");
}
this.publishProgress(PROGRESS_RECOVERY_STARTED);
Logger.log(LogTypes.TYPE_USER, "Sync Recovery payload downloaded");
//Ok. Here's where things get real. We now have a stable copy of the fresh data from the
//server, so it's "safe" for us to wipe the casedb copy of it.
//CTS: We're not doing this in a super good way right now, need to be way more fault tolerant.
//this is the temporary implementation of everything past this point
//Wipe storage
SQLiteDatabase userDb = CommCareApplication.instance().getUserDbHandle();
wipeStorageForFourTwelveSync(userDb);
String failureReason = "";
try {
String syncToken = readInputWithoutCommit(cache.retrieveCache(), factory);
updateUserSyncToken(syncToken);
Logger.log(LogTypes.TYPE_USER, "Sync Recovery Successful");
userDb.setTransactionSuccessful();
return new Pair<>(PROGRESS_DONE, "");
} catch (InvalidStructureException | XmlPullParserException
| UnfullfilledRequirementsException | SessionUnavailableException
| IOException e) {
Logger.exception("Sync recovery failed|" + e.getMessage(), e);
userDb.endTransaction();
} finally {
//destroy temp file
userDb.endTransaction();
cache.release();
}
return new Pair<>(PROGRESS_RECOVERY_FAIL_BAD, failureReason);
}
private void wipeStorageForFourTwelveSync(SQLiteDatabase userDb) {
userDb.beginTransaction();
SqlStorage.wipeTableWithoutCommit(userDb, ACase.STORAGE_KEY);
SqlStorage.wipeTableWithoutCommit(userDb, Ledger.STORAGE_KEY);
SqlStorage.wipeTableWithoutCommit(userDb, AndroidCaseIndexTable.TABLE_NAME);
SqlStorage.wipeTableWithoutCommit(userDb, EntityStorageCache.TABLE_NAME);
EntityStorageCache.setCachedWipedPref();
}
private void updateCurrentUser(String password) {
SqlStorage<User> storage = CommCareApplication.instance().getUserStorage("USER", User.class);
User u = storage.getRecordForValue(User.META_USERNAME, username);
CommCareApplication.instance().getSession().setCurrentUser(u, password);
}
private void updateUserSyncToken(String syncToken) {
SqlStorage<User> storage = CommCareApplication.instance().getUserStorage("USER", User.class);
try {
User u = storage.getRecordForValue(User.META_USERNAME, username);
u.setLastSyncToken(syncToken);
storage.write(u);
} catch (NoSuchElementException nsee) {
//TODO: Something here? Maybe figure out if we downloaded a user from the server and attach the data to it?
}
}
private void initParsers(AndroidTransactionParserFactory factory) {
factory.initCaseParser();
factory.initStockParser();
Hashtable<String, String> formNamespaces = FormSaveUtil.getNamespaceToFilePathMap(context);
factory.initFormInstanceParser(formNamespaces);
}
private void parseStream(InputStream stream,
AndroidTransactionParserFactory factory)
throws InvalidStructureException, IOException, XmlPullParserException,
UnfullfilledRequirementsException {
DataModelPullParser parser = new DataModelPullParser(stream, factory, true, false, this);
parser.parse();
}
private String readInputWithoutCommit(InputStream stream,
AndroidTransactionParserFactory factory)
throws InvalidStructureException, IOException, XmlPullParserException,
UnfullfilledRequirementsException {
initParsers(factory);
parseStream(stream, factory);
return factory.getSyncToken();
}
private String readInput(InputStream stream, AndroidTransactionParserFactory factory)
throws InvalidStructureException, IOException, XmlPullParserException,
UnfullfilledRequirementsException {
initParsers(factory);
//this is _really_ coupled, but we'll tolerate it for now because of the absurd performance gains
SQLiteDatabase db = CommCareApplication.instance().getUserDbHandle();
db.beginTransaction();
try {
parseStream(stream, factory);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
//Return the sync token ID
return factory.getSyncToken();
}
//BEGIN - OTA Listener methods below - Note that most of the methods
//below weren't really implemented
@Override
public void onUpdate(int numberCompleted) {
mCurrentProgress = numberCompleted;
int millisecondsElapsed = (int)(System.currentTimeMillis() - mSyncStartTime);
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, millisecondsElapsed);
}
@Override
public void setTotalForms(int totalItemCount) {
mTotalItems = totalItemCount;
mCurrentProgress = 0;
mSyncStartTime = System.currentTimeMillis();
this.publishProgress(PROGRESS_PROCESSING, mCurrentProgress, mTotalItems, 0);
}
protected void reportServerProgress(int completedSoFar, int total) {
publishProgress(PROGRESS_SERVER_PROCESSING, completedSoFar, total);
}
public void reportDownloadProgress(int totalRead) {
publishProgress(PROGRESS_DOWNLOADING, totalRead);
}
public AsyncRestoreHelper getAsyncRestoreHelper() {
return this.asyncRestoreHelper;
}
public enum PullTaskResult {
DOWNLOAD_SUCCESS(null),
RETRY_NEEDED(null),
AUTH_FAILED(AnalyticsParamValue.SYNC_FAIL_AUTH),
BAD_DATA(AnalyticsParamValue.SYNC_FAIL_BAD_DATA),
BAD_DATA_REQUIRES_INTERVENTION(AnalyticsParamValue.SYNC_FAIL_BAD_DATA),
UNKNOWN_FAILURE(AnalyticsParamValue.SYNC_FAIL_UNKNOWN),
ACTIONABLE_FAILURE(AnalyticsParamValue.SYNC_FAIL_ACTIONABLE),
UNREACHABLE_HOST(AnalyticsParamValue.SYNC_FAIL_UNREACHABLE_HOST),
CONNECTION_TIMEOUT(AnalyticsParamValue.SYNC_FAIL_CONNECTION_TIMEOUT),
SERVER_ERROR(AnalyticsParamValue.SYNC_FAIL_SERVER_ERROR),
STORAGE_FULL(AnalyticsParamValue.SYNC_FAIL_STORAGE_FULL),
AUTH_OVER_HTTP(AnalyticsParamValue.SYNC_FAIL_AUTH_OVER_HTTP);
public final String analyticsFailureReasonParam;
PullTaskResult(String analyticsParam) {
this.analyticsFailureReasonParam = analyticsParam;
}
}
}
|
package cpi;
/**
*
* @author Gonzalo
*/
public class CPI {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// un commit de prueba
// anahi
}
}
|
package org.commcare.utils;
import android.content.SharedPreferences;
import android.text.format.DateUtils;
import org.commcare.CommCareApplication;
import org.commcare.preferences.PrefValues;
import org.commcare.preferences.HiddenPreferences;
import org.commcare.preferences.MainConfigurablePreferences;
import java.util.Calendar;
import java.util.Date;
public class PendingCalcs {
public static boolean isUpdatePending(SharedPreferences preferences) {
// Establish whether or not an AutoUpdate is Pending
String autoUpdateFreq =
preferences.getString(MainConfigurablePreferences.AUTO_UPDATE_FREQUENCY,
PrefValues.FREQUENCY_NEVER);
// See if auto update is even turned on
if (!autoUpdateFreq.equals(PrefValues.FREQUENCY_NEVER)) {
long lastUpdateCheck =
preferences.getLong(HiddenPreferences.LAST_UPDATE_ATTEMPT, 0);
return isTimeForAutoUpdateCheck(lastUpdateCheck, autoUpdateFreq);
}
return false;
}
public static boolean isTimeForAutoUpdateCheck(long lastUpdateCheck, String autoUpdateFreq) {
int checkEveryNDays;
if (PrefValues.FREQUENCY_DAILY.equals(autoUpdateFreq)) {
checkEveryNDays = 1;
} else {
checkEveryNDays = 7;
}
long duration = DateUtils.DAY_IN_MILLIS * checkEveryNDays;
return isPending(lastUpdateCheck, duration);
}
/**
* Used to check if an update, sync, or log submission is pending, based upon the last time
* it occurred and the expected period between occurrences
*/
public static boolean isPending(long last, long period) {
long now = new Date().getTime();
// 1) Straightforward - Time is greater than last + duration
long diff = now - last;
if (diff > period) {
return true;
}
// 2) For daily stuff, we want it to be the case that if the last time you synced was the day prior,
// you still sync, so people can get into the cycle of doing it once in the morning, which
// is more valuable than syncing mid-day.
if (isDifferentDayInPast(now, last, period)) {
return true;
}
// 3) Major time change - (Phone might have had its calendar day manipulated).
// for now we'll simply say that if last was more than a day in the future (timezone blur)
// we should also trigger
return (now < (last - DateUtils.DAY_IN_MILLIS));
}
private static boolean isDifferentDayInPast(long now, long last, long period) {
Calendar lastRestoreCalendar = Calendar.getInstance();
lastRestoreCalendar.setTimeInMillis(last);
return period == DateUtils.DAY_IN_MILLIS &&
lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK) &&
now > last;
}
/**
* @return True if there is a sync action pending.
*/
public static boolean getPendingSyncStatus() {
SharedPreferences prefs = CommCareApplication.instance().getCurrentApp().getAppPreferences();
long period = -1;
// new flag, read what it is.
String periodic = prefs.getString(HiddenPreferences.AUTO_SYNC_FREQUENCY, PrefValues.FREQUENCY_NEVER);
if (!periodic.equals(PrefValues.FREQUENCY_NEVER)) {
period = DateUtils.DAY_IN_MILLIS * (periodic.equals(PrefValues.FREQUENCY_DAILY) ? 1 : 7);
} else {
// Old flag, use a day by default
if ("true".equals(prefs.getString("cc-auto-update", "false"))) {
period = DateUtils.DAY_IN_MILLIS;
}
}
// If we didn't find a period, bail
if (period == -1) {
return false;
}
return PendingCalcs.isPending(HiddenPreferences.getLastUploadSyncAttempt(), period);
}
}
|
package org.jpos.security;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.javatuples.Pair;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.iso.ISOUtil;
import org.jpos.util.*;
import org.jpos.util.NameRegistrar.NotFoundException;
/**
* <p>
* Provides base functionality for the actual Security Module Adapter.
* </p>
* <p>
* You adapter needs to override the methods that end with "Impl"
* </p>
* @author Hani S. Kirollos
* @version $Revision$ $Date$
*/
public class BaseSMAdapter
implements SMAdapter, Configurable, LogSource {
protected Logger logger = null;
protected String realm = null;
protected Configuration cfg;
private String name;
public BaseSMAdapter () {
super();
}
public BaseSMAdapter (Configuration cfg, Logger logger, String realm) throws ConfigurationException
{
super();
setLogger(logger, realm);
setConfiguration(cfg);
}
public void setConfiguration (Configuration cfg) throws ConfigurationException {
this.cfg = cfg;
}
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
}
public Logger getLogger () {
return logger;
}
public String getRealm () {
return realm;
}
/**
* associates this SMAdapter with a name using NameRegistrar
* @param name name to register
* @see NameRegistrar
*/
public void setName (String name) {
this.name = name;
NameRegistrar.register("s-m-adapter." + name, this);
}
/**
* @return this SMAdapter's name ("" if no name was set)
*/
public String getName () {
return this.name;
}
/**
* @param name
* @return SMAdapter instance with given name.
* @throws NotFoundException
* @see NameRegistrar
*/
public static SMAdapter getSMAdapter (String name) throws NameRegistrar.NotFoundException {
return (SMAdapter)NameRegistrar.get("s-m-adapter." + name);
}
public SecureDESKey generateKey (short keyLength, String keyType) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "Key Length", keyLength), new SimpleMsg("parameter",
"Key Type", keyType)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate Key", cmdParameters));
SecureDESKey result = null;
try {
result = generateKeyImpl(keyLength, keyType);
evt.addMessage(new SimpleMsg("result", "Generated Key", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public byte[] generateKeyCheckValue (SecureDESKey kd) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "Key with untrusted check value", kd)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate Key Check Value", cmdParameters));
byte[] result = null;
try {
result = generateKeyCheckValueImpl(kd);
evt.addMessage(new SimpleMsg("result", "Generated Key Check Value", ISOUtil.hexString(result)));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public SecureDESKey importKey (short keyLength, String keyType, byte[] encryptedKey,
SecureDESKey kek, boolean checkParity) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "Key Length", keyLength), new SimpleMsg("parameter",
"Key Type", keyType), new SimpleMsg("parameter", "Encrypted Key",
encryptedKey), new SimpleMsg("parameter", "Key-Encrypting Key", kek), new SimpleMsg("parameter", "Check Parity", checkParity)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Import Key", cmdParameters));
SecureDESKey result = null;
try {
result = importKeyImpl(keyLength, keyType, encryptedKey, kek, checkParity);
evt.addMessage(new SimpleMsg("result", "Imported Key", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public byte[] exportKey (SecureDESKey key, SecureDESKey kek) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "Key", key), new SimpleMsg("parameter", "Key-Encrypting Key",
kek),
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Export Key", cmdParameters));
byte[] result = null;
try {
result = exportKeyImpl(key, kek);
evt.addMessage(new SimpleMsg("result", "Exported Key", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN encryptPIN (String pin, String accountNumber, boolean extract) throws SMException {
accountNumber = extract ? EncryptedPIN.extractAccountNumberPart(accountNumber) : accountNumber;
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "clear pin", pin), new SimpleMsg("parameter", "account number",
accountNumber)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Encrypt Clear PIN", cmdParameters));
EncryptedPIN result = null;
try {
result = encryptPINImpl(pin, accountNumber);
evt.addMessage(new SimpleMsg("result", "PIN under LMK", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN encryptPIN (String pin, String accountNumber) throws SMException {
return encryptPIN(pin, accountNumber, true);
}
public String decryptPIN (EncryptedPIN pinUnderLmk) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk),
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Decrypt PIN", cmdParameters));
String result = null;
try {
result = decryptPINImpl(pinUnderLmk);
evt.addMessage(new SimpleMsg("result", "clear PIN", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN importPIN (EncryptedPIN pinUnderKd1, SecureDESKey kd1) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter",
"Data Key 1", kd1),
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Import PIN", cmdParameters));
EncryptedPIN result = null;
try {
result = importPINImpl(pinUnderKd1, kd1);
evt.addMessage(new SimpleMsg("result", "PIN under LMK", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN translatePIN (EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1), new SimpleMsg("parameter",
"Data Key 1", kd1), new SimpleMsg("parameter", "Data Key 2", kd2),
new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Translate PIN from Data Key 1 to Data Key 2",
cmdParameters));
EncryptedPIN result = null;
try {
result = translatePINImpl(pinUnderKd1, kd1, kd2, destinationPINBlockFormat);
evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN importPIN (EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
SecureDESKey bdk) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under Derived Unique Key", pinUnderDuk), new SimpleMsg("parameter",
"Key Serial Number", ksn), new SimpleMsg("parameter", "Base Derivation Key",
bdk)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Import PIN", cmdParameters));
EncryptedPIN result = null;
try {
result = importPINImpl(pinUnderDuk, ksn, bdk);
evt.addMessage(new SimpleMsg("result", "PIN under LMK", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN translatePIN (EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
SecureDESKey bdk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under Derived Unique Key", pinUnderDuk), new SimpleMsg("parameter",
"Key Serial Number", ksn), new SimpleMsg("parameter", "Base Derivation Key",
bdk), new SimpleMsg("parameter", "Data Key 2", kd2), new SimpleMsg("parameter",
"Destination PIN Block Format", destinationPINBlockFormat)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Translate PIN", cmdParameters));
EncryptedPIN result = null;
try {
result = translatePINImpl(pinUnderDuk, ksn, bdk, kd2, destinationPINBlockFormat);
evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN exportPIN (EncryptedPIN pinUnderLmk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk), new SimpleMsg("parameter",
"Data Key 2", kd2), new SimpleMsg("parameter", "Destination PIN Block Format",
destinationPINBlockFormat)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Export PIN", cmdParameters));
EncryptedPIN result = null;
try {
result = exportPINImpl(pinUnderLmk, kd2, destinationPINBlockFormat);
evt.addMessage(new SimpleMsg("result", "PIN under Data Key 2", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public EncryptedPIN generatePIN(String accountNumber, int pinLen)
throws SMException {
return generatePIN(accountNumber, pinLen, null);
}
public EncryptedPIN generatePIN(String accountNumber, int pinLen, List<String> excludes)
throws SMException {
List<Loggeable> cmdParameters = new ArrayList<Loggeable>();
cmdParameters.add(new SimpleMsg("parameter", "account number", accountNumber));
cmdParameters.add(new SimpleMsg("parameter", "PIN length", pinLen));
if(excludes != null && !excludes.isEmpty())
cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes));
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate PIN", cmdParameters.toArray(new Loggeable[cmdParameters.size()])));
EncryptedPIN result = null;
try {
result = generatePINImpl(accountNumber, pinLen, excludes);
evt.addMessage(new SimpleMsg("result", "Generated PIN", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public String calculatePVV(EncryptedPIN pinUnderLMK, SecureDESKey pvkA,
SecureDESKey pvkB, int pvkIdx) throws SMException {
return calculatePVV(pinUnderLMK, pvkA, pvkB, pvkIdx, null);
}
public String calculatePVV(EncryptedPIN pinUnderLMK, SecureDESKey pvkA,
SecureDESKey pvkB, int pvkIdx,
List<String> excludes) throws SMException {
List<Loggeable> cmdParameters = new ArrayList<Loggeable>();
cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderLMK.getAccountNumber()));
cmdParameters.add(new SimpleMsg("parameter", "PIN under LMK", pinUnderLMK));
cmdParameters.add(new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA));
cmdParameters.add(new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB));
cmdParameters.add(new SimpleMsg("parameter", "PVK index", pvkIdx));
if(excludes != null && !excludes.isEmpty())
cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes));
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Calculate PVV", cmdParameters.toArray(new Loggeable[cmdParameters.size()])));
String result = null;
try {
result = calculatePVVImpl(pinUnderLMK, pvkA, pvkB, pvkIdx, excludes);
evt.addMessage(new SimpleMsg("result", "Calculated PVV", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public String calculatePVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx)
throws SMException {
return calculatePVV(pinUnderKd1, kd1, pvkA, pvkB, pvkIdx, null);
}
public String calculatePVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx,
List<String> excludes) throws SMException {
List<Loggeable> cmdParameters = new ArrayList<Loggeable>();
cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()));
cmdParameters.add(new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1));
cmdParameters.add(new SimpleMsg("parameter", "Data Key 1", kd1));
cmdParameters.add(new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA));
cmdParameters.add(new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB));
cmdParameters.add(new SimpleMsg("parameter", "PVK index", pvkIdx));
if(excludes != null && !excludes.isEmpty())
cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes));
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Calculate PVV", cmdParameters.toArray(new Loggeable[cmdParameters.size()])));
String result = null;
try {
result = calculatePVVImpl(pinUnderKd1, kd1, pvkA, pvkB, pvkIdx, excludes);
evt.addMessage(new SimpleMsg("result", "Calculated PVV", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public boolean verifyPVV(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvkA,
SecureDESKey pvkB, int pvki, String pvv) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()),
new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1),
new SimpleMsg("parameter", "Data Key 1", kd1),
new SimpleMsg("parameter", "PVK-A", pvkA == null ? "" : pvkA),
new SimpleMsg("parameter", "PVK-B", pvkB == null ? "" : pvkB),
new SimpleMsg("parameter", "pvki", pvki),
new SimpleMsg("parameter", "pvv", pvv)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify a PIN Using the VISA Method", cmdParameters));
try {
boolean r = verifyPVVImpl(pinUnderKd1, kd1, pvkA, pvkB, pvki, pvv);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, SecureDESKey pvk,
String decTab, String pinValData, int minPinLen)
throws SMException {
return calculateIBMPINOffset(pinUnderLmk, pvk, decTab, pinValData, minPinLen, null);
}
public String calculateIBMPINOffset(EncryptedPIN pinUnderLmk, SecureDESKey pvk,
String decTab, String pinValData, int minPinLen,
List<String> excludes) throws SMException {
List<Loggeable> cmdParameters = new ArrayList<Loggeable>();
cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderLmk.getAccountNumber()));
cmdParameters.add(new SimpleMsg("parameter", "PIN under LMK", pinUnderLmk));
cmdParameters.add(new SimpleMsg("parameter", "PVK", pvk));
cmdParameters.add(new SimpleMsg("parameter", "decimalisation table", decTab));
cmdParameters.add(new SimpleMsg("parameter", "PIN validation data", pinValData));
cmdParameters.add(new SimpleMsg("parameter", "minimum PIN length", minPinLen));
if(excludes != null && !excludes.isEmpty())
cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes));
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Calculate PIN offset", cmdParameters.toArray(new Loggeable[cmdParameters.size()])));
String result = null;
try {
result = calculateIBMPINOffsetImpl(pinUnderLmk, pvk,
decTab, pinValData, minPinLen, excludes);
evt.addMessage(new SimpleMsg("result", "Calculated PIN offset", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvk, String decTab, String pinValData, int minPinLen)
throws SMException {
return calculateIBMPINOffset(pinUnderKd1, kd1, pvk, decTab,
pinValData, minPinLen, null);
}
public String calculateIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvk, String decTab, String pinValData, int minPinLen,
List<String> excludes) throws SMException {
List<Loggeable> cmdParameters = new ArrayList<Loggeable>();
cmdParameters.add(new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()));
cmdParameters.add(new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1));
cmdParameters.add(new SimpleMsg("parameter", "Data Key 1", kd1));
cmdParameters.add(new SimpleMsg("parameter", "PVK", pvk));
cmdParameters.add(new SimpleMsg("parameter", "decimalisation table", decTab));
cmdParameters.add(new SimpleMsg("parameter", "PIN validation data", pinValData));
cmdParameters.add(new SimpleMsg("parameter", "minimum PIN length", minPinLen));
if(excludes != null && !excludes.isEmpty())
cmdParameters.add(new SimpleMsg("parameter", "Excluded PINs list", excludes));
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Calculate PIN offset", cmdParameters.toArray(new Loggeable[cmdParameters.size()])));
String result = null;
try {
result = calculateIBMPINOffsetImpl(pinUnderKd1, kd1, pvk,
decTab, pinValData, minPinLen, excludes);
evt.addMessage(new SimpleMsg("result", "Calculated PIN offset", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public boolean verifyIBMPINOffset(EncryptedPIN pinUnderKd1, SecureDESKey kd1, SecureDESKey pvk,
String offset, String decTab, String pinValData,
int minPinLen) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", pinUnderKd1.getAccountNumber()),
new SimpleMsg("parameter", "PIN under Data Key 1", pinUnderKd1),
new SimpleMsg("parameter", "Data Key 1", kd1),
new SimpleMsg("parameter", "PVK", pvk),
new SimpleMsg("parameter", "Pin block format", pinUnderKd1.getPINBlockFormat()),
new SimpleMsg("parameter", "decimalisation table", decTab),
new SimpleMsg("parameter", "PIN validation data", pinValData),
new SimpleMsg("parameter", "minimum PIN length", minPinLen),
new SimpleMsg("parameter", "offset", offset)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify PIN offset", cmdParameters));
try {
boolean r = verifyIBMPINOffsetImpl(pinUnderKd1, kd1, pvk, offset, decTab,
pinValData, minPinLen);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public EncryptedPIN deriveIBMPIN(String accountNo, SecureDESKey pvk,
String decTab, String pinValData,
int minPinLen, String offset) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "Offset", offset),
new SimpleMsg("parameter", "PVK", pvk),
new SimpleMsg("parameter", "Decimalisation table", decTab),
new SimpleMsg("parameter", "PIN validation data", pinValData),
new SimpleMsg("parameter", "Minimum PIN length", minPinLen)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Derive a PIN Using the IBM Method", cmdParameters));
EncryptedPIN result = null;
try {
result = deriveIBMPINImpl(accountNo, pvk, decTab, pinValData, minPinLen, offset);
evt.addMessage(new SimpleMsg("result", "Derived PIN", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public String calculateCVV(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
Date expDate, String serviceCode) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "cvk-a", cvkA == null ? "" : cvkA),
new SimpleMsg("parameter", "cvk-b", cvkB == null ? "" : cvkB),
new SimpleMsg("parameter", "Exp date", expDate),
new SimpleMsg("parameter", "Service code", serviceCode)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Calculate CVV/CVC", cmdParameters));
String result = null;
try {
result = calculateCVVImpl(accountNo, cvkA, cvkB, expDate, serviceCode);
evt.addMessage(new SimpleMsg("result", "Calculated CVV/CVC", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public boolean verifyCVV(String accountNo , SecureDESKey cvkA, SecureDESKey cvkB,
String cvv, Date expDate, String serviceCode) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "cvk-a", cvkA == null ? "" : cvkA),
new SimpleMsg("parameter", "cvk-b", cvkB == null ? "" : cvkB),
new SimpleMsg("parameter", "CVV/CVC", cvv),
new SimpleMsg("parameter", "Exp date", expDate),
new SimpleMsg("parameter", "Service code", serviceCode)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify CVV/CVC", cmdParameters));
try {
boolean r = verifyCVVImpl(accountNo, cvkA, cvkB, cvv, expDate, serviceCode);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public boolean verifydCVV(String accountNo, SecureDESKey imkac, String dcvv,
Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "imk-ac", imkac == null ? "" : imkac),
new SimpleMsg("parameter", "dCVV", dcvv),
new SimpleMsg("parameter", "Exp date", expDate),
new SimpleMsg("parameter", "Service code", serviceCode),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "mkd method", mkdm)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify dCVV", cmdParameters));
try {
boolean r = verifydCVVImpl(accountNo, imkac, dcvv, expDate, serviceCode, atc, mkdm);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
/**
* @param imkcvc3 the issuer master key for generating and verifying CVC3
* @param accountNo The account number including BIN and the check digit
* @param acctSeqNo account sequence number, 2 decimal digits
* @param atc application transactin counter. This is used for ICC Master
* Key derivation. A 2 byte value must be supplied.
* @param upn unpredictable number. This is used for Session Key Generation
* A 4 byte value must be supplied.
* @param data track data
* @param mkdm ICC Master Key Derivation Method. If {@code null} specified
* is assumed {@see MKDMethod#OPTION_A}
* @param cvc3 dynamic Card Verification Code 3
* @return
* @throws SMException
*/
public boolean verifyCVC3(SecureDESKey imkcvc3, String accountNo, String acctSeqNo,
byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3)
throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "imk-cvc3", imkcvc3 == null ? "" : imkcvc3),
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)),
new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data)),
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "cvc3", cvc3)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify CVC3", cmdParameters));
try {
boolean r = verifyCVC3Impl( imkcvc3, accountNo, acctSeqNo, atc, upn, data, mkdm, cvc3);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public boolean verifyARQC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc
,byte[] upn, byte[] transData) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "skd method", skdm),
new SimpleMsg("parameter", "imk-ac", imkac),
new SimpleMsg("parameter", "account number", accoutNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)),
new SimpleMsg("parameter", "trans. data", transData == null ? "" : ISOUtil.hexString(transData))
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Verify ARQC/TC/AAC", cmdParameters));
try {
boolean r = verifyARQCImpl( mkdm, skdm, imkac, accoutNo, acctSeqNo, arqc, atc, upn, transData);
evt.addMessage(new SimpleMsg("result", "Verification status", r ? "valid" : "invalid"));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public byte[] generateARPC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn
,ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "skd method", skdm),
new SimpleMsg("parameter", "imk-ac", imkac),
new SimpleMsg("parameter", "account number", accoutNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)),
new SimpleMsg("parameter", "arpc gen. method", arpcMethod),
new SimpleMsg("parameter", "auth. rc", arc == null ? "" : ISOUtil.hexString(arc)),
new SimpleMsg("parameter", "prop auth. data", propAuthData == null
? "" : ISOUtil.hexString(propAuthData))
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Genarate ARPC", cmdParameters));
try {
byte[] result = generateARPCImpl( mkdm, skdm, imkac, accoutNo, acctSeqNo
,arqc, atc, upn, arpcMethod, arc, propAuthData );
evt.addMessage(new SimpleMsg("result", "Generated ARPC", result));
return result;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public byte[] verifyARQCGenerateARPC(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accoutNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn
,byte[] transData, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "skd method", skdm),
new SimpleMsg("parameter", "imk-ac", imkac),
new SimpleMsg("parameter", "account number", accoutNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "upn", upn == null ? "" : ISOUtil.hexString(upn)),
new SimpleMsg("parameter", "trans. data", transData == null ? "" : ISOUtil.hexString(transData)),
new SimpleMsg("parameter", "arpc gen. method", arpcMethod),
new SimpleMsg("parameter", "auth. rc", arc == null ? "" : ISOUtil.hexString(arc)),
new SimpleMsg("parameter", "prop auth. data", propAuthData == null
? "" : ISOUtil.hexString(propAuthData))
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Genarate ARPC", cmdParameters));
try {
byte[] result = verifyARQCGenerateARPCImpl( mkdm, skdm, imkac, accoutNo,
acctSeqNo, arqc, atc, upn, transData, arpcMethod, arc, propAuthData );
evt.addMessage(new SimpleMsg("result", "ARPC", result == null ? "" : ISOUtil.hexString(result)));
return result;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public byte[] generateSM_MAC(MKDMethod mkdm, SKDMethod skdm
,SecureDESKey imksmi, String accountNo, String acctSeqNo
,byte[] atc, byte[] arqc, byte[] data) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "skd method", skdm),
new SimpleMsg("parameter", "imk-smi", imksmi),
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)),
new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data))
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate Secure Messaging MAC", cmdParameters));
try {
byte[] mac = generateSM_MACImpl( mkdm, skdm, imksmi, accountNo, acctSeqNo, atc, arqc, data);
evt.addMessage(new SimpleMsg("result", "Generated MAC", mac!=null ? ISOUtil.hexString(mac) : ""));
return mac;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public Pair<EncryptedPIN,byte[]> translatePINGenerateSM_MAC(MKDMethod mkdm
,SKDMethod skdm, PaddingMethod padm, SecureDESKey imksmi
,String accountNo, String acctSeqNo, byte[] atc, byte[] arqc
,byte[] data, EncryptedPIN currentPIN, EncryptedPIN newPIN
,SecureDESKey kd1, SecureDESKey imksmc, SecureDESKey imkac
,byte destinationPINBlockFormat) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "mkd method", mkdm),
new SimpleMsg("parameter", "skd method", skdm),
new SimpleMsg("parameter", "padding method", padm),
new SimpleMsg("parameter", "imk-smi", imksmi),
new SimpleMsg("parameter", "account number", accountNo),
new SimpleMsg("parameter", "accnt seq no", acctSeqNo),
new SimpleMsg("parameter", "atc", atc == null ? "" : ISOUtil.hexString(atc)),
new SimpleMsg("parameter", "arqc", arqc == null ? "" : ISOUtil.hexString(arqc)),
new SimpleMsg("parameter", "data", data == null ? "" : ISOUtil.hexString(data)),
new SimpleMsg("parameter", "Current Encrypted PIN", currentPIN),
new SimpleMsg("parameter", "New Encrypted PIN", newPIN),
new SimpleMsg("parameter", "Source PIN Encryption Key", kd1),
new SimpleMsg("parameter", "imk-smc", imksmc),
new SimpleMsg("parameter", "imk-ac", imkac),
new SimpleMsg("parameter", "Destination PIN Block Format", destinationPINBlockFormat)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Translate PIN block format and Generate Secure Messaging MAC", cmdParameters));
try {
Pair<EncryptedPIN,byte[]> r = translatePINGenerateSM_MACImpl( mkdm, skdm
,padm, imksmi, accountNo, acctSeqNo, atc, arqc, data, currentPIN
,newPIN, kd1, imksmc, imkac, destinationPINBlockFormat);
SimpleMsg[] cmdResults = {
new SimpleMsg("result", "Translated PIN block", r.getValue0()),
new SimpleMsg("result", "Generated MAC", r.getValue1() == null ? "" : ISOUtil.hexString(r.getValue1()))
};
evt.addMessage(new SimpleMsg("results", "Complex results", cmdResults));
return r;
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
public byte[] generateCBC_MAC (byte[] data, SecureDESKey kd) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "data", data), new SimpleMsg("parameter", "data key",
kd),
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate CBC-MAC", cmdParameters));
byte[] result = null;
try {
result = generateCBC_MACImpl(data, kd);
evt.addMessage(new SimpleMsg("result", "CBC-MAC", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public byte[] generateEDE_MAC (byte[] data, SecureDESKey kd) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "data", data), new SimpleMsg("parameter", "data key",
kd),
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Generate EDE-MAC", cmdParameters));
byte[] result = null;
try {
result = generateEDE_MACImpl(data, kd);
evt.addMessage(new SimpleMsg("result", "EDE-MAC", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public SecureDESKey translateKeyFromOldLMK (SecureDESKey kd) throws SMException {
SimpleMsg[] cmdParameters = {
new SimpleMsg("parameter", "Key under old LMK", kd)
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Translate Key from old to new LMK", cmdParameters));
SecureDESKey result = null;
try {
result = translateKeyFromOldLMKImpl(kd);
evt.addMessage(new SimpleMsg("result", "Translated Key under new LMK", result));
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
return result;
}
public void eraseOldLMK () throws SMException {
SimpleMsg[] cmdParameters = {
};
LogEvent evt = new LogEvent(this, "s-m-operation");
evt.addMessage(new SimpleMsg("command", "Erase the key change storage", cmdParameters));
try {
eraseOldLMKImpl();
} catch (Exception e) {
evt.addMessage(e);
throw e instanceof SMException ? (SMException) e : new SMException(e);
} finally {
Logger.log(evt);
}
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param keyLength
* @param keyType
* @return generated key
* @throws SMException
*/
protected SecureDESKey generateKeyImpl (short keyLength, String keyType) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param kd
* @return generated Key Check Value
* @throws SMException
*/
protected byte[] generateKeyCheckValueImpl (SecureDESKey kd) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param keyLength
* @param keyType
* @param encryptedKey
* @param kek
* @return imported key
* @throws SMException
*/
protected SecureDESKey importKeyImpl (short keyLength, String keyType, byte[] encryptedKey,
SecureDESKey kek, boolean checkParity) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param key
* @param kek
* @return exported key
* @throws SMException
*/
protected byte[] exportKeyImpl (SecureDESKey key, SecureDESKey kek) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pin
* @param accountNumber
* @return encrypted PIN under LMK
* @throws SMException
*/
protected EncryptedPIN encryptPINImpl (String pin, String accountNumber) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderLmk
* @return clear pin as entered by card holder
* @throws SMException
*/
protected String decryptPINImpl (EncryptedPIN pinUnderLmk) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd1
* @param kd1
* @return imported pin
* @throws SMException
*/
protected EncryptedPIN importPINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd1
* @param kd1
* @param kd2
* @param destinationPINBlockFormat
* @return translated pin
* @throws SMException
*/
protected EncryptedPIN translatePINImpl (EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderDuk
* @param ksn
* @param bdk
* @return imported pin
* @throws SMException
*/
protected EncryptedPIN importPINImpl (EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
SecureDESKey bdk) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderDuk
* @param ksn
* @param bdk
* @param kd2
* @param destinationPINBlockFormat
* @return translated pin
* @throws SMException
*/
protected EncryptedPIN translatePINImpl (EncryptedPIN pinUnderDuk, KeySerialNumber ksn,
SecureDESKey bdk, SecureDESKey kd2, byte destinationPINBlockFormat) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderLmk
* @param kd2
* @param destinationPINBlockFormat
* @return exported pin
* @throws SMException
*/
protected EncryptedPIN exportPINImpl (EncryptedPIN pinUnderLmk, SecureDESKey kd2,
byte destinationPINBlockFormat) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param accountNumber
* @param pinLen
* @param excludes
* @return generated PIN under LMK
* @throws SMException
*/
protected EncryptedPIN generatePINImpl(String accountNumber, int pinLen, List<String> excludes) throws
SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderLMK
* @param pvkA
* @param pvkB
* @param pvkIdx
* @return PVV (VISA PIN Verification Value)
* @throws SMException
*/
protected String calculatePVVImpl(EncryptedPIN pinUnderLMK,
SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx,
List<String> excludes) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd1
* @param kd1
* @param pvkA
* @param pvkB
* @param pvkIdx
* @return PVV (VISA PIN Verification Value)
* @throws SMException
*/
protected String calculatePVVImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvkA, SecureDESKey pvkB, int pvkIdx,
List<String> excludes) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd
* @param kd
* @param pvkA
* @param pvkB
* @param pvki
* @param pvv
* @return
* @throws SMException
*/
protected boolean verifyPVVImpl(EncryptedPIN pinUnderKd, SecureDESKey kd, SecureDESKey pvkA,
SecureDESKey pvkB, int pvki, String pvv) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderLmk
* @param pvk
* @param decTab
* @param pinValData
* @param minPinLen
* @param excludes
* @return IBM PIN Offset
* @throws SMException
*/
protected String calculateIBMPINOffsetImpl(EncryptedPIN pinUnderLmk, SecureDESKey pvk,
String decTab, String pinValData, int minPinLen,
List<String> excludes) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd1
* @param kd1
* @param pvk
* @param decTab
* @param pinValData
* @param minPinLen
* @param excludes
* @return IBM PIN Offset
* @throws SMException
*/
protected String calculateIBMPINOffsetImpl(EncryptedPIN pinUnderKd1, SecureDESKey kd1,
SecureDESKey pvk, String decTab, String pinValData,
int minPinLen, List<String> excludes)
throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param pinUnderKd
* @param kd
* @param pvk
* @param offset
* @param decTab
* @param pinValData
* @param minPinLen
* @return
* @throws SMException
*/
protected boolean verifyIBMPINOffsetImpl(EncryptedPIN pinUnderKd, SecureDESKey kd
,SecureDESKey pvk, String offset, String decTab
,String pinValData, int minPinLen) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param accountNo
* @param pvk
* @param decTab
* @param pinValData
* @param minPinLen
* @param offset
* @return derived PIN under LMK
* @throws SMException
*/
protected EncryptedPIN deriveIBMPINImpl(String accountNo, SecureDESKey pvk
,String decTab, String pinValData, int minPinLen
,String offset) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param accountNo
* @param cvkA
* @param cvkB
* @param expDate
* @param serviceCode
* @return Card Verification Code/Value
* @throws SMException
*/
protected String calculateCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
Date expDate, String serviceCode) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param accountNo
* @param cvkA
* @param cvkB
* @param cvv
* @param expDate
* @param serviceCode
* @return true if CVV/CVC is falid or false if not
* @throws SMException
*/
protected boolean verifyCVVImpl(String accountNo, SecureDESKey cvkA, SecureDESKey cvkB,
String cvv, Date expDate, String serviceCode) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param accountNo
* @param imkac
* @param dcvv
* @param expDate
* @param serviceCode
* @param atc
* @param mkdm
* @return
* @throws SMException
*/
protected boolean verifydCVVImpl(String accountNo, SecureDESKey imkac, String dcvv,
Date expDate, String serviceCode, byte[] atc, MKDMethod mkdm)
throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param imkcvc3
* @param accountNo
* @param acctSeqNo
* @param atc
* @param upn
* @param data
* @param mkdm
* @param cvc3
* @return
* @throws SMException
*/
protected boolean verifyCVC3Impl(SecureDESKey imkcvc3, String accountNo, String acctSeqNo,
byte[] atc, byte[] upn, byte[] data, MKDMethod mkdm, String cvc3)
throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param mkdm
* @param skdm
* @param imkac
* @param accountNo
* @param acctSeqNo
* @param arqc
* @param atc
* @param upn
* @param transData
* @return true if ARQC/TC/AAC is falid or false if not
* @throws SMException
*/
protected boolean verifyARQCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc
,byte[] upn, byte[] transData) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param mkdm
* @param skdm
* @param imkac
* @param accountNo
* @param acctSeqNo
* @param arqc
* @param atc
* @param upn
* @param arpcMethod
* @param arc
* @param propAuthData
* @return calculated ARPC
* @throws SMException
*/
protected byte[] generateARPCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc
,byte[] upn, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param mkdm
* @param skdm
* @param imkac
* @param accountNo
* @param acctSeqNo
* @param arqc
* @param atc
* @param upn
* @param arpcMethod
* @param arc
* @param propAuthData
* @return calculated ARPC
* @throws SMException
*/
protected byte[] verifyARQCGenerateARPCImpl(MKDMethod mkdm, SKDMethod skdm, SecureDESKey imkac
,String accountNo, String acctSeqNo, byte[] arqc, byte[] atc, byte[] upn
,byte[] transData, ARPCMethod arpcMethod, byte[] arc, byte[] propAuthData)
throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param mkdm
* @param skdm
* @param imksmi
* @param accountNo
* @param acctSeqNo
* @param atc
* @param arqc
* @param data
* @return generated 8 bytes MAC
* @throws SMException
*/
protected byte[] generateSM_MACImpl(MKDMethod mkdm, SKDMethod skdm
,SecureDESKey imksmi, String accountNo, String acctSeqNo
,byte[] atc, byte[] arqc, byte[] data) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param mkdm
* @param skdm
* @param padm
* @param imksmi
* @param accountNo
* @param acctSeqNo
* @param atc
* @param arqc
* @param data
* @param currentPIN
* @param newPIN
* @param kd1
* @param imksmc
* @param imkac
* @param destinationPINBlockFormat
* @return Pair of values, encrypted PIN and 8 bytes MAC
* @throws SMException
*/
protected Pair<EncryptedPIN,byte[]> translatePINGenerateSM_MACImpl(MKDMethod mkdm
,SKDMethod skdm, PaddingMethod padm, SecureDESKey imksmi
,String accountNo, String acctSeqNo, byte[] atc, byte[] arqc
,byte[] data, EncryptedPIN currentPIN, EncryptedPIN newPIN
,SecureDESKey kd1, SecureDESKey imksmc, SecureDESKey imkac
,byte destinationPINBlockFormat) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param data
* @param kd
* @return generated CBC-MAC
* @throws SMException
*/
protected byte[] generateCBC_MACImpl (byte[] data, SecureDESKey kd) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Your SMAdapter should override this method if it has this functionality
* @param data
* @param kd
* @return generated EDE-MAC
* @throws SMException
*/
protected byte[] generateEDE_MACImpl (byte[] data, SecureDESKey kd) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
protected SecureDESKey translateKeyFromOldLMKImpl (SecureDESKey kd) throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
/**
* Erase the key change storage area of memory
*
* It is recommended that this command is used after keys stored
* by the Host have been translated from old to new LMKs.
*
* @throws SMException
*/
protected void eraseOldLMKImpl () throws SMException {
throw new SMException("Operation not supported in: " + this.getClass().getName());
}
}
|
package synthesis.mapTechnology;
import java.util.HashMap;
import java.util.Map;
public class StringGraph
{
private Map<Integer, Integer> _nodes;
public int stateNum = 0;
public StringGraph()
{
_nodes = new HashMap<Integer, Integer>();
}
public void createStringGraph()
{
StringNode n = new StringNode(stateNum);
_nodes.put(stateNum, stateNum);
stateNum++;
}
}
|
package com.serial;
import com.serial.SerialEventListener;
import com.serial.Serial;
import jssc.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class SerialConnectPanel extends JPanel {
private static class BaudRate{
public String name;
public int id;
BaudRate(String name, int id){
this.name = name;
this.id = id;
}
@Override
public String toString(){
return name;
}
}
private static BaudRate[] rates = new BaudRate[]{
new BaudRate("110 ",SerialPort.BAUDRATE_110 ),
new BaudRate("300 ",SerialPort.BAUDRATE_300 ),
new BaudRate("600 ",SerialPort.BAUDRATE_600 ),
new BaudRate("1200 ",SerialPort.BAUDRATE_1200 ),
new BaudRate("4800 ",SerialPort.BAUDRATE_4800 ),
new BaudRate("9600 ",SerialPort.BAUDRATE_9600 ),
new BaudRate("14400 ",SerialPort.BAUDRATE_14400 ),
new BaudRate("19200 ",SerialPort.BAUDRATE_19200 ),
new BaudRate("38400 ",SerialPort.BAUDRATE_38400 ),
new BaudRate("57600 ",SerialPort.BAUDRATE_57600 ),
new BaudRate("115200",SerialPort.BAUDRATE_115200 )
};
private int baudRate = Serial.BAUD;
private boolean showBaudPanel = false;
private SerialEventListener listener;
private SerialPort connectedPort = null;
private JButton refreshButton;
private JButton connectButton;
private JComboBox dropDown;
private JComboBox<BaudRate> baudSelect;
public SerialConnectPanel(SerialEventListener listener){
this.listener = listener;
refreshButton = new JButton(refreshAction);
connectButton = new JButton(connectAction);
dropDown = new JComboBox();
addSerialList(dropDown);
baudSelect = new JComboBox<BaudRate>(rates);
//if the protocol spec'd baud rate is in the list, choose it
for(int i=0; i<rates.length; i++){
if(rates[i].id == Serial.BAUD){
baudSelect.setSelectedIndex(i);
break;
}
}
baudSelect.setVisible(false);
add(refreshButton);
add(dropDown);
add(baudSelect);
add(connectButton);
setOpaque(false);
}
public void setBaudRate(int baudRate){
this.baudRate = baudRate;
}
public void showBaudSelector(boolean show){
baudSelect.setVisible(show);
}
/*
Sometimes serial port actions can block for many seconds, so connect and
disconnect are run off the UI thread. These functions control the four
states and prevent multiple port actions from racing eachother
*/
private static final String BUTTON_CONNECTING = "Connecting";
private static final String BUTTON_CONNECTED = "Disconnect";
private static final String BUTTON_DISCONNECTING = "Disabling ";
private static final String BUTTON_DISCONNECTED = " Connect ";
private boolean inProgress = false;
private void connect(){
if(inProgress){
System.err.println("Connect command issued while a change was in Progress");
return;
}
refreshButton.setEnabled(false);
dropDown.setEnabled(false);
connectButton.setEnabled(false);
connectButton.setText(BUTTON_CONNECTING);
inProgress = true;
(new Thread(connectSerial)).start();
}
private void connectDone(){
refreshButton.setEnabled(false);
dropDown.setEnabled(false);
connectButton.setEnabled(true);
connectButton.setText(BUTTON_CONNECTED);
inProgress = false;
}
private void disconnect(){
if(inProgress){
System.err.println("Connect command issued while a change was in Progress");
return;
}
refreshButton.setEnabled(false);
dropDown.setEnabled(false);
connectButton.setEnabled(false);
connectButton.setText(BUTTON_DISCONNECTING);
inProgress = true;
(new Thread(disconnectSerial)).start();
}
private void disconnectDone(){
refreshButton.setEnabled(true);
dropDown.setEnabled(true);
connectButton.setEnabled(true);
connectButton.setText(BUTTON_DISCONNECTED);
inProgress = false;
}
Action refreshAction = new AbstractAction(){
{
String text = "Refresh";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
if(inProgress) return;
dropDown.removeAllItems();
addSerialList(dropDown);
SerialConnectPanel.this.updateUI();
}
};
private void addSerialList(JComboBox box){
String[] portNames = SerialPortList.getPortNames();
for(int i = 0; i < portNames.length; i++){
box.addItem(portNames[i]);
}
}
Action connectAction = new AbstractAction(){
{
String text = BUTTON_DISCONNECTED;
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e){
if (connectedPort == null) connect();
else disconnect();
}
};
private Runnable connectSerial = new Runnable(){
public void run(){
if(dropDown.getSelectedItem() == null) return;
SerialPort serialPort = new SerialPort((String)dropDown.getSelectedItem());
try{
serialPort.openPort();
if(baudSelect.isVisible()){
baudRate = ((BaudRate)baudSelect.getSelectedItem()).id;
}
serialPort.setParams(baudRate, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
} catch(SerialPortException ex){
System.err.println(ex.getMessage());
return;
}
connectedPort = serialPort;
listener.connectionEstablished(serialPort);
connectDone();
}
};
private Runnable disconnectSerial = new Runnable(){
public void run(){
listener.disconnectRequest();
try{
connectedPort.closePort();
} catch (Exception e) {
e.printStackTrace();
}
connectedPort = null;
disconnectDone();
}
};
}
|
package org.pentaho.di.ui.spoon.job;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.dnd.DragAndDropContainer;
import org.pentaho.di.core.dnd.XMLTransfer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.gui.GUIPositionInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.Redrawable;
import org.pentaho.di.core.gui.SnapAllignDistribute;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobHopMeta;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.job.JobEntryJob;
import org.pentaho.di.job.entries.trans.JobEntryTrans;
import org.pentaho.di.job.entry.JobEntryCopy;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.XulHelper;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.TabMapEntry;
import org.pentaho.di.ui.spoon.TransPainter;
import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox;
import org.pentaho.xul.menu.XulMenu;
import org.pentaho.xul.menu.XulMenuChoice;
import org.pentaho.xul.menu.XulPopupMenu;
import org.pentaho.xul.swt.tab.TabItem;
public class JobGraph extends Composite implements Redrawable, TabItemInterface
{
private static final int HOP_SEL_MARGIN = 9;
protected Shell shell;
protected Canvas canvas;
protected LogWriter log;
protected JobMeta jobMeta;
// protected Props props;
protected int iconsize;
protected int linewidth;
protected Point lastclick;
protected JobEntryCopy selected_entries[];
protected JobEntryCopy selected_icon;
protected Point prev_locations[];
protected NotePadMeta selected_note;
protected Point previous_note_location;
protected Point lastMove;
protected JobHopMeta hop_candidate;
protected Point drop_candidate;
protected Spoon spoon;
protected Point offset, iconoffset, noteoffset;
protected ScrollBar hori;
protected ScrollBar vert;
// public boolean shift, control;
protected boolean split_hop;
protected int last_button;
protected JobHopMeta last_hop_split;
protected Rectangle selrect;
protected static final double theta = Math.toRadians(10); // arrowhead sharpness
protected static final int size = 30; // arrowhead length
protected int shadowsize;
protected static Map<String,org.pentaho.xul.swt.menu.Menu> menuMap = new HashMap<String,org.pentaho.xul.swt.menu.Menu>();
protected int currentMouseX = 0;
protected int currentMouseY = 0;
protected JobEntryCopy jobEntry;
protected NotePadMeta ni = null;
protected JobHopMeta currentHop;
public JobGraph(Composite par, final Spoon spoon, final JobMeta jobMeta)
{
super(par, SWT.NONE);
shell = par.getShell();
this.log = LogWriter.getInstance();
this.spoon = spoon;
this.jobMeta = jobMeta;
// this.props = Props.getInstance();
try {
menuMap = XulHelper.createPopupMenus(SpoonInterface.XUL_FILE_MENUS, shell,new XulMessages(), "job-graph-hop",
"job-graph-note","job-graph-background","job-graph-entry" );
} catch (Throwable t ) {
log.logError(toString(), Const.getStackTracker(t));
new ErrorDialog(shell, Messages.getString("JobGraph.Exception.ErrorReadingXULFile.Title"), Messages.getString("JobGraph.Exception.ErrorReadingXULFile.Message", Spoon.XUL_FILE_MENUS), new Exception(t));
}
setLayout(new FillLayout());
canvas = new Canvas(this, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND);
newProps();
selrect = null;
hop_candidate = null;
last_hop_split = null;
selected_entries = null;
selected_note = null;
hori = canvas.getHorizontalBar();
vert = canvas.getVerticalBar();
hori.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
vert.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
hori.setThumb(100);
vert.setThumb(100);
hori.setVisible(true);
vert.setVisible(true);
setVisible(true);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
JobGraph.this.paintControl(e);
}
});
selected_entries = null;
lastclick = null;
canvas.addMouseListener(new MouseAdapter()
{
public void mouseDoubleClick(MouseEvent e)
{
clearSettings();
Point real = screen2real(e.x, e.y);
JobEntryCopy jobentry = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (jobentry != null)
{
if (e.button==1)
{
editEntry(jobentry);
}
else // open tab in Spoon
{
launchStuff(jobentry);
}
}
else
{
// Check if point lies on one of the many hop-lines...
JobHopMeta online = findJobHop(real.x, real.y);
if (online != null)
{
// editJobHop(online);
}
else
{
NotePadMeta ni = jobMeta.getNote(real.x, real.y);
if (ni!=null)
{
editNote(ni);
}
}
}
}
public void mouseDown(MouseEvent e)
{
clearSettings();
last_button = e.button;
Point real = screen2real(e.x, e.y);
lastclick = new Point(real.x, real.y);
// Clear the tooltip!
if (spoon.getProperties().showToolTips())
setToolTipText(null);
// Set the pop-up menu
if (e.button==3)
{
setMenu(real.x, real.y);
return;
}
JobEntryCopy je = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (je != null)
{
selected_entries = jobMeta.getSelectedEntries();
selected_icon = je;
// make sure this is correct!!!
// When an icon is moved that is not selected, it gets selected too late.
// It is not captured here, but in the mouseMoveListener...
prev_locations = jobMeta.getSelectedLocations();
Point p = je.getLocation();
iconoffset = new Point(real.x - p.x, real.y - p.y);
}
else
{
// Dit we hit a note?
NotePadMeta ni = jobMeta.getNote(real.x, real.y);
if (ni!=null && last_button == 1)
{
selected_note = ni;
Point loc = ni.getLocation();
previous_note_location = new Point(loc.x, loc.y);
noteoffset = new Point(real.x - loc.x, real.y - loc.y);
// System.out.println("We hit a note!!");
}
else
{
selrect = new Rectangle(real.x, real.y, 0, 0);
}
}
redraw();
}
public void mouseUp(MouseEvent e)
{
boolean control = (e.stateMask & SWT.CONTROL) != 0;
if (iconoffset==null) iconoffset=new Point(0,0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
// See if we need to add a hop...
if (hop_candidate != null)
{
// hop doesn't already exist
if (jobMeta.findJobHop(hop_candidate.from_entry, hop_candidate.to_entry) == null)
{
if (!hop_candidate.from_entry.evaluates() && hop_candidate.from_entry.isUnconditional())
{
hop_candidate.setUnconditional();
}
else
{
hop_candidate.setConditional();
int nr = jobMeta.findNrNextJobEntries(hop_candidate.from_entry);
// If there is one green link: make this one red! (or vice-versa)
if (nr == 1)
{
JobEntryCopy jge = jobMeta.findNextJobEntry(hop_candidate.from_entry, 0);
JobHopMeta other = jobMeta.findJobHop(hop_candidate.from_entry, jge);
if (other != null)
{
hop_candidate.setEvaluation(!other.getEvaluation());
}
}
}
jobMeta.addJobHop(hop_candidate);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { hop_candidate }, new int[] { jobMeta.indexOfJobHop(hop_candidate) } );
spoon.refreshTree();
}
hop_candidate = null;
selected_entries = null;
last_button = 0;
redraw();
}
// Did we select a region on the screen?
else if (selrect != null)
{
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
jobMeta.unselectAll();
selectInRect(jobMeta,selrect);
selrect = null;
redraw();
}
// Clicked on an icon?
else if (selected_icon != null)
{
if (e.button == 1)
{
if (lastclick.x == real.x && lastclick.y == real.y)
{
// Flip selection when control is pressed!
if (control)
{
selected_icon.flipSelected();
}
else
{
// Otherwise, select only the icon clicked on!
jobMeta.unselectAll();
selected_icon.setSelected(true);
}
}
else // We moved around some items: store undo info...
if (selected_entries != null && prev_locations != null)
{
int indexes[] = jobMeta.getEntryIndexes(selected_entries);
spoon.addUndoPosition(jobMeta, selected_entries, indexes, prev_locations, jobMeta.getSelectedLocations());
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if (split_hop)
{
JobHopMeta hi = findJobHop(icon.x + iconsize / 2, icon.y + iconsize / 2);
if (hi != null)
{
int id = 0;
if (!spoon.props.getAutoSplit())
{
MessageDialogWithToggle md = new MessageDialogWithToggle(shell,
Messages.getString("JobGraph.Dialog.SplitHop.Title"),
null,
Messages.getString("JobGraph.Dialog.SplitHop.Message")+Const.CR+hi.from_entry.getName()+" --> "+hi.to_entry.getName(),
MessageDialog.QUESTION,
new String[] { Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") },
0,
Messages.getString("JobGraph.Dialog.SplitHop.Toggle"),
spoon.props.getAutoSplit()
);
id = md.open();
spoon.props.setAutoSplit(md.getToggleState());
}
if ( (id&0xFF) == 0)
{
JobHopMeta newhop1 = new JobHopMeta(hi.from_entry, selected_icon);
jobMeta.addJobHop(newhop1);
JobHopMeta newhop2 = new JobHopMeta(selected_icon, hi.to_entry);
jobMeta.addJobHop(newhop2);
if (!selected_icon.evaluates()) newhop2.setUnconditional();
spoon.addUndoNew(jobMeta, new JobHopMeta[] { (JobHopMeta)newhop1.clone(), (JobHopMeta)newhop2.clone() }, new int[] { jobMeta.indexOfJobHop(newhop1), jobMeta.indexOfJobHop(newhop2)});
int idx = jobMeta.indexOfJobHop(hi);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] { (JobHopMeta)hi.clone() }, new int[] { idx });
jobMeta.removeJobHop(idx);
spoon.refreshTree();
}
}
split_hop = false;
}
selected_entries = null;
redraw();
}
// Notes?
else if (selected_note != null)
{
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
if (last_button == 1)
{
if (lastclick.x != real.x || lastclick.y != real.y)
{
int indexes[] = new int[] { jobMeta.indexOfNote(selected_note) };
spoon.addUndoPosition(jobMeta, new NotePadMeta[] { selected_note }, indexes, new Point[] { previous_note_location }, new Point[] { note });
}
}
selected_note = null;
}
}
});
canvas.addMouseMoveListener(new MouseMoveListener()
{
public void mouseMove(MouseEvent e)
{
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
// Remember the last position of the mouse for paste with keyboard
lastMove = new Point(e.x, e.y);
if (iconoffset==null) iconoffset=new Point(0,0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
setToolTip(real.x, real.y);
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should unselect all other icons,
// selected and move only the one icon
if (selected_icon != null && !selected_icon.isSelected())
{
jobMeta.unselectAll();
selected_icon.setSelected(true);
selected_entries = new JobEntryCopy[] { selected_icon };
prev_locations = new Point[] { selected_icon.getLocation()};
}
// Did we select a region...?
if (selrect != null)
{
selrect.width = real.x - selrect.x;
selrect.height = real.y - selrect.y;
redraw();
}
else
// Or just one entry on the screen?
if (selected_entries != null)
{
if (last_button == 1 && !shift)
{
/*
* One or more icons are selected and moved around...
*
* new : new position of the ICON (not the mouse pointer)
* dx : difference with previous position
*/
int dx = icon.x - selected_icon.getLocation().x;
int dy = icon.y - selected_icon.getLocation().y;
JobHopMeta hi =findJobHop(icon.x+iconsize/2, icon.y+iconsize/2);
if (hi != null)
{
//log.logBasic("MouseMove", "Split hop candidate B!");
if (!jobMeta.isEntryUsedInHops(selected_icon))
{
//log.logBasic("MouseMove", "Split hop candidate A!");
split_hop = true;
last_hop_split = hi;
hi.setSplit(true);
}
}
else
{
if (last_hop_split != null)
{
last_hop_split.setSplit(false);
last_hop_split = null;
split_hop = false;
}
}
// One or more job entries are being moved around!
for (int i = 0; i < jobMeta.nrJobEntries(); i++)
{
JobEntryCopy je = jobMeta.getJobEntry(i);
if (je.isSelected())
{
je.setLocation(je.getLocation().x + dx, je.getLocation().y + dy);
}
}
// selected_icon.setLocation(icon.x, icon.y);
redraw();
}
else
// The middle button perhaps?
if (last_button == 2 || (last_button == 1 && shift))
{
JobEntryCopy si = jobMeta.getJobEntryCopy(real.x, real.y, iconsize);
if (si != null && !selected_icon.equals(si))
{
if (hop_candidate == null)
{
hop_candidate = new JobHopMeta(selected_icon, si);
redraw();
}
}
else
{
if (hop_candidate != null)
{
hop_candidate = null;
redraw();
}
}
}
}
else
// are we moving a note around?
if (selected_note!=null)
{
if (last_button==1)
{
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
selected_note.setLocation(note.x, note.y);
redraw();
//spoon.refreshGraph(); removed in 2.4.1 (SB: defect #4862)
}
}
}
});
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
drop_candidate = getRealPosition(canvas, event.x, event.y);
redraw();
}
public void dragLeave(DropTargetEvent event)
{
drop_candidate = null;
redraw();
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
drop_candidate = getRealPosition(canvas, event.x, event.y);
redraw();
}
public void drop(DropTargetEvent event)
{
// no data to copy, indicate failure in event.detail
if (event.data == null)
{
event.detail = DND.DROP_NONE;
return;
}
Point p = getRealPosition(canvas, event.x, event.y);
try
{
DragAndDropContainer container = (DragAndDropContainer)event.data;
String entry = container.getData();
switch(container.getType())
{
case DragAndDropContainer.TYPE_BASE_JOB_ENTRY: // Create a new Job Entry on the canvas
{
JobEntryCopy jge = spoon.newJobEntry(jobMeta, entry, false);
if (jge != null)
{
jge.setLocation(p.x, p.y);
jge.setDrawn();
redraw();
}
}
break;
case DragAndDropContainer.TYPE_JOB_ENTRY: // Drag existing one onto the canvas
{
JobEntryCopy jge = jobMeta.findJobEntry(entry, 0, true);
if (jge != null) // Create duplicate of existing entry
{
// There can be only 1 start!
if (jge.isStart() && jge.isDrawn())
{
showOnlyStartOnceMessage(shell);
return;
}
boolean jge_changed=false;
// For undo :
JobEntryCopy before = (JobEntryCopy)jge.clone_deep();
JobEntryCopy newjge = jge;
if (jge.isDrawn())
{
newjge = (JobEntryCopy)jge.clone();
if (newjge!=null)
{
// newjge.setEntry(jge.getEntry());
log.logDebug(toString(), "entry aft = "+((Object)jge.getEntry()).toString()); //$NON-NLS-1$
newjge.setNr(jobMeta.findUnusedNr(newjge.getName()));
jobMeta.addJobEntry(newjge);
spoon.addUndoNew(jobMeta, new JobEntryCopy[] {newjge}, new int[] { jobMeta.indexOfJobEntry(newjge)} );
}
else
{
log.logDebug(toString(), "jge is not cloned!"); //$NON-NLS-1$
}
}
else
{
log.logDebug(toString(), jge.toString()+" is not drawn"); //$NON-NLS-1$
jge_changed=true;
}
newjge.setLocation(p.x, p.y);
newjge.setDrawn();
if (jge_changed)
{
spoon.addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] {newjge}, new int[] { jobMeta.indexOfJobEntry(newjge)});
}
redraw();
spoon.refreshTree();
log.logBasic("DropTargetEvent", "DROP "+newjge.toString()+"!, type="+ JobEntryCopy.getTypeDesc(newjge.getEntry()));
}
else
{
log.logError(toString(), "Unknown job entry dropped onto the canvas.");
}
}
break;
default: break;
}
}
catch(Exception e)
{
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorDroppingObject.Message"), Messages.getString("JobGraph.Dialog.ErrorDroppingObject.Title"), e);
}
}
public void dropAccept(DropTargetEvent event)
{
drop_candidate = null;
}
});
// Keyboard shortcuts...
canvas.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
// F2 --> rename Job entry
if (e.keyCode == SWT.F2)
{
renameJobEntry();
}
/*
if (e.character == 3) // CTRL-C
{
copyEntry();
}
if (e.character == 22) // CTRL-V
{
String clipcontent = spoon.fromClipboard();
if (clipcontent != null)
{
if (lastMove != null)
{
spoon.pasteXML(jobMeta, clipcontent, lastMove);
}
}
//spoon.pasteSteps( );
}
if (e.keyCode == SWT.ESC)
{
jobMeta.unselectAll();
redraw();
}
*/
// Delete
if (e.keyCode == SWT.DEL)
{
JobEntryCopy copies[] = jobMeta.getSelectedEntries();
if (copies != null && copies.length > 0)
{
delSelected();
}
}
// CTRL-UP : allignTop();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0)
{
alligntop();
}
// CTRL-DOWN : allignBottom();
if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0)
{
allignbottom();
}
// CTRL-LEFT : allignleft();
if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0)
{
allignleft();
}
// CTRL-RIGHT : allignRight();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0)
{
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0)
{
distributehorizontal();
}
// ALT-UP : distributeVertical();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0)
{
distributevertical();
}
// ALT-HOME : snap to grid
if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0)
{
snaptogrid(ConstUI.GRID_SIZE);
}
}
});
canvas.addKeyListener(spoon.defKeys);
setBackground(GUIResource.getInstance().getColorBackground());
}
public void selectInRect(JobMeta jobMeta, Rectangle rect)
{
int i;
for (i = 0; i < jobMeta.nrJobEntries(); i++)
{
JobEntryCopy je = jobMeta.getJobEntry(i);
Point p = je.getLocation();
if (((p.x >= rect.x && p.x <= rect.x + rect.width) || (p.x >= rect.x + rect.width && p.x <= rect.x))
&& ((p.y >= rect.y && p.y <= rect.y + rect.height) || (p.y >= rect.y + rect.height && p.y <= rect.y))) je.setSelected(true);
}
}
public void redraw()
{
canvas.redraw();
}
public boolean forceFocus()
{
return canvas.forceFocus();
}
public boolean setFocus()
{
return canvas.setFocus();
}
public void renameJobEntry()
{
JobEntryCopy[] selection = jobMeta.getSelectedEntries();
if (selection!=null && selection.length==1)
{
final JobEntryCopy jobEntryMeta = selection[0];
// What is the location of the step?
final String name = jobEntryMeta.getName();
Point stepLocation = jobEntryMeta.getLocation();
Point realStepLocation = real2screen(stepLocation.x, stepLocation.y);
// The location of the step name?
GC gc = new GC(shell.getDisplay());
gc.setFont(GUIResource.getInstance().getFontGraph());
Point namePosition = TransPainter.getNamePosition(gc, name, realStepLocation, iconsize);
int width = gc.textExtent(name).x + 30;
gc.dispose();
// at this very point, create a new text widget...
final Text text = new Text(this, SWT.SINGLE | SWT.BORDER);
text.setText(name);
FormData fdText = new FormData();
fdText.left = new FormAttachment(0, namePosition.x);
fdText.right= new FormAttachment(0, namePosition.x+width);
fdText.top = new FormAttachment(0, namePosition.y);
text.setLayoutData(fdText);
// Add a listener!
// Catch the keys pressed when editing a Text-field...
KeyListener lsKeyText = new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
// "ENTER": close the text editor and copy the data over
if (e.character == SWT.CR)
{
String newName = text.getText();
text.dispose();
if (!name.equals(newName))
renameJobEntry(jobEntryMeta, newName);
}
if (e.keyCode == SWT.ESC)
{
text.dispose();
}
}
};
text.addKeyListener(lsKeyText);
text.addFocusListener(new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
String newName = text.getText();
text.dispose();
if (!name.equals(newName))
renameJobEntry(jobEntryMeta, newName);
}
}
);
this.layout(true, true);
text.setFocus();
text.setSelection(0, name.length());
}
}
/**
* Method gets called, when the user wants to change a job entries name and he indeed entered
* a different name then the old one. Make sure that no other job entry matches this name
* and rename in case of uniqueness.
*
* @param jobEntry
* @param newName
*/
public void renameJobEntry(JobEntryCopy jobEntry, String newName)
{
JobEntryCopy[] jobs = jobMeta.getAllJobGraphEntries(newName);
if (jobs != null && jobs.length > 0)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryNameExists.Message", newName));
mb.setText(Messages.getString("Spoon.Dialog.JobEntryNameExists.Title"));
mb.open();
}
else
{
jobEntry.setName(newName);
jobEntry.setChanged();
spoon.refreshTree(); // to reflect the new name
spoon.refreshGraph();
}
}
public static void showOnlyStartOnceMessage(Shell shell)
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(Messages.getString("JobGraph.Dialog.OnlyUseStartOnce.Message"));
mb.setText(Messages.getString("JobGraph.Dialog.OnlyUseStartOnce.Title"));
mb.open();
}
public void delSelected()
{
JobEntryCopy[] copies = jobMeta.getSelectedEntries();
int nrsels = copies.length;
if (nrsels==0) return;
// Load the list of steps
List<String> stepList = new ArrayList<String>();
for (int i = 0; i < copies.length; ++i) {
stepList.add(copies[i].toString());
}
// Display the delete confirmation message box
MessageBox mb = new DeleteMessageBox(shell,
Messages.getString("Spoon.Dialog.DeletionConfirm.Message"), //$NON-NLS-1$
stepList
);
int answer = mb.open();
if (answer==SWT.YES)
{
// Perform the delete
for (int i=0;i<copies.length;i++)
{
spoon.deleteJobEntryCopies(jobMeta, copies[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
}
public void clearSettings()
{
selected_icon = null;
selected_note = null;
selected_entries = null;
selrect = null;
hop_candidate = null;
last_hop_split = null;
last_button = 0;
iconoffset = null;
for (int i = 0; i < jobMeta.nrJobHops(); i++)
jobMeta.getJobHop(i).setSplit(false);
}
public Point screen2real(int x, int y)
{
getOffset();
Point real;
if (offset != null)
{
real = new Point(x - offset.x, y - offset.y);
}
else
{
real = new Point(x, y);
}
return real;
}
public Point real2screen(int x, int y)
{
getOffset();
Point screen = new Point(x+offset.x, y+offset.y);
return screen;
}
public Point getRealPosition(Composite canvas, int x, int y)
{
Point p = new Point(0, 0);
Composite follow = canvas;
while (follow != null)
{
Point xy = new Point(follow.getLocation().x, follow.getLocation().y);
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
p.x = x - p.x - 8;
p.y = y - p.y - 48;
return screen2real(p.x, p.y);
}
// See if location (x,y) is on a line between two steps: the hop!
// return the HopInfo if so, otherwise: null
protected JobHopMeta findJobHop(int x, int y)
{
int i;
JobHopMeta online = null;
for (i = 0; i < jobMeta.nrJobHops(); i++)
{
JobHopMeta hi = jobMeta.getJobHop(i);
int line[] = getLine(hi.from_entry, hi.to_entry);
if (line!=null && pointOnLine(x, y, line)) online = hi;
}
return online;
}
protected int[] getLine(JobEntryCopy fs, JobEntryCopy ts)
{
if (fs==null || ts==null) return null;
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
public void setJobEntry( JobEntryCopy jobEntry ) {
this.jobEntry = jobEntry;
}
public JobEntryCopy getJobEntry( ) {
return jobEntry;
}
public void openTransformation()
{
final JobEntryInterface entry = getJobEntry().getEntry();
openTransformation((JobEntryTrans) entry );
}
public void launchChef() {
final JobEntryInterface entry = getJobEntry().getEntry();
launchChef( (JobEntryJob) entry );
}
public void newHopClick()
{
selected_entries = null;
newHop();
}
public void editEntryClick()
{
selected_entries = null;
editEntry(getJobEntry());
}
public void editEntryDescription()
{
String title = Messages.getString("JobGraph.Dialog.EditDescription.Title"); //$NON-NLS-1$
String message = Messages.getString("JobGraph.Dialog.EditDescription.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, getJobEntry().getDescription());
String des = dd.open();
if (des != null) jobEntry.setDescription(des);
}
public void duplicateEntry() throws KettleException
{
if (!canDup(jobEntry))
{
JobGraph.showOnlyStartOnceMessage(spoon.getShell());
}
spoon.delegates.jobs.dupeJobEntry(jobMeta, jobEntry);
}
public void copyEntry()
{
JobEntryCopy[] entries = jobMeta.getSelectedEntries();
for (int i=0;i<entries.length;i++)
{
if(!canDup(entries[i]))
entries[i] = null;
}
spoon.delegates.jobs.copyJobEntries(jobMeta, entries);
}
private boolean canDup(JobEntryCopy entry)
{
return !entry.isStart();
}
public void detatchEntry()
{
detach(getJobEntry());
jobMeta.unselectAll();
}
public void hideEntry()
{
getJobEntry().setDrawn(false);
// nr > 1: delete
if (jobEntry.getNr() > 0)
{
int ind = jobMeta.indexOfJobEntry(jobEntry);
jobMeta.removeJobEntry(ind);
spoon.addUndoDelete(jobMeta, new JobEntryCopy[] {getJobEntry()}, new int[] {ind});
}
redraw();
}
public void deleteEntry()
{
spoon.deleteJobEntryCopies(jobMeta, getJobEntry());
redraw();
}
protected void setMenu(int x, int y)
{
currentMouseX = x;
currentMouseY = y;
final JobEntryCopy jobEntry = jobMeta.getJobEntryCopy(x, y, iconsize);
setJobEntry( jobEntry );
if (jobEntry != null) // We clicked on a Job Entry!
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get( "job-graph-entry" ); //$NON-NLS-1$
if( menu != null ) {
int sels = jobMeta.nrSelected();
XulMenuChoice item = menu.getMenuItemById( "job-graph-entry-newhop" ); //$NON-NLS-1$
menu.addMenuListener( "job-graph-entry-newhop", this, JobGraph.class, "newHopClick" ); //$NON-NLS-1$ //$NON-NLS-2$
item.setEnabled( sels == 2 );
item = menu.getMenuItemById( "job-graph-entry-launch" ); //$NON-NLS-1$
switch(jobEntry.getJobEntryType())
{
case TRANS:
{
item.setEnabled(true);
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.LaunchSpoon"));
menu.addMenuListener( "job-graph-entry-launch", this, "openTransformation" ); //$NON-NLS-1$ //$NON-NLS-2$
break;
}
case JOB:
{
item.setEnabled(true);
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.LaunchChef"));
menu.addMenuListener( "job-graph-entry-launch", this, "launchChef" ); //$NON-NLS-1$ //$NON-NLS-2$
}
break;
default:
{
item.setEnabled(false);
}
break;
}
item = menu.getMenuItemById( "job-graph-entry-align-snap" ); //$NON-NLS-1$
item.setText(Messages.getString("JobGraph.PopupMenu.JobEntry.AllignDistribute.SnapToGrid") + ConstUI.GRID_SIZE + ")\tALT-HOME");
XulMenu aMenu = menu.getMenuById( "job-graph-entry-align" ); //$NON-NLS-1$
if( aMenu != null ) {
aMenu.setEnabled( sels > 1 );
}
item = menu.getMenuItemById( "job-graph-entry-detach" ); //$NON-NLS-1$
if( item != null ) {
item.setEnabled( jobMeta.isEntryUsedInHops(jobEntry) );
}
item = menu.getMenuItemById( "job-graph-entry-hide" ); //$NON-NLS-1$
if( item != null ) {
item.setEnabled( jobEntry.isDrawn() && !jobMeta.isEntryUsedInHops(jobEntry) );
}
item = menu.getMenuItemById( "job-graph-entry-delete" ); //$NON-NLS-1$
if( item != null ) {
item.setEnabled( jobEntry.isDrawn() );
}
menu.addMenuListener( "job-graph-entry-align-left", this, "allignleft" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-right", this, "allignright" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-top", this, "alligntop" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-bottom", this, "allignbottom" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-horz", this, "distributehorizontal" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-vert", this, "distributevertical" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-align-snap", this, "snaptogrid" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-edit", this, "editEntryClick" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-edit-description", this, "editEntryDescription" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-duplicate", this, "duplicateEntry" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-copy", this, "copyEntry" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-detach", this, "detatchEntry" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-hide", this, "hideEntry" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-entry-delete", this, "deleteEntry" ); //$NON-NLS-1$ //$NON-NLS-2$
canvas.setMenu((Menu)menu.getNativeObject());
}
}
else // Clear the menu
{
final JobHopMeta hi = findJobHop(x, y);
setCurrentHop( hi );
if (hi != null) // We clicked on a HOP!
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get( "job-graph-hop" ); //$NON-NLS-1$
if( menu != null ) {
XulMenuChoice miPopEvalUncond = menu.getMenuItemById( "job-graph-hop-evaluation-uncond" ); //$NON-NLS-1$
XulMenuChoice miPopEvalTrue = menu.getMenuItemById( "job-graph-hop-evaluation-true" ); //$NON-NLS-1$
XulMenuChoice miPopEvalFalse = menu.getMenuItemById( "job-graph-hop-evaluation-false" ); //$NON-NLS-1$
XulMenuChoice miDisHop = menu.getMenuItemById( "job-graph-hop-enabled" ); //$NON-NLS-1$
menu.addMenuListener( "job-graph-hop-evaluation-uncond", this, "setHopConditional" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-hop-evaluation-true", this, "setHopConditional" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-hop-evaluation-false", this, "setHopConditional" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-hop-flip", this, "flipHop" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-hop-enabled", this, "disableHop" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-hop-delete", this, "deleteHop" ); //$NON-NLS-1$ //$NON-NLS-2$
if (hi.isUnconditional())
{
if(miPopEvalUncond != null) miPopEvalUncond.setChecked(true);
if(miPopEvalTrue != null) miPopEvalTrue.setChecked(false);
if(miPopEvalFalse != null) miPopEvalFalse.setChecked(false);
}
else
{
if (hi.getEvaluation())
{
if(miPopEvalUncond != null) miPopEvalUncond.setChecked(false);
if(miPopEvalTrue != null) miPopEvalTrue.setChecked(true);
if(miPopEvalFalse != null) miPopEvalFalse.setChecked(false);
}
else
{
if(miPopEvalUncond != null) miPopEvalUncond.setChecked(false);
if(miPopEvalTrue != null) miPopEvalTrue.setChecked(false);
if(miPopEvalFalse != null) miPopEvalFalse.setChecked(true);
}
}
if (!hi.from_entry.evaluates())
{
if(miPopEvalTrue != null) miPopEvalTrue.setEnabled(false);
if(miPopEvalFalse != null) miPopEvalFalse.setEnabled(false);
}
if (!hi.from_entry.isUnconditional())
{
if(miPopEvalUncond != null) miPopEvalUncond.setEnabled(false);
}
if( miDisHop != null ) {
if (hi.isEnabled()) miDisHop.setText(Messages.getString("JobGraph.PopupMenu.Hop.Disable")); //$NON-NLS-1$
else miDisHop.setText(Messages.getString("JobGraph.PopupMenu.Hop.Enable")); //$NON-NLS-1$
}
canvas.setMenu((Menu)menu.getNativeObject());
}
}
else
{
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = jobMeta.getNote(x, y);
setCurrentNote( ni );
if (ni!=null)
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get( "job-graph-note" ); //$NON-NLS-1$
if( menu != null ) {
menu.addMenuListener( "job-graph-note-edit", this, "editNote" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-note-delete", this, "deleteNote" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-note-raise", this, "raiseNote" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-note-lower", this, "lowerNote" ); //$NON-NLS-1$ //$NON-NLS-2$
canvas.setMenu((Menu)menu.getNativeObject());
}
}
else
{
XulPopupMenu menu = (XulPopupMenu) menuMap.get( "job-graph-background" ); //$NON-NLS-1$
if( menu != null ) {
menu.addMenuListener( "job-graph-note-new", this, "newNote" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-note-paste", this, "pasteNote" ); //$NON-NLS-1$ //$NON-NLS-2$
menu.addMenuListener( "job-graph-background-settings", this, "editJobProperties" ); //$NON-NLS-1$ //$NON-NLS-2$
final String clipcontent = spoon.fromClipboard();
XulMenuChoice item = menu.getMenuItemById( "job-graph-note-paste" ); //$NON-NLS-1$
if( item != null ) {
item.setEnabled( clipcontent != null );
}
canvas.setMenu((Menu)menu.getNativeObject());
}
}
}
}
}
public void editJobProperties() {
editProperties(jobMeta, spoon, spoon.getRepository(), true);
}
public void pasteNote() {
final String clipcontent = spoon.fromClipboard();
Point loc = new Point(currentMouseX, currentMouseY);
spoon.pasteXML(jobMeta, clipcontent, loc);
}
public void newNote()
{
selrect=null;
String title = Messages.getString("JobGraph.Dialog.EditNote.Title");
String message = Messages.getString("JobGraph.Dialog.EditNote.Message");
EnterTextDialog dd = new EnterTextDialog(shell, title, message, "");
String n = dd.open();
if (n!=null)
{
NotePadMeta npi = new NotePadMeta(n, lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE);
jobMeta.addNote(npi);
spoon.addUndoNew(jobMeta, new NotePadMeta[] {npi}, new int[] { jobMeta.indexOfNote(npi)} );
redraw();
}
}
public void setCurrentNote( NotePadMeta ni ) {
this.ni = ni;
}
public NotePadMeta getCurrentNote() {
return ni;
}
public void editNote() {
selrect=null;
editNote( getCurrentNote() );
}
public void deleteNote() {
selrect=null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx>=0)
{
jobMeta.removeNote(idx);
spoon.addUndoDelete(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void raiseNote()
{
selrect=null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx>=0)
{
jobMeta.raiseNote(idx);
//spoon.addUndoRaise(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void lowerNote()
{
selrect=null;
int idx = jobMeta.indexOfNote(getCurrentNote());
if (idx>=0)
{
jobMeta.lowerNote(idx);
//spoon.addUndoLower(jobMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void flipHop()
{
selrect = null;
JobEntryCopy dummy = currentHop.from_entry;
currentHop.from_entry = currentHop.to_entry;
currentHop.to_entry = dummy;
if (jobMeta.hasLoop(currentHop.from_entry))
{
spoon.refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(Messages.getString("JobGraph.Dialog.HopFlipCausesLoop.Message"));
mb.setText(Messages.getString("JobGraph.Dialog.HopFlipCausesLoop.Title"));
mb.open();
dummy = currentHop.from_entry;
currentHop.from_entry = currentHop.to_entry;
currentHop.to_entry = dummy;
spoon.refreshGraph();
}
else
{
currentHop.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void disableHop()
{
selrect = null;
currentHop.setEnabled(!currentHop.isEnabled());
spoon.refreshGraph();
spoon.refreshTree();
}
public void deleteHop()
{
selrect = null;
int idx = jobMeta.indexOfJobHop(currentHop);
jobMeta.removeJobHop(idx);
spoon.refreshTree();
spoon.refreshGraph();
}
public void setHopConditional( String id ) {
if( "job-graph-hop-evaluation-uncond".equals( id ) ) { //$NON-NLS-1$
currentHop.setUnconditional();
spoon.refreshGraph();
}
else if( "job-graph-hop-evaluation-true".equals( id ) ) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(true);
spoon.refreshGraph();
}
else if( "job-graph-hop-evaluation-false".equals( id ) ) { //$NON-NLS-1$
currentHop.setConditional();
currentHop.setEvaluation(false);
spoon.refreshGraph();
}
}
protected void setCurrentHop( JobHopMeta hop ) {
currentHop = hop;
}
protected JobHopMeta getCurrentHop( ) {
return currentHop;
}
protected void setToolTip(int x, int y)
{
if (!spoon.getProperties().showToolTips())
return;
String newTip=null;
final JobEntryCopy je = jobMeta.getJobEntryCopy(x, y, iconsize);
if (je != null && je.isDrawn()) // We hover above a Step!
{
// Set the tooltip!
String desc = je.getDescription();
if (desc != null)
{
int le = desc.length() >= 200 ? 200 : desc.length();
newTip = desc.substring(0, le);
}
else
{
newTip = je.toString();
}
}
else
{
offset = getOffset();
JobHopMeta hi = findJobHop(x + offset.x, y + offset.x);
if (hi != null)
{
newTip=hi.toString();
}
else
{
newTip=null;
}
}
if (newTip==null || !newTip.equalsIgnoreCase(getToolTipText()))
{
canvas.setToolTipText(newTip);
}
}
public void launchStuff(JobEntryCopy jobentry)
{
if (jobentry.getJobEntryType()==JobEntryType.JOB)
{
final JobEntryJob entry = (JobEntryJob)jobentry.getEntry();
if ( ( entry!=null && entry.getFilename()!=null && spoon.rep==null) ||
( entry!=null && entry.getName()!=null && spoon.rep!=null)
)
{
launchChef(entry);
}
}
else
if (jobentry.getJobEntryType()==JobEntryType.TRANS)
{
final JobEntryTrans entry = (JobEntryTrans)jobentry.getEntry();
if ( ( entry!=null && entry.getFilename()!=null && spoon.rep==null) ||
( entry!=null && entry.getName()!=null && spoon.rep!=null)
)
{
openTransformation(entry);
}
}
}
protected void openTransformation(JobEntryTrans entry)
{
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename() );
String exactTransname = jobMeta.environmentSubstitute(entry.getTransname() );
// check, whether a tab of this name is already opened
TabItem tab = spoon.delegates.tabs.findTabItem(exactFilename, TabMapEntry.OBJECT_TYPE_TRANSFORMATION_GRAPH);
if (tab == null)
{
tab = spoon.delegates.tabs.findTabItem(Const.filenameOnly(exactFilename), TabMapEntry.OBJECT_TYPE_TRANSFORMATION_GRAPH);
}
if (tab != null)
{
spoon.tabfolder.setSelected(tab);
return;
}
// Load from repository?
if ( TransMeta.isRepReference(exactFilename, exactTransname) )
{
try
{
// New transformation?
long id = spoon.rep.getTransformationID(exactTransname, entry.getDirectory().getID());
TransMeta newTrans;
if (id<0) // New
{
newTrans = new TransMeta(null, exactTransname, entry.arguments);
}
else
{
newTrans = new TransMeta(spoon.rep, exactTransname, entry.getDirectory());
}
copyInternalJobVariables(jobMeta, newTrans);
spoon.addTransGraph(newTrans);
newTrans.clearChanged();
spoon.open();
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Title"), Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformation.Message"), (Exception)e);
}
}
else
{
try
{
// only try to load if the file exists...
if (Const.isEmpty(exactFilename))
{
throw new Exception(Messages.getString("JobGraph.Exception.NoFilenameSpecified"));
}
TransMeta launchTransMeta = null;
if (KettleVFS.fileExists(exactFilename))
{
launchTransMeta = new TransMeta( exactFilename );
}
else
{
launchTransMeta = new TransMeta();
}
launchTransMeta.clearChanged();
launchTransMeta.setFilename( exactFilename );
copyInternalJobVariables(jobMeta, launchTransMeta);
spoon.addTransGraph( launchTransMeta );
spoon.open();
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Title"), Messages.getString("JobGraph.Dialog.ErrorLaunchingSpoonCanNotLoadTransformationFromXML.Message"), (Exception)e);
}
}
}
public static void copyInternalJobVariables(JobMeta sourceJobMeta, TransMeta targetTransMeta) {
// Also set some internal JOB variables...
String[] internalVariables = Const.INTERNAL_JOB_VARIABLES;
for (String variableName : internalVariables)
{
targetTransMeta.setVariable(variableName, sourceJobMeta.getVariable(variableName));
}
}
public void launchChef(JobEntryJob entry)
{
String exactFilename = jobMeta.environmentSubstitute(entry.getFilename() );
String exactJobname = jobMeta.environmentSubstitute(entry.getJobName() );
// Load from repository?
if ( Const.isEmpty(exactFilename) && !Const.isEmpty(exactJobname) )
{
try
{
JobMeta newJobMeta = new JobMeta(log, spoon.rep, exactJobname, entry.getDirectory());
newJobMeta.clearChanged();
spoon.delegates.jobs.addJobGraph(newJobMeta);
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Title"), Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJob.Message"), e);
}
}
else
{
try
{
if (Const.isEmpty(exactFilename))
{
throw new Exception(Messages.getString("JobGraph.Exception.NoFilenameSpecified"));
}
JobMeta newJobMeta;
if (KettleVFS.fileExists(exactFilename))
{
newJobMeta = new JobMeta(log, exactFilename, spoon.rep, spoon);
}
else
{
newJobMeta = new JobMeta(log);
}
newJobMeta.setFilename( exactFilename );
newJobMeta.clearChanged();
spoon.delegates.jobs.addJobGraph(newJobMeta);
}
catch(Throwable e)
{
new ErrorDialog(shell, Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Title"), Messages.getString("JobGraph.Dialog.ErrorLaunchingChefCanNotLoadJobFromXML.Message"), e);
}
}
}
public void paintControl(PaintEvent e)
{
Point area = getArea();
if (area.x==0 || area.y==0) return; // nothing to do!
Display disp = shell.getDisplay();
if (disp.isDisposed()) return; // Nothing to do!
Image img = new Image(disp, area.x, area.y);
GC gc = new GC(img);
drawJob(gc, PropsUI.getInstance().isBrandingActive());
e.gc.drawImage(img, 0, 0);
gc.dispose();
img.dispose();
// spoon.setShellText();
}
public void drawJob(GC gc, boolean branded)
{
if (spoon.props.isAntiAliasingEnabled()) gc.setAntialias(SWT.ON);
shadowsize = spoon.props.getShadowSize();
gc.setBackground(GUIResource.getInstance().getColorBackground());
Point area = getArea();
Point max = jobMeta.getMaximum();
Point thumb = getThumb(area, max);
offset = getOffset(thumb, area);
hori.setThumb(thumb.x);
vert.setThumb(thumb.y);
if (branded)
{
Image gradient= GUIResource.getInstance().getImageBanner();
gc.drawImage(gradient, 0, 0);
Image logo = GUIResource.getInstance().getImageKettleLogo();
org.eclipse.swt.graphics.Rectangle logoBounds = logo.getBounds();
gc.drawImage(logo, 20, area.y-logoBounds.height);
}
// First draw the notes...
gc.setFont(GUIResource.getInstance().getFontNote());
for (int i = 0; i < jobMeta.nrNotes(); i++)
{
NotePadMeta ni = jobMeta.getNote(i);
drawNote(gc, ni);
}
gc.setFont(GUIResource.getInstance().getFontGraph());
if (shadowsize>0)
for (int j = 0; j < jobMeta.nrJobEntries(); j++)
{
JobEntryCopy cge = jobMeta.getJobEntry(j);
drawJobGraphEntryShadow(gc, cge);
}
// ... and then the rest on top of it...
for (int i = 0; i < jobMeta.nrJobHops(); i++)
{
JobHopMeta hi = jobMeta.getJobHop(i);
drawJobHop(gc, hi, false);
}
if (hop_candidate != null)
{
drawJobHop(gc, hop_candidate, true);
}
for (int j = 0; j < jobMeta.nrJobEntries(); j++)
{
JobEntryCopy je = jobMeta.getJobEntry(j);
drawJobEntryCopy(gc, je);
}
if (drop_candidate != null)
{
gc.setLineStyle(SWT.LINE_SOLID);
gc.setForeground(GUIResource.getInstance().getColorBlack());
Point screen = real2screen(drop_candidate.x, drop_candidate.y);
gc.drawRectangle(screen.x, screen.y, iconsize, iconsize);
}
drawRect(gc, selrect);
}
protected void drawJobHop(GC gc, JobHopMeta hi, boolean candidate)
{
if (hi==null || hi.from_entry==null || hi.to_entry==null) return;
if (!hi.from_entry.isDrawn() || !hi.to_entry.isDrawn()) return;
if (shadowsize>0) drawLineShadow(gc, hi);
drawLine(gc, hi, candidate);
}
public Image getIcon(JobEntryCopy je)
{
Image im=null;
if (je==null) return null;
switch (je.getJobEntryType())
{
case SPECIAL :
if (je.isStart()) im = GUIResource.getInstance().getImageStart();
if (je.isDummy()) im = GUIResource.getInstance().getImageDummy();
break;
default:
im = (Image)GUIResource.getInstance().getImagesJobentries().get(je.getEntry().getConfigId());
}
return im;
}
protected void drawJobEntryCopy(GC gc, JobEntryCopy je)
{
if (!je.isDrawn()) return;
Point pt = je.getLocation();
int x, y;
if (pt != null)
{
x = pt.x;
y = pt.y;
}
else
{
x = 50;
y = 50;
}
String name = je.getName();
if (je.isSelected()) gc.setLineWidth(3);
else gc.setLineWidth(1);
gc.setBackground(GUIResource.getInstance().getColorRed());
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.fillRectangle(offset.x + x, offset.y + y, iconsize, iconsize);
Image im = getIcon(je);
if (im != null) // Draw the icon!
{
Rectangle bounds = new Rectangle(im.getBounds().x, im.getBounds().y, im.getBounds().width, im.getBounds().height);
gc.drawImage(im, 0, 0, bounds.width, bounds.height, offset.x + x, offset.y + y, iconsize, iconsize);
}
gc.setBackground(GUIResource.getInstance().getColorWhite());
gc.drawRectangle(offset.x + x - 1, offset.y + y - 1, iconsize + 1, iconsize + 1);
//gc.setXORMode(true);
Point textsize = new Point(gc.textExtent(""+name).x, gc.textExtent(""+name).y);
gc.setBackground(GUIResource.getInstance().getColorBackground());
gc.setLineWidth(1);
int xpos = offset.x + x + (iconsize / 2) - (textsize.x / 2);
int ypos = offset.y + y + iconsize + 5;
if (shadowsize>0)
{
gc.setForeground(GUIResource.getInstance().getColorLightGray());
gc.drawText(""+name, xpos+shadowsize, ypos+shadowsize, SWT.DRAW_TRANSPARENT);
}
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(name, xpos, ypos, true);
}
protected void drawJobGraphEntryShadow(GC gc, JobEntryCopy je)
{
if (je==null) return;
if (!je.isDrawn()) return;
Point pt = je.getLocation();
int x, y;
if (pt != null) { x = pt.x; y = pt.y; } else { x = 50; y = 50; }
Point screen = real2screen(x, y);
// Draw the shadow...
gc.setBackground(GUIResource.getInstance().getColorLightGray());
gc.setForeground(GUIResource.getInstance().getColorLightGray());
int s = shadowsize;
gc.fillRectangle(screen.x + s, screen.y + s, iconsize, iconsize);
}
protected void drawNote(GC gc, NotePadMeta ni)
{
int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT;
org.eclipse.swt.graphics.Point ext = gc.textExtent(ni.getNote(), flags);
Point p = new Point(ext.x, ext.y);
Point loc = ni.getLocation();
Point note = real2screen(loc.x, loc.y);
int margin = Const.NOTE_MARGIN;
p.x += 2 * margin;
p.y += 2 * margin;
int width = ni.width;
int height = ni.height;
if (p.x > width)
width = p.x;
if (p.y > height)
height = p.y;
int noteshape[] = new int[] { note.x, note.y, // Top left
note.x + width + 2 * margin, note.y, // Top right
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x + width, note.y + height, // bottom right 3
note.x + width + 2 * margin, note.y + height, // bottom right 1
note.x + width, note.y + height + 2 * margin, // bottom right 2
note.x, note.y + height + 2 * margin // bottom left
};
int s = spoon.props.getShadowSize();
int shadow[] = new int[] { note.x+s, note.y+s, // Top left
note.x + width + 2 * margin+s, note.y+s, // Top right
note.x + width + 2 * margin+s, note.y + height+s, // bottom right 1
note.x + width+s, note.y + height + 2 * margin+s, // bottom right 2
note.x+s, note.y + height + 2 * margin+s // bottom left
};
gc.setForeground(GUIResource.getInstance().getColorLightGray());
gc.setBackground(GUIResource.getInstance().getColorLightGray());
gc.fillPolygon(shadow);
gc.setForeground(GUIResource.getInstance().getColorDarkGray());
gc.setBackground(GUIResource.getInstance().getColorYellow());
gc.fillPolygon(noteshape);
gc.drawPolygon(noteshape);
//gc.fillRectangle(ni.xloc, ni.yloc, width+2*margin, heigth+2*margin);
//gc.drawRectangle(ni.xloc, ni.yloc, width+2*margin, heigth+2*margin);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.drawText(ni.getNote(), note.x + margin, note.y + margin, flags);
ni.width = width; // Save for the "mouse" later on...
ni.height = height;
}
protected void drawLine(GC gc, JobHopMeta hi, boolean is_candidate)
{
int line[] = getLine(hi.from_entry, hi.to_entry);
gc.setLineWidth(linewidth);
Color col;
if (is_candidate)
{
col = GUIResource.getInstance().getColorBlue();
}
else
if (hi.isEnabled())
{
if (hi.isUnconditional())
{
col = GUIResource.getInstance().getColorBlack();
}
else
{
if (hi.getEvaluation())
{
col = GUIResource.getInstance().getColorGreen();
}
else
{
col = GUIResource.getInstance().getColorRed();
}
}
}
else
{
col = GUIResource.getInstance().getColorDarkGray();
}
gc.setForeground(col);
if (hi.isSplit()) gc.setLineWidth(linewidth + 2);
drawArrow(gc, line);
if (hi.isSplit()) gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorBlack());
gc.setBackground(GUIResource.getInstance().getColorBackground());
}
protected void drawLineShadow(GC gc, JobHopMeta hi)
{
int line[] = getLine(hi.from_entry, hi.to_entry);
int s = shadowsize;
for (int i=0;i<line.length;i++) line[i]+=s;
gc.setLineWidth(linewidth);
gc.setForeground(GUIResource.getInstance().getColorLightGray());
drawArrow(gc, line);
}
protected Point getArea()
{
org.eclipse.swt.graphics.Rectangle rect = canvas.getClientArea();
Point area = new Point(rect.width, rect.height);
return area;
}
protected Point getThumb(Point area, Point max)
{
Point thumb = new Point(0, 0);
if (max.x <= area.x) thumb.x = 100;
else thumb.x = 100 * area.x / max.x;
if (max.y <= area.y) thumb.y = 100;
else thumb.y = 100 * area.y / max.y;
return thumb;
}
protected Point getOffset()
{
Point area = getArea();
Point max = jobMeta.getMaximum();
Point thumb = getThumb(area, max);
return getOffset(thumb, area);
}
protected Point getOffset(Point thumb, Point area)
{
Point p = new Point(0, 0);
Point sel = new Point(hori.getSelection(), vert.getSelection());
if (thumb.x==0 || thumb.y==0) return p;
p.x = -sel.x * area.x / thumb.x;
p.y = -sel.y * area.y / thumb.y;
return p;
}
public int sign(int n)
{
return n < 0 ? -1 : (n > 0 ? 1 : 1);
}
protected void newHop()
{
JobEntryCopy fr = jobMeta.getSelected(0);
JobEntryCopy to = jobMeta.getSelected(1);
spoon.newJobHop(jobMeta, fr, to);
}
protected void editEntry(JobEntryCopy je)
{
spoon.editJobEntry(jobMeta, je);
}
protected void editNote(NotePadMeta ni)
{
NotePadMeta before = (NotePadMeta)ni.clone();
String title = Messages.getString("JobGraph.Dialog.EditNote.Title");
String message = Messages.getString("JobGraph.Dialog.EditNote.Message");
EnterTextDialog dd = new EnterTextDialog(shell, title, message, ni.getNote());
String n = dd.open();
if (n!=null)
{
spoon.addUndoChange(jobMeta, new NotePadMeta[] {before}, new NotePadMeta[] {ni}, new int[] {jobMeta.indexOfNote(ni)});
ni.setChanged();
ni.setNote( n );
ni.width = ConstUI.NOTE_MIN_SIZE;
ni.height = ConstUI.NOTE_MIN_SIZE;
spoon.refreshGraph();
}
}
protected void drawArrow(GC gc, int line[])
{
int mx, my;
int x1 = line[0] + offset.x;
int y1 = line[1] + offset.y;
int x2 = line[2] + offset.x;
int y2 = line[3] + offset.y;
int x3;
int y3;
int x4;
int y4;
int a, b, dist;
double factor;
double angle;
//gc.setLineWidth(1);
//WuLine(gc, black, x1, y1, x2, y2);
gc.drawLine(x1, y1, x2, y2);
// What's the distance between the 2 points?
a = Math.abs(x2 - x1);
b = Math.abs(y2 - y1);
dist = (int) Math.sqrt(a * a + b * b);
// determine factor (position of arrow to left side or right side 0-->100%)
if (dist >= 2 * iconsize) factor = 1.5; else factor = 1.2;
// in between 2 points
mx = (int) (x1 + factor * (x2 - x1) / 2);
my = (int) (y1 + factor * (y2 - y1) / 2);
// calculate points for arrowhead
angle = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
x3 = (int) (mx + Math.cos(angle - theta) * size);
y3 = (int) (my + Math.sin(angle - theta) * size);
x4 = (int) (mx + Math.cos(angle + theta) * size);
y4 = (int) (my + Math.sin(angle + theta) * size);
// draw arrowhead
//gc.drawLine(mx, my, x3, y3);
//gc.drawLine(mx, my, x4, y4);
//gc.drawLine( x3, y3, x4, y4 );
Color fore = gc.getForeground();
Color back = gc.getBackground();
gc.setBackground(fore);
gc.fillPolygon(new int[] {mx, my, x3, y3, x4, y4} );
gc.setBackground(back);
}
protected boolean pointOnLine(int x, int y, int line[])
{
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for (dx = -pm; dx <= pm && !retval; dx++)
{
for (dy = -pm; dy <= pm && !retval; dy++)
{
retval = pointOnThinLine(x + dx, y + dy, line);
}
}
return retval;
}
protected boolean pointOnThinLine(int x, int y, int line[])
{
int x1 = line[0];
int y1 = line[1];
int x2 = line[2];
int y2 = line[3];
// Not in the square formed by these 2 points: ignore!
if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1))
&& ((y >= y1 && y <= y2) || (y >= y2 && y <= y1)))
)
return false;
double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
double angle_point = Math.atan2(y - y1, x - x1) + Math.PI;
// Same angle, or close enough?
if (angle_point >= angle_line - 0.01
&& angle_point <= angle_line + 0.01)
return true;
return false;
}
protected SnapAllignDistribute createSnapAllignDistribute()
{
List<GUIPositionInterface> elements = jobMeta.getSelectedDrawnJobEntryList();
int[] indices = jobMeta.getEntryIndexes(elements.toArray(new JobEntryCopy[elements.size()]));
return new SnapAllignDistribute(jobMeta, elements, indices, spoon, this);
}
public void snaptogrid()
{
snaptogrid( ConstUI.GRID_SIZE );
}
protected void snaptogrid(int size)
{
createSnapAllignDistribute().snaptogrid(size);
}
public void allignleft()
{
createSnapAllignDistribute().allignleft();
}
public void allignright()
{
createSnapAllignDistribute().allignright();
}
public void alligntop()
{
createSnapAllignDistribute().alligntop();
}
public void allignbottom()
{
createSnapAllignDistribute().allignbottom();
}
public void distributehorizontal()
{
createSnapAllignDistribute().distributehorizontal();
}
public void distributevertical()
{
createSnapAllignDistribute().distributevertical();
}
protected void drawRect(GC gc, Rectangle rect)
{
if (rect == null) return;
gc.setLineStyle(SWT.LINE_DASHDOT);
gc.setLineWidth(1);
gc.setForeground(GUIResource.getInstance().getColorDarkGray());
gc.drawRectangle(rect.x + offset.x, rect.y + offset.y,rect.width, rect.height);
gc.setLineStyle(SWT.LINE_SOLID);
}
protected void detach(JobEntryCopy je)
{
JobHopMeta hfrom = jobMeta.findJobHopTo(je);
JobHopMeta hto = jobMeta.findJobHopFrom(je);
if (hfrom != null && hto != null)
{
if (jobMeta.findJobHop(hfrom.from_entry, hto.to_entry) == null)
{
JobHopMeta hnew = new JobHopMeta(hfrom.from_entry, hto.to_entry);
jobMeta.addJobHop(hnew);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { (JobHopMeta)hnew.clone() }, new int[] { jobMeta.indexOfJobHop(hnew)});
}
}
if (hfrom != null)
{
int fromidx = jobMeta.indexOfJobHop(hfrom);
if (fromidx >= 0)
{
jobMeta.removeJobHop(fromidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] {hfrom}, new int[] {fromidx} );
}
}
if (hto != null)
{
int toidx = jobMeta.indexOfJobHop(hto);
if (toidx >= 0)
{
jobMeta.removeJobHop(toidx);
spoon.addUndoDelete(jobMeta, new JobHopMeta[] {hto}, new int[] {toidx} );
}
}
spoon.refreshTree();
redraw();
}
public void newProps()
{
iconsize = spoon.props.getIconSize();
linewidth = spoon.props.getLineWidth();
}
public String toString()
{
return Spoon.APP_NAME;
}
public EngineMetaInterface getMeta() {
return jobMeta;
}
/**
* @param jobMeta the jobMeta to set
*/
public void setJobMeta(JobMeta jobMeta)
{
this.jobMeta = jobMeta;
}
public boolean applyChanges()
{
return spoon.saveToFile(jobMeta);
}
public boolean canBeClosed()
{
return !jobMeta.hasChanged();
}
public JobMeta getManagedObject()
{
return jobMeta;
}
public boolean hasContentChanged()
{
return jobMeta.hasChanged();
}
public int showChangedWarning()
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("Spoon.Dialog.FileChangedSaveFirst.Message", spoon.delegates.tabs.makeJobGraphTabName(jobMeta)));//"This model has changed. Do you want to save it?"
mb.setText(Messages.getString("Spoon.Dialog.FileChangedSaveFirst.Title"));
return mb.open();
}
public static int showChangedWarning(Shell shell, String name)
{
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING );
mb.setMessage(Messages.getString("JobGraph.Dialog.PromptSave.Message", name));
mb.setText(Messages.getString("JobGraph.Dialog.PromptSave.Title"));
return mb.open();
}
public static boolean editProperties(JobMeta jobMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange)
{
if (jobMeta==null) return false;
JobDialog jd = new JobDialog(spoon.getShell(), SWT.NONE, jobMeta, rep);
jd.setDirectoryChangeAllowed(allowDirectoryChange);
JobMeta ji = jd.open();
// In this case, load shared objects
if (jd.isSharedObjectsFileChanged())
{
try
{
jobMeta.readSharedObjects(rep);
}
catch(Exception e)
{
new ErrorDialog(spoon.getShell(), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.delegates.tabs.makeJobGraphTabName(jobMeta)), e);
}
}
if (jd.isSharedObjectsFileChanged() || ji!=null)
{
spoon.refreshTree();
spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway
}
spoon.setShellText();
return ji!=null;
}
/**
* @return the lastMove
*/
public Point getLastMove() {
return lastMove;
}
/**
* @param lastMove the lastMove to set
*/
public void setLastMove(Point lastMove) {
this.lastMove = lastMove;
}
}
|
package com.intellij.psi.impl;
import com.intellij.formatting.FormatterEx;
import com.intellij.formatting.FormatterImpl;
import com.intellij.ide.startup.CacheUpdater;
import com.intellij.ide.startup.FileContent;
import com.intellij.ide.startup.FileSystemSynchronizer;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.lang.PsiBuilderFactory;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ex.ProjectRootManagerEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import static com.intellij.psi.impl.PsiTreeChangeEventImpl.PsiEventType.*;
import com.intellij.psi.impl.cache.CacheManager;
import com.intellij.psi.impl.cache.impl.CacheUtil;
import com.intellij.psi.impl.cache.impl.CompositeCacheManager;
import com.intellij.psi.impl.cache.impl.IndexCacheManagerImpl;
import com.intellij.psi.impl.file.impl.FileManager;
import com.intellij.psi.impl.file.impl.FileManagerImpl;
import com.intellij.psi.impl.search.PsiSearchHelperImpl;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class PsiManagerImpl extends PsiManagerEx implements ProjectComponent {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiManagerImpl");
private final Project myProject;
private final FileManager myFileManager;
private final PsiSearchHelperImpl mySearchHelper;
private final CacheManager myCacheManager;
private final PsiModificationTrackerImpl myModificationTracker;
private final ResolveCache myResolveCache;
private final CachedValuesManager myCachedValuesManager;
private final List<PsiTreeChangePreprocessor> myTreeChangePreprocessors = new CopyOnWriteArrayList<PsiTreeChangePreprocessor>();
private final List<PsiTreeChangeListener> myTreeChangeListeners = new CopyOnWriteArrayList<PsiTreeChangeListener>();
private boolean myTreeChangeEventIsFiring = false;
private final List<Runnable> myRunnablesOnChange = new CopyOnWriteArrayList<Runnable>();
private final List<WeakReference<Runnable>> myWeakRunnablesOnChange = new CopyOnWriteArrayList<WeakReference<Runnable>>();
private final List<Runnable> myRunnablesOnAnyChange = new CopyOnWriteArrayList<Runnable>();
private final List<Runnable> myRunnablesAfterAnyChange = new CopyOnWriteArrayList<Runnable>();
private boolean myIsDisposed;
private VirtualFileFilter myAssertOnFileLoadingFilter = VirtualFileFilter.NONE;
private final AtomicInteger myBatchFilesProcessingModeCount = new AtomicInteger(0);
private static final Key<PsiFile> CACHED_PSI_FILE_COPY_IN_FILECONTENT = Key.create("CACHED_PSI_FILE_COPY_IN_FILECONTENT");
private final List<LanguageInjector> myLanguageInjectors = new CopyOnWriteArrayList<LanguageInjector>();
private final ProgressManager myProgressManager;
public PsiManagerImpl(Project project,
final ProjectRootManagerEx projectRootManagerEx,
StartupManager startupManager,
FileTypeManager fileTypeManager,
FileDocumentManager fileDocumentManager,
PsiBuilderFactory psiBuilderFactory) {
myProject = project;
//noinspection UnnecessaryLocalVariable. We need to initialize PsiBuilderFactory service so it won't initialize under PsiLock from ChameleonTransform
Object used = psiBuilderFactory;
boolean isProjectDefault = project.isDefault();
myFileManager = isProjectDefault ? new EmptyFileManager(this) : new FileManagerImpl(this, fileTypeManager, fileDocumentManager,
projectRootManagerEx);
mySearchHelper = new PsiSearchHelperImpl(this);
final CompositeCacheManager cacheManager = new CompositeCacheManager();
if (!isProjectDefault) {
cacheManager.addCacheManager(new IndexCacheManagerImpl(this));
}
else {
cacheManager.addCacheManager(new EmptyCacheManager());
}
final CacheManager[] managers = myProject.getComponents(CacheManager.class);
for (CacheManager manager : managers) {
cacheManager.addCacheManager(manager);
}
myCacheManager = cacheManager;
myModificationTracker = new PsiModificationTrackerImpl(myProject);
myTreeChangePreprocessors.add(myModificationTracker);
myResolveCache = new ResolveCache(this);
myCachedValuesManager = new CachedValuesManagerImpl(this);
if (startupManager != null) {
((StartupManagerEx)startupManager).registerPreStartupActivity(
new Runnable() {
public void run() {
runPreStartupActivity();
}
}
);
}
myProgressManager = ProgressManager.getInstance();
}
public void initComponent() {
}
public void disposeComponent() {
myFileManager.dispose();
myCacheManager.dispose();
myIsDisposed = true;
}
public boolean isDisposed() {
return myIsDisposed;
}
public void dropResolveCaches() {
myResolveCache.clearCache();
physicalChange();
nonPhysicalChange();
}
public boolean isInProject(@NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file instanceof PsiFileImpl && file.isPhysical() && file.getViewProvider().getVirtualFile() instanceof LightVirtualFile) return true;
if (element instanceof PsiDirectoryContainer) {
PsiDirectory[] dirs = ((PsiDirectoryContainer) element).getDirectories();
for (PsiDirectory dir : dirs) {
if (!isInProject(dir)) return false;
}
return true;
}
VirtualFile virtualFile = null;
if (file != null) {
virtualFile = file.getViewProvider().getVirtualFile();
} else if (element instanceof PsiFileSystemItem) {
virtualFile = ((PsiFileSystemItem)element).getVirtualFile();
}
if (virtualFile != null) {
Module module = ModuleUtil.findModuleForFile(virtualFile, element.getProject());
return module != null;
}
return false;
}
public void performActionWithFormatterDisabled(final Runnable r) {
final PostprocessReformattingAspect component = getProject().getComponent(PostprocessReformattingAspect.class);
try {
((FormatterImpl)FormatterEx.getInstance()).disableFormatting();
component.disablePostprocessFormattingInside(new Computable<Object>() {
public Object compute() {
r.run();
return null;
}
});
}
finally {
((FormatterImpl)FormatterEx.getInstance()).enableFormatting();
}
}
public <T extends Throwable> void performActionWithFormatterDisabled(final ThrowableRunnable<T> r) throws T {
final Throwable[] throwable = new Throwable[1];
final PostprocessReformattingAspect component = getProject().getComponent(PostprocessReformattingAspect.class);
try {
((FormatterImpl)FormatterEx.getInstance()).disableFormatting();
component.disablePostprocessFormattingInside(new Computable<Object>() {
public Object compute() { try { r.run(); } catch (Throwable t) { throwable[0] = t; } return null; }
});
}
finally {
((FormatterImpl)FormatterEx.getInstance()).enableFormatting();
}
if (throwable[0] != null) //noinspection unchecked
throw (T)throwable[0];
}
public <T> T performActionWithFormatterDisabled(Computable<T> r) {
try {
final PostprocessReformattingAspect component = PostprocessReformattingAspect.getInstance(getProject());
((FormatterImpl)FormatterEx.getInstance()).disableFormatting();
return component.disablePostprocessFormattingInside(r);
}
finally {
((FormatterImpl)FormatterEx.getInstance()).enableFormatting();
}
}
@NotNull
public List<? extends LanguageInjector> getLanguageInjectors() {
return myLanguageInjectors;
}
public void registerLanguageInjector(@NotNull LanguageInjector injector) {
myLanguageInjectors.add(injector);
InjectedLanguageManagerImpl.getInstanceImpl(myProject).psiManagerInjectorsChanged();
}
public void registerLanguageInjector(@NotNull final LanguageInjector injector, Disposable parentDisposable) {
registerLanguageInjector(injector);
Disposer.register(parentDisposable, new Disposable() {
public void dispose() {
unregisterLanguageInjector(injector);
}
});
}
public void unregisterLanguageInjector(@NotNull LanguageInjector injector) {
myLanguageInjectors.remove(injector);
InjectedLanguageManagerImpl.getInstanceImpl(myProject).psiManagerInjectorsChanged();
}
public void postponeAutoFormattingInside(Runnable runnable) {
PostprocessReformattingAspect.getInstance(getProject()).postponeFormattingInside(runnable);
}
public void projectClosed() {
}
public void projectOpened() {
}
private void runPreStartupActivity() {
if (LOG.isDebugEnabled()) {
LOG.debug("PsiManager.runPreStartupActivity()");
}
myFileManager.runStartupActivity();
myCacheManager.initialize();
StartupManagerEx startupManager = StartupManagerEx.getInstanceEx(myProject);
if (startupManager != null) {
FileSystemSynchronizer synchronizer = startupManager.getFileSystemSynchronizer();
if (PsiManagerConfiguration.getInstance().REPOSITORY_ENABLED) {
CacheUpdater[] updaters = myCacheManager.getCacheUpdaters();
for (CacheUpdater updater : updaters) {
synchronizer.registerCacheUpdater(updater);
}
}
}
}
public void setAssertOnFileLoadingFilter(VirtualFileFilter filter) {
// Find something to ensure there's no changed files waiting to be processed in repository indicies.
myAssertOnFileLoadingFilter = filter;
}
public boolean isAssertOnFileLoading(VirtualFile file) {
return myAssertOnFileLoadingFilter.accept(file);
}
@NotNull
public Project getProject() {
return myProject;
}
public FileManager getFileManager() {
return myFileManager;
}
public CacheManager getCacheManager() {
if (myIsDisposed) {
LOG.error("Project is already disposed.");
}
return myCacheManager;
}
@NotNull
public CodeStyleManager getCodeStyleManager() {
return CodeStyleManager.getInstance(myProject);
}
public ResolveCache getResolveCache() {
myProgressManager.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly
return myResolveCache;
}
public boolean areElementsEquivalent(PsiElement element1, PsiElement element2) {
myProgressManager.checkCanceled(); // We hope this method is being called often enough to cancel daemon processes smoothly
if (element1 == element2) return true;
if (element1 == null || element2 == null) {
return false;
}
return element1.equals(element2) || element1.isEquivalentTo(element2) || element2.isEquivalentTo(element1);
}
public PsiFile findFile(@NotNull VirtualFile file) {
return myFileManager.findFile(file);
}
@Nullable
public FileViewProvider findViewProvider(@NotNull VirtualFile file) {
return myFileManager.findViewProvider(file);
}
@TestOnly
public void cleanupForNextTest() {
//myFileManager.cleanupForNextTest();
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode());
}
@Nullable
public PsiFile getFile(FileContent content) {
PsiFile psiFile = content.getUserData(CACHED_PSI_FILE_COPY_IN_FILECONTENT);
if (psiFile == null) {
final VirtualFile vFile = content.getVirtualFile();
psiFile = myFileManager.getCachedPsiFile(vFile);
if (psiFile == null) {
psiFile = findFile(vFile);
if (psiFile == null) return null;
psiFile = CacheUtil.createFileCopy(content, psiFile);
}
//psiFile = content.putUserDataIfAbsent(CACHED_PSI_FILE_COPY_IN_FILECONTENT, psiFile);
content.putUserData(CACHED_PSI_FILE_COPY_IN_FILECONTENT, psiFile);
}
LOG.assertTrue(psiFile instanceof PsiCompiledElement || psiFile.isValid());
return psiFile;
}
public PsiDirectory findDirectory(@NotNull VirtualFile file) {
myProgressManager.checkCanceled();
return myFileManager.findDirectory(file);
}
public void invalidateFile(PsiFile file) {
if (myIsDisposed) {
LOG.error("Disposed PsiManager calls invalidateFile!");
}
final VirtualFile virtualFile = file.getVirtualFile();
if (file.getViewProvider().isPhysical() && myCacheManager != null) {
myCacheManager.addOrInvalidateFile(virtualFile);
}
}
public void reloadFromDisk(@NotNull PsiFile file) {
myFileManager.reloadFromDisk(file);
}
public void addPsiTreeChangeListener(@NotNull PsiTreeChangeListener listener) {
myTreeChangeListeners.add(listener);
}
public void addPsiTreeChangeListener(@NotNull final PsiTreeChangeListener listener, Disposable parentDisposable) {
addPsiTreeChangeListener(listener);
Disposer.register(parentDisposable, new Disposable() {
public void dispose() {
removePsiTreeChangeListener(listener);
}
});
}
public void removePsiTreeChangeListener(@NotNull PsiTreeChangeListener listener) {
myTreeChangeListeners.remove(listener);
}
public void beforeChildAddition(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_CHILD_ADDITION);
if (LOG.isDebugEnabled()) {
LOG.debug(
"beforeChildAddition: parent = " + event.getParent()
);
}
fireEvent(event);
}
public void beforeChildRemoval(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_CHILD_REMOVAL);
if (LOG.isDebugEnabled()) {
LOG.debug(
"beforeChildRemoval: child = " + event.getChild()
+ ", parent = " + event.getParent()
);
}
fireEvent(event);
}
public void beforeChildReplacement(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_CHILD_REPLACEMENT);
if (LOG.isDebugEnabled()) {
LOG.debug(
"beforeChildReplacement: oldChild = " + event.getOldChild()
+ ", parent = " + event.getParent()
);
}
fireEvent(event);
}
public void beforeChildrenChange(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_CHILDREN_CHANGE);
if (LOG.isDebugEnabled()) {
LOG.debug("beforeChildrenChange: parent = " + event.getParent());
}
fireEvent(event);
}
public void beforeChildMovement(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_CHILD_MOVEMENT);
if (LOG.isDebugEnabled()) {
LOG.debug(
"beforeChildMovement: child = " + event.getChild()
+ ", oldParent = " + event.getOldParent()
+ ", newParent = " + event.getNewParent()
);
}
fireEvent(event);
}
public void beforePropertyChange(PsiTreeChangeEventImpl event) {
event.setCode(BEFORE_PROPERTY_CHANGE);
if (LOG.isDebugEnabled()) {
LOG.debug(
"beforePropertyChange: element = " + event.getElement()
+ ", propertyName = " + event.getPropertyName()
+ ", oldValue = " + event.getOldValue()
);
}
fireEvent(event);
}
public void childAdded(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(CHILD_ADDED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"childAdded: child = " + event.getChild()
+ ", parent = " + event.getParent()
);
}
fireEvent(event);
afterAnyChange();
}
public void childRemoved(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(CHILD_REMOVED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"childRemoved: child = " + event.getChild() + ", parent = " + event.getParent()
);
}
fireEvent(event);
afterAnyChange();
}
public void childReplaced(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(CHILD_REPLACED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"childReplaced: oldChild = " + event.getOldChild()
+ ", newChild = " + event.getNewChild()
+ ", parent = " + event.getParent()
);
}
fireEvent(event);
afterAnyChange();
}
public void childMoved(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(CHILD_MOVED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"childMoved: child = " + event.getChild()
+ ", oldParent = " + event.getOldParent()
+ ", newParent = " + event.getNewParent()
);
}
fireEvent(event);
afterAnyChange();
}
public void childrenChanged(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(CHILDREN_CHANGED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"childrenChanged: parent = " + event.getParent()
);
}
fireEvent(event);
afterAnyChange();
}
public void propertyChanged(PsiTreeChangeEventImpl event) {
onChange(true);
event.setCode(PROPERTY_CHANGED);
if (LOG.isDebugEnabled()) {
LOG.debug(
"propertyChanged: element = " + event.getElement()
+ ", propertyName = " + event.getPropertyName()
+ ", oldValue = " + event.getOldValue()
+ ", newValue = " + event.getNewValue()
);
}
fireEvent(event);
afterAnyChange();
}
public void addTreeChangePreprocessor(PsiTreeChangePreprocessor preprocessor) {
myTreeChangePreprocessors.add(preprocessor);
}
private void fireEvent(PsiTreeChangeEventImpl event) {
boolean isRealTreeChange = event.getCode() != PROPERTY_CHANGED && event.getCode() != BEFORE_PROPERTY_CHANGE;
PsiFile file = event.getFile();
if (file == null || file.isPhysical()) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
}
if (isRealTreeChange) {
LOG.assertTrue(!myTreeChangeEventIsFiring, "Changes to PSI are not allowed inside event processing");
myTreeChangeEventIsFiring = true;
}
try {
for(PsiTreeChangePreprocessor preprocessor: myTreeChangePreprocessors) {
preprocessor.treeChanged(event);
}
for (PsiTreeChangeListener listener : myTreeChangeListeners) {
try {
switch (event.getCode()) {
case BEFORE_CHILD_ADDITION:
listener.beforeChildAddition(event);
break;
case BEFORE_CHILD_REMOVAL:
listener.beforeChildRemoval(event);
break;
case BEFORE_CHILD_REPLACEMENT:
listener.beforeChildReplacement(event);
break;
case BEFORE_CHILD_MOVEMENT:
listener.beforeChildMovement(event);
break;
case BEFORE_CHILDREN_CHANGE:
listener.beforeChildrenChange(event);
break;
case BEFORE_PROPERTY_CHANGE:
listener.beforePropertyChange(event);
break;
case CHILD_ADDED:
listener.childAdded(event);
break;
case CHILD_REMOVED:
listener.childRemoved(event);
break;
case CHILD_REPLACED:
listener.childReplaced(event);
break;
case CHILD_MOVED:
listener.childMoved(event);
break;
case CHILDREN_CHANGED:
listener.childrenChanged(event);
break;
case PROPERTY_CHANGED:
listener.propertyChanged(event);
break;
}
}
catch (Exception e) {
LOG.error(e);
}
}
}
finally {
if (isRealTreeChange) {
myTreeChangeEventIsFiring = false;
}
}
}
public void registerRunnableToRunOnChange(Runnable runnable) {
myRunnablesOnChange.add(runnable);
}
public void registerWeakRunnableToRunOnChange(Runnable runnable) {
myWeakRunnablesOnChange.add(new WeakReference<Runnable>(runnable));
}
public void registerRunnableToRunOnAnyChange(Runnable runnable) { // includes non-physical changes
myRunnablesOnAnyChange.add(runnable);
}
public void registerRunnableToRunAfterAnyChange(Runnable runnable) { // includes non-physical changes
myRunnablesAfterAnyChange.add(runnable);
}
public void nonPhysicalChange() {
onChange(false);
}
public void physicalChange() {
onChange(true);
}
private void onChange(boolean isPhysical) {
if (isPhysical) {
runRunnables(myRunnablesOnChange);
WeakReference[] refs = myWeakRunnablesOnChange.toArray(
new WeakReference[myWeakRunnablesOnChange.size()]);
myWeakRunnablesOnChange.clear();
for (WeakReference ref : refs) {
Runnable runnable = ref != null ? (Runnable)ref.get() : null;
if (runnable != null) {
runnable.run();
}
}
}
runRunnables(myRunnablesOnAnyChange);
}
private void afterAnyChange() {
runRunnables(myRunnablesAfterAnyChange);
}
private static void runRunnables(List<Runnable> runnables) {
if (runnables.isEmpty()) return;
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < runnables.size(); i++) {
runnables.get(i).run();
}
}
@NotNull
public PsiSearchHelper getSearchHelper() {
return mySearchHelper;
}
@NotNull
public PsiModificationTracker getModificationTracker() {
return myModificationTracker;
}
@NotNull
public CachedValuesManager getCachedValuesManager() {
return myCachedValuesManager;
}
public void moveDirectory(@NotNull final PsiDirectory dir, @NotNull PsiDirectory newParent) throws IncorrectOperationException {
checkMove(dir, newParent);
try {
dir.getVirtualFile().move(this, newParent.getVirtualFile());
}
catch (IOException e) {
throw new IncorrectOperationException(e.toString(),e);
}
}
public void moveFile(@NotNull final PsiFile file, @NotNull PsiDirectory newParent) throws IncorrectOperationException {
checkMove(file, newParent);
try {
final VirtualFile virtualFile = file.getVirtualFile();
assert virtualFile != null;
virtualFile.move(this, newParent.getVirtualFile());
}
catch (IOException e) {
throw new IncorrectOperationException(e.toString(),e);
}
}
public void checkMove(@NotNull PsiElement element, @NotNull PsiElement newContainer) throws IncorrectOperationException {
if (element instanceof PsiDirectoryContainer) {
PsiDirectory[] dirs = ((PsiDirectoryContainer)element).getDirectories();
if (dirs.length == 0) {
throw new IncorrectOperationException();
}
else if (dirs.length > 1) {
throw new IncorrectOperationException(
"Moving of packages represented by more than one physical directory is not supported.");
}
checkMove(dirs[0], newContainer);
return;
}
//element.checkDelete(); //move != delete + add
newContainer.checkAdd(element);
checkIfMoveIntoSelf(element, newContainer);
}
private static void checkIfMoveIntoSelf(PsiElement element, PsiElement newContainer) throws IncorrectOperationException {
PsiElement container = newContainer;
while (container != null) {
if (container == element) {
if (element instanceof PsiDirectory) {
if (element == newContainer) {
throw new IncorrectOperationException("Cannot move directory into itself.");
}
else {
throw new IncorrectOperationException("Cannot move directory into its subdirectory.");
}
}
else {
throw new IncorrectOperationException();
}
}
container = container.getParent();
}
}
public void startBatchFilesProcessingMode() {
myBatchFilesProcessingModeCount.incrementAndGet();
}
public void finishBatchFilesProcessingMode() {
myBatchFilesProcessingModeCount.decrementAndGet();
LOG.assertTrue(myBatchFilesProcessingModeCount.get() >= 0);
}
public boolean isBatchFilesProcessingMode() {
return myBatchFilesProcessingModeCount.get() > 0;
}
@NotNull
public String getComponentName() {
return "PsiManager";
}
}
|
package Ontology.Mappings;
/**
* MessageType Class
* The class is used to store the various parameters of the Message like name,min-version and max-version
* @author tirthmehta
*/
import Util.Serializable;
import Util.SerializationConvenience;
import Util.StorageToken;
public class MessageType extends Serializable
{
public static final String MESSAGE_TYPE_NAME_KEY = "messageTypeName";
public static final String MESSAGE_TYPE_CLASS_ID_KEY = "classId";
public static final String MESSAGE_TYPE_MINVERSION_KEY = "messageTypeMinversion";
public static final String MESSAGE_TYPE_MAXVERSION_KEY = "messageTypeMaxversion";
public static final String MESSAGE_TYPE_MESSAGETEMPLATE_KEY = "messageTypeMessagetemplate";
private String classId;
private String messageName;
private float min_Version;
private float max_Version;
private MessageTemplate messageTypeTemplate;
// CONSTRUCTORS
public MessageType(String name, float minversion, float maxversion, MessageTemplate mtemp, String cl)
{
this.messageName = name;
this.min_Version = minversion;
this.max_Version = maxversion;
messageTypeTemplate = mtemp;
classId = cl;
}
public MessageType()
{
this.messageName = "";
this.max_Version = 0.0f;
this.min_Version = 0.0f;
this.messageTypeTemplate = null;
classId = null;
}
// GETTER AND SETTER METHODS FOR GETTING AND SETTING THE MULTIPLE VALUES
// LIKE MESSAGENAME,MIN-VERSION ETC LISTED ABOVE
public String getMessageName()
{
return messageName;
}
public void setMessageName(String name)
{
messageName = name;
}
public float getMinVersion()
{
return min_Version;
}
public void setMinVersion(float minversion)
{
min_Version = minversion;
}
public float getMaxVersion()
{
return max_Version;
}
public void setMaxVersion(float maxversion)
{
max_Version = maxversion;
}
public MessageTemplate getMessageTemplate()
{
if (messageTypeTemplate != null)
return messageTypeTemplate;
else
return null;
}
public void setClassId(String cl)
{
this.classId = cl;
}
public String getClassId()
{
return classId;
}
// Equality Operations
@Override
public boolean equals(Object otherObject)
{
if (!super.equals(otherObject))
return false;
if (!(otherObject instanceof MessageType))
return false;
MessageType other = (MessageType) otherObject;
if (!fieldIsEqual(this.messageName, other.messageName))
return false;
if (!fieldIsEqual(this.min_Version, other.min_Version))
return false;
if (!fieldIsEqual(this.max_Version, other.max_Version))
return false;
if (!fieldIsEqual(this.messageTypeTemplate, other.messageTypeTemplate))
return false;
if (!fieldIsEqual(this.classId, other.classId))
return false;
return true;
}
@Override
public int hashCode()
{
int result = super.hashCode();
int arbitraryPrimeNumber = 23;
if (this.messageName != null)
result = result * arbitraryPrimeNumber + this.messageName.hashCode();
if (this.min_Version != 0.0f)
{
result = result * arbitraryPrimeNumber + Float.hashCode(min_Version);
}
if (this.max_Version != 0.0f)
{
result = result * arbitraryPrimeNumber + Float.hashCode(max_Version);
}
if (this.messageTypeTemplate != null)
result = result * arbitraryPrimeNumber + this.messageTypeTemplate.hashCode();
if (this.classId != null)
result = result * arbitraryPrimeNumber + this.classId.hashCode();
return result;
}
// Serialization/Deserialization
@Override
public void initializeFromToken(StorageToken token)
{
super.initializeFromToken(token);
this.messageName = (String) SerializationConvenience.untokenizeObject(token.getItem(MESSAGE_TYPE_NAME_KEY));
this.min_Version = (float) SerializationConvenience.untokenizeObject(token.getItem(MESSAGE_TYPE_MINVERSION_KEY));
this.max_Version = (float) SerializationConvenience.untokenizeObject(token.getItem(MESSAGE_TYPE_MAXVERSION_KEY));
this.messageTypeTemplate = (MessageTemplate) SerializationConvenience.untokenizeObject(token.getItem(MESSAGE_TYPE_MESSAGETEMPLATE_KEY));
this.classId = (String) SerializationConvenience.untokenizeObject(token.getItem(MESSAGE_TYPE_CLASS_ID_KEY));
}
@Override
public StorageToken saveToToken()
{
StorageToken result = super.saveToToken();
result.setItem(MESSAGE_TYPE_CLASS_ID_KEY, SerializationConvenience.tokenizeObject(this.classId));
result.setItem(MESSAGE_TYPE_NAME_KEY, SerializationConvenience.tokenizeObject(this.messageName));
result.setItem(MESSAGE_TYPE_MINVERSION_KEY, SerializationConvenience.tokenizeObject(this.min_Version));
result.setItem(MESSAGE_TYPE_MAXVERSION_KEY, SerializationConvenience.tokenizeObject(this.max_Version));
result.setItem(MESSAGE_TYPE_MESSAGETEMPLATE_KEY, SerializationConvenience.tokenizeObject(this.messageTypeTemplate));
return result;
}
}
|
package socketfactory;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import sync.ClientCenter;
import threads.ReceiverManager;
public class LinkBuilder {
private Socket sock = null;
public synchronized void buildLink(ServerSocket jsock) {
try {
this.sock = jsock.accept();
ClientCenter.getInstance().getSockets().add(this.sock);
ReceiverManager rc = new ReceiverManager(sock);
Thread t2 = new Thread(rc);
t2.start();
} catch (SocketException e) {
e.printStackTrace();
System.out.println("Socket Ex! On class LinkBuilder Line 27");
if (sock != null) {
try {
ClientCenter.getInstance().removeClientBySocket(sock);
} catch (Throwable e1) {
try {
ServerSocketBuilder.jsock.close();
} catch (IOException e2) {
e2.printStackTrace();
} finally {
ServerSocketBuilder.jsock = null;
try {
ServerSocketBuilder.dumpSocket();
} catch (IOException e3) {
e3.printStackTrace();
}
}
e1.printStackTrace();
}
finally {
ServerSocketBuilder.createSocket();
}
}
} catch (EOFException e) {
System.out.println("EOF Ex! On class LinkBuilder Line 51");
if (sock != null) {
try {
ClientCenter.getInstance().removeClientBySocket(sock);
} catch (Throwable e1) {
e1.printStackTrace();
try {
ServerSocketBuilder.jsock.close();
} catch (IOException e2) {
e2.printStackTrace();
} finally {
ServerSocketBuilder.jsock = null;
try {
ServerSocketBuilder.dumpSocket();
} catch (IOException e3) {
e3.printStackTrace();
}
}
} finally {
ServerSocketBuilder.createSocket();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package storage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import xml.UniprotDbRef;
import xml.UniprotEntry;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
/**
* Intermediate class to add PeptideData to the database
*
* @author Bart Mesuere
*
*/
public class PeptideLoaderData {
// database stuff
private Connection connection;
private PreparedStatement containsSequence;
private PreparedStatement addSequence;
private PreparedStatement addUniprotEntry;
private PreparedStatement addPeptide;
private PreparedStatement addLineage;
private PreparedStatement addDbRef;
private PreparedStatement lineageExists;
private PreparedStatement getTaxon;
private Set<Integer> wrongTaxonIds;
/**
* Creates a new data object
*/
public PeptideLoaderData() {
try {
wrongTaxonIds = new HashSet<Integer>();
connection = Database.getConnection();
prepareStatements();
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ "Database connection failed");
e.printStackTrace();
System.exit(1);
}
}
/**
* creates all prepared statements used in this class.
*/
private void prepareStatements() {
try {
containsSequence = connection
.prepareStatement("SELECT id FROM sequences WHERE `sequence` = ?");
addSequence = connection.prepareStatement(
"INSERT INTO sequences (`sequence`) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
addUniprotEntry = connection
.prepareStatement(
"INSERT INTO uniprot_entries (`uniprot_accession_number`, `version`, `taxon_id`, `type`) VALUES (?,?,?,?)",
Statement.RETURN_GENERATED_KEYS);
addPeptide = connection
.prepareStatement("INSERT INTO peptides (`sequence_id`, `uniprot_entry_id`, `original_sequence_id`) VALUES (?,?,?)");
addLineage = connection
.prepareStatement("INSERT INTO lineages (`taxon_id`) VALUES (?)");
addDbRef = connection
.prepareStatement("INSERT INTO uniprot_cross_references (`uniprot_entry_id`, `type`, `protein_id`, `sequence_id`) VALUES (?,?,?,?)");
lineageExists = connection
.prepareStatement("SELECT COUNT(*) AS aantal FROM lineages WHERE `taxon_id` = ?");
getTaxon = connection
.prepareStatement("SELECT rank, parent_id, valid FROM taxons WHERE id = ?");
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Error creating prepared statements");
e.printStackTrace();
}
}
/**
* Stores a complete UniprotEntry in the database
*
* @param entry
* the UniprotEntry to store
*/
public void store(UniprotEntry entry) {
int uniprotEntryId = addUniprotEntry(entry.getUniprotAccessionNumber(), entry.getVersion(),
entry.getTaxonId(), entry.getType());
if (uniprotEntryId != -1) { // failed to add entry
for (String sequence : entry.digest())
addData(sequence.replace("I", "L"), uniprotEntryId, sequence);
for (UniprotDbRef ref : entry.getReferences())
addDbRef(ref, uniprotEntryId);
}
}
/**
*
* Inserts the entry info of a uniprot entry into the database and returns
* the generated id.
*
* @param uniprotAccessionNumber
* The accession number of the entry
* @param version
* The version of the entry
* @param taxonId
* The taxonId of the organism of the entry
* @param type
* The type of the entry. Can be swissprot or trembl
* @return The database ID of the uniprot entry.
*/
public int addUniprotEntry(String uniprotAccessionNumber, int version, int taxonId, String type) {
try {
addUniprotEntry.setString(1, uniprotAccessionNumber);
addUniprotEntry.setInt(2, version);
addUniprotEntry.setInt(3, taxonId);
addUniprotEntry.setString(4, type);
addUniprotEntry.executeUpdate();
ResultSet res = addUniprotEntry.getGeneratedKeys();
res.next();
int id = res.getInt(1);
res.close();
return id;
} catch (MySQLIntegrityConstraintViolationException e) {
if (!wrongTaxonIds.contains(taxonId)) {
wrongTaxonIds.add(taxonId);
System.err.println(new Timestamp(System.currentTimeMillis()) + " " + taxonId
+ " added to the list of " + wrongTaxonIds.size() + " invalid taxonIds.");
}
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Error executing query.");
e.printStackTrace();
}
return -1;
}
/**
* returns the database ID of given sequence. If the local index is enabled,
* try that index first. If no ID is found, the sequence is added to the
* database.
*
* @param sequence
* String of the sequence of which we want to get the id
* @return the database id of given sequence
*/
private int getSequenceId(String sequence) {
try {
containsSequence.setString(1, sequence);
ResultSet res = containsSequence.executeQuery();
if (res.next()) {// try retrieving
int id = res.getInt("id");
res.close();
return id;
} else {// else add to database
res.close();
addSequence.setString(1, sequence);
addSequence.executeUpdate();
res = addSequence.getGeneratedKeys();
res.next();
int id = res.getInt(1);
res.close();
return id;
}
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Error getting id of sequence " + sequence);
e.printStackTrace();
}
return -1;
}
/**
* Adds peptide data to the database
*
* @param sequence
* The sequence of the peptide
* @param uniprotEntryId
* The id of the uniprot entry from which the peptide data was
* retrieved.
*/
public void addData(String sequence, int uniprotEntryId, String originalSequence) {
try {
addPeptide.setInt(1, getSequenceId(sequence));
addPeptide.setInt(2, uniprotEntryId);
addPeptide.setInt(3, getSequenceId(originalSequence));
addPeptide.executeUpdate();
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Error adding this peptide to the database: " + sequence);
e.printStackTrace();
}
}
/**
* Adds a uniprot entry cross reference to the database
*
* @param ref
* The uniprot cross reference to add
* @param uniprotEntryId
* The uniprotEntry of the cross reference
*/
public void addDbRef(UniprotDbRef ref, int uniprotEntryId) {
try {
addDbRef.setInt(1, uniprotEntryId);
addDbRef.setString(2, ref.getType());
addDbRef.setString(3, ref.getProteinId());
addDbRef.setString(4, ref.getSequenceId());
addDbRef.executeUpdate();
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Error adding this cross reference to the database.");
e.printStackTrace();
}
}
/**
* Returns a List containing all the taxonIds of which the database contains
* a peptide
*
* @return a list of taxonIds
*/
public List<Integer> getUniqueTaxonIds() {
List<Integer> result = new ArrayList<Integer>();
Statement stmt;
try {
stmt = connection.createStatement();
try {
ResultSet rs = stmt.executeQuery("SELECT DISTINCT taxon_id FROM uniprot_entries");
while (rs.next())
result.add(rs.getInt(1));
rs.close();
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong truncating tables.");
e.printStackTrace();
} finally {
stmt.close();
}
} catch (SQLException e1) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong creating a new statement.");
e1.printStackTrace();
}
return result;
}
/**
* Adds the complete lineage to the database for the given taxonomic
* element.
*
* @param taxonId
* The taxonId of the organism
*/
public void addLineage(int taxonId) {
try {
lineageExists.setInt(1, taxonId);
ResultSet rs = lineageExists.executeQuery();
if (rs.next() && rs.getInt("aantal") == 0) {
addLineage.setInt(1, taxonId);
addLineage.execute();
updateLineage(taxonId, taxonId);
}
rs.close();
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong with the database");
e.printStackTrace();
}
}
/**
* Updates the lineage record of the given taxonId with the information in
* the Taxon record of parentId
*
* @param taxonId
* The taxonId of the record that needs updating
* @param parentId
* The taxonId of the record containing new information
* @throws SQLException
*/
private void updateLineage(int taxonId, int parentId) throws SQLException {
// if the parent == 1, we're at the root
if (parentId != 1) {
if (taxonId != parentId) {
addLineage(parentId);
}
// retrieve the parent info
getTaxon.setInt(1, parentId);
ResultSet rs = getTaxon.executeQuery();
if (rs.next()) {
String rank = rs.getString("rank");
// if we have a valid rank, update the lineage
if (!rank.equals("no rank")) {
rank = rank.replace(' ', '_');
Statement stmt = connection.createStatement();
if (rs.getBoolean("valid"))// normal case
stmt.executeUpdate("UPDATE lineages SET `" + rank + "` = " + parentId
+ " WHERE `taxon_id` = " + taxonId);
else
// invalid
stmt.executeUpdate("UPDATE lineages SET `" + rank + "` = "
+ (-1 * parentId) + " WHERE `taxon_id` = " + taxonId);
stmt.close();
}
// recursion if fun!
updateLineage(taxonId, rs.getInt("parent_id"));
}
rs.close();
}
}
/**
* Truncates all peptide tables
*/
public void emptyAllTables() {
Statement stmt;
try {
stmt = connection.createStatement();
try {
stmt.executeQuery("SET FOREIGN_KEY_CHECKS=0");
stmt.executeUpdate("TRUNCATE TABLE `peptides`");
stmt.executeUpdate("TRUNCATE TABLE `sequences`");
stmt.executeUpdate("TRUNCATE TABLE `uniprot_entries`");
stmt.executeUpdate("TRUNCATE TABLE `lineages`");
stmt.executeQuery("SET FOREIGN_KEY_CHECKS=1");
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong truncating tables.");
e.printStackTrace();
} finally {
stmt.close();
}
} catch (SQLException e1) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong creating a new statement.");
e1.printStackTrace();
}
}
public void emptyLineages() {
Statement stmt;
try {
stmt = connection.createStatement();
try {
stmt.executeUpdate("TRUNCATE TABLE `lineages`");
} catch (SQLException e) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong truncating tables.");
e.printStackTrace();
} finally {
stmt.close();
}
} catch (SQLException e1) {
System.err.println(new Timestamp(System.currentTimeMillis())
+ " Something went wrong creating a new statement.");
e1.printStackTrace();
}
}
}
|
package structures.data;
import exceptions.ResourceFailedException;
import javax.sound.sampled.AudioInputStream;
import authoring_environment.FileHandlers.FileManager;
import javafx.scene.media.AudioClip;
import structures.IResource;
public class DataSound implements IResource {
private String myName;
private String myBaseFileName;
private String completeFileName;
private AudioClip clip;
private AudioInputStream audioInputStream;
private boolean myHaveLoaded;
public DataSound(String name, String baseFileName) {
myName = name;
myBaseFileName = baseFileName;
myHaveLoaded = false;
}
public String getName() {
return myName;
}
public String getBaseFileName() {
return myBaseFileName;
}
public AudioInputStream getInputStream(){
return audioInputStream;
}
public void setInputStream(AudioInputStream inputStream){
audioInputStream = inputStream;
}
@Override
public boolean loaded() {
return myHaveLoaded;
}
@Override
public void load(String gameName) throws ResourceFailedException {
FileManager gmf = new FileManager(gameName);
clip = gmf.getSound(myName, this);
myHaveLoaded = true;
}
public String getDirectory(){
return completeFileName;
}
public AudioClip getClip(){
return clip;
}
@Override
public String toString(){
return myName;
}
}
|
package com.africastalking;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Body;
interface IToken {
@FormUrlEncoded
@POST("checkout/token/create")
Call<String> createCheckoutToken(@Field("phoneNumber") String phoneNumber);
@Headers("Content-Type: application/json")
@POST("auth-token/generate")
Call<String> generateAuthToken(@Body String body);
}
|
package sudoku.time;
import common.Sets;
import common.time.AbstractTime;
import common.time.Time;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Stream;
import sudoku.Claim;
import sudoku.Rule;
/**
* <p>A Time in which some Claims are {@link Claim#setFalse(FalsifiedTime) set false}.</p> <p>This
* class is a base class for {@code Time}s that denote events in the process of solving a sudoku
* puzzle, including direct {@link TechniqueEvent}s in which a Technique changes the puzzle and
* indirect {@link Rule.AutoResolve AutoResolve} events in which changes made to the puzzle by some
* solution event allow a part of the puzzle to
* {@link Rule#validateState(FalsifiedTime) automatically detect} a solving action that it can take
* locally.</p>
* @author fiveham
* @author fiveham
*
*/
public abstract class FalsifiedTime extends AbstractTime {
private final Set<Claim> falsified;
/**
* <p>Constructs a FalsifiedTime having the specified {@code parent} and representing the
* falsification of Claims from {@code falsified} that are not included as
* {@link #falsified() claims} of any nth-parents of this Time that are instances of
* FalsifiedTime.</p>
* @param parent the event which caused this event and of which this event is a part
* @param falsified a superset of the Claims set false in this event
* @throws NoUnaccountedClaims if all the Claims in {@code falsified} are accounted for as false
* by this Time's {@code FalsifiedTime} nth-parents
*/
public FalsifiedTime(Time parent, Set<Claim> falsified){
super(parent);
Set<Claim> f = new HashSet<>(falsified);
f.removeAll(upFalsified(this, true));
if(f.isEmpty()){
throw new NoUnaccountedClaims("No unaccounted-for Claims specified.");
}
this.falsified = Collections.unmodifiableSet(f);
this.falsified.stream().forEach(Claim::setFalse);
}
/**
* <p>Returns a set of all the Claims falsified in all the FalsifiedTime nth parents of this
* Time.</p>
* @return a set of all the Claims falsified in all the FalsifiedTime nth parents of this Time
*/
private static Set<Claim> upFalsified(Time time, boolean skip){
return skip(time.upTrail().stream(), skip)
.filter(FalsifiedTime.class::isInstance)
.map(FalsifiedTime.class::cast)
.map(FalsifiedTime::falsified)
.map(HashSet<Claim>::new)
.reduce(
new HashSet<Claim>(),
Sets::mergeCollections);
}
/**
* <p>{@link Stream#skip(long) Skips} the first element of {@code stream} if and only if
* {@code skip} is true.</p<
* @param stream a Stream whose first element may be skipped
* @param skip specifies whether {@code stream}'s first element will be skipped
* @return a Stream consisting of the remaining elements of {@code stream} after discarding the
* first element of {@code stream}.
*/
private static Stream<Time> skip(Stream<Time> stream, boolean skip){
return skip
? stream.skip(1)
: stream;
}
/**
* <p>Returns the unmodifiable set of claims set false by the operation that this time node
* represents.</p>
* @return the set of claims set false by the operation that this time node represents
*/
public Set<Claim> falsified(){
return falsified;
}
@Override
public String toString(){
StringBuilder result = new StringBuilder(toStringStart())
.append(" falsifying ")
.append(falsified().size())
.append(" Claims directly, and ")
.append(deepFalse())
.append(" Claims indirectly.")
.append(System.lineSeparator())
.append("Direct: ")
.append(falsified())
.append(System.lineSeparator());
for(Time t : children()){
String str = t.toString();
for(Scanner s = new Scanner(str); s.hasNextLine();){
result.append(" ").append(s.nextLine()).append(System.lineSeparator());
}
}
return result.toString();
}
@Override
public boolean equals(Object o){
if(o instanceof FalsifiedTime){
FalsifiedTime ft = (FalsifiedTime) o;
return falsified().equals(ft.falsified());
}
return false;
}
/**
* <p>A short description of this type of Time. The output of {@code toString()} begins with
* this. A trailing space should not be included. The description should take the form of a noun
* phrase.</p>
* @return a short description of this type of Time
*/
protected abstract String toStringStart();
/**
* <p>Returns the number of Claims {@link #falsified() falsified} by all the FalsifiedTime
* nth-children of this Time.</p>
* @return the number of Claims {@link #falsified() falsified} by all the FalsifiedTime
* nth-children of this Time
*/
private int deepFalse(){
int count = 0;
Set<Time> layer = new HashSet<>(children());
while(!layer.isEmpty()){
Set<Time> newLayer = new HashSet<>();
for(Time t : layer){
newLayer.addAll(t.children());
if(t instanceof FalsifiedTime){
count += ((FalsifiedTime) t).falsified().size();
}
}
layer = newLayer;
}
return count;
}
/**
* <p>An Exception thrown when a FalsifiedTime is constructed without any specified falsified
* Claims not already {@link #falsified falsified} by the constructed FalsifiedTime's
* FalsifiedTime nth-parents.</p>
* @author fiveham
* @author fiveham
*
*/
public static class NoUnaccountedClaims extends RuntimeException{
private static final long serialVersionUID = 7063069284727178843L;
private NoUnaccountedClaims(String s){
super(s);
}
}
}
|
package cgeo.geocaching.settings;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SelectMapfileActivity;
import cgeo.geocaching.cgeoapplication;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory.NavigationAppsEnum;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.gc.Login;
import cgeo.geocaching.files.SimpleDirChooser;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.utils.DatabaseBackupUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.LogTemplateProvider;
import cgeo.geocaching.utils.LogTemplateProvider.LogTemplate;
import org.apache.commons.lang3.StringUtils;
import org.openintents.intents.FileManagerIntents;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
private static final String INTENT_GOTO = "GOTO";
private static final int INTENT_GOTO_SERVICES = 1;
private static final int DIR_CHOOSER_MAPS_DIRECTORY_REQUEST = 4;
static final int OAUTH_OCDE_REQUEST = 5;
static final int OAUTH_TWITTER_REQUEST = 6;
private EditText signatureText;
/**
* Enumeration for directory choosers. This is how we can retrieve information about the
* directory and preference key in onActivityResult() easily just by knowing
* the result code.
*/
private enum DirChooserType {
GPX_IMPORT_DIR(1, R.string.pref_gpxImportDir,
Environment.getExternalStorageDirectory().getPath() + "/gpx"),
GPX_EXPORT_DIR(2, R.string.pref_gpxExportDir,
Environment.getExternalStorageDirectory().getPath() + "/gpx"),
THEMES_DIR(3, R.string.pref_renderthemepath, "");
public final int requestCode;
public final int keyId;
public final String defaultValue;
DirChooserType(final int requestCode, final int keyId, final String defaultValue) {
this.requestCode = requestCode;
this.keyId = keyId;
this.defaultValue = defaultValue;
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
setTheme(Settings.isLightSkin() ? R.style.settings_light : R.style.settings);
super.onCreate(savedInstanceState);
SettingsActivity.addPreferencesFromResource(this, R.xml.preferences);
initPreferences();
Intent intent = getIntent();
int gotoPage = intent.getIntExtra(INTENT_GOTO, 0);
if (gotoPage == INTENT_GOTO_SERVICES) {
// start with services screen
PreferenceScreen main = (PreferenceScreen) getPreference(R.string.pref_fakekey_main_screen);
int index = getPreference(R.string.pref_fakekey_services_screen).getOrder();
main.onItemClick(null, null, index, 0);
}
}
@Override
protected void onPause() {
Compatibility.dataChanged(getPackageName());
super.onPause();
}
private void initPreferences() {
initMapSourcePreference();
initDirChoosers();
initDefaultNavigationPreferences();
initBackupButtons();
initDbLocationPreference();
initDebugPreference();
initBasicMemberPreferences();
initSend2CgeoPreferences();
initServicePreferences();
initNavigationMenuPreferences();
for (int k : new int[] { R.string.pref_username, R.string.pref_password,
R.string.pref_pass_vote, R.string.pref_signature,
R.string.pref_mapsource, R.string.pref_renderthemepath,
R.string.pref_gpxExportDir, R.string.pref_gpxImportDir,
R.string.pref_mapDirectory, R.string.pref_defaultNavigationTool,
R.string.pref_defaultNavigationTool2, R.string.pref_webDeviceName,
R.string.pref_fakekey_preference_backup_info, }) {
bindSummaryToStringValue(k);
}
}
private void initNavigationMenuPreferences() {
for (NavigationAppsEnum appEnum : NavigationAppsEnum.values()) {
if (appEnum.app.isInstalled()) {
getPreference(appEnum.preferenceKey).setEnabled(true);
}
}
getPreference(R.string.pref_fakekey_basicmembers_screen)
.setEnabled(!Settings.isPremiumMember());
redrawScreen(R.string.pref_fakekey_navigation_menu_screen);
}
private void initServicePreferences() {
getPreference(R.string.pref_connectorOCActive).setOnPreferenceChangeListener(VALUE_CHANGE_LISTENER);
getPreference(R.string.pref_connectorGCActive).setOnPreferenceChangeListener(VALUE_CHANGE_LISTENER);
}
private static String getKey(final int prefKeyId) {
return cgeoapplication.getInstance().getString(prefKeyId);
}
private Preference getPreference(final int keyId) {
return SettingsActivity.findPreference(this, getKey(keyId));
}
// workaround, because OnContextItemSelected nor onMenuItemSelected is never called
OnMenuItemClickListener TEMPLATE_CLICK = new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem item) {
LogTemplate template = LogTemplateProvider.getTemplate(item.getItemId());
if (template != null) {
insertSignatureTemplate(template);
return true;
}
return false;
}
};
// workaround, because OnContextItemSelected and onMenuItemSelected are never called
void setSignatureTextView(final EditText view) {
this.signatureText = view;
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
// context menu for signature templates
if (v.getId() == R.id.signature_templates) {
menu.setHeaderTitle(R.string.init_signature_template_button);
ArrayList<LogTemplate> templates = LogTemplateProvider.getTemplates();
for (int i = 0; i < templates.size(); ++i) {
menu.add(0, templates.get(i).getItemId(), 0, templates.get(i).getResourceId());
menu.getItem(i).setOnMenuItemClickListener(TEMPLATE_CLICK);
}
}
super.onCreateContextMenu(menu, v, menuInfo);
}
private void insertSignatureTemplate(final LogTemplate template) {
String insertText = "[" + template.getTemplateString() + "]";
ActivityMixin.insertAtPosition(signatureText, insertText, true);
}
/**
* Fill the choice list for map sources.
*/
private void initMapSourcePreference() {
ListPreference pref = (ListPreference) getPreference(R.string.pref_mapsource);
List<MapSource> mapSources = MapProviderFactory.getMapSources();
CharSequence[] entries = new CharSequence[mapSources.size()];
CharSequence[] values = new CharSequence[mapSources.size()];
for (int i = 0; i < mapSources.size(); ++i) {
entries[i] = mapSources.get(i).getName();
values[i] = String.valueOf(mapSources.get(i).getNumericalId());
}
pref.setEntries(entries);
pref.setEntryValues(values);
}
/**
* Fill the choice list for default navigation tools.
*/
private void initDefaultNavigationPreferences() {
final List<NavigationAppsEnum> apps = NavigationAppFactory.getInstalledDefaultNavigationApps();
CharSequence[] entries = new CharSequence[apps.size()];
CharSequence[] values = new CharSequence[apps.size()];
for (int i = 0; i < apps.size(); ++i) {
entries[i] = apps.get(i).toString();
values[i] = String.valueOf(apps.get(i).id);
}
ListPreference pref = (ListPreference) getPreference(R.string.pref_defaultNavigationTool);
pref.setEntries(entries);
pref.setEntryValues(values);
pref = (ListPreference) getPreference(R.string.pref_defaultNavigationTool2);
pref.setEntries(entries);
pref.setEntryValues(values);
}
private void initDirChoosers() {
for (final DirChooserType dct : DirChooserType.values()) {
getPreference(dct.keyId).setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
startDirChooser(dct);
return false;
}
});
}
getPreference(R.string.pref_mapDirectory).setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
Intent i = new Intent(SettingsActivity.this,
SelectMapfileActivity.class);
startActivityForResult(i, DIR_CHOOSER_MAPS_DIRECTORY_REQUEST);
return false;
}
});
}
/**
* Fire up a directory chooser on click on the preference.
*
* @see #onActivityResult() for processing of the selected directory
*
* @param dct
* type of directory to be selected
*/
private void startDirChooser(final DirChooserType dct) {
final String startDirectory = Settings.getString(dct.keyId, dct.defaultValue);
try {
final Intent dirChooser = new Intent(FileManagerIntents.ACTION_PICK_DIRECTORY);
if (StringUtils.isNotBlank(startDirectory)) {
dirChooser.setData(Uri.fromFile(new File(startDirectory)));
}
dirChooser.putExtra(FileManagerIntents.EXTRA_TITLE,
getString(R.string.simple_dir_chooser_title));
dirChooser.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT,
getString(android.R.string.ok));
startActivityForResult(dirChooser, dct.requestCode);
} catch (android.content.ActivityNotFoundException ex) {
// OI file manager not available
final Intent dirChooser = new Intent(this, SimpleDirChooser.class);
dirChooser.putExtra(Intents.EXTRA_START_DIR, startDirectory);
startActivityForResult(dirChooser, dct.requestCode);
}
}
private void setChosenDirectory(final DirChooserType dct, final Intent data) {
final String directory = new File(data.getData().getPath()).getAbsolutePath();
if (StringUtils.isNotBlank(directory)) {
Preference p = getPreference(dct.keyId);
if (p == null) {
return;
}
Settings.putString(dct.keyId, directory);
p.setSummary(directory);
}
}
public void initBackupButtons() {
Preference backup = getPreference(R.string.pref_fakekey_preference_backup);
backup.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
return DatabaseBackupUtils.createBackup(SettingsActivity.this, new Runnable() {
@Override
public void run() {
VALUE_CHANGE_LISTENER.onPreferenceChange(SettingsActivity.this.getPreference(R.string.pref_fakekey_preference_backup_info), "");
}
});
}
});
Preference restore = getPreference(R.string.pref_fakekey_preference_restore);
restore.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
DatabaseBackupUtils.restoreDatabase(SettingsActivity.this);
return true;
}
});
}
private void initDbLocationPreference() {
Preference p = getPreference(R.string.pref_dbonsdcard);
p.setPersistent(false);
p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
boolean oldValue = Settings.isDbOnSDCard();
((cgeoapplication) SettingsActivity.this.getApplication())
.moveDatabase(SettingsActivity.this);
return oldValue != Settings.isDbOnSDCard();
}
});
}
private void initDebugPreference() {
Preference p = getPreference(R.string.pref_debug);
p.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
Log.setDebug((Boolean) newValue);
return true;
}
});
}
void initBasicMemberPreferences() {
getPreference(R.string.pref_fakekey_basicmembers_screen)
.setEnabled(!Settings.isPremiumMember());
getPreference(R.string.pref_loaddirectionimg)
.setEnabled(!Settings.isPremiumMember());
getPreference(R.string.pref_showcaptcha)
.setEnabled(!Settings.isPremiumMember());
redrawScreen(R.string.pref_fakekey_services_screen);
}
void redrawScreen(int key) {
PreferenceScreen screen = (PreferenceScreen) getPreference(key);
if (screen == null) {
return;
}
ListAdapter adapter = screen.getRootAdapter();
if (adapter instanceof BaseAdapter) {
((BaseAdapter) adapter).notifyDataSetChanged();
}
}
private static void initSend2CgeoPreferences() {
Settings.putString(R.string.pref_webDeviceName, Settings.getWebDeviceName());
}
void setOCDEAuthTitle() {
getPreference(R.string.pref_fakekey_ocde_authorization)
.setTitle(getString(Settings.hasOCDEAuthorization()
? R.string.init_reregister_oc_de
: R.string.init_register_oc_de));
}
void setTwitterAuthTitle() {
getPreference(R.string.pref_fakekey_twitter_authorization)
.setTitle(getString(Settings.hasTwitterAuthorization()
? R.string.init_twitter_reauthorize
: R.string.init_twitter_authorize));
}
public static void jumpToServicesPage(final Context fromActivity) {
final Intent intent = new Intent(fromActivity, SettingsActivity.class);
intent.putExtra(INTENT_GOTO, INTENT_GOTO_SERVICES);
fromActivity.startActivity(intent);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
for (DirChooserType dct : DirChooserType.values()) {
if (requestCode == dct.requestCode) {
setChosenDirectory(dct, data);
return;
}
}
switch (requestCode) {
case DIR_CHOOSER_MAPS_DIRECTORY_REQUEST:
if (data.hasExtra(Intents.EXTRA_MAP_FILE)) {
final String mapFile = data.getStringExtra(Intents.EXTRA_MAP_FILE);
Settings.setMapFile(mapFile);
if (!Settings.isValidMapFile(Settings.getMapFile())) {
ActivityMixin.showToast(this, R.string.warn_invalid_mapfile);
}
}
initMapSourcePreference();
getPreference(R.string.pref_mapDirectory).setSummary(
Settings.getMapFileDirectory());
break;
case OAUTH_OCDE_REQUEST:
setOCDEAuthTitle();
redrawScreen(R.string.pref_fakekey_services_screen);
break;
case OAUTH_TWITTER_REQUEST:
setTwitterAuthTitle();
redrawScreen(R.string.pref_fakekey_services_screen);
break;
default:
throw new IllegalArgumentException();
}
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static final Preference.OnPreferenceChangeListener VALUE_CHANGE_LISTENER = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object value) {
String stringValue = value.toString();
if (preference instanceof EditPasswordPreference) {
if (StringUtils.isBlank((String) value)) {
preference.setSummary(StringUtils.EMPTY);
} else {
preference.setSummary(StringUtils.repeat("\u2022 ", 10));
}
} else if (isPreference(preference, R.string.pref_mapsource)) {
// reset the cached map source
int mapSourceId = Integer.valueOf(stringValue);
final MapSource mapSource = MapProviderFactory.getMapSource(mapSourceId);
Settings.setMapSource(mapSource);
preference.setSummary(mapSource.getName());
} else if (isPreference(preference, R.string.pref_connectorOCActive) || isPreference(preference, R.string.pref_connectorGCActive)) {
// reset log-in status if connector activation was changed
cgeoapplication.getInstance().checkLogin = true;
} else if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (isPreference(preference, R.string.pref_fakekey_preference_backup_info)) {
final String text;
if (DatabaseBackupUtils.hasBackup()) {
text = preference.getContext().getString(R.string.init_backup_last) + " "
+ DatabaseBackupUtils.getBackupDateTime();
} else {
text = preference.getContext().getString(R.string.init_backup_last_no);
}
preference.setSummary(text);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
if (isPreference(preference, R.string.pref_username) || isPreference(preference, R.string.pref_password)) {
// reset log-in if gc user or password is changed
if (Login.isActualLoginStatus()) {
Login.logout();
}
cgeoapplication.getInstance().checkLogin = true;
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #VALUE_CHANGE_LISTENER
*/
private static void bindSummaryToValue(final Preference preference, final Object value) {
// Set the listener to watch for value changes.
if (preference == null) {
return;
}
preference.setOnPreferenceChangeListener(VALUE_CHANGE_LISTENER);
// Trigger the listener immediately with the preference's
// current value.
VALUE_CHANGE_LISTENER.onPreferenceChange(preference, value);
}
/**
* auto-care for the summary of the preference of string type with this key
*
* @param key
*/
private void bindSummaryToStringValue(final int key) {
Preference pref = getPreference(key);
if (pref == null) {
return;
}
String value = PreferenceManager
.getDefaultSharedPreferences(pref.getContext())
.getString(pref.getKey(), "");
bindSummaryToValue(pref, value);
}
@SuppressWarnings("deprecation")
public static Preference findPreference(final PreferenceActivity preferenceActivity, final CharSequence key) {
return preferenceActivity.findPreference(key);
}
@SuppressWarnings("deprecation")
public static void addPreferencesFromResource(final PreferenceActivity preferenceActivity, final int preferencesResId) {
preferenceActivity.addPreferencesFromResource(preferencesResId);
}
private static boolean isPreference(final Preference preference, int preferenceKeyId) {
return getKey(preferenceKeyId).equals(preference.getKey());
}
}
|
/*
* Thibaut Colar Dec 18, 2009
*/
package net.colar.netbeans.fan;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import net.colar.netbeans.fan.indexer.FanIndexer;
import net.colar.netbeans.fan.indexer.FanIndexerFactory;
import net.colar.netbeans.fan.platform.FanPlatform;
import net.jot.logger.JOTLogger;
import net.jot.persistance.JOTPersistanceManager;
import net.jot.prefs.JOTPreferences;
import org.openide.modules.ModuleInstall;
/**
* Module startup/shutdown hooks.
* @author thibautc
*/
public class FanModuleInstall extends ModuleInstall
{
// IF a breaking change is made to the prefs files compare to a previous version, bump up the number
public static final String PROP_PREF_FILE_VERSION = "nb.fantom.prefs.version";
public static final int PREF_VERSION = 2;
/**
* Startup
*/
@Override
public void restored()
{
System.out.println("Starting up Fantom plugin.");
// Initialize special logging as needed
FanNBLogging.setupLogging();
File fantomHome = FanUtilities.getFanUserHome();
File logHome = new File(fantomHome + File.separator + "log" + File.separator);
logHome.mkdirs();
File prefFile = new File(fantomHome, "jot.prefs");
try
{
if (!prefFile.exists() || isOutdated(prefFile))
{
prefFile = createPrefFiles(fantomHome);
}
System.setProperty("jot.prefs", prefFile.getAbsolutePath());
JOTPreferences prefs = JOTPreferences.getInstance();
// Initializing the Logger
JOTLogger.init(prefs, logHome.getAbsolutePath(), "jot.log");
JOTLogger.setPrintToConcole(true);
// Initialize the persistance / databases(s).
JOTPersistanceManager.getInstance().init(prefs);
} catch (Exception e)
{
e.printStackTrace();
}
//start indexer
FanPlatform platform = FanPlatform.getInstance(true);
if (null == platform)
{
return;
}
if (platform.isConfigured())
{
FanIndexerFactory.getIndexer().indexAll(false);
}
super.restored();
}
/**
* Shutdown
* @return
*/
@Override
public boolean closing()
{
System.out.println("Shutting down Fantom plugin.");
try
{
FanIndexer.shutdown();
Thread.sleep(250);
JOTPersistanceManager.getInstance().destroy();
JOTLogger.destroy();
} catch (Exception e)
{
e.printStackTrace();
}
return super.closing();
}
/**
* Create the pref file(s) and return the main pref file.
* @param fantomHome
* @return
*/
private File createPrefFiles(File fantomHome) throws IOException
{
InputStream is = getClass().getClassLoader().getResourceAsStream("net/colar/netbeans/fan/jot.prefs");
File prefFile = new File(fantomHome, "jot.prefs");
InputStream is2 = getClass().getClassLoader().getResourceAsStream("net/colar/netbeans/fan/db.properties");
copyIsIntoFile(is, prefFile);
File dbFile = new File(fantomHome, "db.properties");
copyIsIntoFile(is2, dbFile);
// Set the DB file path in the db props file
File dbFolder = new File(fantomHome.getAbsolutePath() + File.separator + "db" + File.separator);
dbFolder.mkdirs();
FileInputStream fis = new FileInputStream(dbFile);
Properties props = new Properties();
props.load(fis);
fis.close();
// H2 JDBC
props.setProperty("db.jdbc.url", "jdbc:h2:file:" + dbFolder.getAbsolutePath() + File.separator + "default;TRACE_LEVEL_FILE=1;LOCK_TIMEOUT=8000");
FileOutputStream fos = new FileOutputStream(dbFile);
props.store(fos, "");
fos.close();
// Set the DB path in the main props file
FileInputStream fis2 = new FileInputStream(prefFile);
Properties props2 = new Properties();
props2.load(fis2);
fis2.close();
props2.setProperty("db.fs.root_folder.windows", dbFolder.getAbsolutePath() + File.separator);
props2.setProperty("db.fs.root_folder.others", dbFolder.getAbsolutePath() + File.separator);
// VERSION
props2.setProperty(PROP_PREF_FILE_VERSION, "" + PREF_VERSION);
FileOutputStream fos2 = new FileOutputStream(prefFile);
props2.store(fos2, "");
fos2.close();
return prefFile;
}
private void copyIsIntoFile(InputStream is, File prefFile) throws IOException
{
FileOutputStream out = new FileOutputStream(prefFile);
byte[] buffer = new byte[10000];
int read = -1;
while ((read = is.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
out.close();
is.close();
}
private boolean isOutdated(File prefFile)
{
try
{
FileInputStream fis = new FileInputStream(prefFile);
Properties props = new Properties();
props.load(fis);
String version = props.getProperty(PROP_PREF_FILE_VERSION);
if (version != null && version.compareTo("" + PREF_VERSION) >= 0)
{
return false;
}
} catch (Exception e)
{
}
return true;
}
}
|
package biomodel.gui.textualeditor;
import java.awt.AWTError;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.tree.TreeNode;
import javax.xml.stream.XMLStreamException;
import main.Gui;
import main.util.Utility;
import odk.lang.FastMath;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.ext.SBasePlugin;
import org.sbml.jsbml.ext.comp.CompModelPlugin;
import org.sbml.jsbml.ext.comp.CompSBMLDocumentPlugin;
import org.sbml.jsbml.ext.comp.CompConstant;
import org.sbml.jsbml.ext.comp.CompSBasePlugin;
import org.sbml.jsbml.ext.comp.ExternalModelDefinition;
import org.sbml.jsbml.ext.comp.ModelDefinition;
import org.sbml.jsbml.ext.comp.ReplacedBy;
import org.sbml.jsbml.ext.comp.ReplacedElement;
import org.sbml.jsbml.ext.fbc.FBCConstants;
import org.sbml.jsbml.ext.fbc.FBCModelPlugin;
import org.sbml.jsbml.ext.fbc.FluxBound;
import org.sbml.jsbml.ext.qual.QualConstant;
import org.sbml.jsbml.ext.qual.QualitativeModel;
import org.sbml.jsbml.Compartment;
//CompartmentType not supported in Level 3
//import org.sbml.jsbml.CompartmentType;
import org.sbml.jsbml.Constraint;
import org.sbml.jsbml.Delay;
import org.sbml.jsbml.Event;
import org.sbml.jsbml.EventAssignment;
import org.sbml.jsbml.FunctionDefinition;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.ext.layout.GraphicalObject;
import org.sbml.jsbml.ext.layout.Layout;
import org.sbml.jsbml.ext.layout.LayoutConstants;
import org.sbml.jsbml.ext.layout.LayoutModelPlugin;
import org.sbml.jsbml.text.parser.FormulaParserLL3;
import org.sbml.jsbml.text.parser.IFormulaParser;
import org.sbml.jsbml.text.parser.ParseException;
import org.sbml.jsbml.validator.SBMLValidator;
import org.sbml.jsbml.xml.XMLNode;
import org.sbml.jsbml.AbstractNamedSBase;
import org.sbml.jsbml.AbstractSBase;
import org.sbml.jsbml.Annotation;
import org.sbml.jsbml.ExplicitRule;
import org.sbml.jsbml.ListOf;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.ModifierSpeciesReference;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.QuantityWithUnit;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.Rule;
import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.SBMLException;
import org.sbml.jsbml.SBMLReader;
import org.sbml.jsbml.SBMLWriter;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
//SpeciesType not supported in Level 3
//import org.sbml.jsbml.SpeciesType;
import org.sbml.jsbml.Unit;
import org.sbml.jsbml.UnitDefinition;
import org.sbml.jsbml.JSBML;
import flanagan.math.Fmath;
import flanagan.math.PsRandom;
import biomodel.parser.BioModel;
import biomodel.util.GlobalConstants;
public class SBMLutilities {
/**
* Check that ID is valid and unique
*/
public static boolean checkID(SBMLDocument document, String ID, String selectedID, boolean isReacParam, boolean isMetaId) {
Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
if (ID.equals("")) {
JOptionPane.showMessageDialog(Gui.frame, "An ID is required.", "Enter an ID", JOptionPane.ERROR_MESSAGE);
return true;
}
if (!(IDpat.matcher(ID).matches())) {
JOptionPane.showMessageDialog(Gui.frame, "An ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (ID.equals("t") || ID.equals("time") || ID.equals("true") || ID.equals("false") || ID.equals("notanumber") || ID.equals("pi")
|| ID.equals("infinity") || ID.equals("exponentiale") || ID.equals("abs") || ID.equals("arccos") || ID.equals("arccosh")
|| ID.equals("arcsin") || ID.equals("arcsinh") || ID.equals("arctan") || ID.equals("arctanh") || ID.equals("arccot")
|| ID.equals("arccoth") || ID.equals("arccsc") || ID.equals("arccsch") || ID.equals("arcsec") || ID.equals("arcsech")
|| ID.equals("acos") || ID.equals("acosh") || ID.equals("asin") || ID.equals("asinh") || ID.equals("atan") || ID.equals("atanh")
|| ID.equals("acot") || ID.equals("acoth") || ID.equals("acsc") || ID.equals("acsch") || ID.equals("asec") || ID.equals("asech")
|| ID.equals("cos") || ID.equals("cosh") || ID.equals("cot") || ID.equals("coth") || ID.equals("csc") || ID.equals("csch")
|| ID.equals("ceil") || ID.equals("factorial") || ID.equals("exp") || ID.equals("floor") || ID.equals("ln") || ID.equals("log")
|| ID.equals("sqr") || ID.equals("log10") || ID.equals("pow") || ID.equals("sqrt") || ID.equals("root") || ID.equals("piecewise")
|| ID.equals("sec") || ID.equals("sech") || ID.equals("sin") || ID.equals("sinh") || ID.equals("tan") || ID.equals("tanh")
|| ID.equals("and") || ID.equals("or") || ID.equals("xor") || ID.equals("not") || ID.equals("eq") || ID.equals("geq")
|| ID.equals("leq") || ID.equals("gt") || ID.equals("neq") || ID.equals("lt") || ID.equals("delay")
|| ((document.getLevel() > 2) && (ID.equals("avogadro")))) {
JOptionPane.showMessageDialog(Gui.frame, "ID cannot be a reserved word.", "Illegal ID", JOptionPane.ERROR_MESSAGE);
return true;
}
if (!ID.equals(selectedID) && (getElementBySId(document, ID)!=null || getElementByMetaId(document, ID)!=null)) {
if (isReacParam) {
JOptionPane.showMessageDialog(Gui.frame, "ID shadows a global ID.", "Not a Unique ID", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(Gui.frame, "ID is not unique.", "Enter a Unique ID", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Find invalid reaction variables in a formula
*/
public static ArrayList<String> getInvalidVariables(SBMLDocument document, String formula, String arguments, boolean isFunction) {
ArrayList<String> validVars = new ArrayList<String>();
ArrayList<String> invalidVars = new ArrayList<String>();
Model model = document.getModel();
ListOf sbml = model.getListOfFunctionDefinitions();
for (int i = 0; i < model.getFunctionDefinitionCount(); i++) {
validVars.add(((FunctionDefinition) sbml.get(i)).getId());
}
if (!isFunction) {
sbml = model.getListOfSpecies();
for (int i = 0; i < model.getSpeciesCount(); i++) {
validVars.add(((Species) sbml.get(i)).getId());
}
}
if (isFunction) {
String[] args = arguments.split(" |\\,");
for (int i = 0; i < args.length; i++) {
validVars.add(args[i]);
}
}
else {
sbml = model.getListOfCompartments();
for (int i = 0; i < model.getCompartmentCount(); i++) {
if (document.getLevel() > 2 || ((Compartment) sbml.get(i)).getSpatialDimensions() != 0) {
validVars.add(((Compartment) sbml.get(i)).getId());
}
}
sbml = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
validVars.add(((Parameter) sbml.get(i)).getId());
}
sbml = model.getListOfReactions();
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = (Reaction) sbml.get(i);
validVars.add(reaction.getId());
ListOf sbml2 = reaction.getListOfReactants();
for (int j = 0; j < reaction.getReactantCount(); j++) {
SpeciesReference reactant = (SpeciesReference) sbml2.get(j);
if ((reactant.isSetId()) && (!reactant.getId().equals(""))) {
validVars.add(reactant.getId());
}
}
sbml2 = reaction.getListOfProducts();
for (int j = 0; j < reaction.getProductCount(); j++) {
SpeciesReference product = (SpeciesReference) sbml2.get(j);
if ((product.isSetId()) && (!product.getId().equals(""))) {
validVars.add(product.getId());
}
}
}
String[] kindsL3V1 = { "ampere", "avogadro", "becquerel", "candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal",
"radian", "second", "siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
for (int i = 0; i < kindsL3V1.length; i++) {
validVars.add(kindsL3V1[i]);
}
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
validVars.add(model.getListOfUnitDefinitions().get(i).getId());
}
}
String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-|>|=|<|\\^|%|&|\\||!");
for (int i = 0; i < splitLaw.length; i++) {
if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos") || splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin")
|| splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan") || splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot")
|| splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc") || splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec")
|| splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos") || splitLaw[i].equals("acosh") || splitLaw[i].equals("asin")
|| splitLaw[i].equals("asinh") || splitLaw[i].equals("atan") || splitLaw[i].equals("atanh") || splitLaw[i].equals("acot")
|| splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc") || splitLaw[i].equals("acsch") || splitLaw[i].equals("asec")
|| splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh") || splitLaw[i].equals("cot")
|| splitLaw[i].equals("coth") || splitLaw[i].equals("csc") || splitLaw[i].equals("csch") || splitLaw[i].equals("ceil")
|| splitLaw[i].equals("factorial") || splitLaw[i].equals("exp") || splitLaw[i].equals("floor") || splitLaw[i].equals("ln")
|| splitLaw[i].equals("log") || splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow")
|| splitLaw[i].equals("sqrt") || splitLaw[i].equals("root") || splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec")
|| splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh") || splitLaw[i].equals("tan")
|| splitLaw[i].equals("tanh") || splitLaw[i].equals("") || splitLaw[i].equals("and") || splitLaw[i].equals("or")
|| splitLaw[i].equals("xor") || splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq")
|| splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq") || splitLaw[i].equals("lt")
|| splitLaw[i].equals("delay") || splitLaw[i].equals("t") || splitLaw[i].equals("time") || splitLaw[i].equals("true")
|| splitLaw[i].equals("false") || splitLaw[i].equals("pi") || splitLaw[i].equals("exponentiale")
|| splitLaw[i].equals("infinity") || splitLaw[i].equals("notanumber")
|| ((document.getLevel() > 2) && (splitLaw[i].equals("avogadro")))) {
}
else {
String temp = splitLaw[i];
if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) {
temp = splitLaw[i].substring(0, splitLaw[i].length() - 1);
}
try {
Double.parseDouble(temp);
}
catch (Exception e1) {
if (!validVars.contains(splitLaw[i])) {
if (splitLaw[i].equals("uniform")) {
createFunction(model, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)");
} else if (splitLaw[i].equals("normal")) {
createFunction(model, "normal", "Normal distribution", "lambda(m,s,m)");
} else if (splitLaw[i].equals("exponential")) {
createFunction(model, "exponential", "Exponential distribution", "lambda(l,1/l)");
} else if (splitLaw[i].equals("gamma")) {
createFunction(model, "gamma", "Gamma distribution", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("lognormal")) {
createFunction(model, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))");
} else if (splitLaw[i].equals("chisq")) {
createFunction(model, "chisq", "Chi-squared distribution", "lambda(nu,nu)");
} else if (splitLaw[i].equals("laplace")) {
createFunction(model, "laplace", "Laplace distribution", "lambda(a,0)");
} else if (splitLaw[i].equals("cauchy")) {
createFunction(model, "cauchy", "Cauchy distribution", "lambda(a,a)");
} else if (splitLaw[i].equals("rayleigh")) {
createFunction(model, "rayleigh", "Rayleigh distribution","lambda(s,s*sqrt(pi/2))");
} else if (splitLaw[i].equals("poisson")) {
createFunction(model, "poisson", "Poisson distribution", "lambda(mu,mu)");
} else if (splitLaw[i].equals("binomial")) {
createFunction(model, "binomial", "Binomial distribution", "lambda(p,n,p*n)");
} else if (splitLaw[i].equals("bernoulli")) {
createFunction(model, "bernoulli", "Bernoulli distribution", "lambda(p,p)");
} else if (splitLaw[i].equals("PSt")) {
createFunction(model, "PSt", "Probabilistic Steady State Property", "lambda(x,uniform(0,1))");
} else if (splitLaw[i].equals("St")) {
createFunction(model, "St", "Steady State Property", "lambda(x,not(not(x)))");
} else if (splitLaw[i].equals("PG")) {
createFunction(model, "PG", "Probabilistic Globally Property", "lambda(t,x,uniform(0,1))");
} else if (splitLaw[i].equals("G")) {
createFunction(model, "G", "Globally Property", "lambda(t,x,or(not(t),x))");
} else if (splitLaw[i].equals("PF")) {
createFunction(model, "PF", "Probabilistic Eventually Property", "lambda(t,x,uniform(0,1))");
} else if (splitLaw[i].equals("F")) {
createFunction(model, "F", "Eventually Property", "lambda(t,x,or(not(t),not(x)))");
} else if (splitLaw[i].equals("PU")) {
createFunction(model, "PU", "Probabilistic Until Property", "lambda(t,x,y,uniform(0,1))");
} else if (splitLaw[i].equals("U")) {
createFunction(model, "G", "Globally Property", "lambda(t,x,or(not(t),x))");
createFunction(model, "F", "Eventually Property", "lambda(t,x,or(not(t),not(x)))");
createFunction(model, "U", "Until Property", "lambda(t,x,y,and(G(t,x),F(t,y)))");
} else if (splitLaw[i].equals("rate")) {
createFunction(model, "rate", "Rate", "lambda(a,a)");
} else if (splitLaw[i].equals("BIT")) {
createFunction(model, "BIT", "bit selection", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("BITAND")) {
createFunction(model, "BITAND", "Bitwise AND", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("BITOR")) {
createFunction(model, "BITOR", "Bitwise OR", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("BITNOT")) {
createFunction(model, "BITNOT", "Bitwise NOT", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("BITXOR")) {
createFunction(model, "BITXOR", "Bitwise XOR", "lambda(a,b,a*b)");
} else if (splitLaw[i].equals("mod")) {
createFunction(model, "mod", "Modular", "lambda(a,b,a-floor(a/b)*b)");
} else if (splitLaw[i].equals("neighborQuantityLeft")) {
createFunction(sbml.getModel(), "neighborQuantityLeft", "neighborQuantityLeft", "lambda(a,0)");
createFunction(sbml.getModel(), "neighborQuantityLeftFull", "neighborQuantityLeftFull", "lambda(a,b,c,0)");
} else if (splitLaw[i].equals("neighborQuantityRight")) {
createFunction(sbml.getModel(), "neighborQuantityRight", "neighborQuantityRight", "lambda(a,0)");
createFunction(sbml.getModel(), "neighborQuantityRightFull", "neighborQuantityRightFull", "lambda(a,b,c,0)");
} else if (splitLaw[i].equals("neighborQuantityAbove")) {
createFunction(sbml.getModel(), "neighborQuantityAbove", "neighborQuantityAbove", "lambda(a,0)");
createFunction(sbml.getModel(), "neighborQuantityAboveFull", "neighborQuantityAboveFull", "lambda(a,b,c,0)");
} else if (splitLaw[i].equals("neighborQuantityBelow")) {
createFunction(sbml.getModel(), "neighborQuantityBelow", "neighborQuantityBelow", "lambda(a,0)");
createFunction(sbml.getModel(), "neighborQuantityBelowFull", "neighborQuantityBelowFull", "lambda(a,b,c,0)");
}
else {
invalidVars.add(splitLaw[i]);
}
if (splitLaw[i].contains("neighborQuantity")) {
createFunction(sbml.getModel(), "getCompartmentLocationX", "getCompartmentLocationX", "lambda(a,0)");
createFunction(sbml.getModel(), "getCompartmentLocationY", "getCompartmentLocationY", "lambda(a,0)");
}
}
}
}
}
return invalidVars;
}
public static void pruneUnusedSpecialFunctions(SBMLDocument document) {
if (document.getModel().getFunctionDefinition("uniform")!=null) {
if (!variableInUse(document, "uniform", false, false, true)) {
document.getModel().removeFunctionDefinition("uniform");
}
}
if (document.getModel().getFunctionDefinition("normal")!=null) {
if (!variableInUse(document, "normal", false, false, true)) {
document.getModel().removeFunctionDefinition("normal");
}
}
if (document.getModel().getFunctionDefinition("exponential")!=null) {
if (!variableInUse(document, "exponential", false, false, true)) {
document.getModel().removeFunctionDefinition("exponential");
}
}
if (document.getModel().getFunctionDefinition("gamma")!=null) {
if (!variableInUse(document, "gamma", false, false, true)) {
document.getModel().removeFunctionDefinition("gamma");
}
}
if (document.getModel().getFunctionDefinition("lognormal")!=null) {
if (!variableInUse(document, "lognormal", false, false, true)) {
document.getModel().removeFunctionDefinition("lognormal");
}
}
if (document.getModel().getFunctionDefinition("chisq")!=null) {
if (!variableInUse(document, "chisq", false, false, true)) {
document.getModel().removeFunctionDefinition("chisq");
}
}
if (document.getModel().getFunctionDefinition("laplace")!=null) {
if (!variableInUse(document, "laplace", false, false, true)) {
document.getModel().removeFunctionDefinition("laplace");
}
}
if (document.getModel().getFunctionDefinition("cauchy")!=null) {
if (!variableInUse(document, "cauchy", false, false, true)) {
document.getModel().removeFunctionDefinition("cauchy");
}
}
if (document.getModel().getFunctionDefinition("rayleigh")!=null) {
if (!variableInUse(document, "rayleigh", false, false, true)) {
document.getModel().removeFunctionDefinition("rayleigh");
}
}
if (document.getModel().getFunctionDefinition("poisson")!=null) {
if (!variableInUse(document, "poisson", false, false, true)) {
document.getModel().removeFunctionDefinition("poisson");
}
}
if (document.getModel().getFunctionDefinition("binomial")!=null) {
if (!variableInUse(document, "binomial", false, false, true)) {
document.getModel().removeFunctionDefinition("binomial");
}
}
if (document.getModel().getFunctionDefinition("bernoulli")!=null) {
if (!variableInUse(document, "bernoulli", false, false, true)) {
document.getModel().removeFunctionDefinition("bernoulli");
}
}
if (document.getModel().getFunctionDefinition("St")!=null) {
if (!variableInUse(document, "St", false, false, true)) {
document.getModel().removeFunctionDefinition("St");
}
}
if (document.getModel().getFunctionDefinition("PSt")!=null) {
if (!variableInUse(document, "PSt", false, false, true)) {
document.getModel().removeFunctionDefinition("PSt");
}
}
if (document.getModel().getFunctionDefinition("PG")!=null) {
if (!variableInUse(document, "PG", false, false, true)) {
document.getModel().removeFunctionDefinition("PG");
}
}
if (document.getModel().getFunctionDefinition("PF")!=null) {
if (!variableInUse(document, "PF", false, false, true)) {
document.getModel().removeFunctionDefinition("PF");
}
}
if (document.getModel().getFunctionDefinition("PU")!=null) {
if (!variableInUse(document, "PU", false, false, true)) {
document.getModel().removeFunctionDefinition("PU");
}
}
if (document.getModel().getFunctionDefinition("G")!=null) {
if (!variableInUse(document, "G", false, false, true)) {
document.getModel().removeFunctionDefinition("G");
}
}
if (document.getModel().getFunctionDefinition("F")!=null) {
if (!variableInUse(document, "F", false, false, true)) {
document.getModel().removeFunctionDefinition("F");
}
}
if (document.getModel().getFunctionDefinition("U")!=null) {
if (!variableInUse(document, "U", false, false, true)) {
document.getModel().removeFunctionDefinition("U");
}
}
if (document.getModel().getFunctionDefinition("rate")!=null) {
if (!variableInUse(document, "rate", false, false, true)) {
document.getModel().removeFunctionDefinition("rate");
}
}
if (document.getModel().getFunctionDefinition("mod")!=null) {
if (!variableInUse(document, "mod", false, false, true)) {
document.getModel().removeFunctionDefinition("mod");
}
}
if (document.getModel().getFunctionDefinition("BIT")!=null) {
if (!variableInUse(document, "BIT", false, false, true)) {
document.getModel().removeFunctionDefinition("BIT");
}
}
if (document.getModel().getFunctionDefinition("BITOR")!=null) {
if (!variableInUse(document, "BITOR", false, false, true)) {
document.getModel().removeFunctionDefinition("BITOR");
}
}
if (document.getModel().getFunctionDefinition("BITXOR")!=null) {
if (!variableInUse(document, "BITXOR", false, false, true)) {
document.getModel().removeFunctionDefinition("BITXOR");
}
}
if (document.getModel().getFunctionDefinition("BITNOT")!=null) {
if (!variableInUse(document, "BITNOT", false, false, true)) {
document.getModel().removeFunctionDefinition("BITNOT");
}
}
if (document.getModel().getFunctionDefinition("BITAND")!=null) {
if (!variableInUse(document, "BITAND", false, false, true)) {
document.getModel().removeFunctionDefinition("BITAND");
}
}
// if (document.getModel().getFunctionDefinition("neighborQuantityLeft") != null) {
// if (!variableInUse(document, "neighborQuantityLeft", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityLeft");
// if (document.getModel().getFunctionDefinition("neighborQuantityRight") != null) {
// if (!variableInUse(document, "neighborQuantityRight", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityRight");
// if (document.getModel().getFunctionDefinition("neighborQuantityAbove") != null) {
// if (!variableInUse(document, "neighborQuantityAbove", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityAbove");
// if (document.getModel().getFunctionDefinition("neighborQuantityBelow") != null) {
// if (!variableInUse(document, "neighborQuantityBelow", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityBelow");
// if (document.getModel().getFunctionDefinition("neighborQuantityLeftFull") != null) {
// if (!variableInUse(document, "neighborQuantityLeftFull", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityLeftFull");
// if (document.getModel().getFunctionDefinition("neighborQuantityRightFull") != null) {
// if (!variableInUse(document, "neighborQuantityRightFull", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityRightFull");
// if (document.getModel().getFunctionDefinition("neighborQuantityAboveFull") != null) {
// if (!variableInUse(document, "neighborQuantityAboveFull", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityAboveFull");
// if (document.getModel().getFunctionDefinition("neighborQuantityBelowFull") != null) {
// if (!variableInUse(document, "neighborQuantityBelowFull", false, false, true)) {
// document.getModel().removeFunctionDefinition("neighborQuantityBelowFull");
// if (document.getModel().getFunctionDefinition("getCompartmentLocationX") != null) {
// if (!variableInUse(document, "getCompartmentLocationX", false, false, true)) {
// document.getModel().removeFunctionDefinition("getCompartmentLocationX");
// if (document.getModel().getFunctionDefinition("getCompartmentLocationY") != null) {
// if (!variableInUse(document, "getCompartmentLocationY", false, false, true)) {
// document.getModel().removeFunctionDefinition("getCompartmentLocationY");
}
/**
* Convert ASTNodes into a string
*/
public static String myFormulaToString(ASTNode mathFormula) {
if (mathFormula==null) return "";
setTimeToT(mathFormula);
String formula;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.infix", "").equals("prefix")) {
formula = JSBML.formulaToString(mathFormula);
} else {
formula = myFormulaToStringInfix(mathFormula);
}
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
/**
* Recursive function to change time variable to t
*/
public static void setTimeToT(ASTNode node) {
if (node==null) return;
if (node.getType() == ASTNode.Type.NAME_TIME) {
if (!node.getName().equals("t") || !node.getName().equals("time")) {
node.setName("t");
}
}
else if (node.getType() == ASTNode.Type.NAME_AVOGADRO) {
node.setName("avogadro");
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeToT(node.getChild(c));
}
/**
* Convert String into ASTNodes
*/
public static ASTNode myParseFormula(String formula) {
ASTNode mathFormula = null;
Preferences biosimrc = Preferences.userRoot();
try {
IFormulaParser parser = new FormulaParserLL3(new StringReader(""));
if (biosimrc.get("biosim.general.infix", "").equals("prefix")) {
mathFormula = ASTNode.parseFormula(formula, parser);
}
else {
mathFormula = ASTNode.parseFormula(formula, parser);
// mathFormula = libsbml.parseL3Formula(formula);
}
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
/**
* Recursive function to set time and trig functions
*/
public static void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == ASTNode.Type.NAME) {
if (node.getName().equals("t")) {
node.setType(ASTNode.Type.NAME_TIME);
}
else if (node.getName().equals("time")) {
node.setType(ASTNode.Type.NAME_TIME);
}
else if (node.getName().equals("avogadro")) {
node.setType(ASTNode.Type.NAME_AVOGADRO);
}
}
if (node.getType() == ASTNode.Type.FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(ASTNode.Type.FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(ASTNode.Type.FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(ASTNode.Type.FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(ASTNode.Type.FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(ASTNode.Type.FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(ASTNode.Type.FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(ASTNode.Type.FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(ASTNode.Type.FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(ASTNode.Type.FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
/**
* Check the number of arguments to a function
*/
public static boolean checkNumFunctionArguments(SBMLDocument document, ASTNode node) {
ListOf sbml = document.getModel().getListOfFunctionDefinitions();
switch (node.getType()) {
case FUNCTION_ABS:
case FUNCTION_ARCCOS:
case FUNCTION_ARCCOSH:
case FUNCTION_ARCSIN:
case FUNCTION_ARCSINH:
case FUNCTION_ARCTAN:
case FUNCTION_ARCTANH:
case FUNCTION_ARCCOT:
case FUNCTION_ARCCOTH:
case FUNCTION_ARCCSC:
case FUNCTION_ARCCSCH:
case FUNCTION_ARCSEC:
case FUNCTION_ARCSECH:
case FUNCTION_COS:
case FUNCTION_COSH:
case FUNCTION_SIN:
case FUNCTION_SINH:
case FUNCTION_TAN:
case FUNCTION_TANH:
case FUNCTION_COT:
case FUNCTION_COTH:
case FUNCTION_CSC:
case FUNCTION_CSCH:
case FUNCTION_SEC:
case FUNCTION_SECH:
case FUNCTION_CEILING:
case FUNCTION_FACTORIAL:
case FUNCTION_EXP:
case FUNCTION_FLOOR:
case FUNCTION_LN:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found " + node.getNumChildren() + ".",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument for " + node.getName() + " function must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case LOGICAL_NOT:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found " + node.getNumChildren() + ".",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument for not function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case LOGICAL_AND:
case LOGICAL_OR:
case LOGICAL_XOR:
for (int i = 0; i < node.getNumChildren(); i++) {
if (!node.getChild(i).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument " + i + " for " + node.getName() + " function is not of type Boolean.",
"Boolean Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
}
break;
case PLUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case MINUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if ((node.getNumChildren() > 1) && (node.getChild(1).isBoolean())) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case TIMES:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case DIVIDE:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case POWER:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case FUNCTION_DELAY:
case FUNCTION_POWER:
case FUNCTION_ROOT:
case RELATIONAL_GEQ:
case RELATIONAL_LEQ:
case RELATIONAL_LT:
case RELATIONAL_GT:
case FUNCTION_LOG:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found " + node.getNumChildren() + ".",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 1 for " + node.getName() + " function must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Argument 2 for " + node.getName() + " function must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case RELATIONAL_EQ:
case RELATIONAL_NEQ:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found " + node.getNumChildren() + ".",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if ((node.getChild(0).isBoolean() && !node.getChild(1).isBoolean()) || (!node.getChild(0).isBoolean() && node.getChild(1).isBoolean())) {
JOptionPane.showMessageDialog(Gui.frame, "Arguments for " + node.getName() + " function must either both be numbers or Booleans.",
"Argument Mismatch", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case FUNCTION_PIECEWISE:
if (node.getNumChildren() < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 1; i < node.getNumChildren(); i += 2) {
if (!node.getChild(i).isBoolean()) {
JOptionPane.showMessageDialog(Gui.frame, "Even arguments of piecewise function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
int pieceType = -1;
for (int i = 0; i < node.getNumChildren(); i += 2) {
if (node.getChild(i).isBoolean()) {
if (pieceType == 2) {
JOptionPane.showMessageDialog(Gui.frame, "All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 1;
}
else {
if (pieceType == 1) {
JOptionPane.showMessageDialog(Gui.frame, "All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 2;
}
}
case FUNCTION:
for (int i = 0; i < document.getModel().getFunctionDefinitionCount(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
if (numArgs != node.getNumChildren()) {
JOptionPane.showMessageDialog(Gui.frame,
"Expected " + numArgs + " argument(s) for " + node.getName() + " but found " + node.getNumChildren() + ".",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
}
}
break;
case NAME:
if (node.getName().equals("abs") || node.getName().equals("arccos") || node.getName().equals("arccosh")
|| node.getName().equals("arcsin") || node.getName().equals("arcsinh") || node.getName().equals("arctan")
|| node.getName().equals("arctanh") || node.getName().equals("arccot") || node.getName().equals("arccoth")
|| node.getName().equals("arccsc") || node.getName().equals("arccsch") || node.getName().equals("arcsec")
|| node.getName().equals("arcsech") || node.getName().equals("acos") || node.getName().equals("acosh")
|| node.getName().equals("asin") || node.getName().equals("asinh") || node.getName().equals("atan")
|| node.getName().equals("atanh") || node.getName().equals("acot") || node.getName().equals("acoth")
|| node.getName().equals("acsc") || node.getName().equals("acsch") || node.getName().equals("asec")
|| node.getName().equals("asech") || node.getName().equals("cos") || node.getName().equals("cosh")
|| node.getName().equals("cot") || node.getName().equals("coth") || node.getName().equals("csc") || node.getName().equals("csch")
|| node.getName().equals("ceil") || node.getName().equals("factorial") || node.getName().equals("exp")
|| node.getName().equals("floor") || node.getName().equals("ln") || node.getName().equals("log") || node.getName().equals("sqr")
|| node.getName().equals("log10") || node.getName().equals("sqrt") || node.getName().equals("sec")
|| node.getName().equals("sech") || node.getName().equals("sin") || node.getName().equals("sinh") || node.getName().equals("tan")
|| node.getName().equals("tanh") || node.getName().equals("not")) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 1 argument for " + node.getName() + " but found 0.",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("and") || node.getName().equals("or") || node.getName().equals("xor") || node.getName().equals("pow")
|| node.getName().equals("eq") || node.getName().equals("geq") || node.getName().equals("leq") || node.getName().equals("gt")
|| node.getName().equals("neq") || node.getName().equals("lt") || node.getName().equals("delay") || node.getName().equals("root")) {
JOptionPane.showMessageDialog(Gui.frame, "Expected 2 arguments for " + node.getName() + " but found 0.",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("piecewise")) {
JOptionPane.showMessageDialog(Gui.frame, "Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 0; i < document.getModel().getFunctionDefinitionCount(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
JOptionPane.showMessageDialog(Gui.frame, "Expected " + numArgs + " argument(s) for " + node.getName() + " but found 0.",
"Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
}
break;
}
for (int c = 0; c < node.getNumChildren(); c++) {
if (checkNumFunctionArguments(document, node.getChild(c))) {
return true;
}
}
return false;
}
public static Boolean isSpecialFunction(String functionId) {
if (functionId.equals("uniform")) return true;
else if (functionId.equals("normal")) return true;
else if (functionId.equals("exponential")) return true;
else if (functionId.equals("gamma")) return true;
else if (functionId.equals("lognormal")) return true;
else if (functionId.equals("chisq")) return true;
else if (functionId.equals("laplace")) return true;
else if (functionId.equals("cauchy")) return true;
else if (functionId.equals("poisson")) return true;
else if (functionId.equals("binomial")) return true;
else if (functionId.equals("bernoulli")) return true;
else if (functionId.equals("St")) return true;
else if (functionId.equals("PSt")) return true;
else if (functionId.equals("PG")) return true;
else if (functionId.equals("PF")) return true;
else if (functionId.equals("PU")) return true;
else if (functionId.equals("G")) return true;
else if (functionId.equals("F")) return true;
else if (functionId.equals("U")) return true;
return false;
}
public static void fillBlankMetaIDs (SBMLDocument document) {
int metaIDIndex = 1;
Model model = document.getModel();
setDefaultMetaID(document, model, metaIDIndex);
for (int i = 0; i < model.getNumParameters(); i++)
metaIDIndex = setDefaultMetaID(document, model.getParameter(i), metaIDIndex);
for (int i = 0; i < model.getSpeciesCount(); i++)
metaIDIndex = setDefaultMetaID(document, model.getSpecies(i), metaIDIndex);
for (int i = 0; i < model.getReactionCount(); i++)
metaIDIndex = setDefaultMetaID(document, model.getReaction(i), metaIDIndex);
for (int i = 0; i < model.getRuleCount(); i++)
metaIDIndex = setDefaultMetaID(document, model.getRule(i), metaIDIndex);
CompModelPlugin compModel = (CompModelPlugin) document.getModel().getExtension(CompConstant.namespaceURI);
if (compModel != null && compModel.isSetListOfSubmodels()) {
for (int i = 0; i < compModel.getListOfSubmodels().size(); i++)
metaIDIndex = setDefaultMetaID(document, compModel.getListOfSubmodels().get(i), metaIDIndex);
}
}
public static int setDefaultMetaID(SBMLDocument document, SBase sbmlObject, int metaIDIndex) {
CompSBMLDocumentPlugin compDocument = (CompSBMLDocumentPlugin) document.getExtension(CompConstant.namespaceURI);
String metaID = sbmlObject.getMetaId();
if (metaID == null || metaID.equals("")) {
metaID = "iBioSim" + metaIDIndex;
while (getElementByMetaId(document, metaID) != null
|| (compDocument != null && getElementByMetaId(compDocument, metaID) != null)) {
metaIDIndex++;
metaID = "iBioSim" + metaIDIndex;
}
setMetaId(sbmlObject, metaID);
metaIDIndex++;
}
return metaIDIndex;
}
public static ArrayList<String> CreateListOfUsedIDs(SBMLDocument document) {
ArrayList<String> usedIDs = new ArrayList<String>();
if (document==null) return usedIDs;
Model model = document.getModel();
if (model.isSetId()) {
usedIDs.add(model.getId());
}
ListOf ids = model.getListOfFunctionDefinitions();
for (int i = 0; i < model.getFunctionDefinitionCount(); i++) {
usedIDs.add(((FunctionDefinition) ids.get(i)).getId());
}
usedIDs.add("uniform");
usedIDs.add("normal");
usedIDs.add("exponential");
usedIDs.add("gamma");
usedIDs.add("lognormal");
usedIDs.add("chisq");
usedIDs.add("laplace");
usedIDs.add("cauchy");
usedIDs.add("poisson");
usedIDs.add("binomial");
usedIDs.add("bernoulli");
usedIDs.add("St");
usedIDs.add("PSt");
usedIDs.add("PG");
usedIDs.add("PF");
usedIDs.add("PU");
usedIDs.add("G");
usedIDs.add("F");
usedIDs.add("U");
ids = model.getListOfUnitDefinitions();
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
usedIDs.add(((UnitDefinition) ids.get(i)).getId());
}
// CompartmentType and SpeciesType not supported in Level 3
// ids = model.getListOfCompartmentTypes();
// for (int i = 0; i < model.getNumCompartmentTypes(); i++) {
// usedIDs.add(((CompartmentType) ids.get(i)).getId());
// ids = model.getListOfSpeciesTypes();
// for (int i = 0; i < model.getSpeciesTypeCount(); i++) {
// usedIDs.add(((SpeciesType) ids.get(i)).getId());
ids = model.getListOfCompartments();
for (int i = 0; i < model.getCompartmentCount(); i++) {
usedIDs.add(((Compartment) ids.get(i)).getId());
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
usedIDs.add(((Parameter) ids.get(i)).getId());
}
ids = model.getListOfReactions();
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = (Reaction) ids.get(i);
usedIDs.add(reaction.getId());
ListOf ids2 = reaction.getListOfReactants();
for (int j = 0; j < reaction.getReactantCount(); j++) {
SpeciesReference reactant = (SpeciesReference) ids2.get(j);
if ((reactant.isSetId()) && (!reactant.getId().equals(""))) {
usedIDs.add(reactant.getId());
}
}
ids2 = reaction.getListOfProducts();
for (int j = 0; j < reaction.getProductCount(); j++) {
SpeciesReference product = (SpeciesReference) ids2.get(j);
if ((product.isSetId()) && (!product.getId().equals(""))) {
usedIDs.add(product.getId());
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getSpeciesCount(); i++) {
usedIDs.add(((Species) ids.get(i)).getId());
}
ids = model.getListOfConstraints();
for (int i = 0; i < model.getConstraintCount(); i++) {
if (((Constraint) ids.get(i)).isSetMetaId()) {
usedIDs.add(((Constraint) ids.get(i)).getMetaId());
}
}
ids = model.getListOfEvents();
for (int i = 0; i < model.getEventCount(); i++) {
if (((org.sbml.jsbml.Event) ids.get(i)).isSetId()) {
usedIDs.add(((org.sbml.jsbml.Event) ids.get(i)).getId());
}
}
return usedIDs;
}
/**
* Check for cycles in initialAssignments and assignmentRules
*/
public static boolean checkCycles(SBMLDocument document) {
Model model = document.getModel();
ListOf listOfReactions = model.getListOfReactions();
String[] rateLaws = new String[(int) model.getReactionCount()];
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = (Reaction) listOfReactions.get(i);
if (reaction.getKineticLaw()==null || reaction.getKineticLaw().getMath()==null) {
rateLaws[i] = reaction.getId() + " = 0.0";
} else {
rateLaws[i] = reaction.getId() + " = " + myFormulaToString(reaction.getKineticLaw().getMath());
}
}
ListOf listOfInitials = model.getListOfInitialAssignments();
String[] initRules = new String[(int) model.getInitialAssignmentCount()];
for (int i = 0; i < model.getInitialAssignmentCount(); i++) {
InitialAssignment init = (InitialAssignment) listOfInitials.get(i);
initRules[i] = init.getSymbol() + " = " + myFormulaToString(init.getMath());
}
ListOf listOfRules = model.getListOfRules();
String[] rules = new String[(int) model.getRuleCount()];
for (int i = 0; i < model.getRuleCount(); i++) {
Rule rule = (Rule) listOfRules.get(i);
if (rule.isAlgebraic()) {
rules[i] = "0 = " + SBMLutilities.myFormulaToString(rule.getMath());
}
else if (rule.isAssignment()) {
rules[i] = getVariable(rule) + " = " + SBMLutilities.myFormulaToString(rule.getMath());
}
else {
rules[i] = "d( " + getVariable(rule) + " )/dt = " + SBMLutilities.myFormulaToString(rule.getMath());
}
}
String[] result = new String[rules.length + initRules.length + rateLaws.length];
int j = 0;
boolean[] used = new boolean[rules.length + initRules.length + rateLaws.length];
for (int i = 0; i < rules.length + initRules.length + rateLaws.length; i++) {
used[i] = false;
}
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("0")) {
result[j] = rules[i];
used[i] = true;
j++;
}
}
boolean progress;
do {
progress = false;
for (int i = 0; i < rules.length + initRules.length + rateLaws.length; i++) {
String[] rule;
if (i < rules.length) {
if (used[i] || (rules[i].split(" ")[0].equals("0")) || (rules[i].split(" ")[0].equals("d(")))
continue;
rule = rules[i].split(" ");
}
else if (i < rules.length + initRules.length) {
if (used[i])
continue;
rule = initRules[i - rules.length].split(" ");
}
else {
if (used[i])
continue;
rule = rateLaws[i - (rules.length + initRules.length)].split(" ");
}
boolean insert = true;
for (int k = 1; k < rule.length; k++) {
for (int l = 0; l < rules.length + initRules.length + rateLaws.length; l++) {
String rule2;
if (l < rules.length) {
if (used[l] || (rules[l].split(" ")[0].equals("0")) || (rules[l].split(" ")[0].equals("d(")))
continue;
rule2 = rules[l].split(" ")[0];
}
else if (l < rules.length + initRules.length) {
if (used[l])
continue;
rule2 = initRules[l - rules.length].split(" ")[0];
}
else {
if (used[l])
continue;
rule2 = rateLaws[l - (rules.length + initRules.length)].split(" ")[0];
}
if (rule[k].equals(rule2)) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
if (i < rules.length) {
result[j] = rules[i];
}
else if (i < rules.length + initRules.length) {
result[j] = initRules[i - rules.length];
}
else {
result[j] = rateLaws[i - (rules.length + initRules.length)];
}
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < rules.length + initRules.length + rateLaws.length));
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("d(")) {
result[j] = rules[i];
j++;
}
}
if (j != rules.length + initRules.length + rateLaws.length) {
return true;
}
return false;
}
/**
* Checks consistency of the sbml file.
*/
public static void checkOverDetermined(SBMLDocument document) {
if (Gui.isLibsbmlFound()) {
try {
org.sbml.libsbml.SBMLDocument doc = new org.sbml.libsbml.SBMLReader().readSBMLFromString(new SBMLWriter().writeSBMLToString(document));
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_MODELING_PRACTICE, false);
doc.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, true);
long numErrors = document.checkConsistency();
/*
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",
// ".\n");
message += i + ":" + error + "\n";
}
*/
if (numErrors > 0) {
JOptionPane.showMessageDialog(Gui.frame, "Algebraic rules make model overdetermined.", "Model is Overdetermined",
JOptionPane.WARNING_MESSAGE);
}
} catch (SBMLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.GENERAL_CONSISTENCY, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.UNITS_CONSISTENCY, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MATHML_CONSISTENCY, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.SBO_CONSISTENCY, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MODELING_PRACTICE, false);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
long numErrors = document.checkConsistency();
/*
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",
// ".\n");
message += i + ":" + error + "\n";
}
*/
if (numErrors > 0) {
JOptionPane.showMessageDialog(Gui.frame, "Algebraic rules make model overdetermined.", "Model is Overdetermined",
JOptionPane.WARNING_MESSAGE);
}
}
}
/**
* Create check if species used in reaction
*/
public static boolean usedInReaction(SBMLDocument document, String id) {
for (int i = 0; i < document.getModel().getReactionCount(); i++) {
for (int j = 0; j < document.getModel().getReaction(i).getReactantCount(); j++) {
if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id)) {
return true;
}
}
for (int j = 0; j < document.getModel().getReaction(i).getProductCount(); j++) {
if (document.getModel().getReaction(i).getProduct(j).getSpecies().equals(id)) {
return true;
}
}
}
return false;
}
/**
* Checks if species is a reactant in a non-degradation reaction
*/
public static boolean usedInNonDegradationReaction(SBMLDocument document, String id) {
for (int i = 0; i < document.getModel().getReactionCount(); i++) {
for (int j = 0; j < document.getModel().getReaction(i).getReactantCount(); j++) {
if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id)
&& (document.getModel().getReaction(i).getProductCount() > 0 || document.getModel().getReaction(i).getReactantCount() > 1)) {
return true;
}
}
}
return false;
}
/**
* Update variable in math formula using String
*/
public static String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + ",", " " + newVar + ",");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
s = s.replace(" " + origVar + "^", " " + newVar + "^");
return s.trim();
}
/**
* Update variable in math formula using ASTNode
*/
public static ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
/**
* Check if compartment is in use.
*/
public static boolean compartmentInUse(SBMLDocument document, String compartmentId) {
boolean remove = true;
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getSpeciesCount(); i++) {
Species species = (Species) document.getModel().getListOfSpecies().get(i);
if (species.isSetCompartment()) {
if (species.getCompartment().equals(compartmentId)) {
remove = false;
speciesUsing.add(species.getId());
}
}
}
ArrayList<String> reactionsUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getReactionCount(); i++) {
Reaction reaction = document.getModel().getReaction(i);
if (reaction.isSetCompartment()) {
if (reaction.getCompartment().equals(compartmentId)){
remove = false;
reactionsUsing.add(reaction.getId());
}
}
}
ArrayList<String> outsideUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getCompartmentCount(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.isSetOutside()) {
if (compartment.getOutside().equals(compartmentId)) {
remove = false;
outsideUsing.add(compartment.getId());
}
}
}
if (!remove) {
String message = "Unable to remove the selected compartment.";
if (speciesUsing.size() != 0) {
message += "\n\nIt contains the following species:\n";
String[] vars = speciesUsing.toArray(new String[0]);
Utility.sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
if (reactionsUsing.size() != 0) {
message += "\n\nIt contains the following reactions:\n";
String[] vars = reactionsUsing.toArray(new String[0]);
Utility.sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
if (outsideUsing.size() != 0) {
message += "\n\nIt outside the following compartments:\n";
String[] vars = outsideUsing.toArray(new String[0]);
Utility.sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scroll, "Unable To Remove Compartment", JOptionPane.ERROR_MESSAGE);
}
return !remove;
}
/**
* Check if a variable is in use.
*/
public static boolean variableInUse(SBMLDocument document, String species, boolean zeroDim, boolean displayMessage,
boolean checkReactions) {
Model model = document.getModel();
boolean inUse = false;
boolean isSpecies = (document.getModel().getSpecies(species) != null);
if (species.equals("")) {
return inUse;
}
boolean usedInModelConversionFactor = false;
ArrayList<String> stoicMathUsing = new ArrayList<String>();
ArrayList<String> reactantsUsing = new ArrayList<String>();
ArrayList<String> productsUsing = new ArrayList<String>();
ArrayList<String> modifiersUsing = new ArrayList<String>();
ArrayList<String> kineticLawsUsing = new ArrayList<String>();
ArrayList<String> defaultParametersNeeded = new ArrayList<String>();
ArrayList<String> initsUsing = new ArrayList<String>();
ArrayList<String> rulesUsing = new ArrayList<String>();
ArrayList<String> constraintsUsing = new ArrayList<String>();
ArrayList<String> eventsUsing = new ArrayList<String>();
ArrayList<String> speciesUsing = new ArrayList<String>();
if (document.getLevel() > 2) {
if (model.isSetConversionFactor() && model.getConversionFactor().equals(species)) {
inUse = true;
usedInModelConversionFactor = true;
}
for (int i = 0; i < model.getSpeciesCount(); i++) {
Species speciesConv = (Species) model.getListOfSpecies().get(i);
if (speciesConv.isSetConversionFactor()) {
if (species.equals(speciesConv.getConversionFactor())) {
inUse = true;
speciesUsing.add(speciesConv.getId());
}
}
}
}
if (checkReactions) {
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
if (isSpecies && (BioModel.isDegradationReaction(reaction) || BioModel.isDiffusionReaction(reaction) ||
BioModel.isConstitutiveReaction(reaction))) continue;
if (BioModel.isProductionReaction(reaction) && BioModel.IsDefaultProductionParameter(species)) {
defaultParametersNeeded.add(reaction.getId());
inUse = true;
}
for (int j = 0; j < reaction.getProductCount(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
String specRef = reaction.getProduct(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
productsUsing.add(reaction.getId());
}
else if (reaction.getProduct(j).isSetStoichiometryMath()) {
String[] vars = SBMLutilities.myFormulaToString(reaction.getProduct(j).getStoichiometryMath().getMath()).split(
" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getReactantCount(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
String specRef = reaction.getReactant(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
reactantsUsing.add(reaction.getId());
}
else if (reaction.getReactant(j).isSetStoichiometryMath()) {
String[] vars = SBMLutilities.myFormulaToString(reaction.getReactant(j).getStoichiometryMath().getMath()).split(
" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getModifierCount(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
String specRef = reaction.getModifier(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
modifiersUsing.add(reaction.getId());
}
}
}
String[] vars = SBMLutilities.myFormulaToString(reaction.getKineticLaw().getMath()).split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
kineticLawsUsing.add(reaction.getId());
inUse = true;
break;
}
}
}
}
ListOf ia = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getInitialAssignmentCount(); i++) {
InitialAssignment init = (InitialAssignment) ia.get(i);
String initStr = SBMLutilities.myFormulaToString(init.getMath());
String[] vars = initStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
initsUsing.add(init.getSymbol() + " = " + SBMLutilities.myFormulaToString(init.getMath()));
inUse = true;
break;
}
}
}
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getRuleCount(); i++) {
Rule rule = (Rule) r.get(i);
String initStr = SBMLutilities.myFormulaToString(rule.getMath());
if (rule.isAssignment() || rule.isRate()) {
initStr += " = " + getVariable(rule);
}
String[] vars = initStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
if (rule.isAssignment()) {
rulesUsing.add(getVariable(rule) + " = " + SBMLutilities.myFormulaToString(rule.getMath()));
}
else if (rule.isRate()) {
rulesUsing.add("d(" + getVariable(rule) + ")/dt = " + SBMLutilities.myFormulaToString(rule.getMath()));
}
else {
rulesUsing.add("0 = " + SBMLutilities.myFormulaToString(rule.getMath()));
}
inUse = true;
break;
}
}
}
ListOf c = document.getModel().getListOfConstraints();
for (int i = 0; i < document.getModel().getConstraintCount(); i++) {
Constraint constraint = (Constraint) c.get(i);
String consStr = SBMLutilities.myFormulaToString(constraint.getMath());
String[] vars = consStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
constraintsUsing.add(consStr);
inUse = true;
break;
}
}
}
ListOf e = model.getListOfEvents();
for (int i = 0; i < model.getEventCount(); i++) {
org.sbml.jsbml.Event event = (org.sbml.jsbml.Event) e.get(i);
String trigger = SBMLutilities.myFormulaToString(event.getTrigger().getMath());
String eventStr = trigger;
if (event.isSetDelay()) {
eventStr += " " + SBMLutilities.myFormulaToString(event.getDelay().getMath());
}
for (int j = 0; j < event.getEventAssignmentCount(); j++) {
eventStr += " " + (event.getListOfEventAssignments().get(j).getVariable()) + " = "
+ SBMLutilities.myFormulaToString(event.getListOfEventAssignments().get(j).getMath());
}
String[] vars = eventStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
eventsUsing.add(event.getId());
inUse = true;
break;
}
}
}
if (inUse) {
String reactants = "";
String products = "";
String modifiers = "";
String kineticLaws = "";
String defaults = "";
String stoicMath = "";
String initAssigns = "";
String rules = "";
String constraints = "";
String events = "";
String speciesConvFac = "";
String[] speciesConvFactors = speciesUsing.toArray(new String[0]);
Utility.sort(speciesConvFactors);
String[] reacts = reactantsUsing.toArray(new String[0]);
Utility.sort(reacts);
String[] prods = productsUsing.toArray(new String[0]);
Utility.sort(prods);
String[] mods = modifiersUsing.toArray(new String[0]);
Utility.sort(mods);
String[] kls = kineticLawsUsing.toArray(new String[0]);
Utility.sort(kls);
String[] dps = defaultParametersNeeded.toArray(new String[0]);
Utility.sort(dps);
String[] sm = stoicMathUsing.toArray(new String[0]);
Utility.sort(sm);
String[] inAs = initsUsing.toArray(new String[0]);
Utility.sort(inAs);
String[] ruls = rulesUsing.toArray(new String[0]);
Utility.sort(ruls);
String[] consts = constraintsUsing.toArray(new String[0]);
Utility.sort(consts);
String[] evs = eventsUsing.toArray(new String[0]);
Utility.sort(evs);
for (int i = 0; i < speciesConvFactors.length; i++) {
if (i == speciesConvFactors.length - 1) {
speciesConvFac += speciesConvFactors[i];
}
else {
speciesConvFac += speciesConvFactors[i] + "\n";
}
}
for (int i = 0; i < reacts.length; i++) {
if (i == reacts.length - 1) {
reactants += reacts[i];
}
else {
reactants += reacts[i] + "\n";
}
}
for (int i = 0; i < prods.length; i++) {
if (i == prods.length - 1) {
products += prods[i];
}
else {
products += prods[i] + "\n";
}
}
for (int i = 0; i < mods.length; i++) {
if (i == mods.length - 1) {
modifiers += mods[i];
}
else {
modifiers += mods[i] + "\n";
}
}
for (int i = 0; i < kls.length; i++) {
if (i == kls.length - 1) {
kineticLaws += kls[i];
}
else {
kineticLaws += kls[i] + "\n";
}
}
for (int i = 0; i < dps.length; i++) {
if (i == dps.length - 1) {
defaults += dps[i];
}
else {
defaults += dps[i] + "\n";
}
}
for (int i = 0; i < sm.length; i++) {
if (i == sm.length - 1) {
stoicMath += sm[i];
}
else {
stoicMath += sm[i] + "\n";
}
}
for (int i = 0; i < inAs.length; i++) {
if (i == inAs.length - 1) {
initAssigns += inAs[i];
}
else {
initAssigns += inAs[i] + "\n";
}
}
for (int i = 0; i < ruls.length; i++) {
if (i == ruls.length - 1) {
rules += ruls[i];
}
else {
rules += ruls[i] + "\n";
}
}
for (int i = 0; i < consts.length; i++) {
if (i == consts.length - 1) {
constraints += consts[i];
}
else {
constraints += consts[i] + "\n";
}
}
for (int i = 0; i < evs.length; i++) {
if (i == evs.length - 1) {
events += evs[i];
}
else {
events += evs[i] + "\n";
}
}
String message;
if (zeroDim) {
message = "Unable to change compartment to 0-dimensions.";
}
else {
message = "Unable to remove the selected variable.";
}
if (usedInModelConversionFactor) {
message += "\n\nIt is used as the model conversion factor.\n";
}
if (speciesUsing.size() != 0) {
message += "\n\nIt is used as a conversion factor in the following species:\n" + speciesConvFac;
}
if (reactantsUsing.size() != 0) {
message += "\n\nIt is used as a reactant in the following reactions:\n" + reactants;
}
if (productsUsing.size() != 0) {
message += "\n\nIt is used as a product in the following reactions:\n" + products;
}
if (modifiersUsing.size() != 0) {
message += "\n\nIt is used as a modifier in the following reactions:\n" + modifiers;
}
if (kineticLawsUsing.size() != 0) {
message += "\n\nIt is used in the kinetic law in the following reactions:\n" + kineticLaws;
}
if (defaultParametersNeeded.size() != 0) {
message += "\n\nDefault parameter is needed by the following reactions:\n" + defaults;
}
if (stoicMathUsing.size() != 0) {
message += "\n\nIt is used in the stoichiometry math for the following reaction/species:\n" + stoicMath;
}
if (initsUsing.size() != 0) {
message += "\n\nIt is used in the following initial assignments:\n" + initAssigns;
}
if (rulesUsing.size() != 0) {
message += "\n\nIt is used in the following rules:\n" + rules;
}
if (constraintsUsing.size() != 0) {
message += "\n\nIt is used in the following constraints:\n" + constraints;
}
if (eventsUsing.size() != 0) {
message += "\n\nIt is used in the following events:\n" + events;
}
if (displayMessage) {
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(400, 400));
scroll.setPreferredSize(new Dimension(400, 400));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scroll, "Unable To Remove Variable", JOptionPane.ERROR_MESSAGE);
}
}
return inUse;
}
/**
* Update variable Id
*/
public static void updateVarId(SBMLDocument document, boolean isSpecies, String origId, String newId) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getProductCount(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(SBMLutilities.updateMathVar(specRef.getStoichiometryMath().getMath(), origId, newId));
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getModifierCount(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getReactantCount(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(SBMLutilities.updateMathVar(specRef.getStoichiometryMath().getMath(), origId, newId));
}
}
}
if (reaction.isSetKineticLaw()) {
reaction.getKineticLaw().setMath(SBMLutilities.updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
}
if (document.getLevel() > 2) {
if (model.isSetConversionFactor() && origId.equals(model.getConversionFactor())) {
model.setConversionFactor(newId);
}
if (model.getSpeciesCount() > 0) {
for (int i = 0; i < model.getSpeciesCount(); i++) {
Species species = (Species) model.getListOfSpecies().get(i);
if (species.isSetConversionFactor()) {
if (origId.equals(species.getConversionFactor())) {
species.setConversionFactor(newId);
}
}
}
}
}
if (model.getInitialAssignmentCount() > 0) {
for (int i = 0; i < model.getInitialAssignmentCount(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(SBMLutilities.updateMathVar(init.getMath(), origId, newId));
}
try {
if (SBMLutilities.checkCycles(document)) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (model.getRuleCount() > 0) {
for (int i = 0; i < model.getRuleCount(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (isSetVariable(rule) && origId.equals(getVariable(rule))) {
setVariable(rule, newId);
}
rule.setMath(SBMLutilities.updateMathVar(rule.getMath(), origId, newId));
}
try {
if (SBMLutilities.checkCycles(document)) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected within initial assignments, assignment rules, and rate laws.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Cycle detected in assignments.", "Cycle Detected", JOptionPane.ERROR_MESSAGE);
}
}
if (model.getConstraintCount() > 0) {
for (int i = 0; i < model.getConstraintCount(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(SBMLutilities.updateMathVar(constraint.getMath(), origId, newId));
}
}
if (model.getEventCount() > 0) {
for (int i = 0; i < model.getEventCount(); i++) {
org.sbml.jsbml.Event event = (org.sbml.jsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
event.getTrigger().setMath(SBMLutilities.updateMathVar(event.getTrigger().getMath(), origId, newId));
}
if (event.isSetDelay()) {
event.getDelay().setMath(SBMLutilities.updateMathVar(event.getDelay().getMath(), origId, newId));
}
for (int j = 0; j < event.getEventAssignmentCount(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(SBMLutilities.updateMathVar(ea.getMath(), origId, newId));
}
}
}
}
}
/**
* Variable that is updated by a rule or event cannot be constant
*/
public static boolean checkConstant(SBMLDocument document, String varType, String val) {
for (int i = 0; i < document.getModel().getRuleCount(); i++) {
Rule rule = document.getModel().getRule(i);
if (getVariable(rule).equals(val)) {
JOptionPane.showMessageDialog(Gui.frame, varType + " cannot be constant if updated by a rule.", varType + " Cannot Be Constant",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
for (int i = 0; i < document.getModel().getEventCount(); i++) {
org.sbml.jsbml.Event event = (org.sbml.jsbml.Event) document.getModel().getListOfEvents().get(i);
for (int j = 0; j < event.getEventAssignmentCount(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(val)) {
JOptionPane.showMessageDialog(Gui.frame, varType + " cannot be constant if updated by an event.",
varType + " Cannot Be Constant", JOptionPane.ERROR_MESSAGE);
return true;
}
}
}
return false;
}
/**
* Checks consistency of the sbml file.
*/
public static void check(String file) {
// Hack to avoid weird bug.
// By reloading the file before consistency checks, it seems to avoid a
// crash when attempting to save a newly added parameter with no units
String message = "";
long numErrors = 0;
if (Gui.isLibsbmlFound()) {
org.sbml.libsbml.SBMLDocument document = new org.sbml.libsbml.SBMLReader().readSBML(file);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_SBO_CONSISTENCY, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_MODELING_PRACTICE, true);
document.setConsistencyChecks(org.sbml.libsbml.libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, true);
numErrors = document.checkConsistency();
for (int i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",
message += i + ":" + error + "\n";
}
}
else {
SBMLDocument document = Gui.readSBML(file);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.GENERAL_CONSISTENCY, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.IDENTIFIER_CONSISTENCY, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.UNITS_CONSISTENCY, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MATHML_CONSISTENCY, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.SBO_CONSISTENCY, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.MODELING_PRACTICE, true);
document.setConsistencyChecks(SBMLValidator.CHECK_CATEGORY.OVERDETERMINED_MODEL, true);
numErrors = document.checkConsistency();
for (int i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",
message += i + ":" + error + "\n";
}
}
if (numErrors > 0) {
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scroll, "SBML Errors and Warnings", JOptionPane.ERROR_MESSAGE);
}
}
public static boolean checkUnitsInAssignmentRule(SBMLDocument document,Rule rule) {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(getVariable(rule));
Compartment compartment = document.getModel().getCompartment(getVariable(rule));
Parameter parameter = document.getModel().getParameter(getVariable(rule));
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
return true;
}
return false;
}
public static boolean checkUnitsInRateRule(SBMLDocument document,Rule rule) {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(getVariable(rule));
Compartment compartment = document.getModel().getCompartment(getVariable(rule));
Parameter parameter = document.getModel().getParameter(getVariable(rule));
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = unitDefVar.createUnit();
recTimeUnit.setKind(timeUnit.getKind());
if (document.getLevel() < 3) {
recTimeUnit.setExponent(timeUnit.getExponent() * (-1));
}
else {
recTimeUnit.setExponent(timeUnit.getExponentAsDouble() * (-1));
}
recTimeUnit.setScale(timeUnit.getScale());
recTimeUnit.setMultiplier(timeUnit.getMultiplier());
}
}
else {
Unit unit = unitDefVar.createUnit();
unit.setKind(Unit.Kind.valueOf("second".toUpperCase()));
unit.setExponent(-1);
unit.setScale(0);
unit.setMultiplier(1.0);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
return true;
}
return false;
}
public static boolean checkUnitsInInitialAssignment(SBMLDocument document,InitialAssignment init) {
UnitDefinition unitDef = init.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(init.getSymbol());
Compartment compartment = document.getModel().getCompartment(init.getSymbol());
Parameter parameter = document.getModel().getParameter(init.getSymbol());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
return true;
}
return false;
}
public static boolean checkUnitsInKineticLaw(SBMLDocument document,KineticLaw law) {
UnitDefinition unitDef = law.getDerivedUnitDefinition();
UnitDefinition unitDefLaw = new UnitDefinition(document.getLevel(), document.getVersion());
if (document.getModel().getUnitDefinition("substance") != null) {
UnitDefinition subUnitDef = document.getModel().getUnitDefinition("substance");
for (int i = 0; i < subUnitDef.getNumUnits(); i++) {
Unit subUnit = subUnitDef.getUnit(i);
unitDefLaw.addUnit(subUnit);
}
}
else {
Unit unit = unitDefLaw.createUnit();
unit.setKind(Unit.Kind.valueOf("mole".toUpperCase()));
unit.setExponent(1);
unit.setScale(0);
unit.setMultiplier(1.0);
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = unitDefLaw.createUnit();
recTimeUnit.setKind(timeUnit.getKind());
if (document.getLevel() < 3) {
recTimeUnit.setExponent(timeUnit.getExponent() * (-1));
}
else {
recTimeUnit.setExponent(timeUnit.getExponentAsDouble() * (-1));
}
recTimeUnit.setScale(timeUnit.getScale());
recTimeUnit.setMultiplier(timeUnit.getMultiplier());
}
}
else {
Unit unit = unitDefLaw.createUnit();
unit.setKind(Unit.Kind.valueOf("second".toUpperCase()));
unit.setExponent(-1);
unit.setScale(0);
unit.setMultiplier(1.0);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefLaw)) {
return true;
}
return false;
}
public static boolean checkUnitsInEventDelay(SBMLDocument document,Delay delay) {
UnitDefinition unitDef = delay.getDerivedUnitDefinition();
if (unitDef != null && !(unitDef.isVariantOfTime())) {
return true;
}
return false;
}
public static boolean checkUnitsInEventAssignment(SBMLDocument document,EventAssignment assign) {
UnitDefinition unitDef = assign.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(assign.getVariable());
Compartment compartment = document.getModel().getCompartment(assign.getVariable());
Parameter parameter = document.getModel().getParameter(assign.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
return true;
}
return false;
}
/**
* Checks consistency of the sbml file.
*/
public static boolean checkUnits(SBMLDocument document) {
//TODO: Does this need to be ported over?
//document.getModel().populateListFormulaUnitsData();
long numErrors = 0;
String message = "Change in unit definition causes unit errors in the following elements:\n";
for (int i = 0; i < document.getModel().getReactionCount(); i++) {
Reaction reaction = document.getModel().getReaction(i);
KineticLaw law = reaction.getKineticLaw();
if (law != null) {
if (checkUnitsInKineticLaw(document,law)) {
message += "Reaction: " + reaction.getId() + "\n";
numErrors++;
}
}
}
for (int i = 0; i < document.getModel().getInitialAssignmentCount(); i++) {
InitialAssignment init = document.getModel().getInitialAssignment(i);
if (checkUnitsInInitialAssignment(document,init)) {
message += "Initial assignment on variable: " + init.getSymbol() + "\n";
numErrors++;
}
}
for (int i = 0; i < document.getModel().getRuleCount(); i++) {
Rule rule = document.getModel().getRule(i);
if (rule.isAssignment()) {
if (checkUnitsInAssignmentRule(document,rule)) {
message += "Assignment rule on variable: " + getVariable(rule) + "\n";
numErrors++;
}
} else if (rule.isRate()) {
if (checkUnitsInRateRule(document,rule)) {
message += "Rate rule on variable: " + getVariable(rule) + "\n";
numErrors++;
}
}
}
for (int i = 0; i < document.getModel().getEventCount(); i++) {
Event event = document.getModel().getEvent(i);
Delay delay = event.getDelay();
if (delay != null) {
if (checkUnitsInEventDelay(document,delay)) {
message += "Delay on event: " + event.getId() + "\n";
numErrors++;
}
}
for (int j = 0; j < event.getEventAssignmentCount(); j++) {
EventAssignment assign = event.getListOfEventAssignments().get(j);
if (checkUnitsInEventAssignment(document,assign)) {
message += "Event assignment for event " + event.getId() + " on variable: " + assign.getVariable() + "\n";
numErrors++;
}
}
}
/*
document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, true);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, false);
long numErrorsWarnings = document.checkConsistency();
for (long i = 0; i < numErrorsWarnings; i++) {
if (!document.getError(i).isWarning()) {
String error = document.getError(i).getMessage();
message += i + ":" + error + "\n";
numErrors++;
}
}
*/
if (numErrors > 0) {
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(Gui.frame, scroll, "Unit Errors in Model", JOptionPane.ERROR_MESSAGE);
return true;
}
return false;
}
public static void addRandomFunctions(SBMLDocument document) {
Model model = document.getModel();
createFunction(model, "uniform", "Uniform distribution", "lambda(a,b,(a+b)/2)");
createFunction(model, "normal", "Normal distribution", "lambda(m,s,m)");
createFunction(model, "exponential", "Exponential distribution", "lambda(l,1/l)");
createFunction(model, "gamma", "Gamma distribution", "lambda(a,b,a*b)");
createFunction(model, "lognormal", "Lognormal distribution", "lambda(z,s,exp(z+s^2/2))");
createFunction(model, "chisq", "Chi-squared distribution", "lambda(nu,nu)");
createFunction(model, "laplace", "Laplace distribution", "lambda(a,0)");
createFunction(model, "cauchy", "Cauchy distribution", "lambda(a,a)");
createFunction(model, "rayleigh", "Rayleigh distribution","lambda(s,s*sqrt(pi/2))");
createFunction(model, "poisson", "Poisson distribution", "lambda(mu,mu)");
createFunction(model, "binomial", "Binomial distribution", "lambda(p,n,p*n)");
createFunction(model, "bernoulli", "Bernoulli distribution", "lambda(p,p)");
}
/**
* Add a new function
*/
public static void createFunction(Model model, String id, String name, String formula) {
if (model.getFunctionDefinition(id) == null) {
FunctionDefinition f = model.createFunctionDefinition();
f.setId(id);
f.setName(name);
try {
IFormulaParser parser = new FormulaParserLL3(new StringReader(""));
f.setMath(ASTNode.parseFormula(formula, parser));
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static boolean isBoolean(SBMLDocument document, ASTNode node) {
if (node == null) {
return false;
} else if ( node.isBoolean() ) {
return true;
} else if (node.getType() == ASTNode.Type.FUNCTION) {
FunctionDefinition fd = document.getModel().getFunctionDefinition( node.getName() );
if (fd != null && fd.isSetMath()) {
return isBoolean( document, fd.getMath().getRightChild() );
} else {
return false;
}
} else if (node.getType() == ASTNode.Type.FUNCTION_PIECEWISE) {
for (int c = 0; c < node.getNumChildren(); c += 2) {
if ( !isBoolean( document, node.getChild(c) ) ) return false;
}
return true;
}
return false;
}
public static boolean isBoolean(Parameter parameter) {
if (parameter.isSetSBOTerm()) {
if (parameter.getSBOTerm()==GlobalConstants.SBO_BOOLEAN) {
parameter.setSBOTerm(GlobalConstants.SBO_LOGICAL);
return true;
} else if (parameter.getSBOTerm()==GlobalConstants.SBO_LOGICAL) {
return true;
}
}
return false;
}
public static boolean isPlace(Parameter parameter) {
if (parameter.isSetSBOTerm()) {
if (parameter.getSBOTerm()==GlobalConstants.SBO_PLACE) {
parameter.setSBOTerm(GlobalConstants.SBO_PETRI_NET_PLACE);
return true;
} else if (parameter.getSBOTerm()==GlobalConstants.SBO_PETRI_NET_PLACE) {
return true;
}
}
return false;
}
public static boolean isTransition(Event event) {
if (event.isSetSBOTerm()) {
if (event.getSBOTerm()==GlobalConstants.SBO_TRANSITION) {
event.setSBOTerm(GlobalConstants.SBO_PETRI_NET_TRANSITION);
return true;
} else if (event.getSBOTerm()==GlobalConstants.SBO_PETRI_NET_TRANSITION) {
return true;
}
}
return false;
}
public static ASTNode addPreset(ASTNode math,String place) {
return myParseFormula("and("+myFormulaToString(math)+",eq("+place+","+"1))");
}
public static ASTNode removePreset(ASTNode math,String place) {
if (math.getType() == ASTNode.Type.LOGICAL_AND) {
ASTNode rightChild = math.getRightChild();
if (rightChild.getType() == ASTNode.Type.RELATIONAL_EQ &&
rightChild.getLeftChild().getName().equals(place)) {
return deepCopy(math.getLeftChild());
}
}
for (int i = 0; i < math.getNumChildren(); i++) {
ASTNode child = removePreset(math.getChild(i),place);
math.replaceChild(i, child);
}
return deepCopy(math);
}
public static String addBoolean(String formula,String boolVar) {
formula = formula.replace(" "+boolVar+" ", " eq("+boolVar+",1) ");
formula = formula.replace(","+boolVar+",",",eq("+boolVar+",1),");
formula = formula.replace("("+boolVar+",", "(eq("+boolVar+",1),");
formula = formula.replace(","+boolVar+")", ",eq("+boolVar+",1))");
formula = formula.replace("("+boolVar+" ", "(eq("+boolVar+",1) ");
formula = formula.replace(" "+boolVar+")", " eq("+boolVar+",1))");
formula = formula.replace("("+boolVar+")", " eq("+boolVar+",1)");
if (formula.startsWith(boolVar+" ")) {
formula = formula.replaceFirst(boolVar+" ", "eq(" + boolVar + ",1)");
}
if (formula.endsWith(" " + boolVar)) {
formula = formula.replaceFirst(" " + boolVar, "eq(" + boolVar + ",1)");
}
if (formula.equals(boolVar)) {
formula = formula.replace(boolVar, "eq(" + boolVar + ",1)");
}
return formula;
}
public static ASTNode removeBoolean(ASTNode math,String boolVar) {
if (math.getType() == ASTNode.Type.RELATIONAL_EQ) {
if (math.getLeftChild().getName()!=null && math.getLeftChild().getName().equals(boolVar)) {
return deepCopy(math.getLeftChild());
}
}
for (int i = 0; i < math.getNumChildren(); i++) {
ASTNode child = removeBoolean(math.getChild(i),boolVar);
math.replaceChild(i, child);
}
return deepCopy(math);
}
public static String myFormulaToStringInfix(ASTNode math) {
if (math.getType() == ASTNode.Type.CONSTANT_E) {
return "exponentiale";
} else if (math.getType() == ASTNode.Type.CONSTANT_FALSE) {
return "false";
} else if (math.getType() == ASTNode.Type.CONSTANT_PI) {
return "pi";
} else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) {
return "true";
} else if (math.getType() == ASTNode.Type.DIVIDE) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " / " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION) {
String result = math.getName() + "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.FUNCTION_ABS) {
return "abs(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOS) {
return "acos(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOSH) {
return "acosh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOT) {
return "acot(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOTH) {
return "acoth(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSC) {
return "acsc(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSCH) {
return "acsch(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSEC) {
return "asec(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSECH) {
return "asech(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSIN) {
return "asin(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSINH) {
return "asinh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCTAN) {
return "atan(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCTANH) {
return "atanh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_CEILING) {
return "ceil(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_COS) {
return "cos(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_COSH) {
return "cosh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_COT) {
return "cot(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_COTH) {
return "coth(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_CSC) {
return "csc(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_CSCH) {
return "csch(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_DELAY) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "delay(" + leftStr + " , " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_EXP) {
return "exp(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_FACTORIAL) {
return "factorial(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_FLOOR) {
return "floor(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_LN) {
return "ln(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_LOG) {
String result = "log(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE) {
String result = "piecewise(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.FUNCTION_POWER) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "pow(" + leftStr + " , " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_ROOT) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "root(" + leftStr + " , " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_SEC) {
return "sec(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_SECH) {
return "sech(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_SIN) {
return "sin(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_SINH) {
return "sinh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_TAN) {
return "tan(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.FUNCTION_TANH) {
return "tanh(" + myFormulaToStringInfix(math.getChild(0)) + ")";
} else if (math.getType() == ASTNode.Type.INTEGER) {
if (math.hasUnits()) {
return "" + math.getInteger() + " " + math.getUnits();
} else {
return "" + math.getInteger();
}
} else if (math.getType() == ASTNode.Type.LOGICAL_AND) {
if (math.getNumChildren()==0) return "";
String result = "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += " && ";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_NOT) {
if (math.getNumChildren()==0) return "";
String result = "!(";
String child = myFormulaToStringInfix(math.getChild(0));
result += child;
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_OR) {
if (math.getNumChildren()==0) return "";
String result = "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += " || ";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_XOR) {
if (math.getNumChildren()==0) return "";
String result = "xor(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = myFormulaToStringInfix(math.getChild(i));
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.MINUS) {
if (math.getNumChildren()==1) {
return "-" + myFormulaToStringInfix(math.getChild(0));
} else {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " - " + rightStr + ")";
}
} else if (math.getType() == ASTNode.Type.NAME) {
return math.getName();
} else if (math.getType() == ASTNode.Type.NAME_AVOGADRO) {
return "avogadro";
} else if (math.getType() == ASTNode.Type.NAME_TIME) {
return "t";
} else if (math.getType() == ASTNode.Type.PLUS) {
String returnVal = "(";
boolean first = true;
for (int i=0; i < math.getNumChildren(); i++) {
if (first) {
first = false;
} else {
returnVal += " + ";
}
returnVal += myFormulaToStringInfix(math.getChild(i));
}
returnVal += ")";
return returnVal;
} else if (math.getType() == ASTNode.Type.POWER) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " ^ " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RATIONAL) {
if (math.hasUnits()) {
return math.getNumerator() + "/" + math.getDenominator() + " " + math.getUnits();
} else {
return math.getNumerator() + "/" + math.getDenominator();
}
} else if (math.getType() == ASTNode.Type.REAL) {
if (math.hasUnits()) {
return "" + math.getReal() + " " + math.getUnits();
} else {
return "" + math.getReal();
}
} else if (math.getType() == ASTNode.Type.REAL_E) {
if (math.hasUnits()) {
return math.getMantissa() + "e" + math.getExponent() + " " + math.getUnits();
} else {
return math.getMantissa() + "e" + math.getExponent();
}
} else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " == " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " >= " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_GT) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " > " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " <= " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_LT) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " < " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) {
String leftStr = myFormulaToStringInfix(math.getLeftChild());
String rightStr = myFormulaToStringInfix(math.getRightChild());
return "(" + leftStr + " != " + rightStr + ")";
} else if (math.getType() == ASTNode.Type.TIMES) {
String returnVal = "(";
boolean first = true;
for (int i=0; i < math.getNumChildren(); i++) {
if (first) {
first = false;
} else {
returnVal += " * ";
}
returnVal += myFormulaToStringInfix(math.getChild(i));
}
returnVal += ")";
return returnVal;
} else {
if (math.isOperator()) {
System.out.println("Operator " + math.getName() + " is not currently supported.");
} else {
System.out.println(math.getName() + " is not currently supported.");
}
}
return "";
}
public static boolean returnsBoolean(ASTNode math, Model model) {
if (math.isBoolean()) {
return true;
} else if (math.getType() == ASTNode.Type.CONSTANT_E) {
return false;
} else if (math.getType() == ASTNode.Type.CONSTANT_FALSE) {
return true;
} else if (math.getType() == ASTNode.Type.CONSTANT_PI) {
return false;
} else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) {
return true;
} else if (math.getType() == ASTNode.Type.DIVIDE) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION) {
return returnsBoolean(math.getRightChild(), model);
} else if (math.getType() == ASTNode.Type.FUNCTION_ABS) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOS) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOSH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOT) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCOTH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSC) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCCSCH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSEC) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSECH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSIN) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCSINH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCTAN) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ARCTANH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_CEILING) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_COS) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_COSH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_COT) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_COTH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_CSC) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_CSCH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_DELAY) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_EXP) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_FACTORIAL) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_FLOOR) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_LN) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_LOG) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE) {
boolean result = true;
for (int i = 0; i < math.getNumChildren(); i++) {
result = result && returnsBoolean(math.getChild(i), model);
}
return result;
} else if (math.getType() == ASTNode.Type.FUNCTION_POWER) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_ROOT) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_SEC) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_SECH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_SIN) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_SINH) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_TAN) {
return false;
} else if (math.getType() == ASTNode.Type.FUNCTION_TANH) {
return false;
} else if (math.getType() == ASTNode.Type.INTEGER) {
return false;
} else if (math.getType() == ASTNode.Type.LOGICAL_AND) {
return true;
} else if (math.getType() == ASTNode.Type.LOGICAL_NOT) {
return true;
} else if (math.getType() == ASTNode.Type.LOGICAL_OR) {
return true;
} else if (math.getType() == ASTNode.Type.LOGICAL_XOR) {
return true;
} else if (math.getType() == ASTNode.Type.MINUS) {
return false;
} else if (math.getType() == ASTNode.Type.NAME) {
return false;
} else if (math.getType() == ASTNode.Type.NAME_AVOGADRO) {
return false;
} else if (math.getType() == ASTNode.Type.NAME_TIME) {
return false;
} else if (math.getType() == ASTNode.Type.PLUS) {
return false;
} else if (math.getType() == ASTNode.Type.POWER) {
return false;
} else if (math.getType() == ASTNode.Type.RATIONAL) {
return false;
} else if (math.getType() == ASTNode.Type.REAL) {
return false;
} else if (math.getType() == ASTNode.Type.REAL_E) {
return false;
} else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) {
return true;
} else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) {
return true;
} else if (math.getType() == ASTNode.Type.RELATIONAL_GT) {
return true;
} else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) {
return true;
} else if (math.getType() == ASTNode.Type.RELATIONAL_LT) {
return true;
} else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) {
return true;
} else if (math.getType() == ASTNode.Type.TIMES) {
return false;
} else {
if (math.isOperator()) {
System.out.println("Operator " + math.getName() + " is not currently supported.");
} else {
System.out.println(math.getName() + " is not currently supported.");
}
}
return false;
}
public static String SBMLMathToBoolLPNString(ASTNode math,HashMap<String,Integer> constants,ArrayList<String> booleans) {
if (math.getType() == ASTNode.Type.FUNCTION_PIECEWISE && math.getNumChildren() > 1) {
return SBMLMathToLPNString(math.getChild(1),constants,booleans);
}
return SBMLMathToLPNString(math,constants,booleans);
}
public static String SBMLMathToLPNString(ASTNode math,HashMap<String,Integer> constants,ArrayList<String> booleans) {
if (math.getType() == ASTNode.Type.CONSTANT_FALSE) {
return "false";
} else if (math.getType() == ASTNode.Type.CONSTANT_TRUE) {
return "true";
} else if (math.getType() == ASTNode.Type.REAL) {
return "" + math.getReal();
} else if (math.getType() == ASTNode.Type.INTEGER) {
return "" + math.getInteger();
} else if (math.getType() == ASTNode.Type.NAME) {
if (constants.containsKey(math.getName())) {
return "" + constants.get(math.getName());
}
return math.getName();
} else if (math.getType() == ASTNode.Type.FUNCTION) {
String result = math.getName() + "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = SBMLMathToLPNString(math.getChild(i),constants,booleans);
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.PLUS) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "+" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.MINUS) {
if (math.getNumChildren()==1) {
return "-" + SBMLMathToLPNString(math.getChild(0),constants,booleans);
}
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "-" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.TIMES) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "*" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.DIVIDE) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "/" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.POWER) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "^" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_EQ) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
if (booleans.contains(leftStr) && rightStr.equals("1")) {
return leftStr;
} else {
return "(" + leftStr + "=" + rightStr + ")";
}
} else if (math.getType() == ASTNode.Type.RELATIONAL_GEQ) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + ">=" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_GT) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + ">" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_LEQ) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "<=" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_LT) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "<" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.RELATIONAL_NEQ) {
String leftStr = SBMLMathToLPNString(math.getLeftChild(),constants,booleans);
String rightStr = SBMLMathToLPNString(math.getRightChild(),constants,booleans);
return "(" + leftStr + "!=" + rightStr + ")";
} else if (math.getType() == ASTNode.Type.LOGICAL_NOT) {
if (math.getNumChildren()==0) return "";
String result = "~(";
String child = SBMLMathToLPNString(math.getChild(0),constants,booleans);
result += child;
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_AND) {
if (math.getNumChildren()==0) return "";
String result = "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = SBMLMathToLPNString(math.getChild(i),constants,booleans);
result += child;
if (i+1 < math.getNumChildren()) {
result += "&";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_OR) {
if (math.getNumChildren()==0) return "";
String result = "(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = SBMLMathToLPNString(math.getChild(i),constants,booleans);
result += child;
if (i+1 < math.getNumChildren()) {
result += "|";
}
}
result += ")";
return result;
} else if (math.getType() == ASTNode.Type.LOGICAL_XOR) {
if (math.getNumChildren()==0) return "";
String result = "exor(";
for (int i = 0; i < math.getNumChildren(); i++) {
String child = SBMLMathToLPNString(math.getChild(i),constants,booleans);
result += child;
if (i+1 < math.getNumChildren()) {
result += ",";
}
}
result += ")";
return result;
} else {
if (math.isOperator()) {
System.out.println("Operator " + math.getName() + " is not currently supported.");
} else {
System.out.println(math.getName() + " is not currently supported.");
}
}
return "";
}
public static ArrayList<String> getPreset(SBMLDocument doc,Event event) {
ArrayList<String> preset = new ArrayList<String>();
for (int i = 0; i < event.getEventAssignmentCount(); i++) {
EventAssignment ea = event.getListOfEventAssignments().get(i);
Parameter p = doc.getModel().getParameter(ea.getVariable());
if (p != null && SBMLutilities.isPlace(p) && SBMLutilities.myFormulaToString(ea.getMath()).equals("0")) {
preset.add(p.getId());
}
}
return preset;
}
public static ArrayList<String> getPostset(SBMLDocument doc,Event event) {
ArrayList<String> postset = new ArrayList<String>();
for (int i = 0; i < event.getEventAssignmentCount(); i++) {
EventAssignment ea = event.getListOfEventAssignments().get(i);
Parameter p = doc.getModel().getParameter(ea.getVariable());
if (p != null && SBMLutilities.isPlace(p) && SBMLutilities.myFormulaToString(ea.getMath()).equals("1")) {
postset.add(p.getId());
}
}
return postset;
}
public static void replaceArgument(ASTNode formula,String bvar, ASTNode arg) {
int n = 0;
for (int i = 0; i < formula.getNumChildren(); i++) {
ASTNode child = formula.getChild(i);
if (child.getName() != null && child.getName().equals(bvar)) {
formula.replaceChild(n, deepCopy(arg));
} else if (child.getNumChildren() > 0) {
replaceArgument(child, bvar, arg);
}
n++;
}
}
/**
* recursively puts every astnode child into the arraylist passed in
*
* @param node
* @param nodeChildrenList
*/
protected static void getAllASTNodeChildren(ASTNode node, ArrayList<ASTNode> nodeChildrenList) {
for (int i = 0; i < node.getNumChildren(); i++) {
ASTNode child = node.getChild(i);
if (child.getNumChildren() == 0)
nodeChildrenList.add(child);
else {
nodeChildrenList.add(child);
getAllASTNodeChildren(child, nodeChildrenList);
}
}
}
/**
* inlines a formula with function definitions
*
* @param formula
* @return
*/
public static ASTNode inlineFormula(Model model, ASTNode formula) {
HashSet<String> ibiosimFunctionDefinitions = new HashSet<String>();
ibiosimFunctionDefinitions.add("uniform");
ibiosimFunctionDefinitions.add("exponential");
ibiosimFunctionDefinitions.add("gamma");
ibiosimFunctionDefinitions.add("chisq");
ibiosimFunctionDefinitions.add("lognormal");
ibiosimFunctionDefinitions.add("laplace");
ibiosimFunctionDefinitions.add("cauchy");
ibiosimFunctionDefinitions.add("poisson");
ibiosimFunctionDefinitions.add("binomial");
ibiosimFunctionDefinitions.add("bernoulli");
ibiosimFunctionDefinitions.add("normal");
ibiosimFunctionDefinitions.add("rate");
ibiosimFunctionDefinitions.add("BIT");
ibiosimFunctionDefinitions.add("BITNOT");
ibiosimFunctionDefinitions.add("BITAND");
ibiosimFunctionDefinitions.add("BITOR");
ibiosimFunctionDefinitions.add("BITXOR");
ibiosimFunctionDefinitions.add("G");
ibiosimFunctionDefinitions.add("PG");
ibiosimFunctionDefinitions.add("F");
ibiosimFunctionDefinitions.add("PF");
ibiosimFunctionDefinitions.add("U");
ibiosimFunctionDefinitions.add("PU");
if (formula.isFunction() == false /* || formula.isLeaf() == false*/) {
for (int i = 0; i < formula.getNumChildren(); ++i)
formula.replaceChild(i, inlineFormula(model,formula.getChild(i)));//.clone()));
} else if (formula.isFunction() && model.getFunctionDefinition(formula.getName()) != null) {
if (ibiosimFunctionDefinitions.contains(formula.getName()))
return formula;
ASTNode inlinedFormula = deepCopy(model.getFunctionDefinition(formula.getName()).getBody());
ASTNode oldFormula = deepCopy(formula);
ArrayList<ASTNode> inlinedChildren = new ArrayList<ASTNode>();
getAllASTNodeChildren(inlinedFormula, inlinedChildren);
if (inlinedChildren.size() == 0)
inlinedChildren.add(inlinedFormula);
HashMap<String, Integer> inlinedChildToOldIndexMap = new HashMap<String, Integer>();
for (int i = 0; i < model.getFunctionDefinition(formula.getName()).getNumArguments(); ++i) {
inlinedChildToOldIndexMap.put(model.getFunctionDefinition(formula.getName()).getArgument(i).getName(), i);
}
for (int i = 0; i < inlinedChildren.size(); ++i) {
ASTNode child = inlinedChildren.get(i);
if (child.getNumChildren()==0 && child.isName()) {
int index = inlinedChildToOldIndexMap.get(child.getName());
replaceArgument(inlinedFormula,myFormulaToString(child), oldFormula.getChild(index));
if (inlinedFormula.getNumChildren() == 0)
inlinedFormula = oldFormula.getChild(index);
}
}
return inlinedFormula;
}
return formula;
}
public static void expandFunctionDefinitions(SBMLDocument doc) {
Model model = doc.getModel();
for (int i = 0; i < model.getInitialAssignmentCount(); i++) {
InitialAssignment ia = model.getListOfInitialAssignments().get(i);
if (ia.isSetMath()) {
ia.setMath(inlineFormula(model,ia.getMath()));
}
}
for (int i = 0; i < model.getRuleCount(); i++) {
Rule r = model.getRule(i);
if (r.isSetMath()) {
r.setMath(inlineFormula(model,r.getMath()));
}
}
for (int i = 0; i < model.getConstraintCount(); i++) {
Constraint c = model.getConstraint(i);
if (c.isSetMath()) {
c.setMath(inlineFormula(model,c.getMath()));
}
}
for (int i = 0; i < model.getEventCount(); i++) {
Event e = model.getEvent(i);
if (e.getDelay()!=null && e.getDelay().isSetMath()) {
e.getDelay().setMath(inlineFormula(model,e.getDelay().getMath()));
}
if (e.getTrigger()!=null && e.getTrigger().isSetMath()) {
e.getTrigger().setMath(inlineFormula(model,e.getTrigger().getMath()));
}
if (e.getPriority()!=null && e.getPriority().isSetMath()) {
e.getPriority().setMath(inlineFormula(model,e.getPriority().getMath()));
}
for (int j = 0; j < e.getEventAssignmentCount(); j++) {
EventAssignment ea = e.getListOfEventAssignments().get(j);
if (ea.isSetMath()) {
ea.setMath(inlineFormula(model,ea.getMath()));
}
}
}
}
public static void expandInitialAssignments(SBMLDocument document) {
for (InitialAssignment ia : document.getModel().getListOfInitialAssignments()) {
SBase sb = getElementBySId(document, ia.getVariable());
if (sb instanceof QuantityWithUnit) {
((QuantityWithUnit) sb).setValue(evaluateExpression(document.getModel(), ia.getMath()));
}
}
for (int i = 0; i < document.getModel().getListOfInitialAssignments().size(); i ++) {
document.getModel().getListOfInitialAssignments().remove(i);
}
}
public static String getVariable(Rule r) {
if (r instanceof ExplicitRule) {
return ((ExplicitRule) r).getVariable();
}
return null;
}
public static void setVariable(Rule r, String variable) {
if (r instanceof ExplicitRule) {
((ExplicitRule) r).setVariable(variable);
}
}
public static boolean isSetVariable(Rule r) {
if (r instanceof ExplicitRule) {
return ((ExplicitRule) r).isSetVariable();
}
return false;
}
public static ASTNode deepCopy(ASTNode original) {
return new ASTNode(original);
}
public static void removeFromParentAndDelete(SBase element) {
element.removeFromParent();
}
public static SBase getElementByMetaId(SBMLDocument document, String metaId) {
return document.findSBase(metaId);
}
public static SBase getElementBySId(SBMLDocument document, String id) {
return getElementBySId(document.getModel(), id);
}
public static SBase getElementByMetaId(Model m, String metaId) {
return getElementByMetaId(m.getSBMLDocument(), metaId);
}
public static SBase getElementBySId(Model m, String id) {
return m.findNamedSBase(id);
}
private static SBase getElementByMetaId(CompSBMLDocumentPlugin compDocument, String metaId) {
for (SBase sb : getListOfAllElements(compDocument)) {
if (sb.getMetaId().equals(metaId)) {
return sb;
}
}
return null;
}
public static ArrayList<SBase> getListOfAllElements(TreeNode node) {
ArrayList<SBase> elements = new ArrayList<SBase>();
if (node instanceof SBase) {
elements.add((SBase) node);
}
for (int i = 0; i < node.getChildCount(); i++) {
elements.addAll(getListOfAllElements(node.getChildAt(i)));
}
return elements;
}
// public static ListOf<SBase> getListOfAllElements(Model m) {
// ListOf<SBase> elements = new ListOf<SBase>();
// for (Compartment c : m.getListOfCompartments()) {
// for (Constraint c : m.getListOfConstraints()) {
// for (Event e : m.getListOfEvents()) {
// elements.add(e);
// for (EventAssignment ea : e.getListOfEventAssignments()) {
// elements.add(ea);
// for (FunctionDefinition fd : m.getListOfFunctionDefinitions()) {
// elements.add(fd);
// for (InitialAssignment ia : m.getListOfInitialAssignments()) {
// elements.add(ia);
// for (Parameter p : m.getListOfParameters()) {
// elements.add(p);
// for (UnitDefinition ud : m.getListOfPredefinedUnitDefinitions()) {
// elements.add(ud);
// for (Reaction r : m.getListOfReactions()) {
// elements.add(r);
// for (ModifierSpeciesReference msr : r.getListOfModifiers()) {
// elements.add(msr);
// for (SpeciesReference sr : r.getListOfProducts()) {
// elements.add(sr);
// for (SpeciesReference sr : r.getListOfReactants()) {
// elements.add(sr);
// for (LocalParameter lp : r.getKineticLaw().getListOfLocalParameters()) {
// elements.add(lp);
// for (Rule r : m.getListOfRules()) {
// elements.add(r);
// for (Species s : m.getListOfSpecies()) {
// elements.add(s);
// for (UnitDefinition ud : m.getListOfUnitDefinitions()) {
// elements.add(ud);
// return elements;
public static String getId(SBase sb) {
if (sb instanceof AbstractNamedSBase) {
return ((AbstractNamedSBase) sb).getId();
}
else {
return null;
}
}
public static int appendAnnotation(SBase sbmlObject, String annotation) {
sbmlObject.getAnnotation().appendNoRDFAnnotation(annotation);
//sbmlObject.setAnnotation(new Annotation(sbmlObject.getAnnotationString().replace("<annotation>", "").replace("</annotation>", "").trim() + annotation));
return JSBML.OPERATION_SUCCESS;
}
public static int appendAnnotation(SBase sbmlObject, XMLNode annotation) {
sbmlObject.setAnnotation(new Annotation(sbmlObject.getAnnotationString().replace("<annotation>", "").replace("</annotation>", "").trim() + annotation.toXMLString()));
return JSBML.OPERATION_SUCCESS;
}
public static void addPackage(SBMLDocument document,String packageName,String packageURI,String required) {
document.addNamespace(packageName,"xmlns",packageURI);
Map<String, String> docAttr = document.getSBMLDocumentAttributes();
if (!docAttr.containsKey(packageName+":required")) {
docAttr.put(packageName+":required",required);
}
document.setSBMLDocumentAttributes(docAttr);
}
public static SBasePlugin getPlugin(String namespace, SBase sb, boolean createPlugin) {
if (sb.getExtension(namespace) != null) {
return sb.getExtension(namespace);
}
else if (createPlugin && namespace.equals(CompConstant.namespaceURI)) {
SBasePlugin comp;
if (sb instanceof SBMLDocument) {
comp = new CompSBMLDocumentPlugin((SBMLDocument) sb);
}
else if (sb instanceof Model) {
comp = new CompModelPlugin((Model) sb);;
}
else {
comp = new CompSBasePlugin(sb);
}
sb.addExtension(namespace, comp);
return comp;
}
else if (createPlugin && namespace.equals(LayoutConstants.namespaceURI) && sb instanceof Model) {
LayoutModelPlugin layout = new LayoutModelPlugin((Model) sb);
sb.addExtension(namespace, layout);
return layout;
}
else if (createPlugin && namespace.equals(FBCConstants.namespaceURI) && sb instanceof Model) {
FBCModelPlugin fbc = new FBCModelPlugin((Model) sb);
sb.addExtension(namespace, fbc);
return fbc;
}
else if (createPlugin && namespace.equals(QualConstant.namespaceURI) && sb instanceof Model) {
QualitativeModel qual = new QualitativeModel((Model) sb);
sb.addExtension(namespace, qual);
return qual;
}
else {
return null;
}
}
public static void setNamespaces(SBMLDocument document, SortedSet<String> namespaces) {
ArrayList<String> remove = new ArrayList<String>();
for (String namespace : document.getNamespaces()) {
remove.add(namespace);
}
for (String namespace : remove) {
document.removeNamespace(namespace);
}
for (String namespace : namespaces) {
document.addNamespace(namespace);
}
}
public static boolean getBooleanFromDouble(double value) {
if (value == 0.0)
return false;
else
return true;
}
public static double getDoubleFromBoolean(boolean value) {
if (value == true)
return 1.0;
else
return 0.0;
}
public static double evaluateExpression(Model model, ASTNode node) {
PsRandom prng = new PsRandom();
if (node.isBoolean()) {
switch (node.getType()) {
case CONSTANT_TRUE:
return 1.0;
case CONSTANT_FALSE:
return 0.0;
case LOGICAL_NOT:
return getDoubleFromBoolean(!(getBooleanFromDouble(evaluateExpression(model, node.getLeftChild()))));
case LOGICAL_AND: {
boolean andResult = true;
for (int childIter = 0; childIter < node.getNumChildren(); ++childIter)
andResult = andResult && getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter)));
return getDoubleFromBoolean(andResult);
}
case LOGICAL_OR: {
boolean orResult = false;
for (int childIter = 0; childIter < node.getNumChildren(); ++childIter)
orResult = orResult || getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter)));
return getDoubleFromBoolean(orResult);
}
case LOGICAL_XOR: {
boolean xorResult = getBooleanFromDouble(evaluateExpression(model, node.getChild(0)));
for (int childIter = 1; childIter < node.getNumChildren(); ++childIter)
xorResult = xorResult ^ getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter)));
return getDoubleFromBoolean(xorResult);
}
case RELATIONAL_EQ:
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) == evaluateExpression(model, node.getRightChild()));
case RELATIONAL_NEQ:
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) != evaluateExpression(model, node.getRightChild()));
case RELATIONAL_GEQ:
{
//System.out.println("Node: " + libsbml.formulaToString(node.getRightChild()) + " " + evaluateExpressionRecursive(modelstate, node.getRightChild()));
//System.out.println("Node: " + evaluateExpressionRecursive(modelstate, node.getLeftChild()) + " " + evaluateExpressionRecursive(modelstate, node.getRightChild()));
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) >= evaluateExpression(model, node.getRightChild()));
}
case RELATIONAL_LEQ:
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) <= evaluateExpression(model, node.getRightChild()));
case RELATIONAL_GT:
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) > evaluateExpression(model, node.getRightChild()));
case RELATIONAL_LT:
{
return getDoubleFromBoolean(
evaluateExpression(model, node.getLeftChild()) < evaluateExpression(model, node.getRightChild()));
}
}
}
//if it's a mathematical constant
else if (node.isConstant()) {
switch (node.getType()) {
case CONSTANT_E:
return Math.E;
case CONSTANT_PI:
return Math.PI;
}
}
else if (node.isInteger())
return node.getInteger();
//if it's a number
else if (node.isReal())
return node.getReal();
//if it's a user-defined variable
//eg, a species name or global/local parameter
else if (node.isName()) {
SBase sb = getElementBySId(model, node.getName());
if (sb instanceof QuantityWithUnit) {
return ((QuantityWithUnit) sb).getValue();
}
}
//operators/functions with two children
else {
ASTNode leftChild = node.getLeftChild();
ASTNode rightChild = node.getRightChild();
switch (node.getType()) {
case PLUS: {
double sum = 0.0;
for (int childIter = 0; childIter < node.getNumChildren(); ++childIter)
sum += evaluateExpression(model, node.getChild(childIter));
return sum;
}
case MINUS: {
double sum = evaluateExpression(model, leftChild);
for (int childIter = 1; childIter < node.getNumChildren(); ++childIter)
sum -= evaluateExpression(model, node.getChild(childIter));
return sum;
}
case TIMES: {
double product = 1.0;
for (int childIter = 0; childIter < node.getNumChildren(); ++childIter)
product *= evaluateExpression(model, node.getChild(childIter));
return product;
}
case DIVIDE:
return (evaluateExpression(model, leftChild) / evaluateExpression(model, rightChild));
case FUNCTION_POWER:
return (FastMath.pow(evaluateExpression(model, leftChild), evaluateExpression(model, rightChild)));
case FUNCTION: {
//use node name to determine function
//i'm not sure what to do with completely user-defined functions, though
String nodeName = node.getName();
//generates a uniform random number between the upper and lower bound
if (nodeName.equals("uniform")) {
double leftChildValue = evaluateExpression(model, node.getLeftChild());
double rightChildValue = evaluateExpression(model, node.getRightChild());
double lowerBound = FastMath.min(leftChildValue, rightChildValue);
double upperBound = FastMath.max(leftChildValue, rightChildValue);
return prng.nextDouble(lowerBound, upperBound);
}
else if (nodeName.equals("exponential")) {
return prng.nextExponential(evaluateExpression(model, node.getLeftChild()), 1);
}
else if (nodeName.equals("gamma")) {
return prng.nextGamma(1, evaluateExpression(model, node.getLeftChild()),
evaluateExpression(model, node.getRightChild()));
}
else if (nodeName.equals("chisq")) {
return prng.nextChiSquare((int) evaluateExpression(model, node.getLeftChild()));
}
else if (nodeName.equals("lognormal")) {
return prng.nextLogNormal(evaluateExpression(model, node.getLeftChild()),
evaluateExpression(model, node.getRightChild()));
}
else if (nodeName.equals("laplace")) {
//function doesn't exist in current libraries
return 0;
}
else if (nodeName.equals("cauchy")) {
return prng.nextLorentzian(0, evaluateExpression(model, node.getLeftChild()));
}
else if (nodeName.equals("poisson")) {
return prng.nextPoissonian(evaluateExpression(model, node.getLeftChild()));
}
else if (nodeName.equals("binomial")) {
return prng.nextBinomial(evaluateExpression(model, node.getLeftChild()),
(int) evaluateExpression(model, node.getRightChild()));
}
else if (nodeName.equals("bernoulli")) {
return prng.nextBinomial(evaluateExpression(model, node.getLeftChild()), 1);
}
else if (nodeName.equals("normal")) {
return prng.nextGaussian(evaluateExpression(model, node.getLeftChild()),
evaluateExpression(model, node.getRightChild()));
}
break;
}
case FUNCTION_ABS:
return FastMath.abs(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCOS:
return FastMath.acos(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCSIN:
return FastMath.asin(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCTAN:
return FastMath.atan(evaluateExpression(model, node.getChild(0)));
case FUNCTION_CEILING:
return FastMath.ceil(evaluateExpression(model, node.getChild(0)));
case FUNCTION_COS:
return FastMath.cos(evaluateExpression(model, node.getChild(0)));
case FUNCTION_COSH:
return FastMath.cosh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_EXP:
return FastMath.exp(evaluateExpression(model, node.getChild(0)));
case FUNCTION_FLOOR:
return FastMath.floor(evaluateExpression(model, node.getChild(0)));
case FUNCTION_LN:
return FastMath.log(evaluateExpression(model, node.getChild(0)));
case FUNCTION_LOG:
return FastMath.log10(evaluateExpression(model, node.getChild(0)));
case FUNCTION_SIN:
return FastMath.sin(evaluateExpression(model, node.getChild(0)));
case FUNCTION_SINH:
return FastMath.sinh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_TAN:
return FastMath.tan(evaluateExpression(model, node.getChild(0)));
case FUNCTION_TANH:
return FastMath.tanh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_PIECEWISE: {
//loop through child triples
//if child 1 is true, return child 0, else return child 2
for (int childIter = 0; childIter < node.getNumChildren(); childIter += 3) {
if ((childIter + 1) < node.getNumChildren() &&
getBooleanFromDouble(evaluateExpression(model, node.getChild(childIter + 1)))) {
return evaluateExpression(model, node.getChild(childIter));
}
else if ((childIter + 2) < node.getNumChildren()) {
return evaluateExpression(model, node.getChild(childIter + 2));
}
}
return 0;
}
case FUNCTION_ROOT:
return FastMath.pow(evaluateExpression(model, node.getRightChild()),
1 / evaluateExpression(model, node.getLeftChild()));
case FUNCTION_SEC:
return Fmath.sec(evaluateExpression(model, node.getChild(0)));
case FUNCTION_SECH:
return Fmath.sech(evaluateExpression(model, node.getChild(0)));
case FUNCTION_FACTORIAL:
return Fmath.factorial(evaluateExpression(model, node.getChild(0)));
case FUNCTION_COT:
return Fmath.cot(evaluateExpression(model, node.getChild(0)));
case FUNCTION_COTH:
return Fmath.coth(evaluateExpression(model, node.getChild(0)));
case FUNCTION_CSC:
return Fmath.csc(evaluateExpression(model, node.getChild(0)));
case FUNCTION_CSCH:
return Fmath.csch(evaluateExpression(model, node.getChild(0)));
case FUNCTION_DELAY:
//NOT PLANNING TO SUPPORT THIS
return 0;
case FUNCTION_ARCTANH:
return Fmath.atanh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCSINH:
return Fmath.asinh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCOSH:
return Fmath.acosh(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCOT:
return Fmath.acot(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCOTH:
return Fmath.acoth(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCSC:
return Fmath.acsc(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCCSCH:
return Fmath.acsch(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCSEC:
return Fmath.asec(evaluateExpression(model, node.getChild(0)));
case FUNCTION_ARCSECH:
return Fmath.asech(evaluateExpression(model, node.getChild(0)));
} //end switch
}
return 0.0;
}
public static void setMetaId(AbstractSBase asb, String newId) {
if (!asb.getMetaId().equals(newId)){
asb.setMetaId(newId);
}
}
public static void setMetaId(SBase asb, String newId) {
if (!asb.getMetaId().equals(newId)){
asb.setMetaId(newId);
}
}
public static ModifierSpeciesReference removeModifier(Reaction r, String species) {
if (r.getListOfModifiers() != null) {
return r.removeModifier(species);
}
else {
return null;
}
}
public static void checkModelCompleteness(SBMLDocument document) {
FBCModelPlugin fbc = (FBCModelPlugin)SBMLutilities.getPlugin(FBCConstants.namespaceURI, document.getModel(), true);
JTextArea messageArea = new JTextArea();
messageArea.append("Model is incomplete. Cannot be simulated until the following information is provided.\n");
boolean display = false;
org.sbml.jsbml.Model model = document.getModel();
ListOf list = model.getListOfCompartments();
for (int i = 0; i < model.getCompartmentCount(); i++) {
Compartment compartment = (Compartment) list.get(i);
if (!compartment.isSetSize()) {
messageArea.append("
messageArea.append("Compartment " + compartment.getId() + " needs a size.\n");
display = true;
}
}
list = model.getListOfSpecies();
for (int i = 0; i < model.getSpeciesCount(); i++) {
Species species = (Species) list.get(i);
if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) {
messageArea.append("
messageArea.append("Species " + species.getId() + " needs an initial amount or concentration.\n");
display = true;
}
}
list = model.getListOfParameters();
for (int i = 0; i < model.getParameterCount(); i++) {
Parameter parameter = (Parameter) list.get(i);
if (!(parameter.isSetValue())) {
messageArea.append("
messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n");
display = true;
}
}
for (int i = 0; i < model.getReactionCount(); i++) {
Reaction reaction = model.getReaction(i);
if (fbc!=null) {
boolean foundIt = false;
for (int j = 0; j < fbc.getListOfFluxBounds().size(); j++) {
FluxBound fb = fbc.getFluxBound(j);
if (fb.getReaction().equals(reaction.getId())) {
foundIt = true;
break;
}
}
if (foundIt) continue;
}
if (!(reaction.isSetKineticLaw())) {
messageArea.append("
messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n");
display = true;
}
else {
ListOf params = reaction.getKineticLaw().getListOfLocalParameters();
for (int j = 0; j < reaction.getKineticLaw().getLocalParameterCount(); j++) {
LocalParameter param = (LocalParameter) params.get(j);
if (!(param.isSetValue())) {
messageArea.append("
messageArea.append("Local parameter " + param.getId() + " for reaction " + reaction.getId() + " needs an initial value.\n");
display = true;
}
}
}
}
if (display) {
final JFrame f = new JFrame("SBML Model Completeness Errors");
messageArea.setLineWrap(true);
messageArea.setEditable(false);
messageArea.setSelectionStart(0);
messageArea.setSelectionEnd(0);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JButton close = new JButton("Dismiss");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
JPanel consistencyPanel = new JPanel(new BorderLayout());
consistencyPanel.add(scroll, "Center");
consistencyPanel.add(close, "South");
f.setContentPane(consistencyPanel);
f.pack();
Dimension screenSize;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
screenSize = tk.getScreenSize();
}
catch (AWTError awe) {
screenSize = new Dimension(640, 480);
}
Dimension frameSize = f.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
int x = screenSize.width / 2 - frameSize.width / 2;
int y = screenSize.height / 2 - frameSize.height / 2;
f.setLocation(x, y);
f.setVisible(true);
}
}
}
|
package hex.genmodel;
import water.genmodel.IGeneratedModel;
import hex.ModelCategory;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
/** This is a helper class to support Java generated models. */
public abstract class GenModel implements IGenModel, IGeneratedModel, Serializable {
/** Column names; last is response for supervised models */
public final String[] _names;
/** Categorical/factor/enum mappings, per column. Null for non-enum cols.
* Columns match the post-init cleanup columns. The last column holds the
* response col enums for SupervisedModels. */
public final String[][] _domains;
public GenModel( String[] names, String[][] domains ) { _names = names; _domains = domains; }
@Override public boolean isSupervised() {
// FIXME: can be derived directly from model category?
return false;
}
@Override public int nfeatures() {
return _names.length;
}
@Override public int nclasses() {
return 0;
}
@Override public int getNumCols() {
return nfeatures();
}
@Override public int getResponseIdx() {
if (!isSupervised())
throw new UnsupportedOperationException("Cannot provide response index for unsupervised models.");
return _domains.length - 1;
}
@Override public String getResponseName() {
throw new UnsupportedOperationException("getResponseName is not supported in h2o-dev!");
}
@Override public int getNumResponseClasses() {
if (isClassifier())
return nclasses();
else
throw new UnsupportedOperationException("Cannot provide number of response classes for non-classifiers.");
}
@Override public String[] getNames() {
return _names;
}
@Override public int getColIdx(String name) {
String[] names = getNames();
for (int i=0; i<names.length; i++) if (names[i].equals(name)) return i;
return -1;
}
@Override public int getNumClasses(int colIdx) {
String[] domval = getDomainValues(colIdx);
return domval!=null?domval.length:-1;
}
@Override public String[] getDomainValues(String name) {
int colIdx = getColIdx(name);
return colIdx != -1 ? getDomainValues(colIdx) : null;
}
@Override public String[] getDomainValues(int i) {
return getDomainValues()[i];
}
@Override public int mapEnum(int colIdx, String enumValue) {
String[] domain = getDomainValues(colIdx);
if (domain==null || domain.length==0) return -1;
for (int i=0; i<domain.length;i++) if (enumValue.equals(domain[i])) return i;
return -1;
}
@Override
public String[][] getDomainValues() {
return _domains;
}
@Override public boolean isClassifier() {
ModelCategory cat = getModelCategory();
return cat == ModelCategory.Binomial || cat == ModelCategory.Multinomial;
}
@Override public boolean isAutoEncoder() {
ModelCategory cat = getModelCategory();
return cat == ModelCategory.AutoEncoder;
}
@Override public int getPredsSize() {
return isClassifier() ? 1 + getNumResponseClasses() : 2;
}
public String getHeader() { return null; }
/** Takes a HashMap mapping column names to doubles.
* <p>
* Looks up the column names needed by the model, and places the doubles into
* the data array in the order needed by the model. Missing columns use NaN.
* </p>
*/
public double[] map( Map<String, Double> row, double data[] ) {
String[] colNames = _names;
for( int i=0; i<nfeatures(); i++ ) {
Double d = row.get(colNames[i]);
data[i] = d==null ? Double.NaN : d;
}
return data;
}
@Override
public float[] predict(double[] data, float[] preds) {
return predict(data, preds, 0);
}
@Override
public float[] predict(double[] data, float[] preds, int maxIters) {
throw new UnsupportedOperationException("Unsupported operation - uses score0 method!");
}
/** Subclasses implement the scoring logic. The data is pre-loaded into a
* re-used temp array, in the order the model expects. The predictions are
* loaded into the re-used temp array, which is also returned. This call
* exactly matches the hex.Model.score0, but uses the light-weight
* GenModel class. */
abstract public double[] score0( double[] data, double[] preds );
// Does the mapping lookup for every row, no allocation.
// data and preds arrays are pre-allocated and can be re-used for every row.
public double[] score0( Map<String, Double> row, double data[], double preds[] ) {
return score0(map(row,data),preds);
}
// Does the mapping lookup for every row.
// preds array is pre-allocated and can be re-used for every row.
// Allocates a double[] for every row.
public double[] score0( Map<String, Double> row, double preds[] ) {
return score0(map(row,new double[nfeatures()]),preds);
}
// Does the mapping lookup for every row.
// Allocates a double[] and a float[] for every row.
public double[] score0( Map<String, Double> row ) {
return score0(map(row,new double[nfeatures()]),new double[nclasses()+1]);
}
public static double[] correctProbabilities(double[] scored, double[] priorClassDist, double[] modelClassDist) {
double probsum=0;
for( int c=1; c<scored.length; c++ ) {
final double original_fraction = priorClassDist[c-1];
final double oversampled_fraction = modelClassDist[c-1];
assert(!Double.isNaN(scored[c])) : "Predicted NaN class probability";
if (original_fraction != 0 && oversampled_fraction != 0) scored[c] *= original_fraction / oversampled_fraction;
probsum += scored[c];
}
if (probsum>0) for (int i=1;i<scored.length;++i) scored[i] /= probsum;
return scored;
}
/** Utility function to get a best prediction from an array of class
* prediction distribution. It returns index of max value if predicted
* values are unique. In the case of tie, the implementation solve it in
* pseudo-random way.
* @param preds an array of prediction distribution. Length of arrays is equal to a number of classes+1.
* @param threshold threshold for binary classifier
* @return the best prediction (index of class, zero-based)
*/
public static int getPrediction(double[] preds, double data[], double threshold) {
if (preds.length == 3) {
return (preds[2] >= threshold) ? 1 : 0; //no tie-breaking
}
int best=1, tieCnt=0; // Best class; count of ties
for( int c=2; c<preds.length; c++) {
if( preds[best] < preds[c] ) {
best = c; // take the max index
tieCnt=0; // No ties
} else if (preds[best] == preds[c]) {
tieCnt++; // Ties
}
}
if( tieCnt==0 ) return best-1; // Return zero-based best class
// Tie-breaking logic
double res = preds[best]; // One of the tied best results
long hash = 0; // hash for tie-breaking
if( data != null )
for( double d : data ) hash ^= Double.doubleToRawLongBits(d) >> 6; // drop 6 least significants bits of mantisa (layout of long is: 1b sign, 11b exp, 52b mantisa)
int idx = (int)hash%(tieCnt+1); // Which of the ties we'd like to keep
for( best=1; best<preds.length; best++)
if( res == preds[best] && --idx < 0 )
return best-1; // Return best
throw new RuntimeException("Should Not Reach Here");
}
// Utility to do bitset lookup
public static boolean bitSetContains(byte[] bits, int bitoff, int num ) {
if (Integer.MIN_VALUE == num) { //Missing value got cast'ed to Integer.MIN_VALUE via (int)-Float.MAX_VALUE in GenModel.*_fclean
num = 0; // all missing values are treated the same as the first enum level //FIXME
}
assert num >= 0;
num -= bitoff;
return (num >= 0) && (num < (bits.length<<3)) &&
(bits[num >> 3] & ((byte)1 << (num & 7))) != 0;
}
// KMeans utilities
// For KMeansModel scoring; just the closest cluster center
public static int KMeans_closest(double[][] centers, double[] point, String[][] domains, double[] means, double[] mults) {
int min = -1;
double minSqr = Double.MAX_VALUE;
for( int cluster = 0; cluster < centers.length; cluster++ ) {
double sqr = KMeans_distance(centers[cluster],point,domains,means,mults);
if( sqr < minSqr ) { // Record nearest cluster center
min = cluster;
minSqr = sqr;
}
}
return min;
}
// only used for metric builder - uses float[] and fills up colSum & colSumSq arrays, otherwise the same as method below.
// WARNING - if changing this code - also change the code below
public static double KMeans_distance(double[] center, float[] point, String[][] domains, double[] means, double[] mults,
double[] colSum, double[] colSumSq) {
double sqr = 0; // Sum of dimensional distances
int pts = point.length; // Count of valid points
for(int column = 0; column < center.length; column++) {
float d = point[column];
if( Float.isNaN(d) ) { pts--; continue; }
if( domains[column] != null ) { // Categorical?
if( d != center[column] ) {
sqr += 1.0; // Manhattan distance
}
} else { // Euclidean distance
if( mults != null ) { // Standardize if requested
d -= means[column];
d *= mults[column];
}
double delta = d - center[column];
sqr += delta * delta;
}
colSum[column] += d;
colSumSq[column] += d*d;
}
// Scale distance by ratio of valid dimensions to all dimensions - since
// we did not add any error term for the missing point, the sum of errors
// is small - ratio up "as if" the missing error term is equal to the
// average of other error terms. Same math another way:
// double avg_dist = sqr / pts; // average distance per feature/column/dimension
// sqr = sqr * point.length; // Total dist is average*#dimensions
if( 0 < pts && pts < point.length ) {
double scale = point.length / pts;
sqr *= scale;
// for (int i=0; i<colSum.length; ++i) {
// colSum[i] *= Math.sqrt(scale);
// colSumSq[i] *= scale;
}
return sqr;
}
// WARNING - if changing this code - also change the code above
public static double KMeans_distance(double[] center, double[] point, String[][] domains, double[] means, double[] mults) {
double sqr = 0; // Sum of dimensional distances
int pts = point.length; // Count of valid points
for(int column = 0; column < center.length; column++) {
double d = point[column];
if( Double.isNaN(d) ) { pts--; continue; }
if( domains[column] != null ) { // Categorical?
if( d != center[column] )
sqr += 1.0; // Manhattan distance
} else { // Euclidean distance
if( mults != null ) { // Standardize if requested
d -= means[column];
d *= mults[column];
}
double delta = d - center[column];
sqr += delta * delta;
}
}
// Scale distance by ratio of valid dimensions to all dimensions - since
// we did not add any error term for the missing point, the sum of errors
// is small - ratio up "as if" the missing error term is equal to the
// average of other error terms. Same math another way:
// double avg_dist = sqr / pts; // average distance per feature/column/dimension
// sqr = sqr * point.length; // Total dist is average*#dimensions
if( 0 < pts && pts < point.length )
sqr *= point.length / pts;
return sqr;
}
// SharedTree utilities
// Tree scoring; NaNs always "go left": count as -Float.MAX_VALUE
public static double[] SharedTree_clean( double[] data ) {
double[] fs = new double[data.length];
for( int i=0; i<data.length; i++ )
fs[i] = Double.isNaN(data[i]) ? -Double.MAX_VALUE : data[i];
return fs;
}
// Build a class distribution from a log scale.
// Because we call Math.exp, we have to be numerically stable or else we get
// Infinities, and then shortly NaN's. Rescale the data so the largest value
// is +/-1 and the other values are smaller. See notes here:
public static double log_rescale(double[] preds) {
// Find a max
double maxval=Double.NEGATIVE_INFINITY;
for( int k=1; k<preds.length; k++) maxval = Math.max(maxval,preds[k]);
assert !Double.isInfinite(maxval) : "Something is wrong with GBM trees since returned prediction is " + Arrays.toString(preds);
// exponentiate the scaled predictions; keep a rolling sum
double dsum=0;
for( int k=1; k<preds.length; k++ )
dsum += (preds[k]=Math.exp(preds[k]-maxval));
return dsum; // Return rolling sum; predictions are log-scaled
}
// Build a class distribution from a log scale; find the top prediction
public static void GBM_rescale(double[] preds) {
double sum = log_rescale(preds);
for( int k=1; k<preds.length; k++ ) preds[k] /= sum;
}
// GLM utilities
public static double GLM_identityInv( double x ) { return x; }
public static double GLM_logitInv( double x ) { return 1.0 / (Math.exp(-x) + 1.0); }
public static double GLM_logInv( double x ) { return Math.exp(x); }
public static double GLM_inverseInv( double x ) { double xx = (x < 0) ? Math.min(-1e-5, x) : Math.max(1e-5, x); return 1.0 / xx; }
public static double GLM_tweedieInv( double x, double tweedie_link_power ) { return Math.pow(x, 1/ tweedie_link_power); }
}
|
package ui;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import seaquellersbb.*;
/**
*
* @author serenachen
*/
public class ThreadUI extends javax.swing.JFrame {
private SeaQuellersBBAPI seaQuellers;
private seaquellersbb.Thread thread;
private ArrayList<Comment> comments;
private User loggedInUser;
private Forum forum;
private Subforum subforum;
private SubforumUI subUI;
private boolean isMod;
private Comment activeComment;
/**
* Creates new form ThreadUI
*/
public ThreadUI(SeaQuellersBBAPI seaQuellers, seaquellersbb.Thread thread, User user, Forum forum, Subforum subforum, SubforumUI subUI, int[] modIds) {
initComponents();
this.seaQuellers = seaQuellers;
this.thread = thread;
this.loggedInUser = user;
this.forum = forum;
this.subforum = subforum;
this.subUI = subUI;
username.setText(loggedInUser.username);
threadTitle.setText(thread.title);
this.isMod = (user.isSuperAdmin || forum.userId == user.id || thread.poster.id == user.id || Arrays.stream(modIds).anyMatch(x -> x == user.id));
if (!isMod) deleteThreadButton.setVisible(false);
editButton.setVisible(false);
cancelEditButton.setVisible(false);
drawComments();
}
/**
* 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() {
jPanel2 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
toolbarPanel = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
username = new javax.swing.JLabel();
threadTitle = new javax.swing.JLabel();
deleteThreadButton = new javax.swing.JButton();
panel = new javax.swing.JScrollPane();
commentPanel = new javax.swing.JTextPane();
replyBtn = new javax.swing.JButton();
DisplayPanel = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
editButton = new javax.swing.JButton();
cancelEditButton = new javax.swing.JButton();
deleteCommentButton = new javax.swing.JButton();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel6.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
toolbarPanel.setBackground(new java.awt.Color(0, 102, 204));
jLabel5.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Currently logged in:");
username.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
username.setForeground(new java.awt.Color(255, 255, 255));
username.setText("[username]");
threadTitle.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
threadTitle.setForeground(new java.awt.Color(255, 255, 255));
threadTitle.setText("[threadTitle]");
deleteThreadButton.setText("Delete This Thread");
deleteThreadButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
deleteThreadButtonMouseClicked(evt);
}
});
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()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(username)
.addGap(67, 67, 67)
.addComponent(threadTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 158, Short.MAX_VALUE)
.addComponent(deleteThreadButton)
.addContainerGap())
);
toolbarPanelLayout.setVerticalGroup(
toolbarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(toolbarPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(toolbarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(username)
.addComponent(threadTitle)
.addComponent(deleteThreadButton))
.addContainerGap(12, Short.MAX_VALUE))
);
panel.setViewportView(commentPanel);
replyBtn.setText("Reply");
replyBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
replyBtnMouseClicked(evt);
}
});
javax.swing.GroupLayout DisplayPanelLayout = new javax.swing.GroupLayout(DisplayPanel);
DisplayPanel.setLayout(DisplayPanelLayout);
DisplayPanelLayout.setHorizontalGroup(
DisplayPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
DisplayPanelLayout.setVerticalGroup(
DisplayPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 259, Short.MAX_VALUE)
);
jButton1.setText("Exit");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});
editButton.setText("Edit");
editButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
editButtonMouseClicked(evt);
}
});
cancelEditButton.setText("Cancel");
cancelEditButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelEditButtonMouseClicked(evt);
}
});
deleteCommentButton.setText("Delete");
deleteCommentButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
deleteCommentButtonMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(toolbarPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteCommentButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelEditButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(editButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(replyBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(DisplayPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 326, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(0, 326, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(toolbarPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DisplayPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(replyBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(editButton)
.addComponent(cancelEditButton)
.addComponent(deleteCommentButton))
.addContainerGap())
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 224, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(0, 225, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// TODO: need IDs
// mouse event to create a new thread comment, clear commentPanel, and refresh the window
private void replyBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_replyBtnMouseClicked
String body = commentPanel.getText();
seaQuellers.createComment(thread.id, thread.subId, thread.forumId, body, loggedInUser.id);
commentPanel.setText("");
this.refreshComments();
}//GEN-LAST:event_replyBtnMouseClicked
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
this.dispose();
}//GEN-LAST:event_jButton1MouseClicked
private void deleteThreadButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteThreadButtonMouseClicked
seaQuellers.deleteThread(thread.id, thread.subId, thread.forumId);
subUI.refreshThreads();
this.dispose();
}//GEN-LAST:event_deleteThreadButtonMouseClicked
private void editButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editButtonMouseClicked
if (activeComment != null){
String newCommentBody = commentPanel.getText();
seaQuellers.editCommentBody(activeComment.id, thread.id, thread.subId, thread.forumId, newCommentBody);
}
else{
String newThreadBody = commentPanel.getText();
seaQuellers.editThreadBody(thread.id, thread.subId, thread.forumId, newThreadBody);
}
commentPanel.setText("");
editButton.setVisible(false);
cancelEditButton.setVisible(false);
deleteCommentButton.setVisible(false);
replyBtn.setVisible(true);
this.refreshComments();
}//GEN-LAST:event_editButtonMouseClicked
private void cancelEditButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelEditButtonMouseClicked
commentPanel.setText("");
activeComment = null;
editButton.setVisible(false);
cancelEditButton.setVisible(false);
deleteCommentButton.setVisible(false);
replyBtn.setVisible(true);
}//GEN-LAST:event_cancelEditButtonMouseClicked
private void deleteCommentButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteCommentButtonMouseClicked
seaQuellers.deleteComment(activeComment.id, thread.id, thread.subId, thread.forumId);
commentPanel.setText("");
activeComment = null;
editButton.setVisible(false);
cancelEditButton.setVisible(false);
deleteCommentButton.setVisible(false);
replyBtn.setVisible(true);
this.refreshComments();
}//GEN-LAST:event_deleteCommentButtonMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ThreadUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ThreadUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ThreadUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ThreadUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new ThreadUI(new SeaQuellersBBAPI()).setVisible(true);
}
public void refreshComments(){
DisplayPanel.removeAll();
commentPanel.removeAll();
drawComments();
DisplayPanel.revalidate();
DisplayPanel.repaint();
commentPanel.revalidate();
commentPanel.repaint();
this.pack();
}
public void drawComments(){
comments = seaQuellers.getComments(thread.id, thread.subId, thread.forumId);
DisplayPanel.setLayout(new GridLayout(0, 1)); // One column, unlimited rows
DisplayPanel.add(new JSeparator(SwingConstants.HORIZONTAL));
JLabel threadBody = new JLabel(thread.body);
threadBody.setName("" + 0);
threadBody.setFont(Font.decode("Lucida-Grande-Bold-16"));
threadBody.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (thread.poster.id == loggedInUser.id){
activeComment = null;
commentPanel.setText(threadBody.getText());
replyBtn.setVisible(false);
editButton.setVisible(true);
cancelEditButton.setVisible(true);
deleteCommentButton.setVisible(false);
}
}
});
DisplayPanel.add(threadBody);
JLabel poster = new JLabel(thread.poster.username);
poster.setName("c"+0);
poster.setFont(Font.decode("Times-New-Roman-11"));
DisplayPanel.add(poster);
DisplayPanel.add(new JSeparator(SwingConstants.HORIZONTAL));
for (int i = 0; i < comments.size(); i++) {
Comment comment = comments.get(i);
JLabel commentBody = new JLabel(comments.get(i).body);
commentBody.setName("" + (i+1));
commentBody.setFont(Font.decode("Lucida-Grande-Bold-14"));
commentBody.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (comment.poster.id == loggedInUser.id){
activeComment = comment;
commentPanel.setText(commentBody.getText());
replyBtn.setVisible(false);
editButton.setVisible(true);
cancelEditButton.setVisible(true);
deleteCommentButton.setVisible(true);
}
else if (isMod){
activeComment = comment;
commentPanel.setText(commentBody.getText());
replyBtn.setVisible(false);
cancelEditButton.setVisible(true);
deleteCommentButton.setVisible(true);
}
}
});
DisplayPanel.add(commentBody);
JLabel commenter = new JLabel(comments.get(i).poster.username);
commenter.setName("c"+(i+1));
commenter.setFont(Font.decode("Times-New-Roman-9"));
DisplayPanel.add(commenter);
DisplayPanel.add(new JSeparator(SwingConstants.HORIZONTAL));
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel DisplayPanel;
private javax.swing.JButton cancelEditButton;
private javax.swing.JTextPane commentPanel;
private javax.swing.JButton deleteCommentButton;
private javax.swing.JButton deleteThreadButton;
private javax.swing.JButton editButton;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane panel;
private javax.swing.JButton replyBtn;
private javax.swing.JLabel threadTitle;
private javax.swing.JPanel toolbarPanel;
private javax.swing.JLabel username;
// End of variables declaration//GEN-END:variables
}
|
package org.bouncycastle.math.ec;
import java.math.BigInteger;
import java.util.Random;
public abstract class ECFieldElement
implements ECConstants
{
BigInteger x;
protected ECFieldElement(BigInteger x)
{
this.x = x;
}
public BigInteger toBigInteger()
{
return x;
}
public abstract String getFieldName();
public abstract ECFieldElement add(ECFieldElement b);
public abstract ECFieldElement subtract(ECFieldElement b);
public abstract ECFieldElement multiply(ECFieldElement b);
public abstract ECFieldElement divide(ECFieldElement b);
public abstract ECFieldElement negate();
public abstract ECFieldElement square();
public abstract ECFieldElement invert();
public abstract ECFieldElement sqrt();
public static class Fp extends ECFieldElement
{
BigInteger q;
public Fp(BigInteger q, BigInteger x)
{
super(x);
if (x.compareTo(q) >= 0)
{
throw new IllegalArgumentException("x value too large in field element");
}
this.q = q;
}
/**
* return the field name for this field.
*
* @return the string "Fp".
*/
public String getFieldName()
{
return "Fp";
}
public BigInteger getQ()
{
return q;
}
public ECFieldElement add(ECFieldElement b)
{
return new Fp(q, x.add(b.x).mod(q));
}
public ECFieldElement subtract(ECFieldElement b)
{
return new Fp(q, x.subtract(b.x).mod(q));
}
public ECFieldElement multiply(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x).mod(q));
}
public ECFieldElement divide(ECFieldElement b)
{
return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q));
}
public ECFieldElement negate()
{
return new Fp(q, x.negate().mod(q));
}
public ECFieldElement square()
{
return new Fp(q, x.multiply(x).mod(q));
}
public ECFieldElement invert()
{
return new Fp(q, x.modInverse(q));
}
// D.1.4 91
/**
* return a sqrt root - the routine verifies that the calculation
* returns the right value - if none exists it returns null.
*/
public ECFieldElement sqrt()
{
// p mod 4 == 3
if (q.testBit(1)) // TODO Shouldn't this include q.testBit(0)?
{
// z = g^(u+1) + p, p = 4u + 3
ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q));
return z.square().equals(this) ? z : null;
}
// p mod 4 == 1
if (q.testBit(0))
{
/*
* TODO: Use Lucas sequence to be faster
BigInteger Q = this.x;
BigInteger P = this.x;
BigInteger U, V;
while (true)
{
while (!(P.multiply(P).subtract(Q.multiply(ECConstants.FOUR)).compareTo(ECConstants.ZERO) == 1))
{
P = new BigInteger(this.x.bitLength(), new Random());
}
BigInteger u = q.subtract(ECConstants.ONE).divide(
ECConstants.FOUR);
BigInteger result[] = lucasSequence(q, P, Q, u.multiply(
ECConstants.TWO).add(ECConstants.ONE));
U = result[0];
V = result[1];
if (V.multiply(V).equals(Q.multiply(ECConstants.FOUR)))
{
return new Fp(q, V.divide(ECConstants.TWO));
}
if (!U.equals(ECConstants.ONE))
{
return null;
}
}
*/
BigInteger qMinusOne = q.subtract(ECConstants.ONE);
BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO);
if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
{
return null;
}
Random rand = new Random();
BigInteger fourX = x.shiftLeft(2);
BigInteger r;
do
{
r = new BigInteger(q.bitLength(), rand);
}
while (r.compareTo(q) >= 0
|| !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne)));
BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR);
BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR);
BigInteger wOne = WOne(r, x, q);
BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q);
BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r);
BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q)
.multiply(x).mod(q)
.multiply(wSum).mod(q);
return new Fp(q, root);
}
throw new RuntimeException("not done yet");
}
private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p)
{
if (n.equals(ECConstants.ONE))
{
return wOne;
}
boolean isEven = !n.testBit(0);
n = n.shiftRight(1);//divide(ECConstants.TWO);
if (isEven)
{
BigInteger w = W(n, wOne, p);
return w.multiply(w).subtract(ECConstants.TWO).mod(p);
}
BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p);
BigInteger w2 = W(n, wOne, p);
return w1.multiply(w2).subtract(wOne).mod(p);
}
private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p)
{
return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p);
}
public boolean equals(Object other)
{
if (other == this)
{
return true;
}
if (!(other instanceof ECFieldElement.Fp))
{
return false;
}
ECFieldElement.Fp o = (ECFieldElement.Fp)other;
return q.equals(o.q) && x.equals(o.x);
}
public int hashCode()
{
return q.hashCode() ^ x.hashCode();
}
}
/**
* Class representing the Elements of the finite field
* <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB)
* representation. Both trinomial (TPB) and pentanomial (PPB) polynomial
* basis representations are supported. Gaussian normal basis (GNB)
* representation is not supported.
*/
public static class F2m extends ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public static final int GNB = 1;
/**
* Indicates trinomial basis representation (TPB). Number chosen
* according to X9.62.
*/
public static final int TPB = 2;
/**
* Indicates pentanomial basis representation (PPB). Number chosen
* according to X9.62.
*/
public static final int PPB = 3;
/**
* TPB or PPB.
*/
private int representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m;
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k1;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k2;
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k3;
/**
* Constructor for PPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger x)
{
super(x);
if ((k2 == 0) && (k3 == 0))
{
this.representation = TPB;
}
else
{
if (k2 >= k3)
{
throw new IllegalArgumentException(
"k2 must be smaller than k3");
}
if (k2 <= 0)
{
throw new IllegalArgumentException(
"k2 must be larger than 0");
}
this.representation = PPB;
}
if (x.signum() < 0)
{
throw new IllegalArgumentException("x value cannot be negative");
}
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
}
/**
* Constructor for TPB.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The BigInteger representing the value of the field element.
*/
public F2m(int m, int k, BigInteger x)
{
// Set k1 to k, and set k2 and k3 to 0
this(m, k, 0, 0, x);
}
public String getFieldName()
{
return "F2m";
}
public static void checkFieldElements(
ECFieldElement a,
ECFieldElement b)
{
if ((!(a instanceof F2m)) || (!(b instanceof F2m)))
{
throw new IllegalArgumentException("Field elements are not "
+ "both instances of ECFieldElement.F2m");
}
if ((a.x.signum() < 0) || (b.x.signum() < 0))
{
throw new IllegalArgumentException(
"x value may not be negative");
}
ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a;
ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b;
if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1)
|| (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3))
{
throw new IllegalArgumentException("Field elements are not "
+ "elements of the same field F2m");
}
if (aF2m.representation != bF2m.representation)
{
// Should never occur
throw new IllegalArgumentException(
"One of the field "
+ "elements are not elements has incorrect representation");
}
}
/**
* Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is
* the reduction polynomial of <code>this</code>.
* @param a The polynomial <code>a(z)</code> to be multiplied by
* <code>z mod f(z)</code>.
* @return <code>z * a(z) mod f(z)</code>
*/
private BigInteger multZModF(final BigInteger a)
{
// Left-shift of a(z)
BigInteger az = a.shiftLeft(1);
if (az.testBit(this.m))
{
// If the coefficient of z^m in a(z) equals 1, reduction
// modulo f(z) is performed: Add f(z) to to a(z):
// Step 1: Unset mth coeffient of a(z)
az = az.clearBit(this.m);
// Step 2: Add r(z) to a(z), where r(z) is defined as
// f(z) = z^m + r(z), and k1, k2, k3 are the positions of
// the non-zero coefficients in r(z)
az = az.flipBit(0);
az = az.flipBit(this.k1);
if (this.representation == PPB)
{
az = az.flipBit(this.k2);
az = az.flipBit(this.k3);
}
}
return az;
}
public ECFieldElement add(final ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x));
}
public ECFieldElement subtract(final ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return add(b);
}
public ECFieldElement multiply(final ECFieldElement b)
{
// Left-to-right shift-and-add field multiplication in F2m
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
final BigInteger az = this.x;
BigInteger bz = b.x;
BigInteger cz;
// Compute c(z) = a(z) * b(z) mod f(z)
if (az.testBit(0))
{
cz = bz;
}
else
{
cz = ECConstants.ZERO;
}
for (int i = 1; i < this.m; i++)
{
// b(z) := z * b(z) mod f(z)
bz = multZModF(bz);
if (az.testBit(i))
{
// If the coefficient of x^i in a(z) equals 1, b(z) is added
// to c(z)
cz = cz.xor(bz);
}
}
return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz);
}
public ECFieldElement divide(final ECFieldElement b)
{
// There may be more efficient implementations
ECFieldElement bInv = b.invert();
return multiply(bInv);
}
public ECFieldElement negate()
{
// -x == x holds for all x in F2m, hence a copy of this is returned
return new F2m(this.m, this.k1, this.k2, this.k3, this.x);
}
public ECFieldElement square()
{
// Naive implementation, can probably be speeded up using modular
// reduction
return multiply(this);
}
public ECFieldElement invert()
{
// Inversion in F2m using the extended Euclidean algorithm
// Input: A nonzero polynomial a(z) of degree at most m-1
// Output: a(z)^(-1) mod f(z)
// u(z) := a(z)
BigInteger uz = this.x;
if (uz.signum() <= 0)
{
throw new ArithmeticException("x is zero or negative, " +
"inversion is impossible");
}
// v(z) := f(z)
BigInteger vz = ECConstants.ONE.shiftLeft(m);
vz = vz.setBit(0);
vz = vz.setBit(this.k1);
if (this.representation == PPB)
{
vz = vz.setBit(this.k2);
vz = vz.setBit(this.k3);
}
// g1(z) := 1, g2(z) := 0
BigInteger g1z = ECConstants.ONE;
BigInteger g2z = ECConstants.ZERO;
// while u != 1
while (!(uz.equals(ECConstants.ZERO)))
{
// j := deg(u(z)) - deg(v(z))
int j = uz.bitLength() - vz.bitLength();
// If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j
if (j < 0)
{
final BigInteger uzCopy = uz;
uz = vz;
vz = uzCopy;
final BigInteger g1zCopy = g1z;
g1z = g2z;
g2z = g1zCopy;
j = -j;
}
// u(z) := u(z) + z^j * v(z)
// Note, that no reduction modulo f(z) is required, because
// deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z)))
// = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z))
// = deg(u(z))
uz = uz.xor(vz.shiftLeft(j));
// g1(z) := g1(z) + z^j * g2(z)
g1z = g1z.xor(g2z.shiftLeft(j));
// if (g1z.bitLength() > this.m) {
// throw new ArithmeticException(
// "deg(g1z) >= m, g1z = " + g1z.toString(2));
}
return new ECFieldElement.F2m(
this.m, this.k1, this.k2, this.k3, g2z);
}
public ECFieldElement sqrt()
{
throw new RuntimeException("Not implemented");
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* TPB (trinomial
* basis representation) or
* PPB (pentanomial
* basis representation).
*/
public int getRepresentation()
{
return this.representation;
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int getM()
{
return this.m;
}
/**
* @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK1()
{
return this.k1;
}
/**
* @return TPB: Always returns <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK2()
{
return this.k2;
}
/**
* @return TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
public int getK3()
{
return this.k3;
}
public String toString()
{
return this.x.toString(2);
}
public boolean equals(Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECFieldElement.F2m))
{
return false;
}
ECFieldElement.F2m b = (ECFieldElement.F2m)anObject;
return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2)
&& (this.k3 == b.k3)
&& (this.representation == b.representation)
&& (this.x.equals(b.x)));
}
public int hashCode()
{
return x.hashCode() ^ m ^ k1 ^ k2 ^ k3;
}
}
}
|
package org.helioviewer.jhv.camera;
import javax.annotation.Nullable;
import org.helioviewer.jhv.astronomy.Sun;
import org.helioviewer.jhv.display.Display;
import org.helioviewer.jhv.display.Viewport;
import org.helioviewer.jhv.layers.ImageLayers;
import org.helioviewer.jhv.math.Quat;
import org.helioviewer.jhv.math.Vec2;
import org.helioviewer.jhv.math.Vec3;
public class CameraHelper {
private static double computeNormalizedX(Viewport vp, double screenX) {
return 2. * ((screenX - vp.x) / vp.width - 0.5);
}
private static double computeNormalizedY(Viewport vp, double screenY) {
return -2. * ((screenY - vp.yAWT) / vp.height - 0.5);
}
public static double computeUpX(Camera camera, Viewport vp, double screenX) {
double width = camera.getWidth();
Vec2 translation = camera.getCurrentTranslation();
return computeNormalizedX(vp, screenX) * width * vp.aspect - translation.x;
}
public static double computeUpY(Camera camera, Viewport vp, double screenY) {
double width = camera.getWidth();
Vec2 translation = camera.getCurrentTranslation();
return computeNormalizedY(vp, screenY) * width - translation.y;
}
static Vec3 getVectorFromSphereTrackball(Camera camera, Viewport vp, double screenX, double screenY, double refRadius2) {
double up1x = computeUpX(camera, vp, screenX);
double up1y = computeUpY(camera, vp, screenY);
double radius2 = up1x * up1x + up1y * up1y;
double z = radius2 <= 0.5 * refRadius2 ? Math.sqrt(refRadius2 - radius2) : 0.5 * refRadius2 / Math.sqrt(radius2);
Vec3 hitPoint = new Vec3(up1x, up1y, z);
return camera.getCurrentDragRotation().rotateInverseVector(hitPoint);
}
@Nullable
public static Vec3 getVectorFromSphere(Camera camera, Viewport vp, double screenX, double screenY, Quat rotation, boolean correctDrag) {
double up1x = computeUpX(camera, vp, screenX);
double up1y = computeUpY(camera, vp, screenY);
double radius2 = up1x * up1x + up1y * up1y;
if (radius2 > Sun.Radius2)
return null;
Vec3 hitPoint = new Vec3(up1x, up1y, Math.sqrt(Sun.Radius2 - radius2));
if (correctDrag)
hitPoint = camera.getCurrentDragRotation().rotateInverseVector(hitPoint);
return rotation.rotateInverseVector(hitPoint);
}
@Nullable
public static Vec3 getVectorFromPlane(Camera camera, Viewport vp, double screenX, double screenY, Quat rotation, boolean correctDrag) {
Quat currentDragRotation = camera.getCurrentDragRotation();
Vec3 altnormal = rotation.rotateVector(Vec3.ZAxis);
if (correctDrag)
altnormal = currentDragRotation.rotateVector(Vec3.ZAxis);
if (altnormal.z == 0)
return null;
double up1x = computeUpX(camera, vp, screenX);
double up1y = computeUpY(camera, vp, screenY);
double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z;
Vec3 hitPoint = new Vec3(up1x, up1y, zvalue);
if (correctDrag)
hitPoint = currentDragRotation.rotateInverseVector(hitPoint);
return rotation.rotateInverseVector(hitPoint);
}
@Nullable
public static Vec3 getVectorFromSphereOrPlane(Camera camera, Viewport vp, double x, double y, Quat cameraDifferenceRotation) {
Vec3 rotatedHitPoint = getVectorFromSphere(camera, vp, x, y, cameraDifferenceRotation, false);
if (rotatedHitPoint != null && rotatedHitPoint.z > 0.)
return rotatedHitPoint;
return getVectorFromPlane(camera, vp, x, y, cameraDifferenceRotation, false);
}
public static void zoomToFit(Camera camera) {
double size = 1;
if (Display.mode == Display.DisplayMode.Orthographic) {
size = ImageLayers.getLargestPhysicalHeight();
}
double newFOV = Camera.INITFOV;
if (size != 0)
newFOV = 2. * Math.atan2(0.5 * size, camera.getViewpoint().distance);
camera.setFOV(newFOV);
}
}
|
package org.linuxguy.MarketBot;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
public class FlowDockNotifier extends Notifier<Comment> implements ResultListener<Comment> {
private static final String FLOWDOCK_CHAT_API = "https://api.flowdock.com/v1/messages/chat/";
private static final String FLOWDOCK_INBOX_API = "https://api.flowdock.com/v1/messages/team_inbox/";
public enum FlowDockNotificationType {
CHAT,
INBOX
}
private String mAppName;
private String mFlowDockName;
private String mAPIToken;
private FlowDockNotificationType mNotificationType;
public FlowDockNotifier(String appName, String flowDockName, String apiToken, FlowDockNotificationType notificationType) {
mAppName = appName;
mFlowDockName = flowDockName;
mAPIToken = apiToken;
mNotificationType = notificationType;
}
@Override
public void onNewResult(Comment result) {
try {
String toPost = getJsonPayloadForComment(result);
if (!postCommentToFlowDock(toPost)) {
System.err.println("Failed to post payload");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean postCommentToFlowDock(String comment) {
final String assembledURL = String.format("%s%s", getURLForNotificationType(mNotificationType), mAPIToken);
HttpsURLConnection httpcon = null;
try {
URL url = new URL(assembledURL);
httpcon = (HttpsURLConnection) url.openConnection();
httpcon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpcon.setRequestMethod("POST");
httpcon.setDoOutput(true);
httpcon.connect();
byte[] outputBytes = comment.getBytes("UTF-8");
OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
os.write(outputBytes);
os.flush();
os.close();
return httpcon.getResponseCode() == 202;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if ( httpcon != null ) {
httpcon.disconnect();
}
}
}
private String getJsonPayloadForComment(Comment c) throws UnsupportedEncodingException {
final String tags = "#review";
final String flowdockChatJSONFormat =
"{\"content\" : \"%s\", \"external_user_name\" : \"%s\", \"tags\" : \"%s\" }";
final String flowdockInboxJSONFormat =
"{\"source\" : \"%s\", \"from_address\" : \"marketbot@linuxguy.org\", \"subject\" : \"%s Review\", \"content\" : \"%s\", \"tags\" : \"%s\" }";
String jsonPayload = null;
switch (mNotificationType) {
case CHAT:
jsonPayload = String.format(flowdockChatJSONFormat,
Utils.formatComment(mAppName, c),
mFlowDockName,
tags);
break;
case INBOX:
jsonPayload = String.format(flowdockInboxJSONFormat,
mFlowDockName,
mAppName,
Utils.formatComment(mAppName, c),
tags);
break;
}
return jsonPayload;
}
private String getURLForNotificationType(FlowDockNotificationType notificationType) {
String apiURL = null;
switch (notificationType) {
case CHAT:
apiURL = FLOWDOCK_CHAT_API;
break;
case INBOX:
apiURL = FLOWDOCK_INBOX_API;
break;
default:
}
return apiURL;
}
}
|
// API class
package org.mozilla.javascript;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.mozilla.javascript.ScriptRuntime.StringIdOrIndex;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;
import org.mozilla.javascript.annotations.JSGetter;
import org.mozilla.javascript.annotations.JSSetter;
import org.mozilla.javascript.annotations.JSStaticFunction;
import org.mozilla.javascript.debug.DebuggableObject;
/**
* This is the default implementation of the Scriptable interface. This
* class provides convenient default behavior that makes it easier to
* define host objects.
* <p>
* Various properties and methods of JavaScript objects can be conveniently
* defined using methods of ScriptableObject.
* <p>
* Classes extending ScriptableObject must define the getClassName method.
*
* @see org.mozilla.javascript.Scriptable
* @author Norris Boyd
*/
public abstract class ScriptableObject implements Scriptable,
SymbolScriptable,
Serializable,
DebuggableObject,
ConstProperties
{
private static final long serialVersionUID = 2829861078851942586L;
/**
* The empty property attribute.
*
* Used by getAttributes() and setAttributes().
*
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int EMPTY = 0x00;
/**
* Property attribute indicating assignment to this property is ignored.
*
* @see org.mozilla.javascript.ScriptableObject
* #put(String, Scriptable, Object)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int READONLY = 0x01;
/**
* Property attribute indicating property is not enumerated.
*
* Only enumerated properties will be returned by getIds().
*
* @see org.mozilla.javascript.ScriptableObject#getIds()
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int DONTENUM = 0x02;
/**
* Property attribute indicating property cannot be deleted.
*
* @see org.mozilla.javascript.ScriptableObject#delete(String)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int PERMANENT = 0x04;
/**
* Property attribute indicating that this is a const property that has not
* been assigned yet. The first 'const' assignment to the property will
* clear this bit.
*/
public static final int UNINITIALIZED_CONST = 0x08;
public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST;
/**
* The prototype of this object.
*/
private Scriptable prototypeObject;
/**
* The parent scope of this object.
*/
private Scriptable parentScopeObject;
/**
* This holds all the slots. It may or may not be thread-safe, and may expand itself to
* a different data structure depending on the size of the object.
*/
private transient SlotMapContainer slotMap;
// Where external array data is stored.
private transient ExternalArrayData externalData;
private volatile Map<Object,Object> associatedValues;
enum SlotAccess {
QUERY, MODIFY, MODIFY_CONST, MODIFY_GETTER_SETTER, CONVERT_ACCESSOR_TO_DATA
}
private boolean isExtensible = true;
private boolean isSealed = false;
private static final Method GET_ARRAY_LENGTH;
static {
try {
GET_ARRAY_LENGTH = ScriptableObject.class.getMethod("getExternalArrayLength");
} catch (NoSuchMethodException nsm) {
throw new RuntimeException(nsm);
}
}
/**
* This is the object that is stored in the SlotMap. For historical reasons it remains
* inside this class. SlotMap references a number of members of this class directly.
*/
static class Slot implements Serializable
{
private static final long serialVersionUID = -6090581677123995491L;
Object name; // This can change due to caching
int indexOrHash;
private short attributes;
Object value;
transient Slot next; // next in hash table bucket
transient Slot orderedNext; // next in linked list
Slot(Object name, int indexOrHash, int attributes)
{
this.name = name;
this.indexOrHash = indexOrHash;
this.attributes = (short)attributes;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (name != null) {
indexOrHash = name.hashCode();
}
}
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if ((attributes & READONLY) != 0) {
if (Context.getContext().isStrictMode()) {
throw ScriptRuntime.typeError1("msg.modify.readonly", name);
}
return true;
}
if (owner == start) {
this.value = value;
return true;
}
return false;
}
Object getValue(Scriptable start) {
return value;
}
int getAttributes()
{
return attributes;
}
synchronized void setAttributes(int value)
{
checkValidAttributes(value);
attributes = (short)value;
}
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
return buildDataDescriptor(scope, value, attributes);
}
}
protected static ScriptableObject buildDataDescriptor(Scriptable scope,
Object value,
int attributes) {
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("value", value, EMPTY);
desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY);
desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY);
return desc;
}
/**
* A GetterSlot is a specialication of a Slot for properties that are assigned functions
* via Object.defineProperty() and its friends instead of regular values.
*/
static final class GetterSlot extends Slot
{
private static final long serialVersionUID = -4900574849788797588L;
Object getter;
Object setter;
GetterSlot(Object name, int indexOrHash, int attributes)
{
super(name, indexOrHash, attributes);
}
@Override
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
int attr = getAttributes();
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("enumerable", (attr & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attr & PERMANENT) == 0, EMPTY);
if (getter == null && setter == null) {
desc.defineProperty("writable", (attr & READONLY) == 0, EMPTY);
}
String fName = name == null ? "f" : name.toString();
if (getter != null) {
if ( getter instanceof MemberBox ) {
desc.defineProperty("get", new FunctionObject(fName, ((MemberBox)getter).member(), scope), EMPTY);
} else if ( getter instanceof Member ) {
desc.defineProperty("get", new FunctionObject(fName, (Member)getter, scope), EMPTY);
} else {
desc.defineProperty("get", getter, EMPTY);
}
}
if (setter != null) {
if ( setter instanceof MemberBox ) {
desc.defineProperty("set", new FunctionObject(fName, ((MemberBox) setter).member(), scope), EMPTY);
} else if ( setter instanceof Member ) {
desc.defineProperty("set", new FunctionObject(fName, (Member) setter, scope), EMPTY);
} else {
desc.defineProperty("set", setter, EMPTY);
}
}
return desc;
}
@Override
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if (setter == null) {
if (getter != null) {
Context cx = Context.getContext();
if (cx.isStrictMode() ||
// Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2,
// we should throw a TypeError in this case.
cx.hasFeature(Context.FEATURE_STRICT_MODE)) {
String prop = "";
if (name != null) {
prop = "[" + start.getClassName() + "]." + name.toString();
}
throw ScriptRuntime.typeError2("msg.set.prop.no.setter", prop, Context.toString(value));
}
// Assignment to a property with only a getter defined. The
// assignment is ignored. See bug 478047.
return true;
}
} else {
Context cx = Context.getContext();
if (setter instanceof MemberBox) {
MemberBox nativeSetter = (MemberBox)setter;
Class<?> pTypes[] = nativeSetter.argTypes;
// XXX: cache tag since it is already calculated in
// defineProperty ?
Class<?> valueType = pTypes[pTypes.length - 1];
int tag = FunctionObject.getTypeTag(valueType);
Object actualArg = FunctionObject.convertArg(cx, start,
value, tag);
Object setterThis;
Object[] args;
if (nativeSetter.delegateTo == null) {
setterThis = start;
args = new Object[] { actualArg };
} else {
setterThis = nativeSetter.delegateTo;
args = new Object[] { start, actualArg };
}
nativeSetter.invoke(setterThis, args);
} else if (setter instanceof Function) {
Function f = (Function)setter;
f.call(cx, f.getParentScope(), start,
new Object[] { value });
}
return true;
}
return super.setValue(value, owner, start);
}
@Override
Object getValue(Scriptable start) {
if (getter != null) {
if (getter instanceof MemberBox) {
MemberBox nativeGetter = (MemberBox)getter;
Object getterThis;
Object[] args;
if (nativeGetter.delegateTo == null) {
getterThis = start;
args = ScriptRuntime.emptyArgs;
} else {
getterThis = nativeGetter.delegateTo;
args = new Object[] { start };
}
return nativeGetter.invoke(getterThis, args);
} else if (getter instanceof Function) {
Function f = (Function)getter;
Context cx = Context.getContext();
return f.call(cx, f.getParentScope(), start,
ScriptRuntime.emptyArgs);
}
}
Object val = this.value;
if (val instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor)val;
try {
initializer.init();
} finally {
this.value = val = initializer.getValue();
}
}
return val;
}
}
static void checkValidAttributes(int attributes)
{
final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST;
if ((attributes & ~mask) != 0) {
throw new IllegalArgumentException(String.valueOf(attributes));
}
}
private SlotMapContainer createSlotMap(int initialSize)
{
Context cx = Context.getCurrentContext();
if ((cx != null) && cx.hasFeature(Context.FEATURE_THREAD_SAFE_OBJECTS)) {
return new ThreadSafeSlotMapContainer(initialSize);
}
return new SlotMapContainer(initialSize);
}
public ScriptableObject()
{
slotMap = createSlotMap(0);
}
public ScriptableObject(Scriptable scope, Scriptable prototype)
{
if (scope == null)
throw new IllegalArgumentException();
parentScopeObject = scope;
prototypeObject = prototype;
slotMap = createSlotMap(0);
}
/**
* Gets the value that will be returned by calling the typeof operator on this object.
* @return default is "object" unless {@link #avoidObjectDetection()} is <code>true</code> in which
* case it returns "undefined"
*/
public String getTypeOf() {
return avoidObjectDetection() ? "undefined" : "object";
}
/**
* Return the name of the class.
*
* This is typically the same name as the constructor.
* Classes extending ScriptableObject must implement this abstract
* method.
*/
@Override
public abstract String getClassName();
/**
* Returns true if the named property is defined.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
@Override
public boolean has(String name, Scriptable start)
{
return null != slotMap.query(name, 0);
}
/**
* Returns true if the property index is defined.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
@Override
public boolean has(int index, Scriptable start)
{
if (externalData != null) {
return (index < externalData.getArrayLength());
}
return null != slotMap.query(null, index);
}
/**
* A version of "has" that supports symbols.
*/
@Override
public boolean has(Symbol key, Scriptable start)
{
return null != slotMap.query(key, 0);
}
/**
* Returns the value of the named property or NOT_FOUND.
*
* If the property was created using defineProperty, the
* appropriate getter method is called.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
@Override
public Object get(String name, Scriptable start)
{
Slot slot = slotMap.query(name, 0);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Returns the value of the indexed property or NOT_FOUND.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
@Override
public Object get(int index, Scriptable start)
{
if (externalData != null) {
if (index < externalData.getArrayLength()) {
return externalData.getArrayElement(index);
}
return Scriptable.NOT_FOUND;
}
Slot slot = slotMap.query(null, index);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Another version of Get that supports Symbol keyed properties.
*/
@Override
public Object get(Symbol key, Scriptable start)
{
Slot slot = slotMap.query(key, 0);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Sets the value of the named property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
@Override
public void put(String name, Scriptable start, Object value)
{
if (putImpl(name, 0, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(name, start, value);
}
/**
* Sets the value of the indexed property, creating it if need be.
*
* @param index the numeric index for the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
@Override
public void put(int index, Scriptable start, Object value)
{
if (externalData != null) {
if (index < externalData.getArrayLength()) {
externalData.setArrayElement(index, value);
} else {
throw new JavaScriptException(
ScriptRuntime.newNativeError(Context.getCurrentContext(), this,
TopLevel.NativeErrors.RangeError,
new Object[] { "External array index out of bounds " }),
null, 0);
}
return;
}
if (putImpl(null, index, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(index, start, value);
}
/**
* Implementation of put required by SymbolScriptable objects.
*/
@Override
public void put(Symbol key, Scriptable start, Object value)
{
if (putImpl(key, 0, start, value))
return;
if (start == this) throw Kit.codeBug();
ensureSymbolScriptable(start).put(key, start, value);
}
/**
* Removes a named property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param name the name of the property
*/
@Override
public void delete(String name)
{
checkNotSealed(name, 0);
slotMap.remove(name, 0);
}
/**
* Removes the indexed property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param index the numeric index for the property
*/
@Override
public void delete(int index)
{
checkNotSealed(null, index);
slotMap.remove(null, index);
}
/**
* Removes an object like the others, but using a Symbol as the key.
*/
@Override
public void delete(Symbol key)
{
checkNotSealed(key, 0);
slotMap.remove(key, 0);
}
/**
* Sets the value of the named const property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
@Override
public void putConst(String name, Scriptable start, Object value)
{
if (putConstImpl(name, 0, start, value, READONLY))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).putConst(name, start, value);
else
start.put(name, start, value);
}
@Override
public void defineConst(String name, Scriptable start)
{
if (putConstImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).defineConst(name, start);
}
/**
* Returns true if the named property is defined as a const on this object.
* @param name
* @return true if the named property is defined as a const, false
* otherwise.
*/
@Override
public boolean isConst(String name)
{
Slot slot = slotMap.query(name, 0);
if (slot == null) {
return false;
}
return (slot.getAttributes() & (PERMANENT|READONLY)) ==
(PERMANENT|READONLY);
}
/**
* @deprecated Use {@link #getAttributes(String name)}. The engine always
* ignored the start argument.
*/
@Deprecated
public final int getAttributes(String name, Scriptable start)
{
return getAttributes(name);
}
/**
* @deprecated Use {@link #getAttributes(int index)}. The engine always
* ignored the start argument.
*/
@Deprecated
public final int getAttributes(int index, Scriptable start)
{
return getAttributes(index);
}
/**
* @deprecated Use {@link #setAttributes(String name, int attributes)}.
* The engine always ignored the start argument.
*/
@Deprecated
public final void setAttributes(String name, Scriptable start,
int attributes)
{
setAttributes(name, attributes);
}
/**
* @deprecated Use {@link #setAttributes(int index, int attributes)}.
* The engine always ignored the start argument.
*/
@Deprecated
public void setAttributes(int index, Scriptable start,
int attributes)
{
setAttributes(index, attributes);
}
/**
* Get the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* @param name the identifier for the property
* @return the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(String name)
{
return findAttributeSlot(name, 0, SlotAccess.QUERY).getAttributes();
}
/**
* Get the attributes of an indexed property.
*
* @param index the numeric index for the property
* @exception EvaluatorException if the named property is not found
* is not found
* @return the bitset of attributes
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(int index)
{
return findAttributeSlot(null, index, SlotAccess.QUERY).getAttributes();
}
public int getAttributes(Symbol sym)
{
return findAttributeSlot(sym, SlotAccess.QUERY).getAttributes();
}
/**
* Set the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* The possible attributes are READONLY, DONTENUM,
* and PERMANENT. Combinations of attributes
* are expressed by the bitwise OR of attributes.
* EMPTY is the state of no attributes set. Any unused
* bits are reserved for future use.
*
* @param name the name of the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(String name, int attributes)
{
checkNotSealed(name, 0);
findAttributeSlot(name, 0, SlotAccess.MODIFY).setAttributes(attributes);
}
/**
* Set the attributes of an indexed property.
*
* @param index the numeric index for the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(int index, int attributes)
{
checkNotSealed(null, index);
findAttributeSlot(null, index, SlotAccess.MODIFY).setAttributes(attributes);
}
/**
* Set attributes of a Symbol-keyed property.
*/
public void setAttributes(Symbol key, int attributes)
{
checkNotSealed(key, 0);
findAttributeSlot(key, SlotAccess.MODIFY).setAttributes(attributes);
}
/**
* XXX: write docs.
*/
public void setGetterOrSetter(String name, int index,
Callable getterOrSetter, boolean isSetter)
{
setGetterOrSetter(name, index, getterOrSetter, isSetter, false);
}
private void setGetterOrSetter(String name, int index, Callable getterOrSetter,
boolean isSetter, boolean force)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
if (!force) {
checkNotSealed(name, index);
}
final GetterSlot gslot;
if (isExtensible()) {
gslot = (GetterSlot)slotMap.get(name, index, SlotAccess.MODIFY_GETTER_SETTER);
} else {
Slot slot = slotMap.query(name, index);
if (!(slot instanceof GetterSlot))
return;
gslot = (GetterSlot) slot;
}
if (!force) {
int attributes = gslot.getAttributes();
if ((attributes & READONLY) != 0) {
throw Context.reportRuntimeError1("msg.modify.readonly", name);
}
}
if (isSetter) {
gslot.setter = getterOrSetter;
} else {
gslot.getter = getterOrSetter;
}
gslot.value = Undefined.instance;
}
public Object getGetterOrSetter(String name, int index, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
Slot slot = slotMap.query(name, index);
if (slot == null)
return null;
if (slot instanceof GetterSlot) {
GetterSlot gslot = (GetterSlot)slot;
Object result = isSetter ? gslot.setter : gslot.getter;
return result != null ? result : Undefined.instance;
}
return Undefined.instance;
}
/**
* Returns whether a property is a getter or a setter
* @param name property name
* @param index property index
* @param setter true to check for a setter, false for a getter
* @return whether the property is a getter or a setter
*/
protected boolean isGetterOrSetter(String name, int index, boolean setter) {
Slot slot = slotMap.query(name, index);
if (slot instanceof GetterSlot) {
if (setter && ((GetterSlot)slot).setter != null) return true;
if (!setter && ((GetterSlot)slot).getter != null) return true;
}
return false;
}
void addLazilyInitializedValue(String name, int index,
LazilyLoadedCtor init, int attributes)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
checkNotSealed(name, index);
GetterSlot gslot = (GetterSlot)slotMap.get(name, index,
SlotAccess.MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = null;
gslot.setter = null;
gslot.value = init;
}
/**
* Attach the specified object to this object, and delegate all indexed property lookups to it. In other words,
* if the object has 3 elements, then an attempt to look up or modify "[0]", "[1]", or "[2]" will be delegated
* to this object. Additional indexed properties outside the range specified, and additional non-indexed
* properties, may still be added. The object specified must implement the ExternalArrayData interface.
*
* @param array the List to use for delegated property access. Set this to null to revert back to regular
* property access.
* @since 1.7.6
*/
public void setExternalArrayData(ExternalArrayData array)
{
externalData = array;
if (array == null) {
delete("length");
} else {
// Define "length" to return whatever length the List gives us.
defineProperty("length", null,
GET_ARRAY_LENGTH, null, READONLY | DONTENUM);
}
}
/**
* Return the array that was previously set by the call to "setExternalArrayData".
*
* @return the array, or null if it was never set
* @since 1.7.6
*/
public ExternalArrayData getExternalArrayData()
{
return externalData;
}
/**
* This is a function used by setExternalArrayData to dynamically get the "length" property value.
*/
public Object getExternalArrayLength()
{
return (externalData == null ? 0 : externalData.getArrayLength());
}
/**
* Returns the prototype of the object.
*/
@Override
public Scriptable getPrototype()
{
return prototypeObject;
}
/**
* Sets the prototype of the object.
*/
@Override
public void setPrototype(Scriptable m)
{
if (!isExtensible()
&& Context.getContext().getLanguageVersion() >= Context.VERSION_1_8) {
throw ScriptRuntime.typeError0("msg.not.extensible");
}
prototypeObject = m;
}
/**
* Returns the parent (enclosing) scope of the object.
*/
@Override
public Scriptable getParentScope()
{
return parentScopeObject;
}
/**
* Sets the parent (enclosing) scope of the object.
*/
@Override
public void setParentScope(Scriptable m)
{
parentScopeObject = m;
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>Any properties with the attribute DONTENUM are not listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
@Override
public Object[] getIds() {
return getIds(false, false);
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>All properties, even those with attribute DONTENUM, are listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
@Override
public Object[] getAllIds() {
return getIds(true, false);
}
/**
* Implements the [[DefaultValue]] internal method.
*
* <p>Note that the toPrimitive conversion is a no-op for
* every type other than Object, for which [[DefaultValue]]
* is called. See ECMA 9.1.<p>
*
* A <code>hint</code> of null means "no hint".
*
* @param typeHint the type hint
* @return the default value for the object
*
* See ECMA 8.6.2.6.
*/
@Override
public Object getDefaultValue(Class<?> typeHint)
{
return getDefaultValue(this, typeHint);
}
public static Object getDefaultValue(Scriptable object, Class<?> typeHint)
{
Context cx = null;
for (int i=0; i < 2; i++) {
boolean tryToString;
if (typeHint == ScriptRuntime.StringClass) {
tryToString = (i == 0);
} else {
tryToString = (i == 1);
}
String methodName;
if (tryToString) {
methodName = "toString";
} else {
methodName = "valueOf";
}
Object v = getProperty(object, methodName);
if (!(v instanceof Function))
continue;
Function fun = (Function) v;
if (cx == null) {
cx = Context.getContext();
}
v = fun.call(cx, fun.getParentScope(), object, ScriptRuntime.emptyArgs);
if (v != null) {
if (!(v instanceof Scriptable)) {
return v;
}
if (typeHint == ScriptRuntime.ScriptableClass
|| typeHint == ScriptRuntime.FunctionClass)
{
return v;
}
if (tryToString && v instanceof Wrapper) {
// Let a wrapped java.lang.String pass for a primitive
// string.
Object u = ((Wrapper)v).unwrap();
if (u instanceof String)
return u;
}
}
}
// fall through to error
String arg = (typeHint == null) ? "undefined" : typeHint.getName();
throw ScriptRuntime.typeError1("msg.default.value", arg);
}
/**
* Implements the instanceof operator.
*
* <p>This operator has been proposed to ECMA.
*
* @param instance The value that appeared on the LHS of the instanceof
* operator
* @return true if "this" appears in value's prototype chain
*
*/
@Override
public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing. This will be overridden in NativeFunction and non-JS
// objects.
return ScriptRuntime.jsDelegatesTo(instance, this);
}
public boolean avoidObjectDetection() {
return false;
}
/**
* Custom <tt>==</tt> operator.
* Must return {@link Scriptable#NOT_FOUND} if this object does not
* have custom equality operator for the given value,
* <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>,
* <tt>Boolean.FALSE</tt> if this object is not equivalent to
* <tt>value</tt>.
* <p>
* The default implementation returns Boolean.TRUE
* if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise.
* It indicates that by default custom equality is available only if
* <tt>value</tt> is <tt>this</tt> in which case true is returned.
*/
protected Object equivalentValues(Object value)
{
return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND;
}
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, false, false);
}
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz, boolean sealed)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, sealed, false);
}
public static <T extends Scriptable> String defineClass(
Scriptable scope, Class<T> clazz, boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
BaseFunction ctor = buildClassCtor(scope, clazz, sealed,
mapInheritance);
if (ctor == null)
return null;
String name = ctor.getClassPrototype().getClassName();
defineProperty(scope, name, ctor, ScriptableObject.DONTENUM);
return name;
}
static <T extends Scriptable> BaseFunction buildClassCtor(
Scriptable scope, Class<T> clazz,
boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < methods.length; i++) {
Method method = methods[i];
if (!method.getName().equals("init"))
continue;
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ContextClass &&
parmTypes[1] == ScriptRuntime.ScriptableClass &&
parmTypes[2] == Boolean.TYPE &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { Context.getContext(), scope,
sealed ? Boolean.TRUE : Boolean.FALSE };
method.invoke(null, args);
return null;
}
if (parmTypes.length == 1 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { scope };
method.invoke(null, args);
return null;
}
}
// If we got here, there isn't an "init" method with the right
// parameter types.
Constructor<?>[] ctors = clazz.getConstructors();
Constructor<?> protoCtor = null;
for (int i=0; i < ctors.length; i++) {
if (ctors[i].getParameterTypes().length == 0) {
protoCtor = ctors[i];
break;
}
}
if (protoCtor == null) {
throw Context.reportRuntimeError1(
"msg.zero.arg.ctor", clazz.getName());
}
Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs);
String className = proto.getClassName();
// check for possible redefinition
Object existing = getProperty(getTopLevelScope(scope), className);
if (existing instanceof BaseFunction) {
Object existingProto = ((BaseFunction)existing).getPrototypeProperty();
if (existingProto != null && clazz.equals(existingProto.getClass())) {
return (BaseFunction)existing;
}
}
// Set the prototype's prototype, trying to map Java inheritance to JS
// prototype-based inheritance if requested to do so.
Scriptable superProto = null;
if (mapInheritance) {
Class<? super T> superClass = clazz.getSuperclass();
if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) &&
!Modifier.isAbstract(superClass.getModifiers()))
{
Class<? extends Scriptable> superScriptable =
extendsScriptable(superClass);
String name = ScriptableObject.defineClass(scope,
superScriptable, sealed, mapInheritance);
if (name != null) {
superProto = ScriptableObject.getClassPrototype(scope, name);
}
}
}
if (superProto == null) {
superProto = ScriptableObject.getObjectPrototype(scope);
}
proto.setPrototype(superProto);
// Find out whether there are any methods that begin with
// "js". If so, then only methods that begin with special
// prefixes will be defined as JavaScript entities.
final String functionPrefix = "jsFunction_";
final String staticFunctionPrefix = "jsStaticFunction_";
final String getterPrefix = "jsGet_";
final String setterPrefix = "jsSet_";
final String ctorName = "jsConstructor";
Member ctorMember = findAnnotatedMember(methods, JSConstructor.class);
if (ctorMember == null) {
ctorMember = findAnnotatedMember(ctors, JSConstructor.class);
}
if (ctorMember == null) {
ctorMember = FunctionObject.findSingleMethod(methods, ctorName);
}
if (ctorMember == null) {
if (ctors.length == 1) {
ctorMember = ctors[0];
} else if (ctors.length == 2) {
if (ctors[0].getParameterTypes().length == 0)
ctorMember = ctors[1];
else if (ctors[1].getParameterTypes().length == 0)
ctorMember = ctors[0];
}
if (ctorMember == null) {
throw Context.reportRuntimeError1(
"msg.ctor.multiple.parms", clazz.getName());
}
}
FunctionObject ctor = new FunctionObject(className, ctorMember, scope);
if (ctor.isVarArgsMethod()) {
throw Context.reportRuntimeError1
("msg.varargs.ctor", ctorMember.getName());
}
ctor.initAsConstructor(scope, proto);
Method finishInit = null;
HashSet<String> staticNames = new HashSet<String>(),
instanceNames = new HashSet<String>();
for (Method method : methods) {
if (method == ctorMember) {
continue;
}
String name = method.getName();
if (name.equals("finishInit")) {
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
parmTypes[1] == FunctionObject.class &&
parmTypes[2] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
finishInit = method;
continue;
}
}
// ignore any compiler generated methods.
if (name.indexOf('$') != -1)
continue;
if (name.equals(ctorName))
continue;
Annotation annotation = null;
String prefix = null;
if (method.isAnnotationPresent(JSFunction.class)) {
annotation = method.getAnnotation(JSFunction.class);
} else if (method.isAnnotationPresent(JSStaticFunction.class)) {
annotation = method.getAnnotation(JSStaticFunction.class);
} else if (method.isAnnotationPresent(JSGetter.class)) {
annotation = method.getAnnotation(JSGetter.class);
} else if (method.isAnnotationPresent(JSSetter.class)) {
continue;
}
if (annotation == null) {
if (name.startsWith(functionPrefix)) {
prefix = functionPrefix;
} else if (name.startsWith(staticFunctionPrefix)) {
prefix = staticFunctionPrefix;
} else if (name.startsWith(getterPrefix)) {
prefix = getterPrefix;
} else {
// note that setterPrefix is among the unhandled names here -
// we deal with that when we see the getter
continue;
}
}
boolean isStatic = annotation instanceof JSStaticFunction
|| prefix == staticFunctionPrefix;
HashSet<String> names = isStatic ? staticNames : instanceNames;
String propName = getPropertyName(name, prefix, annotation);
if (names.contains(propName)) {
throw Context.reportRuntimeError2("duplicate.defineClass.name",
name, propName);
}
names.add(propName);
name = propName;
if (annotation instanceof JSGetter || prefix == getterPrefix) {
if (!(proto instanceof ScriptableObject)) {
throw Context.reportRuntimeError2(
"msg.extend.scriptable",
proto.getClass().toString(), name);
}
Method setter = findSetterMethod(methods, name, setterPrefix);
int attr = ScriptableObject.PERMANENT |
ScriptableObject.DONTENUM |
(setter != null ? 0
: ScriptableObject.READONLY);
((ScriptableObject) proto).defineProperty(name, null,
method, setter,
attr);
continue;
}
if (isStatic && !Modifier.isStatic(method.getModifiers())) {
throw Context.reportRuntimeError(
"jsStaticFunction must be used with static method.");
}
FunctionObject f = new FunctionObject(name, method, proto);
if (f.isVarArgsConstructor()) {
throw Context.reportRuntimeError1
("msg.varargs.fun", ctorMember.getName());
}
defineProperty(isStatic ? ctor : proto, name, f, DONTENUM);
if (sealed) {
f.sealObject();
}
}
// Call user code to complete initialization if necessary.
if (finishInit != null) {
Object[] finishArgs = { scope, ctor, proto };
finishInit.invoke(null, finishArgs);
}
// Seal the object if necessary.
if (sealed) {
ctor.sealObject();
if (proto instanceof ScriptableObject) {
((ScriptableObject) proto).sealObject();
}
}
return ctor;
}
private static Member findAnnotatedMember(AccessibleObject[] members,
Class<? extends Annotation> annotation) {
for (AccessibleObject member : members) {
if (member.isAnnotationPresent(annotation)) {
return (Member) member;
}
}
return null;
}
private static Method findSetterMethod(Method[] methods,
String name,
String prefix) {
String newStyleName = "set"
+ Character.toUpperCase(name.charAt(0))
+ name.substring(1);
for (Method method : methods) {
JSSetter annotation = method.getAnnotation(JSSetter.class);
if (annotation != null) {
if (name.equals(annotation.value()) ||
("".equals(annotation.value()) && newStyleName.equals(method.getName()))) {
return method;
}
}
}
String oldStyleName = prefix + name;
for (Method method : methods) {
if (oldStyleName.equals(method.getName())) {
return method;
}
}
return null;
}
private static String getPropertyName(String methodName,
String prefix,
Annotation annotation) {
if (prefix != null) {
return methodName.substring(prefix.length());
}
String propName = null;
if (annotation instanceof JSGetter) {
propName = ((JSGetter) annotation).value();
if (propName == null || propName.length() == 0) {
if (methodName.length() > 3 && methodName.startsWith("get")) {
propName = methodName.substring(3);
if (Character.isUpperCase(propName.charAt(0))) {
if (propName.length() == 1) {
propName = propName.toLowerCase();
} else if (!Character.isUpperCase(propName.charAt(1))){
propName = Character.toLowerCase(propName.charAt(0))
+ propName.substring(1);
}
}
}
}
} else if (annotation instanceof JSFunction) {
propName = ((JSFunction) annotation).value();
} else if (annotation instanceof JSStaticFunction) {
propName = ((JSStaticFunction) annotation).value();
}
if (propName == null || propName.length() == 0) {
propName = methodName;
}
return propName;
}
@SuppressWarnings({"unchecked"})
private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c)
{
if (ScriptRuntime.ScriptableClass.isAssignableFrom(c))
return (Class<T>) c;
return null;
}
/**
* Define a JavaScript property.
*
* Creates the property with an initial value and sets its attributes.
*
* @param propertyName the name of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Object value,
int attributes)
{
checkNotSealed(propertyName, 0);
put(propertyName, this, value);
setAttributes(propertyName, attributes);
}
/**
* A version of defineProperty that uses a Symbol key.
* @param key symbol of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
*/
public void defineProperty(Symbol key, Object value,
int attributes)
{
checkNotSealed(key, 0);
put(key, this, value);
setAttributes(key, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
* @param destination ScriptableObject to define the property on
* @param propertyName the name of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
*/
public static void defineProperty(Scriptable destination,
String propertyName, Object value,
int attributes)
{
if (!(destination instanceof ScriptableObject)) {
destination.put(propertyName, destination, value);
return;
}
ScriptableObject so = (ScriptableObject)destination;
so.defineProperty(propertyName, value, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
* @param destination ScriptableObject to define the property on
* @param propertyName the name of the property to define.
*/
public static void defineConstProperty(Scriptable destination,
String propertyName)
{
if (destination instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)destination;
cp.defineConst(propertyName, destination);
} else
defineProperty(destination, propertyName, Undefined.instance, CONST);
}
/**
* Define a JavaScript property with getter and setter side effects.
*
* If the setter is not found, the attribute READONLY is added to
* the given attributes. <p>
*
* The getter must be a method with zero parameters, and the setter, if
* found, must be a method with one parameter.<p>
*
* @param propertyName the name of the property to define. This name
* also affects the name of the setter and getter
* to search for. If the propertyId is "foo", then
* <code>clazz</code> will be searched for "getFoo"
* and "setFoo" methods.
* @param clazz the Java class to search for the getter and setter
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Class<?> clazz,
int attributes)
{
int length = propertyName.length();
if (length == 0) throw new IllegalArgumentException();
char[] buf = new char[3 + length];
propertyName.getChars(0, length, buf, 3);
buf[3] = Character.toUpperCase(buf[3]);
buf[0] = 'g';
buf[1] = 'e';
buf[2] = 't';
String getterName = new String(buf);
buf[0] = 's';
String setterName = new String(buf);
Method[] methods = FunctionObject.getMethodList(clazz);
Method getter = FunctionObject.findSingleMethod(methods, getterName);
Method setter = FunctionObject.findSingleMethod(methods, setterName);
if (setter == null)
attributes |= ScriptableObject.READONLY;
defineProperty(propertyName, null, getter,
setter == null ? null : setter, attributes);
}
/**
* Define a JavaScript property.
*
* Use this method only if you wish to define getters and setters for
* a given property in a ScriptableObject. To create a property without
* special getter or setter side effects, use
* <code>defineProperty(String,int)</code>.
*
* If <code>setter</code> is null, the attribute READONLY is added to
* the given attributes.<p>
*
* Several forms of getters or setters are allowed. In all cases the
* type of the value parameter can be any one of the following types:
* Object, String, boolean, Scriptable, byte, short, int, long, float,
* or double. The runtime will perform appropriate conversions based
* upon the type of the parameter (see description in FunctionObject).
* The first forms are nonstatic methods of the class referred to
* by 'this':
* <pre>
* Object getFoo();
* void setFoo(SomeType value);</pre>
* Next are static methods that may be of any class; the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* static Object getFoo(Scriptable obj);
* static void setFoo(Scriptable obj, SomeType value);</pre>
* Finally, it is possible to delegate to another object entirely using
* the <code>delegateTo</code> parameter. In this case the methods are
* nonstatic methods of the class delegated to, and the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* Object getFoo(Scriptable obj);
* void setFoo(Scriptable obj, SomeType value);</pre>
*
* @param propertyName the name of the property to define.
* @param delegateTo an object to call the getter and setter methods on,
* or null, depending on the form used above.
* @param getter the method to invoke to get the value of the property
* @param setter the method to invoke to set the value of the property
* @param attributes the attributes of the JavaScript property
*/
public void defineProperty(String propertyName, Object delegateTo,
Method getter, Method setter, int attributes)
{
MemberBox getterBox = null;
if (getter != null) {
getterBox = new MemberBox(getter);
boolean delegatedForm;
if (!Modifier.isStatic(getter.getModifiers())) {
delegatedForm = (delegateTo != null);
getterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static getter but store
// non-null delegateTo indicator.
getterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = getter.getParameterTypes();
if (parmTypes.length == 0) {
if (delegatedForm) {
errorId = "msg.obj.getter.parms";
}
} else if (parmTypes.length == 1) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.bad.getter.parms";
} else if (!delegatedForm) {
errorId = "msg.bad.getter.parms";
}
} else {
errorId = "msg.bad.getter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, getter.toString());
}
}
MemberBox setterBox = null;
if (setter != null) {
if (setter.getReturnType() != Void.TYPE)
throw Context.reportRuntimeError1("msg.setter.return",
setter.toString());
setterBox = new MemberBox(setter);
boolean delegatedForm;
if (!Modifier.isStatic(setter.getModifiers())) {
delegatedForm = (delegateTo != null);
setterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static setter but store
// non-null delegateTo indicator.
setterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = setter.getParameterTypes();
if (parmTypes.length == 1) {
if (delegatedForm) {
errorId = "msg.setter2.expected";
}
} else if (parmTypes.length == 2) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.setter2.parms";
} else if (!delegatedForm) {
errorId = "msg.setter1.parms";
}
} else {
errorId = "msg.setter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, setter.toString());
}
}
GetterSlot gslot = (GetterSlot)slotMap.get(propertyName, 0,
SlotAccess.MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = getterBox;
gslot.setter = setterBox;
}
/**
* Defines one or more properties on this object.
*
* @param cx the current Context
* @param props a map of property ids to property descriptors
*/
public void defineOwnProperties(Context cx, ScriptableObject props) {
Object[] ids = props.getIds(false, true);
ScriptableObject[] descs = new ScriptableObject[ids.length];
for (int i = 0, len = ids.length; i < len; ++i) {
Object descObj = ScriptRuntime.getObjectElem(props, ids[i], cx);
ScriptableObject desc = ensureScriptableObject(descObj);
checkPropertyDefinition(desc);
descs[i] = desc;
}
for (int i = 0, len = ids.length; i < len; ++i) {
defineOwnProperty(cx, ids[i], descs[i]);
}
}
/**
* Defines a property on an object.
*
* @param cx the current Context
* @param id the name/index of the property
* @param desc the new property descriptor, as described in 8.6.1
*/
public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
checkPropertyDefinition(desc);
defineOwnProperty(cx, id, desc, true);
}
/**
* Defines a property on an object.
*
* Based on [[DefineOwnProperty]] from 8.12.10 of the spec.
*
* @param cx the current Context
* @param id the name/index of the property
* @param desc the new property descriptor, as described in 8.6.1
* @param checkValid whether to perform validity checks
*/
protected void defineOwnProperty(Context cx, Object id, ScriptableObject desc,
boolean checkValid) {
Slot slot = getSlot(cx, id, SlotAccess.QUERY);
boolean isNew = slot == null;
if (checkValid) {
ScriptableObject current = slot == null ?
null : slot.getPropertyDescriptor(cx, this);
checkPropertyChange(id, current, desc);
}
boolean isAccessor = isAccessorDescriptor(desc);
final int attributes;
if (slot == null) { // new slot
slot = getSlot(cx, id, isAccessor ? SlotAccess.MODIFY_GETTER_SETTER : SlotAccess.MODIFY);
attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc);
} else {
attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc);
}
if (isAccessor) {
if ( !(slot instanceof GetterSlot) ) {
slot = getSlot(cx, id, SlotAccess.MODIFY_GETTER_SETTER);
}
GetterSlot gslot = (GetterSlot) slot;
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND) {
gslot.getter = getter;
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND) {
gslot.setter = setter;
}
gslot.value = Undefined.instance;
gslot.setAttributes(attributes);
} else {
if (slot instanceof GetterSlot && isDataDescriptor(desc)) {
slot = getSlot(cx, id, SlotAccess.CONVERT_ACCESSOR_TO_DATA);
}
Object value = getProperty(desc, "value");
if (value != NOT_FOUND) {
slot.value = value;
} else if (isNew) {
slot.value = Undefined.instance;
}
slot.setAttributes(attributes);
}
}
protected void checkPropertyDefinition(ScriptableObject desc) {
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND && getter != Undefined.instance
&& !(getter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(getter);
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND && setter != Undefined.instance
&& !(setter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(setter);
}
if (isDataDescriptor(desc) && isAccessorDescriptor(desc)) {
throw ScriptRuntime.typeError0("msg.both.data.and.accessor.desc");
}
}
protected void checkPropertyChange(Object id, ScriptableObject current,
ScriptableObject desc) {
if (current == null) { // new property
if (!isExtensible()) throw ScriptRuntime.typeError0("msg.not.extensible");
} else {
if (isFalse(current.get("configurable", current))) {
if (isTrue(getProperty(desc, "configurable")))
throw ScriptRuntime.typeError1(
"msg.change.configurable.false.to.true", id);
if (isTrue(current.get("enumerable", current)) != isTrue(getProperty(desc, "enumerable")))
throw ScriptRuntime.typeError1(
"msg.change.enumerable.with.configurable.false", id);
boolean isData = isDataDescriptor(desc);
boolean isAccessor = isAccessorDescriptor(desc);
if (!isData && !isAccessor) {
// no further validation required for generic descriptor
} else if (isData && isDataDescriptor(current)) {
if (isFalse(current.get("writable", current))) {
if (isTrue(getProperty(desc, "writable")))
throw ScriptRuntime.typeError1(
"msg.change.writable.false.to.true.with.configurable.false", id);
if (!sameValue(getProperty(desc, "value"), current.get("value", current)))
throw ScriptRuntime.typeError1(
"msg.change.value.with.writable.false", id);
}
} else if (isAccessor && isAccessorDescriptor(current)) {
if (!sameValue(getProperty(desc, "set"), current.get("set", current)))
throw ScriptRuntime.typeError1(
"msg.change.setter.with.configurable.false", id);
if (!sameValue(getProperty(desc, "get"), current.get("get", current)))
throw ScriptRuntime.typeError1(
"msg.change.getter.with.configurable.false", id);
} else {
if (isDataDescriptor(current))
throw ScriptRuntime.typeError1(
"msg.change.property.data.to.accessor.with.configurable.false", id);
throw ScriptRuntime.typeError1(
"msg.change.property.accessor.to.data.with.configurable.false", id);
}
}
}
}
protected static boolean isTrue(Object value) {
return (value != NOT_FOUND) && ScriptRuntime.toBoolean(value);
}
protected static boolean isFalse(Object value) {
return !isTrue(value);
}
/**
* Implements SameValue as described in ES5 9.12, additionally checking
* if new value is defined.
* @param newValue the new value
* @param currentValue the current value
* @return true if values are the same as defined by ES5 9.12
*/
protected boolean sameValue(Object newValue, Object currentValue) {
if (newValue == NOT_FOUND) {
return true;
}
if (currentValue == NOT_FOUND) {
currentValue = Undefined.instance;
}
// Special rules for numbers: NaN is considered the same value,
// while zeroes with different signs are considered different.
if (currentValue instanceof Number && newValue instanceof Number) {
double d1 = ((Number)currentValue).doubleValue();
double d2 = ((Number)newValue).doubleValue();
if (Double.isNaN(d1) && Double.isNaN(d2)) {
return true;
}
if (d1 == 0.0 && Double.doubleToLongBits(d1) != Double.doubleToLongBits(d2)) {
return false;
}
}
return ScriptRuntime.shallowEq(currentValue, newValue);
}
protected int applyDescriptorToAttributeBitset(int attributes,
ScriptableObject desc)
{
Object enumerable = getProperty(desc, "enumerable");
if (enumerable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(enumerable)
? attributes & ~DONTENUM : attributes | DONTENUM;
}
Object writable = getProperty(desc, "writable");
if (writable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(writable)
? attributes & ~READONLY : attributes | READONLY;
}
Object configurable = getProperty(desc, "configurable");
if (configurable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(configurable)
? attributes & ~PERMANENT : attributes | PERMANENT;
}
return attributes;
}
/**
* Implements IsDataDescriptor as described in ES5 8.10.2
* @param desc a property descriptor
* @return true if this is a data descriptor.
*/
protected boolean isDataDescriptor(ScriptableObject desc) {
return hasProperty(desc, "value") || hasProperty(desc, "writable");
}
/**
* Implements IsAccessorDescriptor as described in ES5 8.10.1
* @param desc a property descriptor
* @return true if this is an accessor descriptor.
*/
protected boolean isAccessorDescriptor(ScriptableObject desc) {
return hasProperty(desc, "get") || hasProperty(desc, "set");
}
/**
* Implements IsGenericDescriptor as described in ES5 8.10.3
* @param desc a property descriptor
* @return true if this is a generic descriptor.
*/
protected boolean isGenericDescriptor(ScriptableObject desc) {
return !isDataDescriptor(desc) && !isAccessorDescriptor(desc);
}
protected static Scriptable ensureScriptable(Object arg) {
if ( !(arg instanceof Scriptable) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (Scriptable) arg;
}
protected static SymbolScriptable ensureSymbolScriptable(Object arg) {
if ( !(arg instanceof SymbolScriptable) )
throw ScriptRuntime.typeError1("msg.object.not.symbolscriptable", ScriptRuntime.typeof(arg));
return (SymbolScriptable) arg;
}
protected static ScriptableObject ensureScriptableObject(Object arg) {
if ( !(arg instanceof ScriptableObject) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (ScriptableObject) arg;
}
/**
* Search for names in a class, adding the resulting methods
* as properties.
*
* <p> Uses reflection to find the methods of the given names. Then
* FunctionObjects are constructed from the methods found, and
* are added to this object as properties with the given names.
*
* @param names the names of the Methods to add as function properties
* @param clazz the class to search for the Methods
* @param attributes the attributes of the new properties
* @see org.mozilla.javascript.FunctionObject
*/
public void defineFunctionProperties(String[] names, Class<?> clazz,
int attributes)
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < names.length; i++) {
String name = names[i];
Method m = FunctionObject.findSingleMethod(methods, name);
if (m == null) {
throw Context.reportRuntimeError2(
"msg.method.not.found", name, clazz.getName());
}
FunctionObject f = new FunctionObject(name, m, this);
defineProperty(name, f, attributes);
}
}
/**
* Get the Object.prototype property.
* See ECMA 15.2.4.
* @param scope an object in the scope chain
*/
public static Scriptable getObjectPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Object);
}
/**
* Get the Function.prototype property.
* See ECMA 15.3.4.
* @param scope an object in the scope chain
*/
public static Scriptable getFunctionPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Function);
}
public static Scriptable getArrayPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Array);
}
/**
* Get the prototype for the named class.
*
* For example, <code>getClassPrototype(s, "Date")</code> will first
* walk up the parent chain to find the outermost scope, then will
* search that scope for the Date constructor, and then will
* return Date.prototype. If any of the lookups fail, or
* the prototype is not a JavaScript object, then null will
* be returned.
*
* @param scope an object in the scope chain
* @param className the name of the constructor
* @return the prototype for the named class, or null if it
* cannot be found.
*/
public static Scriptable getClassPrototype(Scriptable scope,
String className)
{
scope = getTopLevelScope(scope);
Object ctor = getProperty(scope, className);
Object proto;
if (ctor instanceof BaseFunction) {
proto = ((BaseFunction)ctor).getPrototypeProperty();
} else if (ctor instanceof Scriptable) {
Scriptable ctorObj = (Scriptable)ctor;
proto = ctorObj.get("prototype", ctorObj);
} else {
return null;
}
if (proto instanceof Scriptable) {
return (Scriptable)proto;
}
return null;
}
/**
* Get the global scope.
*
* <p>Walks the parent scope chain to find an object with a null
* parent scope (the global object).
*
* @param obj a JavaScript object
* @return the corresponding global scope
*/
public static Scriptable getTopLevelScope(Scriptable obj)
{
for (;;) {
Scriptable parent = obj.getParentScope();
if (parent == null) {
return obj;
}
obj = parent;
}
}
public boolean isExtensible() {
return isExtensible;
}
public void preventExtensions() {
isExtensible = false;
}
/**
* Seal this object.
*
* It is an error to add properties to or delete properties from
* a sealed object. It is possible to change the value of an
* existing property. Once an object is sealed it may not be unsealed.
*
* @since 1.4R3
*/
public void sealObject() {
if (!isSealed) {
final long stamp = slotMap.readLock();
try {
for (Slot slot : slotMap) {
Object value = slot.value;
if (value instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor) value;
try {
initializer.init();
} finally {
slot.value = initializer.getValue();
}
}
}
isSealed = true;
} finally {
slotMap.unlockRead(stamp);
}
}
}
/**
* Return true if this object is sealed.
*
* @return true if sealed, false otherwise.
* @since 1.4R3
* @see #sealObject()
*/
public final boolean isSealed() {
return isSealed;
}
private void checkNotSealed(Object key, int index)
{
if (!isSealed())
return;
String str = (key != null) ? key.toString() : Integer.toString(index);
throw Context.reportRuntimeError1("msg.modify.sealed", str);
}
/**
* Gets a named property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, String name)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(name, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* This is a version of getProperty that works with Symbols.
*/
public static Object getProperty(Scriptable obj, Symbol key)
{
Scriptable start = obj;
Object result;
do {
result = ensureSymbolScriptable(obj).get(key, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets an indexed property from an object or any object in its prototype
* chain and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param s a JavaScript object
* @param index an integral index
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, int index, Class<T> type) {
Object val = getProperty(s, index);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Gets an indexed property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param obj a JavaScript object
* @param index an integral index
* @return the value of a property with index <code>index</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, int index)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(index, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets a named property from an object or any object in its prototype chain
* and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param s a JavaScript object
* @param name a property name
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, String name, Class<T> type) {
Object val = getProperty(s, name);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Returns whether a named property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, String name)
{
return null != getBase(obj, name);
}
/**
* If hasProperty(obj, name) would return true, then if the property that
* was found is compatible with the new property, this method just returns.
* If the property is not compatible, then an exception is thrown.
*
* A property redefinition is incompatible if the first definition was a
* const declaration or if this one is. They are compatible only if neither
* was const.
*/
public static void redefineProperty(Scriptable obj, String name,
boolean isConst)
{
Scriptable base = getBase(obj, name);
if (base == null)
return;
if (base instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)base;
if (cp.isConst(name))
throw ScriptRuntime.typeError1("msg.const.redecl", name);
}
if (isConst)
throw ScriptRuntime.typeError1("msg.var.redecl", name);
}
/**
* Returns whether an indexed property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property with index <code>index</code>.
* <p>
* @param obj a JavaScript object
* @param index a property index
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, int index)
{
return null != getBase(obj, index);
}
/**
* A version of hasProperty for properties with Symbol keys.
*/
public static boolean hasProperty(Scriptable obj, Symbol key)
{
return null != getBase(obj, key);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
base.put(name, obj, value);
}
/**
* This is a version of putProperty for Symbol keys.
*/
public static void putProperty(Scriptable obj, Symbol key, Object value)
{
Scriptable base = getBase(obj, key);
if (base == null)
base = obj;
ensureSymbolScriptable(base).put(key, obj, value);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
}
/**
* Puts an indexed property in an object or in an object in its prototype chain.
* <p>
* Searches for the indexed property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(int, Scriptable, Object)} on the prototype
* passing <code>obj</code> as the <code>start</code> argument. This allows
* the prototype to veto the property setting in case the prototype defines
* the property with [[ReadOnly]] attribute. If the property is not found,
* it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param index a property index
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, int index, Object value)
{
Scriptable base = getBase(obj, index);
if (base == null)
base = obj;
base.put(index, obj, value);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>name</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param name a property name
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, String name)
{
Scriptable base = getBase(obj, name);
if (base == null)
return true;
base.delete(name);
return !base.has(name, obj);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>index</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param index a property index
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, int index)
{
Scriptable base = getBase(obj, index);
if (base == null)
return true;
base.delete(index);
return !base.has(index, obj);
}
/**
* Returns an array of all ids from an object and its prototypes.
* <p>
* @param obj a JavaScript object
* @return an array of all ids from all object in the prototype chain.
* If a given id occurs multiple times in the prototype chain,
* it will occur only once in this list.
* @since 1.5R2
*/
public static Object[] getPropertyIds(Scriptable obj)
{
if (obj == null) {
return ScriptRuntime.emptyArgs;
}
Object[] result = obj.getIds();
ObjToIntMap map = null;
for (;;) {
obj = obj.getPrototype();
if (obj == null) {
break;
}
Object[] ids = obj.getIds();
if (ids.length == 0) {
continue;
}
if (map == null) {
if (result.length == 0) {
result = ids;
continue;
}
map = new ObjToIntMap(result.length + ids.length);
for (int i = 0; i != result.length; ++i) {
map.intern(result[i]);
}
result = null; // Allow to GC the result
}
for (int i = 0; i != ids.length; ++i) {
map.intern(ids[i]);
}
}
if (map != null) {
result = map.getKeys();
}
return result;
}
/**
* Call a method of an object.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*
* @see Context#getCurrentContext()
*/
public static Object callMethod(Scriptable obj, String methodName,
Object[] args)
{
return callMethod(null, obj, methodName, args);
}
/**
* Call a method of an object.
* @param cx the Context object associated with the current thread.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*/
public static Object callMethod(Context cx, Scriptable obj,
String methodName,
Object[] args)
{
Object funObj = getProperty(obj, methodName);
if (!(funObj instanceof Function)) {
throw ScriptRuntime.notFunctionError(obj, methodName);
}
Function fun = (Function)funObj;
// XXX: What should be the scope when calling funObj?
// The following favor scope stored in the object on the assumption
// that is more useful especially under dynamic scope setup.
// An alternative is to check for dynamic scope flag
// and use ScriptableObject.getTopLevelScope(fun) if the flag is not
// set. But that require access to Context and messy code
// so for now it is not checked.
Scriptable scope = ScriptableObject.getTopLevelScope(obj);
if (cx != null) {
return fun.call(cx, scope, obj, args);
}
return Context.call(null, fun, scope, obj, args);
}
private static Scriptable getBase(Scriptable obj, String name)
{
do {
if (obj.has(name, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
private static Scriptable getBase(Scriptable obj, int index)
{
do {
if (obj.has(index, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
private static Scriptable getBase(Scriptable obj, Symbol key)
{
do {
if (ensureSymbolScriptable(obj).has(key, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
/**
* Get arbitrary application-specific value associated with this object.
* @param key key object to select particular value.
* @see #associateValue(Object key, Object value)
*/
public final Object getAssociatedValue(Object key)
{
Map<Object,Object> h = associatedValues;
if (h == null)
return null;
return h.get(key);
}
/**
* Get arbitrary application-specific value associated with the top scope
* of the given scope.
* The method first calls {@link #getTopLevelScope(Scriptable scope)}
* and then searches the prototype chain of the top scope for the first
* object containing the associated value with the given key.
*
* @param scope the starting scope.
* @param key key object to select particular value.
* @see #getAssociatedValue(Object key)
*/
public static Object getTopScopeValue(Scriptable scope, Object key)
{
scope = ScriptableObject.getTopLevelScope(scope);
for (;;) {
if (scope instanceof ScriptableObject) {
ScriptableObject so = (ScriptableObject)scope;
Object value = so.getAssociatedValue(key);
if (value != null) {
return value;
}
}
scope = scope.getPrototype();
if (scope == null) {
return null;
}
}
}
/**
* Associate arbitrary application-specific value with this object.
* Value can only be associated with the given object and key only once.
* The method ignores any subsequent attempts to change the already
* associated value.
* <p> The associated values are not serialized.
* @param key key object to select particular value.
* @param value the value to associate
* @return the passed value if the method is called first time for the
* given key or old value for any subsequent calls.
* @see #getAssociatedValue(Object key)
*/
public synchronized final Object associateValue(Object key, Object value)
{
if (value == null) throw new IllegalArgumentException();
Map<Object,Object> h = associatedValues;
if (h == null) {
h = new HashMap<Object,Object>();
associatedValues = h;
}
return Kit.initHash(h, key, value);
}
/**
*
* @param key
* @param index
* @param start
* @param value
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putImpl(Object key, int index, Scriptable start,
Object value)
{
// This method is very hot (basically called on each assignment)
// so we inline the extensible/sealed checks below.
Slot slot;
if (this != start) {
slot = slotMap.query(key, index);
if(!isExtensible
&& (slot == null
|| (!(slot instanceof GetterSlot)
&& (slot.getAttributes() & READONLY) != 0))
&& Context.getContext().isStrictMode()) {
throw ScriptRuntime.typeError0("msg.not.extensible");
}
if (slot == null) {
return false;
}
} else if (!isExtensible) {
slot = slotMap.query(key, index);
if((slot == null
|| (!(slot instanceof GetterSlot) && (slot.getAttributes() & READONLY) != 0))
&& Context.getContext().isStrictMode()) {
throw ScriptRuntime.typeError0("msg.not.extensible");
}
if (slot == null) {
return true;
}
} else {
if (isSealed) {
checkNotSealed(key, index);
}
slot = slotMap.get(key, index, SlotAccess.MODIFY);
}
return slot.setValue(value, this, start);
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means
* defineConstProperty. READONLY means const initialization expression.
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putConstImpl(String name, int index, Scriptable start,
Object value, int constFlag)
{
assert (constFlag != EMPTY);
if (!isExtensible) {
Context cx = Context.getContext();
if (cx.isStrictMode()) {
throw ScriptRuntime.typeError0("msg.not.extensible");
}
}
Slot slot;
if (this != start) {
slot = slotMap.query(name, index);
if (slot == null) {
return false;
}
} else if (!isExtensible()) {
slot = slotMap.query(name, index);
if (slot == null) {
return true;
}
} else {
checkNotSealed(name, index);
// either const hoisted declaration or initialization
slot = slotMap.get(name, index, SlotAccess.MODIFY_CONST);
int attr = slot.getAttributes();
if ((attr & READONLY) == 0)
throw Context.reportRuntimeError1("msg.var.redecl", name);
if ((attr & UNINITIALIZED_CONST) != 0) {
slot.value = value;
// clear the bit on const initialization
if (constFlag != UNINITIALIZED_CONST)
slot.setAttributes(attr & ~UNINITIALIZED_CONST);
}
return true;
}
return slot.setValue(value, this, start);
}
private Slot findAttributeSlot(String name, int index, SlotAccess accessType)
{
Slot slot = slotMap.get(name, index, accessType);
if (slot == null) {
String str = (name != null ? name : Integer.toString(index));
throw Context.reportRuntimeError1("msg.prop.not.found", str);
}
return slot;
}
private Slot findAttributeSlot(Symbol key, SlotAccess accessType)
{
Slot slot = slotMap.get(key, 0, accessType);
if (slot == null) {
throw Context.reportRuntimeError1("msg.prop.not.found", key);
}
return slot;
}
Object[] getIds(boolean getNonEnumerable, boolean getSymbols) {
Object[] a;
int externalLen = (externalData == null ? 0 : externalData.getArrayLength());
if (externalLen == 0) {
a = ScriptRuntime.emptyArgs;
} else {
a = new Object[externalLen];
for (int i = 0; i < externalLen; i++) {
a[i] = Integer.valueOf(i);
}
}
if (slotMap.isEmpty()) {
return a;
}
int c = externalLen;
final long stamp = slotMap.readLock();
try {
for (Slot slot : slotMap) {
if ((getNonEnumerable || (slot.getAttributes() & DONTENUM) == 0) &&
(getSymbols || !(slot.name instanceof Symbol))) {
if (c == externalLen) {
// Special handling to combine external array with additional properties
Object[] oldA = a;
a = new Object[slotMap.dirtySize() + externalLen];
if (oldA != null) {
System.arraycopy(oldA, 0, a, 0, externalLen);
}
}
a[c++] = slot.name != null
? slot.name
: Integer.valueOf(slot.indexOrHash);
}
}
} finally {
slotMap.unlockRead(stamp);
}
Object[] result;
if (c == (a.length + externalLen)) {
result = a;
} else {
result = new Object[c];
System.arraycopy(a, 0, result, 0, c);
}
Context cx = Context.getCurrentContext();
if ((cx != null) && cx.hasFeature(Context.FEATURE_ENUMERATE_IDS_FIRST)) {
// Move all the numeric IDs to the front in numeric order
Arrays.sort(result, KEY_COMPARATOR);
}
return result;
}
private void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
final long stamp = slotMap.readLock();
try {
int objectsCount = slotMap.dirtySize();
if (objectsCount == 0) {
out.writeInt(0);
} else {
out.writeInt(objectsCount);
for (Slot slot : slotMap) {
out.writeObject(slot);
}
}
} finally {
slotMap.unlockRead(stamp);
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
int tableSize = in.readInt();
slotMap = createSlotMap(tableSize);
for (int i = 0; i < tableSize; i++) {
Slot slot = (Slot)in.readObject();
slotMap.addSlot(slot);
}
}
protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
Slot slot = getSlot(cx, id, SlotAccess.QUERY);
if (slot == null) return null;
Scriptable scope = getParentScope();
return slot.getPropertyDescriptor(cx, (scope == null ? this : scope));
}
protected Slot getSlot(Context cx, Object id, SlotAccess accessType) {
if (id instanceof Symbol) {
return slotMap.get(id, 0, accessType);
}
StringIdOrIndex s = ScriptRuntime.toStringIdOrIndex(cx, id);
if (s.stringId == null) {
return slotMap.get(null, s.index, accessType);
}
return slotMap.get(s.stringId, 0, accessType);
}
// Partial implementation of java.util.Map. See NativeObject for
// a subclass that implements java.util.Map.
public int size() {
return slotMap.size();
}
public boolean isEmpty() {
return slotMap.isEmpty();
}
public Object get(Object key) {
Object value = null;
if (key instanceof String) {
value = get((String) key, this);
} else if (key instanceof Symbol) {
value = get((Symbol) key, this);
} else if (key instanceof Number) {
value = get(((Number) key).intValue(), this);
}
if (value == Scriptable.NOT_FOUND || value == Undefined.instance) {
return null;
} else if (value instanceof Wrapper) {
return ((Wrapper) value).unwrap();
} else {
return value;
}
}
private static final Comparator<Object> KEY_COMPARATOR = new KeyComparator();
/**
* This comparator sorts property fields in spec-compliant order. Numeric ids first, in numeric
* order, followed by string ids, in insertion order. Since this class already keeps string keys
* in insertion-time order, we treat all as equal. The "Arrays.sort" method will then not
* change their order, but simply move all the numeric properties to the front, since this
* method is defined to be stable.
*/
public static final class KeyComparator
implements Comparator<Object>, Serializable
{
private static final long serialVersionUID = 6411335891523988149L;
@Override
public int compare(Object o1, Object o2)
{
if (o1 instanceof Integer) {
if (o2 instanceof Integer) {
int i1 = (Integer) o1;
int i2 = (Integer) o2;
if (i1 < i2) {
return -1;
}
if (i1 > i2) {
return 1;
}
return 0;
}
return -1;
}
if (o2 instanceof Integer) {
return 1;
}
return 0;
}
}
}
|
package org.myrobotlab.framework;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.framework.interfaces.MessageSender;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.slf4j.Logger;
public class FileMsgScanner extends Thread {
public final static Logger log = LoggerFactory.getLogger(FileMsgScanner.class);
static String MSGS_DIR = "msgs";
transient static MessageSender sender = null;
public boolean scanning = false;
xxx
static String id;
static FileMsgScanner fileMsgScanner = null;
public FileMsgScanner(String id) {
super(String.format("%s.%s", FileMsgScanner.class.getSimpleName().toLowerCase(), id));
FileMsgScanner.id = id;
}
public void run() {
File folder = new File(MSGS_DIR);
folder.mkdirs();
log.info("enabling file msgs in {}", MSGS_DIR);
scanning = true;
try {
while (scanning) {
if (!scanForMsgs()) {
sleep(500);
}
}
} catch (Exception e) {
}
}
public boolean scanForMsgs() {
File folder = new File(MSGS_DIR);
File[] listOfFiles = folder.listFiles();
boolean filesExist = false;
for (int i = 0; i < listOfFiles.length; i++) {
File json = listOfFiles[i];
if (json.isFile() && json.getName().endsWith(".json") && json.getName().startsWith(id)) {
try {
String data = new String(toByteArray(json));
log.info("%s - %s", json, data);
Message msg = CodecUtils.fromJson(data, Message.class);
json.delete();
sender.send(msg);
filesExist = true;
} catch (Exception e) {
log.error("msgs/{} threw", json);
}
}
}
return filesExist;
}
/**
* @param is
* IntputStream to byte array
* @return byte array
*/
static public final byte[] toByteArray(File file) {
FileInputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
is = new FileInputStream(file.getAbsolutePath());
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
baos.write(data, 0, nRead);
}
baos.flush();
baos.close();
is.close();
return baos.toByteArray();
} catch (Exception e) {
Logging.logError(e);
}
return null;
}
static public void enableFileMsgs(Boolean b, String id) {
if (b) {
fileMsgScanner = new FileMsgScanner(id);
fileMsgScanner.start();
} else {
fileMsgScanner.scanning = false;
fileMsgScanner.interrupt();
fileMsgScanner = null;
}
}
}
|
package org.openid4java.association;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
/**
* @author Marius Scurtescu, Johnny Bufu
*/
public class Association implements Serializable
{
private static Log _log = LogFactory.getLog(Association.class);
private static final boolean DEBUG = _log.isDebugEnabled();
public static final String FAILED_ASSOC_HANDLE = " ";
public static final String TYPE_HMAC_SHA1 = "HMAC-SHA1";
public static final String TYPE_HMAC_SHA256 = "HMAC-SHA256";
public static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
public static final int HMAC_SHA1_KEYSIZE = 160;
public static final int HMAC_SHA256_KEYSIZE = 256;
private String _type;
private String _handle;
private SecretKey _macKey;
private Date _expiry;
private Association(String type, String handle, SecretKey macKey, Date expiry)
{
if (DEBUG) _log.debug("Creating association, type: " + type +
" handle: " + handle + " expires: " + expiry);
_type = type;
_handle = handle;
_macKey = macKey;
_expiry = expiry;
}
private Association(String type, String handle, SecretKey macKey, int expiryIn)
{
this(type, handle, macKey, new Date(System.currentTimeMillis() + expiryIn * 1000));
}
public static Association getFailedAssociation(Date expiry)
{
return new Association(null, FAILED_ASSOC_HANDLE, null, expiry);
}
public static Association getFailedAssociation(int expiryIn)
{
return getFailedAssociation(new Date(System.currentTimeMillis() + expiryIn * 1000));
}
public static Association generate(String type, String handle, int expiryIn) throws AssociationException
{
if (TYPE_HMAC_SHA1.equals(type))
{
return generateHmacSha1(handle, expiryIn);
}
else if (TYPE_HMAC_SHA256.equals(type))
{
return generateHmacSha256(handle, expiryIn);
}
else
{
throw new AssociationException("Unknown association type: " + type);
}
}
public static Association generateHmacSha1(String handle, int expiryIn)
{
SecretKey macKey = generateMacSha1Key();
if (DEBUG) _log.debug("Generated SHA1 MAC key: " + macKey);
return new Association(TYPE_HMAC_SHA1, handle, macKey, expiryIn);
}
public static Association createHmacSha1(String handle, byte[] macKeyBytes, int expiryIn)
{
SecretKey macKey = createMacKey(HMAC_SHA1_ALGORITHM, macKeyBytes);
return new Association(TYPE_HMAC_SHA1, handle, macKey, expiryIn);
}
public static Association createHmacSha1(String handle, byte[] macKeyBytes, Date expDate)
{
SecretKey macKey = createMacKey(HMAC_SHA1_ALGORITHM, macKeyBytes);
return new Association(TYPE_HMAC_SHA1, handle, macKey, expDate);
}
public static Association generateHmacSha256(String handle, int expiryIn)
{
SecretKey macKey = generateMacSha256Key();
if (DEBUG) _log.debug("Generated SHA256 MAC key: " + macKey);
return new Association(TYPE_HMAC_SHA256, handle, macKey, expiryIn);
}
public static Association createHmacSha256(String handle, byte[] macKeyBytes, int expiryIn)
{
SecretKey macKey = createMacKey(HMAC_SHA256_ALGORITHM, macKeyBytes);
return new Association(TYPE_HMAC_SHA256, handle, macKey, expiryIn);
}
public static Association createHmacSha256(String handle, byte[] macKeyBytes, Date expDate)
{
SecretKey macKey = createMacKey(HMAC_SHA256_ALGORITHM, macKeyBytes);
return new Association(TYPE_HMAC_SHA256, handle, macKey, expDate);
}
protected static SecretKey generateMacKey(String algorithm, int keySize)
{
try
{
KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
keyGen.init(keySize);
return keyGen.generateKey();
}
catch (NoSuchAlgorithmException e)
{
_log.error("Unsupported algorithm: " + algorithm + ", size: " + keySize, e);
return null;
}
}
protected static SecretKey generateMacSha1Key()
{
return generateMacKey(HMAC_SHA1_ALGORITHM, HMAC_SHA1_KEYSIZE);
}
protected static SecretKey generateMacSha256Key()
{
return generateMacKey(HMAC_SHA256_ALGORITHM, HMAC_SHA256_KEYSIZE);
}
public static boolean isHmacSupported(String hMacType)
{
String hMacAlgorithm;
if (TYPE_HMAC_SHA1.equals(hMacType))
hMacAlgorithm = HMAC_SHA1_ALGORITHM;
else if (TYPE_HMAC_SHA256.equals(hMacType))
hMacAlgorithm = HMAC_SHA256_ALGORITHM;
else
return false;
try
{
KeyGenerator.getInstance(hMacAlgorithm);
}
catch (NoSuchAlgorithmException e)
{
return false;
}
return true;
}
public static boolean isHmacSha256Supported()
{
try
{
KeyGenerator.getInstance(HMAC_SHA256_ALGORITHM);
return true;
}
catch (NoSuchAlgorithmException e)
{
return false;
}
}
public static boolean isHmacSha1Supported()
{
try
{
KeyGenerator.getInstance(HMAC_SHA1_ALGORITHM);
return true;
}
catch (NoSuchAlgorithmException e)
{
return false;
}
}
protected static SecretKey createMacKey(String algorithm, byte[] macKey)
{
return new SecretKeySpec(macKey, algorithm);
}
public String getType()
{
return _type;
}
public String getHandle()
{
return _handle;
}
public SecretKey getMacKey()
{
return _macKey;
}
public Date getExpiry()
{
return _expiry;
}
public boolean hasExpired()
{
Date now = new Date();
return _expiry.before(now);
}
protected byte[] sign(byte[] data) throws AssociationException
{
try
{
String algorithm = _macKey.getAlgorithm();
Mac mac = Mac.getInstance(algorithm);
mac.init(_macKey);
return mac.doFinal(data);
}
catch (GeneralSecurityException e)
{
throw new AssociationException("Cannot sign!", e);
}
}
public String sign(String text) throws AssociationException
{
if (DEBUG) _log.debug("Computing signature for input data:\n" + text);
try
{
String signature = new String(Base64.encodeBase64(sign(text.getBytes("utf-8"))), "utf-8");
if (DEBUG)
_log.debug("Calculated signature: " + signature);
return signature;
}
catch (UnsupportedEncodingException e)
{
throw new AssociationException("Unsupported encoding for signed text.", e);
}
}
public boolean verifySignature(String text, String signature) throws AssociationException
{
if (DEBUG) _log.debug("Verifying signature: " + signature);
// The Java String.equals() method returns on the first difference in
// its inputs, which allows a timing attack to recover signature values.
// This verification method will take the same amount of time for any
// two inputs of equal length.
try {
byte[] sigBytes = signature.getBytes("utf-8");
byte[] textSigBytes = sign(text).getBytes("utf-8");
if (sigBytes.length == 0 ||
sigBytes.length != textSigBytes.length) {
return false;
}
int result = 0;
for (int i = 0; i < sigBytes.length; i++) {
result |= sigBytes[i] ^ textSigBytes[i];
}
return result == 0;
}
catch (UnsupportedEncodingException e)
{
throw new AssociationException("Unsupported encoding for signed text.", e);
}
}
}
|
package com.hbasebook.hush;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import com.hbasebook.hush.model.LongUrl;
import com.hbasebook.hush.model.ShortUrl;
import com.hbasebook.hush.servlet.RequestInfo;
import com.hbasebook.hush.table.HushTable;
import com.hbasebook.hush.table.LongUrlTable;
import com.hbasebook.hush.table.ShortUrlTable;
import com.hbasebook.hush.table.UserShortUrlTable;
public class UrlManager {
private final Log LOG = LogFactory.getLog(UrlManager.class);
private final ResourceManager rm;
UrlManager(ResourceManager rm) throws IOException {
this.rm = rm;
}
/**
* Initialize the instance. This is done lazily as it requires global
* resources that need to be setup first.
*
* @throws IOException When preparing the stored data fails.
*/
public void init() throws IOException {
initializeShortIdCounter();
}
/**
* Initializes the short ID counter
*
* @throws IOException
*/
private void initializeShortIdCounter() throws IOException {
HTable table = rm.getTable(HushTable.NAME);
try {
Put put = new Put(HushTable.GLOBAL_ROW_KEY);
byte[] value = Bytes.toBytes(HushUtil.hushDecode("0337"));
put.add(HushTable.COUNTERS_FAMILY, HushTable.SHORT_ID, value);
boolean hasPut = table.checkAndPut(HushTable.GLOBAL_ROW_KEY,
HushTable.COUNTERS_FAMILY, HushTable.SHORT_ID, null, put);
if (hasPut) {
LOG.info("Short Id counter initialized.");
}
} catch (Exception e) {
LOG.error("Unable to initialize counters.", e);
throw new IOException(e);
} finally {
rm.putTable(table);
}
}
/**
* Creates a new short URL entry. Details are stored in various tables.
*
* @param url The URL to shorten.
* @param username The name of the current user.
* @return The shortened URL.
* @throws IOException When reading or writing the data fails.
*/
public ShortUrl shorten(URL url, String username, RequestInfo info)
throws IOException {
String shortId = generateShortId();
String domain = rm.getDomainManager().shorten(url.getHost());
String urlString = url.toString();
String refShortId = getReferenceShortId(domain, urlString, username);
ShortUrl shortUrl;
if (refShortId != null && UserManager.isAnonymous(username)) {
// no need to create a new link, just look up an existing one
shortUrl = getShortUrl(refShortId);
createUserShortUrl(username, refShortId);
} else {
shortUrl = new ShortUrl(shortId, domain, urlString, refShortId, username);
createShortUrl(shortUrl);
createUserShortUrl(username, shortId);
rm.getCounters().incrementUsage(shortId, info, 0L);
}
return shortUrl;
}
/**
* Returns the reference short Id of a given URL. The reference Id is the
* first short Id created for a URL. If there is no entry yet a new one is
* created.
*
* @param domain The domain name to use.
* @param url The long URL to look up.
* @param username The current username.
* @return The reference shortId for the URL.
* @throws IOException When reading or writing the data fails.
*/
private String getReferenceShortId(String domain, String url, String username)
throws IOException {
String shortId = addLongUrl(domain, url, username);
if (shortId == null) {
LongUrl longUrl = getLongUrl(url);
shortId = longUrl != null ? longUrl.getShortId() : null;
}
return shortId;
}
/**
* Adds a new long URL record to the table, but only if there is no previous
* entry.
*
* @param domain The domain name to use.
* @param url The long URL to look up.
* @param username The current username.
* @return The new short Id when the add has succeeded.
* @throws IOException When adding the new URL fails.
*/
private String addLongUrl(String domain, String url, String username)
throws IOException {
ResourceManager manager = ResourceManager.getInstance();
HTable table = manager.getTable(LongUrlTable.NAME);
byte[] md5Url = DigestUtils.md5(url);
Put put = new Put(md5Url);
put.add(LongUrlTable.DATA_FAMILY, LongUrlTable.URL,
Bytes.toBytes(url));
boolean hasPut = table.checkAndPut(md5Url, LongUrlTable.DATA_FAMILY,
LongUrlTable.URL, null, put);
String shortId = null;
// check if we added a new URL, if so assign an Id subsequently
if (hasPut) {
shortId = generateShortId();
createShortUrl(new ShortUrl(shortId, domain, url, null, username));
put.add(LongUrlTable.DATA_FAMILY, LongUrlTable.SHORT_ID,
Bytes.toBytes(shortId));
table.put(put);
table.flushCommits();
}
manager.putTable(table);
return shortId;
}
/**
* Saves a mapping between the short Id and long URL.
*
* @param shortUrl The short URL details.
* @throws IOException When saving the record fails.
*/
private void createShortUrl(ShortUrl shortUrl) throws IOException {
HTable table = rm.getTable(ShortUrlTable.NAME);
Put put = new Put(Bytes.toBytes(shortUrl.getId()));
put.add(ShortUrlTable.DATA_FAMILY, ShortUrlTable.URL,
Bytes.toBytes(shortUrl.getLongUrl()));
put.add(ShortUrlTable.DATA_FAMILY, ShortUrlTable.SHORT_DOMAIN,
Bytes.toBytes(shortUrl.getDomain()));
put.add(ShortUrlTable.DATA_FAMILY, ShortUrlTable.USER_ID,
Bytes.toBytes(shortUrl.getUser()));
if (shortUrl.getRefShortId() != null) {
put.add(ShortUrlTable.DATA_FAMILY, ShortUrlTable.REF_SHORT_ID,
Bytes.toBytes(shortUrl.getRefShortId()));
}
put.add(ShortUrlTable.DATA_FAMILY, ShortUrlTable.CLICKS,
Bytes.toBytes(shortUrl.getClicks()));
table.put(put);
table.flushCommits();
rm.putTable(table);
}
/**
* Saves a mapping between the short Id and long URL.
*
* @param username The current username.
* @param shortId The short Id to kink the user to.
* @throws IOException When saving the record fails.
*/
private void createUserShortUrl(String username, String shortId)
throws IOException {
HTable table = rm.getTable(UserShortUrlTable.NAME);
byte[] rowKey = Bytes.add(Bytes.toBytes(username), ResourceManager.ZERO,
Bytes.toBytes(shortId));
Put put = new Put(rowKey);
put.add(UserShortUrlTable.DATA_FAMILY, UserShortUrlTable.TIMESTAMP,
Bytes.toBytes(System.currentTimeMillis()));
table.put(put);
table.flushCommits();
rm.putTable(table);
}
/**
* Loads the details of a shortened URL by Id.
*
* @param shortId The Id to load.
* @return The shortened URL details, or <code>null</code> if not found.
* @throws IOException When reading the data fails.
*/
public ShortUrl getShortUrl(String shortId) throws IOException {
if (shortId == null) {
return null;
}
HTable table = rm.getTable(ShortUrlTable.NAME);
Get get = new Get(Bytes.toBytes(shortId));
get.addColumn(ShortUrlTable.DATA_FAMILY, ShortUrlTable.URL);
get.addColumn(ShortUrlTable.DATA_FAMILY, ShortUrlTable.SHORT_DOMAIN);
get.addColumn(ShortUrlTable.DATA_FAMILY, ShortUrlTable.REF_SHORT_ID);
get.addColumn(ShortUrlTable.DATA_FAMILY, ShortUrlTable.USER_ID);
get.addColumn(ShortUrlTable.DATA_FAMILY, ShortUrlTable.CLICKS);
Result result = table.get(get);
if (result.isEmpty()) {
return null;
}
String url = Bytes.toString(result.getValue(ShortUrlTable.DATA_FAMILY,
ShortUrlTable.URL));
if (url == null) {
LOG.warn("Found " + shortId + " but no URL column.");
return null;
}
String domain = Bytes.toString(result.getValue(ShortUrlTable.DATA_FAMILY,
ShortUrlTable.SHORT_DOMAIN));
if (domain == null) {
LOG.warn("Found " + shortId + " but no short domain column.");
return null;
}
String refShortId = Bytes.toString(result.getValue(
ShortUrlTable.DATA_FAMILY, ShortUrlTable.REF_SHORT_ID));
String user = Bytes.toString(result.getValue(ShortUrlTable.DATA_FAMILY,
ShortUrlTable.USER_ID));
long clicks = Bytes.toLong(result.getValue(ShortUrlTable.DATA_FAMILY,
ShortUrlTable.CLICKS));
rm.putTable(table);
return new ShortUrl(shortId, domain, url, refShortId, user, clicks);
}
/**
* Loads a URL from the URL table.
*
* @param longUrl The URL to load.
* @return The URL with its details, or <code>null</code> if not found.
* @throws IOException When loading the URL fails.
*/
private LongUrl getLongUrl(String longUrl) throws IOException {
HTable table = rm.getTable(LongUrlTable.NAME);
byte[] md5Url = DigestUtils.md5(longUrl);
Get get = new Get(md5Url);
get.addColumn(LongUrlTable.DATA_FAMILY, LongUrlTable.URL);
get.addColumn(LongUrlTable.DATA_FAMILY, LongUrlTable.SHORT_ID);
Result result = table.get(get);
if (result.isEmpty()) {
return null;
}
String url = Bytes.toString(result.getValue(LongUrlTable.DATA_FAMILY,
LongUrlTable.URL));
String shortId = Bytes.toString(result.getValue(LongUrlTable.DATA_FAMILY,
LongUrlTable.SHORT_ID));
rm.putTable(table);
return new LongUrl(url, shortId);
}
/**
* Convenience method to retrieve a new short Id. Each call increments the
* counter by one.
*
* @return The newly created short Id.
* @throws IOException When communicating with HBase fails.
*/
private String generateShortId() throws IOException {
return generateShortId(1L);
}
/**
* Creates a new short Id.
*
* @param incrBy The increment value.
* @return The newly created short id, encoded as String.
* @throws IOException When the counter fails to increment.
*/
private String generateShortId(long incrBy) throws IOException {
ResourceManager manager = ResourceManager.getInstance();
HTable table = manager.getTable(HushTable.NAME);
try {
Increment increment = new Increment(HushTable.GLOBAL_ROW_KEY);
increment.addColumn(HushTable.COUNTERS_FAMILY, HushTable.SHORT_ID,
incrBy);
Result result = table.increment(increment);
long id = Bytes.toLong(result.getValue(HushTable.COUNTERS_FAMILY,
HushTable.SHORT_ID));
return HushUtil.hushEncode(id);
} catch (Exception e) {
LOG.error("Unable to create a new short Id.", e);
throw new IOException(e);
} finally {
try {
manager.putTable(table);
} catch (Exception e) {
// ignore
}
}
}
private List<String> getShortUrlIdsByUser(String username)
throws IOException {
HTable table = rm.getTable(UserShortUrlTable.NAME);
byte[] startRow = Bytes.toBytes(username);
byte[] stopRow = Bytes.add(startRow, ResourceManager.ONE);
Scan scan = new Scan(startRow, stopRow);
scan.addFamily(UserShortUrlTable.DATA_FAMILY);
ResultScanner scanner = table.getScanner(scan);
List<String> ids = new ArrayList<String>();
for (Result result : scanner) {
String rowKey = Bytes.toString(result.getRow());
String shortId = rowKey.substring(rowKey.indexOf(0) + 1);
ids.add(shortId);
}
rm.putTable(table);
return ids;
}
public List<ShortUrl> getShortUrlsByUser(String username)
throws IOException {
List<ShortUrl> surls = new ArrayList<ShortUrl>();
for (String id : getShortUrlIdsByUser(username)) {
surls.add(getShortUrl(id));
}
return surls;
}
}
|
package pt.up.fe.aiad.gui;
import jade.core.AID;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.Stage;
import pt.up.fe.aiad.scheduler.ScheduleEvent;
import pt.up.fe.aiad.scheduler.SchedulerAgent;
import pt.up.fe.aiad.utils.FXUtils;
import pt.up.fe.aiad.utils.StringUtils;
import pt.up.fe.aiad.utils.TimeInterval;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.stream.Collectors;
public class CreateEventController {
@FXML
private TextField _eventName;
@FXML
private TextField _hours;
@FXML
private ChoiceBox<Integer> _minutes;
@FXML
private Button _confirmButton;
@FXML
private ListView<String> _otherAgents;
private SchedulerAgent _agent;
private Stage _stage;
@FXML
private DatePicker _minDate;
@FXML
private ChoiceBox<Integer> _minHours;
@FXML
private ChoiceBox<Integer> _minMinutes;
@FXML
private DatePicker _maxDate;
@FXML
private ChoiceBox<Integer> _maxHours;
@FXML
private ChoiceBox<Integer> _maxMinutes;
public void initData(SchedulerAgent agent, final Stage stage) {
System.out.println("ClientController.initData");
_minutes.getItems().addAll(0, 30);
_minutes.setValue(0);
_agent = agent;
_stage = stage;
_confirmButton.setDisable(true);
_eventName.textProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_hours.textProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_minutes.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_minDate.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_minHours.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_minMinutes.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_maxDate.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_maxHours.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_maxMinutes.valueProperty().addListener((observable, oldValue, newValue) -> validateEventData());
_otherAgents.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
_otherAgents.setItems(agent.otherAgents);
for (int i=0; i < 24; i++) {
_minHours.getItems().add(i);
_maxHours.getItems().add(i);
}
_minHours.setValue(0);
_maxHours.setValue(0);
_minMinutes.getItems().addAll(0, 30);
_minMinutes.setValue(0);
_maxMinutes.getItems().addAll(0, 30);
_maxMinutes.setValue(0);
}
private void validateEventData() {
_confirmButton.setDisable(true);
if (StringUtils.isNullOrEmpty(_eventName.getText()))
return;
if (StringUtils.isNullOrEmpty(_hours.getText()))
return;
if (_eventName.getText().length() > 64)
return;
int val;
try {
val = Integer.parseInt(_hours.getText());
} catch (NumberFormatException nfe) {
return;
}
if (val < 0 || val + _minutes.getValue() <= 0)
return;
LocalDate minLd = _minDate.getValue();
if (minLd == null)
return;
Calendar minC = Calendar.getInstance();
minC.set(minLd.getYear(), minLd.getMonthValue()-1, minLd.getDayOfMonth(), _minHours.getValue(), _minMinutes.getValue(), 0);
LocalDate maxLd = _maxDate.getValue();
if (maxLd == null)
return;
Calendar maxC = Calendar.getInstance();
maxC.set(maxLd.getYear(), maxLd.getMonthValue()-1, maxLd.getDayOfMonth(), _maxHours.getValue(), _maxMinutes.getValue(), 0);
TimeInterval ti;
try {
ti = new TimeInterval(minC, maxC);
} catch (IllegalArgumentException iae) {
return;
}
if (!ti.fits(Integer.parseInt(_hours.getText()) * 3600 + _minutes.getValue() * 60))
return;
_confirmButton.setDisable(false);
}
@FXML
public void saveEvent(ActionEvent event) {
ArrayList<AID> agents = new ArrayList<>();
agents.add (_agent.getAID());
agents.addAll(_otherAgents.getSelectionModel().getSelectedItems().stream().map(_agent.agentNameToAid::get).collect(Collectors.toList()));
LocalDate minLd = _minDate.getValue();
Calendar minC = Calendar.getInstance();
minC.set(minLd.getYear(), minLd.getMonthValue()-1, minLd.getDayOfMonth(), _minHours.getValue(), _minMinutes.getValue(), 0);
LocalDate maxLd = _maxDate.getValue();
Calendar maxC = Calendar.getInstance();
maxC.set(maxLd.getYear(), maxLd.getMonthValue()-1, maxLd.getDayOfMonth(), _maxHours.getValue(), _maxMinutes.getValue(), 0);
TimeInterval ti = new TimeInterval(minC, maxC);
ScheduleEvent _newEvent = new ScheduleEvent(_eventName.getText(), Integer.parseInt(_hours.getText()) * 3600 + _minutes.getValue() * 60, agents, ti);
_agent.dispatchInvitations(_newEvent);
_stage.close();
}
@FXML
public void cancelCreation(ActionEvent event) {
_stage.close();
}
}
|
/* High level API */
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* High level API for mapping queries to DNS Records. Caching is used
* when possible to reduce the number of DNS requests, and a Resolver
* is used to perform the queries. A search path can be set or determined
* by FindServer, which allows lookups of unqualified names.
* @see Resolver
* @see FindServer
*
* @author Brian Wellington
*/
public final class dns {
private static Resolver res;
private static Cache cache;
private static Name [] searchPath;
private static boolean searchPathSet;
private static boolean initialized;
/* Otherwise the class could be instantiated */
private
dns() {}
synchronized private static void
initialize() {
if (initialized)
return;
initialized = true;
if (res == null) {
try {
setResolver(new ExtendedResolver());
}
catch (UnknownHostException uhe) {
System.err.println("Failed to initialize resolver");
System.exit(-1);
}
}
if (!searchPathSet)
searchPath = FindServer.searchPath();
if (cache == null)
cache = new Cache();
}
static boolean
matchType(short type1, short type2) {
return (type1 == Type.ANY || type2 == Type.ANY || type1 == type2);
}
/**
* Converts an InetAddress into the corresponding domain name
* (127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.)
* @return A String containing the domain name.
*/
public static String
inaddrString(InetAddress addr) {
byte [] address = addr.getAddress();
StringBuffer sb = new StringBuffer();
for (int i = 3; i >= 0; i
sb.append(address[i] & 0xFF);
sb.append(".");
}
sb.append("IN-ADDR.ARPA.");
return sb.toString();
}
/**
* Converts an String containing an IP address in dotted quad form into the
* corresponding domain name.
* ex. 127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.
* @return A String containing the domain name.
*/
public static String
inaddrString(String s) {
InetAddress address;
try {
address = InetAddress.getByName(s);
}
catch (UnknownHostException e) {
return null;
}
return inaddrString(address);
}
/**
* Sets the Resolver to be used by functions in the dns class
*/
public static synchronized void
setResolver(Resolver _res) {
res = _res;
if (cache != null)
cache.clearCache();
}
/**
* Obtains the Resolver used by functions in the dns class. This can be used
* to set Resolver properties.
*/
public static synchronized Resolver
getResolver() {
initialize();
return res;
}
/**
* Specifies the domains which will be appended to unqualified names before
* beginning the lookup process. If this is not set, FindServer will be used.
* @see FindServer
*/
public static synchronized void
setSearchPath(String [] domains) {
if (domains == null || domains.length == 0)
searchPath = null;
else {
searchPath = new Name[domains.length];
for (int i = 0; i < domains.length; i++)
searchPath[i] = new Name(domains[i]);
}
searchPathSet = true;
}
/**
* Obtains the Cache used by functions in the dns class. This can be used
* to perform more specific queries and/or remove elements.
*/
public static synchronized Cache
getCache() {
initialize();
return cache;
}
private static Record []
lookup(Name name, short type, short dclass, byte cred, boolean querysent) {
Record [] answers;
int answerCount = 0, n = 0;
Enumeration e;
if (Options.check("verbose"))
System.err.println("lookup " + name + " " + Type.string(type));
SetResponse cached = cache.lookupRecords(name, type, dclass, cred);
if (Options.check("verbose"))
System.err.println(cached);
if (cached.isSuccessful()) {
RRset [] rrsets = cached.answers();
answerCount = 0;
for (int i = 0; i < rrsets.length; i++)
answerCount += rrsets[i].size();
answers = new Record[answerCount];
for (int i = 0; i < rrsets.length; i++) {
e = rrsets[i].rrs();
while (e.hasMoreElements()) {
Record r = (Record)e.nextElement();
answers[n++] = r;
}
}
}
else if (cached.isNegative()) {
return null;
}
else if (querysent) {
return null;
}
else {
Record question = Record.newRecord(name, type, dclass);
Message query = Message.newQuery(question);
Message response;
try {
response = res.send(query);
}
catch (Exception ex) {
return null;
}
short rcode = response.getHeader().getRcode();
if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN)
cache.addMessage(response);
if (rcode != Rcode.NOERROR)
return null;
return lookup(name, type, dclass, cred, true);
}
return answers;
}
/**
* Finds records with the given name, type, and class with a certain credibility
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @param cred The minimum credibility of the desired records
* @see Credibility
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, short type, short dclass, byte cred) {
Record [] answers = null;
Name name = new Name(namestr);
if (!Type.isRR(type) && type != Type.ANY)
return null;
initialize();
if (searchPath == null || name.isQualified())
answers = lookup(name, type, dclass, cred, false);
else {
for (int i = 0; i < searchPath.length; i++) {
answers = lookup(new Name(namestr, searchPath[i]),
type, dclass, cred, false);
if (answers != null)
break;
}
}
return answers;
}
/**
* Finds credible records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, short type, short dclass) {
return getRecords(namestr, type, dclass, Credibility.NONAUTH_ANSWER);
}
/**
* Finds any records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String namestr, short type, short dclass) {
return getRecords(namestr, type, dclass, Credibility.AUTH_ADDITIONAL);
}
/**
* Finds credible records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String name, short type) {
return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER);
}
/**
* Finds any records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String name, short type) {
return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL);
}
/**
* Finds credible records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecordsByAddress(String addr, short type) {
String name = inaddrString(addr);
return getRecords(name, type, DClass.IN, Credibility.NONAUTH_ANSWER);
}
/**
* Finds any records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecordsByAddress(String addr, short type) {
String name = inaddrString(addr);
return getRecords(name, type, DClass.IN, Credibility.AUTH_ADDITIONAL);
}
}
|
package org.xbill.DNS;
import java.util.*;
import java.net.*;
/**
* A high level API for mapping queries to DNS Records.
* <P>
* As of dnsjava 1.4.0, all functions in this class are wrappers
* around functions in the Lookup and ReverseMap class, and those should be
* used instead.
*
* @see Lookup
* @see ReverseMap
*
* @author Brian Wellington
*/
public final class dns {
/* Otherwise the class could be instantiated */
private
dns() {}
/**
* Converts an InetAddress into the corresponding domain name
* (127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.)
* @return A String containing the domain name.
*/
public static String
inaddrString(InetAddress addr) {
return ReverseMap.fromAddress(addr).toString();
}
/**
* Converts an String containing an IP address in dotted quad form into the
* corresponding domain name.
* ex. 127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.
* @return A String containing the domain name.
*/
public static String
inaddrString(String s) {
try {
return ReverseMap.fromAddress(s).toString();
}
catch (UnknownHostException e) {
return null;
}
}
/**
* Sets the Resolver to be used by functions in the dns class
*/
public static synchronized void
setResolver(Resolver res) {
Lookup.setDefaultResolver(res);
}
/**
* Obtains the Resolver used by functions in the dns class. This can be used
* to set Resolver properties.
*/
public static synchronized Resolver
getResolver() {
return Lookup.getDefaultResolver();
}
/**
* Specifies the domains which will be appended to unqualified names before
* beginning the lookup process. If this is not set, FindServer will be used.
* Unlike the Lookup setSearchPath function, this will silently ignore
* invalid names.
* @see FindServer
*/
public static synchronized void
setSearchPath(String [] domains) {
if (domains == null || domains.length == 0) {
Lookup.setDefaultSearchPath((Name []) null);
return;
}
List l = new ArrayList();
for (int i = 0; i < domains.length; i++) {
try {
l.add(Name.fromString(domains[i], Name.root));
}
catch (TextParseException e) {
}
}
Name [] searchPath = (Name [])l.toArray(new Name[l.size()]);
Lookup.setDefaultSearchPath(searchPath);
}
/**
* Obtains the Cache used by functions in the dns class. This can be used
* to perform more specific queries and/or remove elements.
*
* @param dclass The dns class of data in the cache
*/
public static synchronized Cache
getCache(int dclass) {
return Lookup.getDefaultCache(dclass);
}
/**
* Obtains the (class IN) Cache used by functions in the dns class. This
* can be used to perform more specific queries and/or remove elements.
*/
public static synchronized Cache
getCache() {
return Lookup.getDefaultCache(DClass.IN);
}
/**
* Finds records with the given name, type, and class with a certain credibility
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @param cred The minimum credibility of the desired records
* @see Credibility
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, int type, int dclass, byte cred) {
try {
Lookup lookup = new Lookup(namestr, type, dclass);
lookup.setCredibility(cred);
return lookup.run();
} catch (Exception e) {
return null;
}
}
/**
* Finds credible records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, int type, int dclass) {
return getRecords(namestr, type, dclass, Credibility.NORMAL);
}
/**
* Finds any records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String namestr, int type, int dclass) {
return getRecords(namestr, type, dclass, Credibility.ANY);
}
/**
* Finds credible records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, int type) {
return getRecords(namestr, type, DClass.IN, Credibility.NORMAL);
}
/**
* Finds any records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String namestr, int type) {
return getRecords(namestr, type, DClass.IN, Credibility.ANY);
}
/**
* Finds credible records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecordsByAddress(String addr, int type) {
String namestr = inaddrString(addr);
return getRecords(namestr, type, DClass.IN, Credibility.NORMAL);
}
/**
* Finds any records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecordsByAddress(String addr, int type) {
String name = inaddrString(addr);
return getRecords(name, type, DClass.IN, Credibility.ANY);
}
}
|
/* High level API */
package org.xbill.DNS;
import java.util.*;
import java.io.*;
import java.net.*;
/**
* High level API for mapping queries to DNS Records. Caching is used
* when possible to reduce the number of DNS requests, and a Resolver
* is used to perform the queries. A search path can be set or determined
* by FindServer, which allows lookups of unqualified names.
* @see Resolver
* @see FindServer
*
* @author Brian Wellington
*/
public final class dns {
private static Resolver res;
private static Map caches;
private static Name [] searchPath;
private static boolean searchPathSet;
private static boolean initialized;
static {
initialize();
}
/* Otherwise the class could be instantiated */
private
dns() {}
private static synchronized void
clearCaches() {
Iterator it = caches.entrySet().iterator();
while (it.hasNext()) {
Cache c = (Cache)it.next();
c.clearCache();
}
}
private static synchronized void
initialize() {
if (initialized)
return;
initialized = true;
if (res == null) {
try {
setResolver(new ExtendedResolver());
}
catch (UnknownHostException uhe) {
System.err.println("Failed to initialize resolver");
System.exit(-1);
}
}
if (!searchPathSet)
searchPath = FindServer.searchPath();
if (caches == null)
caches = new HashMap();
else
clearCaches();
}
static boolean
matchType(short type1, short type2) {
return (type1 == Type.ANY || type2 == Type.ANY || type1 == type2);
}
/**
* Converts an InetAddress into the corresponding domain name
* (127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.)
* @return A String containing the domain name.
*/
public static String
inaddrString(InetAddress addr) {
byte [] address = addr.getAddress();
StringBuffer sb = new StringBuffer();
for (int i = 3; i >= 0; i
sb.append(address[i] & 0xFF);
sb.append(".");
}
sb.append("IN-ADDR.ARPA.");
return sb.toString();
}
/**
* Converts an String containing an IP address in dotted quad form into the
* corresponding domain name.
* ex. 127.0.0.1 -> 1.0.0.127.IN-ADDR.ARPA.
* @return A String containing the domain name.
*/
public static String
inaddrString(String s) {
InetAddress address;
try {
address = InetAddress.getByName(s);
}
catch (UnknownHostException e) {
return null;
}
return inaddrString(address);
}
/**
* Sets the Resolver to be used by functions in the dns class
*/
public static synchronized void
setResolver(Resolver res) {
initialize();
dns.res = res;
}
/**
* Obtains the Resolver used by functions in the dns class. This can be used
* to set Resolver properties.
*/
public static synchronized Resolver
getResolver() {
return res;
}
/**
* Specifies the domains which will be appended to unqualified names before
* beginning the lookup process. If this is not set, FindServer will be used.
* @see FindServer
*/
public static synchronized void
setSearchPath(String [] domains) {
if (domains == null || domains.length == 0)
searchPath = null;
else {
List l = new ArrayList();
for (int i = 0; i < domains.length; i++) {
try {
l.add(Name.fromString(domains[i], Name.root));
}
catch (TextParseException e) {
}
}
searchPath = (Name [])l.toArray(new Name[l.size()]);
}
searchPathSet = true;
}
/**
* Obtains the Cache used by functions in the dns class. This can be used
* to perform more specific queries and/or remove elements.
*
* @param dclass The dns class of data in the cache
*/
public static synchronized Cache
getCache(short dclass) {
Cache c = (Cache) caches.get(DClass.toShort(dclass));
if (c == null) {
c = new Cache(dclass);
caches.put(DClass.toShort(dclass), c);
}
return c;
}
/**
* Obtains the (class IN) Cache used by functions in the dns class. This
* can be used to perform more specific queries and/or remove elements.
*
* @param dclass The dns class of data in the cache
*/
public static synchronized Cache
getCache() {
return getCache(DClass.IN);
}
private static Record []
lookup(Name name, short type, short dclass, byte cred, int iterations,
boolean querysent)
{
Cache cache;
if (iterations > 6)
return null;
if (Options.check("verbose"))
System.err.println("lookup " + name + " " + Type.string(type));
cache = getCache(dclass);
SetResponse cached = cache.lookupRecords(name, type, cred);
if (Options.check("verbose"))
System.err.println(cached);
if (cached.isSuccessful()) {
RRset [] rrsets = cached.answers();
List l = new ArrayList();
Iterator it;
Record [] answers;
int i = 0;
for (i = 0; i < rrsets.length; i++) {
it = rrsets[i].rrs();
while (it.hasNext()) {
l.add(it.next());
}
}
return (Record []) l.toArray(new Record[l.size()]);
}
else if (cached.isNXDOMAIN() || cached.isNXRRSET()) {
return null;
}
else if (cached.isCNAME()) {
CNAMERecord cname = cached.getCNAME();
return lookup(cname.getTarget(), type, dclass, cred,
++iterations, false);
}
else if (cached.isDNAME()) {
DNAMERecord dname = cached.getDNAME();
Name newname;
try {
newname = name.fromDNAME(dname);
}
catch (NameTooLongException e) {
return null;
}
return lookup(newname, type, dclass, cred, ++iterations, false);
}
else if (querysent) {
return null;
}
else {
Record question = Record.newRecord(name, type, dclass);
Message query = Message.newQuery(question);
Message response;
try {
response = res.send(query);
}
catch (Exception ex) {
return null;
}
short rcode = response.getHeader().getRcode();
if (rcode == Rcode.NOERROR || rcode == Rcode.NXDOMAIN)
cache.addMessage(response);
if (rcode != Rcode.NOERROR)
return null;
return lookup(name, type, dclass, cred, iterations, true);
}
}
private static Record []
lookupAppend(Name name, Name suffix, short type, short dclass, byte cred,
int iterations, boolean querysent)
{
try {
Name newname = Name.concatenate(name, suffix);
return lookup(newname, type, dclass, cred, iterations,
querysent);
}
catch (NameTooLongException e) {
return null;
}
}
/**
* Finds records with the given name, type, and class with a certain credibility
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @param cred The minimum credibility of the desired records
* @see Credibility
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, short type, short dclass, byte cred) {
Record [] answers = null;
Name name;
try {
name = Name.fromString(namestr, null);
} catch (TextParseException e) {
return null;
}
if (!Type.isRR(type) && type != Type.ANY)
return null;
if (name.isAbsolute())
answers = lookup(name, type, dclass, cred, 0, false);
else if (searchPath == null) {
answers = lookupAppend(name, Name.root, type, dclass,
cred, 0, false);
} else {
answers = null;
if (name.labels() > 1)
answers = lookupAppend(name, Name.root, type, dclass,
cred, 0, false);
for (int i = 0; answers == null && i < searchPath.length; i++)
answers = lookupAppend(name, searchPath[i], type,
dclass, cred, 0, false);
if (answers == null && name.labels() <= 1)
answers = lookupAppend(name, Name.root, type, dclass,
cred, 0, false);
}
return answers;
}
/**
* Finds credible records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String namestr, short type, short dclass) {
return getRecords(namestr, type, dclass, Credibility.NORMAL);
}
/**
* Finds any records with the given name, type, and class
* @param namestr The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String namestr, short type, short dclass) {
return getRecords(namestr, type, dclass, Credibility.ANY);
}
/**
* Finds credible records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecords(String name, short type) {
return getRecords(name, type, DClass.IN, Credibility.NORMAL);
}
/**
* Finds any records with the given name and type in class IN
* @param namestr The name of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecords(String name, short type) {
return getRecords(name, type, DClass.IN, Credibility.ANY);
}
/**
* Finds credible records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getRecordsByAddress(String addr, short type) {
String name = inaddrString(addr);
return getRecords(name, type, DClass.IN, Credibility.NORMAL);
}
/**
* Finds any records for the given dotted quad address and type in class IN
* @param addr The dotted quad address of the desired records
* @param type The type of the desired records
* @return The matching records, or null if none are found
*/
public static Record []
getAnyRecordsByAddress(String addr, short type) {
String name = inaddrString(addr);
return getRecords(name, type, DClass.IN, Credibility.ANY);
}
}
|
package com.adt.blackjack;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Button;
import android.widget.Toast;
public class SpielenActivity extends ActionBarActivity {
private int spielNr=0;
private int spielerPunkte=0;
private int croupierPunkte=0;
private int spielerGewinne=0;
private int croupierGewinne=0;
private int zaehler=3;
private TextView spielNrView;
private TextView spielerPunkteView;
private TextView croupierPunkteView;
private Button karteZiehenButton, aufhoerenButton, spielStartenButton, ergebnissButton;
private int resId = 0;
private int imageViewId=0;
private ImageView img;
private Kartenstapel kartenstapel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spielen);
karteZiehenButton = (Button)findViewById(R.id.bKartenZiehen);
aufhoerenButton = (Button)findViewById(R.id.bAufhoeren);
spielStartenButton = (Button)findViewById(R.id.bSpielStarten);
ergebnissButton = (Button)findViewById(R.id.bErgebnisseAnzeigen);
spielNrView= (TextView)findViewById(R.id.tvSpielZaehler);
spielerPunkteView = (TextView)findViewById(R.id.tvPunkteZaehlerSpieler);
croupierPunkteView = (TextView)findViewById(R.id.tvPunkteZaehlerCroupier);
for(int i = 1; i <= 16; i++)
{
resId = getResources().getIdentifier("kb", "drawable", getPackageName());
imageViewId = getResources().getIdentifier("imageView" + i, "id", getPackageName());
img=(ImageView)findViewById(imageViewId);
img.setImageResource(resId);
}
}
public void spielStarten(View v) {
croupierPunkte = 0;
spielerPunkte = 0;
spielNr++;
zaehler=3;
spielNrView.setText(Integer.toString(spielNr));
spielerPunkteView.setText(Integer.toString(spielerPunkte));
croupierPunkteView.setText(Integer.toString(croupierPunkte));
for(int i = 1; i <= 16; i++)
{
resId = getResources().getIdentifier("kb", "drawable", getPackageName());
imageViewId = getResources().getIdentifier("imageView" + i, "id", getPackageName());
img=(ImageView)findViewById(imageViewId);
img.setImageResource(resId);
}
// Bei jedem neuen Spielstart muss der Kartenstapel neu erstellt oder
// gemischt werden.
kartenstapel = new Kartenstapel();
// Die ersten drei Karten werden abwechselnd an Spieler und Gegner verteilt
spielerPunkte=karteGeben(kartenstapel,1,spielerPunkte);
spielerPunkteView.setText(Integer.toString(spielerPunkte));
croupierPunkte=karteGeben(kartenstapel,9,croupierPunkte);
croupierPunkteView.setText(Integer.toString(croupierPunkte));
spielerPunkte=karteGeben(kartenstapel,2,spielerPunkte);
spielerPunkteView.setText(Integer.toString(spielerPunkte));
// Die vierte verdeckte Karte in das ImageView10 legen:
resId = getResources().getIdentifier("back01" , "drawable", getPackageName());
imageViewId= getResources().getIdentifier("imageView"+ 10 , "id", getPackageName());
img= (ImageView)findViewById(imageViewId);
img.setImageResource(resId);
// Beim Spielstart kann der Spieler sofort gewinnen,
// wenn er mit den ersten zwei Karten sofort 21 Punkte hat:
if(spielerPunkte == 21 )
{
Toast.makeText(this,"Du gewinnst das Spiel!", Toast.LENGTH_LONG).show();
spielerGewinne++;
}
else {
// Wechselt die Sichtbarkeit der Button, so dass nun "Karte ziehen" und "Aufhoeren" zu sehen sind
spielStartenButton.setVisibility(View.INVISIBLE);
ergebnissButton.setVisibility(View.INVISIBLE);
karteZiehenButton.setVisibility(View.VISIBLE);
aufhoerenButton.setVisibility(View.VISIBLE);
}
}
public void karteZiehen(View button)
{
if (spielerPunkte < 21 && zaehler <= 8){
spielerPunkte=karteGeben(kartenstapel,zaehler,spielerPunkte);
spielerPunkteView.setText(Integer.toString(spielerPunkte));
zaehler++;
if (spielerPunkte >21)
{
// Der Spieler verliert wenn er mehr als 21 Punkte zieht.
Toast.makeText(this,"Dein Gegner gewinnt das Spiel!", Toast.LENGTH_LONG).show();
croupierGewinne++;
spielStartenButton.setVisibility(View.VISIBLE);
ergebnissButton.setVisibility(View.VISIBLE);
karteZiehenButton.setVisibility(View.INVISIBLE);
aufhoerenButton.setVisibility(View.INVISIBLE);
}
else if (spielerPunkte == 21){
// Der Spieler gewinnt falls er genau 21 Punkte zieht.
Toast.makeText(this,"Du gewinnst das Spiel!", Toast.LENGTH_LONG).show();
spielerGewinne++;
spielStartenButton.setVisibility(View.VISIBLE);
ergebnissButton.setVisibility(View.VISIBLE);
karteZiehenButton.setVisibility(View.INVISIBLE);
aufhoerenButton.setVisibility(View.INVISIBLE);
}
}
}
public void aufhoeren(View button)
{
// ImageView iV10 gelegt werden, daher zaehler=10
zaehler = 10;
// Thread sorgt dafuer, dass der Zug jeder Karte des Croupiers um 1 Sekunde verzoegert wird.
new Thread(){
public void run(){
while (croupierPunkte <17)
{
try {
runOnUiThread(new Runnable(){
@Override
public void run()
{
croupierPunkte=karteGeben(kartenstapel,zaehler,croupierPunkte);
croupierPunkteView.setText(Integer.toString(croupierPunkte));
zaehler++;
if (croupierPunkte>=17)
{
spielAuswerten();
}
}
});
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
spielStartenButton.setVisibility(View.VISIBLE);
ergebnissButton.setVisibility(View.VISIBLE);
karteZiehenButton.setVisibility(View.INVISIBLE);
aufhoerenButton.setVisibility(View.INVISIBLE);
}
public int karteGeben(Kartenstapel st, int n, int erg){
Karte k;
k = (Karte)st.gibKartenstapel().top();
st.gibKartenstapel().pop();
int nr = k.getKartennummer();
erg = erg + k.kartenWert();
resId = getResources().getIdentifier("ka_"+nr , "drawable", getPackageName());
imageViewId= getResources().getIdentifier("imageView"+ n , "id", getPackageName());
img=(ImageView) findViewById(imageViewId);
img.setImageResource(resId);
return erg;
}
public void spielAuswerten()
{
// Vergleich der Ergebnisse von Spieler und Croupier:
if (croupierPunkte > spielerPunkte&& croupierPunkte <= 21)
{
croupierGewinne++;
Toast.makeText(this,"Dein Gegner gewinnt das Spiel!", Toast.LENGTH_LONG).show();
}
else
{
spielerGewinne++;
Toast.makeText(this,"Du gewinnst das Spiel!", Toast.LENGTH_LONG).show();
}
}
public void ergebnisseAnzeigen(View v) {
// Uebertraegt Ergebnisse an Ergebnis-Activity
final Intent intent = new Intent(this,ErgebnisActivity.class);
intent.putExtra("ANZSPIELE",""+spielNr);
intent.putExtra("COGEWINNE",""+croupierGewinne);
intent.putExtra("SPGEWINNE",""+spielerGewinne);
startActivity(intent);
}
}
|
package io.tracee;
public final class TraceeConstants {
private TraceeConstants() {
}
public static final String HTTP_HEADER_NAME = "X-TracEE-Context";
public static final String JMS_HEADER_NAME = "X-TracEE-Context";
public static final String SESSION_ID_KEY = "traceeSessionId";
public static final String REQUEST_ID_KEY = "traceeRequestId";
public static final String PROFILE_HIDE_INBOUND = "HideInbound";
public static final String PROFILE_HIDE_OUTBOUND = "HideOutbound";
}
|
package tp.pr5.logic;
import tp.pr5.Resources.Resources;
public class ReversiRules implements GameRules {
private int dimX = Resources.DIMX_REVERSI;
private int dimY = Resources.DIMY_REVERSI;
private Counter winner;
public ReversiRules() {
winner = Counter.EMPTY;
}
public Counter initialPlayer() {
return Counter.BLACK;
}
public Counter winningMove(Move lastMove, Board b) {
Counter colorWinner = Counter.EMPTY;
int totalWhite, totalBlack;
if (b.isFull()) { // Si est lleno el tablero, vemos qu color tiene ms fichas
totalWhite = countTiles(Counter.WHITE, b);
totalBlack = countTiles(Counter.BLACK, b);
if (totalWhite < totalBlack) {
colorWinner = Counter.BLACK;
System.out.println("w:" + totalWhite);
System.out.println("b:" + totalBlack);
}
else if (totalWhite > totalBlack) {
colorWinner = Counter.WHITE; // Hay ms fichas BLANCAS! Gana
System.out.println("w:" + totalWhite);
System.out.println("b:" + totalBlack);
}
}
winner = colorWinner;
return colorWinner;
}
// Return total number of appearances of a Color
public int countTiles(Counter c, Board b) {
int total = 0;
for(int i = 1; i <= dimX; i++) {
for(int j = 1; j <= dimX; j++) {
if (b.getPosition(i, j) == c)
total++;
}
}
return total;
}
public boolean isDraw(Counter lastMove, Board b) {
boolean isDraw = false;
if ((b.isFull()) && (winner == Counter.EMPTY)) {
isDraw = true;
}
else {
isDraw = false;
}
return isDraw;
}
public Board newBoard() { // Creates a Board with some tiles on the center
Board b = new Board(dimX, dimY);
int initX = dimX / 2, initY = dimY / 2;
b.setPosition(initX, initX+1, Counter.WHITE); // Initializing board with tiles
b.setPosition(initX, initY, Counter.BLACK);
b.setPosition(initX+1, initY+1, Counter.BLACK);
b.setPosition(initX+1, initY, Counter.WHITE);
return b;
}
public Counter nextTurn(Counter lastMove, Board b) {
Counter nextTurn = Counter.EMPTY;
if (lastMove == Counter.WHITE) nextTurn = Counter.BLACK;
else if (lastMove == Counter.BLACK) nextTurn = Counter.WHITE;
return nextTurn;
}
public int getDimX() {
return this.dimX;
}
public int getDimY() {
return this.dimY;
}
public int intRules() {
return 3;
}
}
|
package uk.co.panaxiom.playjongo;
import play.Application;
import play.Play;
import play.Plugin;
public class JongoPlugin extends Plugin {
public JongoPlugin(Application application) {
}
@Override
public void onStart() {
PlayJongo.getInstance();
}
@Override
public void onStop() {
if (!Play.isTest()) {
PlayJongo.mongo().close();
}
}
}
|
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import controller.MutantController;
import mutant.Mutant;
public class MutantsView extends ViewComponent{
protected MutantController mutant_controller;
protected JScrollPane mutantPane;
private JPanel innerPanel;
private ArrayList<Mutant> d;
public MutantsView(){
innerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
mutantPane = new JScrollPane(innerPanel);
}
public void connectMutantController(MutantController m){
mutant_controller = m;
}
@Override
public void update(Collection<Mutant> data, Mutant current) {
// TODO Auto-generated method stub
d = (ArrayList<Mutant>) data;
}
@Override
public void draw() {
//innerPanel.setLocation(0, 30);
//innerPanel.add(new JLabel("Mutants"));
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
for(int i = 0; i < d.size(); i++){
JButton temp = new JButton("Mutant " + (i+1));
if(d.get(i).isKilled())
temp.setBackground(Color.GREEN);
else
temp.setBackground(Color.RED);
temp.setName(String.valueOf((i+1)));
temp.setOpaque(true);
temp.setBorderPainted(false);
temp.setPreferredSize(new Dimension(30,20));
temp.setMaximumSize(new Dimension(125,20));
temp.addActionListener(mutant_controller);
innerPanel.add(temp);
}
mutantPane = new JScrollPane(innerPanel);
mutantPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//mutantPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mutantPane.setBounds(0, 30, 200, 350);
container.add(mutantPane, BorderLayout.CENTER);
}
}
|
package burp;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.tree.*;
import mjson.Json;
public class JsonJTree extends MouseAdapter implements IMessageEditorTab, ClipboardOwner
{
private final JPanel panel = new JPanel(new BorderLayout());
private final DefaultMutableTreeNode root = new DefaultMutableTreeNode();
private final JTree tree = new JTree(root);
private final JComboBox<Part> comboBox = new JComboBox<>();
private final DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
private byte[] content;
private final IExtensionHelpers helpers;
private final IBurpExtenderCallbacks callbacks;
private static final Pattern JWT_RE = Pattern.compile(
"(?:[-_A-Z0-9]+\\.){2}[-_A-Z0-9]+", Pattern.CASE_INSENSITIVE);
JsonJTree(IBurpExtenderCallbacks callbacks) {
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addMouseListener(this);
this.callbacks = callbacks;
this.helpers = callbacks.getHelpers();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
root.removeAllChildren();
Part part = comboBox.getItemAt(comboBox.getSelectedIndex());
Json node = Json.read(part.decode());
root.setUserObject(new Node(null, node));
if (node.isObject()) {
dumpObjectNode(root, node);
} else if (node.isArray()) {
dumpArrayNode(root, node);
}
model.reload(root);
expandAllNodes(tree, 0, tree.getRowCount());
}
});
panel.add(comboBox, BorderLayout.NORTH);
panel.add(new JScrollPane(tree), BorderLayout.CENTER);
}
@Override public void mousePressed (MouseEvent e) { if (e.isPopupTrigger()) doPop(e); }
@Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPop(e); }
private void doPop(MouseEvent e) {
final JPopupMenu popup = new JPopupMenu();
final TreePath sp = tree.getSelectionPath();
if (sp == null) return; // nothing was selected
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)sp.getLastPathComponent();
final Node item = (Node)node.getUserObject();
if (node != root) {
addToPopup(popup, "Copy key", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(item.asKeyString());
}
});
}
if (!item.isArrayOrObject()) {
final String value = item.asValueString();
addToPopup(popup, "Copy value as string", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(value);
}
});
if (mayBeJwt(value)) {
addToPopup(popup, "Convert JWT to EsPReSSO format", new ActionListener() {
public void actionPerformed(ActionEvent e) {
convertJwt(value);
}
});
}
}
addToPopup(popup, "Copy value as JSON", new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyString(item.asJsonString());
}
});
popup.show(e.getComponent(), e.getX(), e.getY());
}
private static boolean mayBeJwt(final String value) {
return JWT_RE.matcher(value).matches();
}
private void convertJwt(final String jwt) {
final java.util.List<String> headers = Arrays.asList(
"GET / HTTP/1.0",
"Content-Type: application/x-www-form-urlencoded",
"X-Message: dummy request, do not send!");
final byte[] body = helpers.stringToBytes("access_token=" + jwt);
final byte[] request = helpers.buildHttpMessage(headers, body);
callbacks.sendToRepeater("example.com", 80, false, request, "JWT");
}
private static void addToPopup(JPopupMenu pm, String title, ActionListener al) {
final JMenuItem mi = new JMenuItem(title);
mi.addActionListener(al);
pm.add(mi);
}
private void copyString(final String value) {
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(value), this);
}
public boolean isEnabled(byte[] content, boolean isRequest) {
if (content.length == 0) {
root.removeAllChildren();
model.reload(root);
return false;
}
return !parse(content, isRequest).isEmpty();
// TODO try parsing at this stage
}
private final static byte[] BOM_UTF8 = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
private final static int MIN_LEN = 2;
private void detectRawJson(Vector<Part> dest, byte[] content, int bodyOffset,
IRequestInfo req) {
final int len = content.length;
final int bodyLen = len - bodyOffset;
if (bodyLen < MIN_LEN) return;
byte[] firstThreeBytes = Arrays.copyOfRange(content,
bodyOffset, bodyOffset + BOM_UTF8.length);
if (Arrays.equals(firstThreeBytes, BOM_UTF8) &&
bodyLen > BOM_UTF8.length + MIN_LEN) bodyOffset += BOM_UTF8.length;
addIfJson(dest, bytesToString(Arrays.copyOfRange(content, bodyOffset, len)), null);
}
private final CharsetDecoder utfDecoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(
CodingErrorAction.REPORT);
private String bytesToString(byte[] source) {
try {
return utfDecoder.decode(ByteBuffer.wrap(source)).toString();
} catch (CharacterCodingException e) {
return helpers.bytesToString(source);
}
}
private void detectParamJson(Vector<Part> dest, byte[] content, int bodyOffset,
IRequestInfo req) {
if (req == null) return;
java.util.List<IParameter> params = req.getParameters();
ArrayList<Part> parts = new ArrayList<>(params.size());
for (IParameter param : params) {
String value = param.getValue();
for (final String s : new String[] {value, helpers.urlDecode(value)}) {
addIfJson(dest, s, param);
}
}
}
public interface Part {
public String decode();
}
private static void addIfJson(Vector<Part> dest, String value, IParameter param) {
if (mightBeJson(value)) {
dest.add(new Part() {
public String decode() { return value; }
@Override
public String toString() {
if (param == null) return "HTTP body";
return parameterTypeToString(param.getType()) +
" \"" + param.getName() + '"';
}
});
}
}
private static boolean mightBeJson(final String value) {
final int len = value.length();
if (len < MIN_LEN) return false;
final char firstChar = value.charAt(0);
return
((firstChar | (byte)0x20) == (byte)0x7b) && // '[' = 0x5b, '{' = 0x7b, former missing bit 0x20
(value.charAt(len - 1) == firstChar + 2); // ']' = 0x5d, '}' = 0x7d, offset is 2 for both
}
private static String parameterTypeToString(final byte type) {
switch (type) {
case IParameter.PARAM_URL: return "URL parameter";
case IParameter.PARAM_BODY: return "Body parameter";
case IParameter.PARAM_COOKIE: return "HTTP cookie";
case IParameter.PARAM_XML: return "XML element";
case IParameter.PARAM_XML_ATTR: return "XML attribute";
case IParameter.PARAM_MULTIPART_ATTR: return "MIME multipart attribute";
case IParameter.PARAM_JSON: return "JSON item";
default: return "Unknown parameter";
}
}
private Vector<Part> parse(byte[] content, boolean isRequest) {
IRequestInfo req = null;
int bodyOffset;
if (isRequest) {
req = helpers.analyzeRequest(content);
bodyOffset = req.getBodyOffset();
} else {
IResponseInfo i = helpers.analyzeResponse(content);
bodyOffset = i.getBodyOffset();
}
Vector<Part> parts = new Vector<>();
detectRawJson(parts, content, bodyOffset, req);
detectParamJson(parts, content, bodyOffset, req);
return parts;
}
public void setMessage(byte[] content, boolean isRequest) {
this.content = content;
root.removeAllChildren();
if (content != null) {
Vector<Part> parts = parse(content, isRequest);
if (parts.size() == 1) {
Json node = Json.read(parts.get(0).decode());
root.setUserObject(new Node(null, node));
if (node.isObject()) {
dumpObjectNode(root, node);
} else if (node.isArray()) {
dumpArrayNode(root, node);
}
comboBox.setVisible(false);
} else {
comboBox.setModel(new DefaultComboBoxModel<>(parts));
comboBox.setSelectedIndex(0);
comboBox.setVisible(true);
}
} else {
root.setUserObject(new Node(null, null));
}
model.reload(root);
expandAllNodes(tree, 0, tree.getRowCount());
}
private static class Node {
private final String key;
private final Json value;
Node(String key, Json value) {
this.key = key;
this.value = value;
}
public boolean isArrayOrObject() {
return value.isArray() || value.isObject();
}
public String asValueString() { return value.asString(); }
public String asJsonString() { return value.toString(); }
public String asKeyString() { return key; }
@Override
public String toString() {
if (key == null) return "(JSON root)";
if (value.isNull()) {
return key + ": null";
} else if (value.isString()) {
return key + ": \"" + value.asString() + '"';
} else if (value.isNumber() || value.isBoolean()) {
return key + ": " + value.toString();
}
return key;
}
}
private static void dumpObjectNode(DefaultMutableTreeNode dst, Json src) {
Map<String, Json> tm = new TreeMap(String.CASE_INSENSITIVE_ORDER);
tm.putAll(src.asJsonMap());
for (Map.Entry<String, Json> e : tm.entrySet()) {
processNode(dst, e.getKey(), e.getValue());
}
}
private static void dumpArrayNode(DefaultMutableTreeNode dst, Json src) {
int i = 0;
for (Json value : src.asJsonList()) {
String key = '[' + String.valueOf(i++) + ']';
processNode(dst, key, value);
}
}
private static void processNode(DefaultMutableTreeNode dst, String key, Json value) {
final DefaultMutableTreeNode node =
new DefaultMutableTreeNode(new Node(key, value));
dst.add(node);
if (value.isObject()) {
dumpObjectNode(node, value);
} else if (value.isArray()) {
dumpArrayNode(node, value);
}
}
private static void expandAllNodes(JTree tree, int startingIndex, int rowCount) {
for(int i=startingIndex;i<rowCount;++i){
tree.expandRow(i);
}
if(tree.getRowCount()!=rowCount){
expandAllNodes(tree, rowCount, tree.getRowCount());
}
}
public String getTabCaption() { return "JSON JTree"; }
public Component getUiComponent() { return panel; }
public byte[] getMessage() { return content; }
public boolean isModified() { return false; }
public byte[] getSelectedData() { return null; }
public void lostOwnership(Clipboard aClipboard, Transferable aContents) {}
}
|
package sg.edu.cs2103aug2015_w13_2j;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
public class StorageTest {
// Use the same Storage object across the tests
private Storage storage = new Storage();
@Test
public void readAndWriteTest() throws Exception {
String filename = "StorageTest.txt";
String stringToWrite = "NAME:Task one\nCOMPLETED:FALSE\nARCHIVED:FALSE\nCREATED:1443958836657\nIMPORTANT:FALSE\n\n";
stringToWrite += "NAME:Task two\nCOMPLETED:FALSE\nARCHIVED:FALSE\nCREATED:1443958836657\nIMPORTANT:FALSE\n\n";
stringToWrite += "NAME:Task three\nCOMPLETED:FALSE\nARCHIVED:FALSE\nCREATED:1443958836657\nIMPORTANT:FALSE\n\n";
storage.writeRawFile(stringToWrite, filename);
List<Task> listWritten = storage.readFile(filename);
storage.writeFile(listWritten, filename);
String stringWritten = storage.readRawFile(filename);
assertTrue(stringToWrite.equals(stringWritten));
}
@Test
public void dataFilePathTest() throws Exception {
/* Not performed by storage eventually,
* but this is to test if Java's interaction
* with file directories work as intended.
*/
// current execution directory
String dir = System.getProperty("user.dir");
System.out.println(dir);
// create (empty) data file
String dataFilePath = storage.readRawFile("DATA_FILE_PATH");
System.out.println(dataFilePath);
storage.writeRawFile("", dataFilePath);
}
@Test
public void stringEscapeTest() throws Exception {
/* StringEscapeTestInput.txt looks like this:
* > NAME:Task one" has s'trange\ncharacters
* > COMPLETED:FALSE
* > ARCHIVED:FALSE
* > CREATED:1443958836657
* > IMPORTANT:FALSE
*/
List<Task> list = storage.readFile("StringEscapeTestInput.txt");
storage.writeFile(list, "StringEscapeTestOutput.txt");
String inputContent = storage.readRawFile("StringEscapeTestInput.txt");
String outputContent = storage.readRawFile("StringEscapeTestOutput.txt");
assertTrue(inputContent.equals(outputContent));
}
}
|
package org.ccnx.ccn.test;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* Utility class to provide facilities to be used by all of
* the CCN tests, most importantly a standardized namespace for
* them to write their data into.
*
* Given a unit test class named UnitTestClass, we name all the data generated
* by that test class as
* /ccnx.org/test/UnitTestClass-TIMESTAMP
*
* for a unit test UnitTest in that class, ideally the data for that specific unit test
* will be stored under
* /ccnx.org/test/UnitTestClass-TIMESTAMP/UnitTest
*
* To use, make a static CCNTestHelper in your test class, e.g.:
*
* static CCNTestHelper testHelper = new CCNTestHelper(TestClass.class);
*
* and then in a test called TestFoo, get the name prefix to use for generated data by:
*
* ContentName dataPrefix = testHelper.getTestNamespace("TestFoo");
*
* for data shared across tests, use the class-level name prefix:
*
* ContentName sharedFileName = ContentName.fromNative(testHelper.getClassNamespace(), "shared_file.txt");
*
*/
public class CCNTestHelper {
protected static final String TEST_PREFIX_STRING = "/ccnx.org/test";
protected static ContentName TEST_PREFIX;
ContentName _testNamespace;
String _testName;
CCNTime _testTime;
static {
try {
TEST_PREFIX = ContentName.fromNative(TEST_PREFIX_STRING);
} catch (MalformedContentNameStringException e) {
Log.warning("Cannot parse default test namespace name {1}!", TEST_PREFIX_STRING);
throw new RuntimeException("Cannot parse default test namespace name: " + TEST_PREFIX_STRING +".");
}
}
protected ContentName testPrefix() { return TEST_PREFIX; }
/**
* Create a test helper for a named unit test class.
* @param testClassName The class name, if the package is included it will be stripped.
*/
public CCNTestHelper(String testClassName) {
_testName = testClassName;
if (_testName.contains(".")) {
_testName = testClassName.substring(testClassName.lastIndexOf(".") + 1);
}
_testTime = new CCNTime();
_testNamespace = ContentName.fromNative(testPrefix(), _testName + "-" + _testTime.toShortString());
Log.info("Initializing test {0}, data can be found under {1}.", testClassName, _testNamespace);
}
/**
* Create a test helper for a specified unit test class.
* @param unitTestClass The class containing the unit tests.
*/
public CCNTestHelper(Class<?> unitTestClass) {
this(unitTestClass.getName().toString());
}
/**
* Retrieve the timestamped, top-level name for data generated by this set of test cases.
* @return the name prefix to use for data shared across this set of unit tests.
*/
public ContentName getClassNamespace() { return _testNamespace; }
/**
* Helper method to build child names for the class under test.
*/
public ContentName getClassChildName(String childName) {
return ContentName.fromNative(_testNamespace, childName);
}
/**
* Retrieve a name for data for a specific test.
* @param testName the name of the test method, as a string
* @return the name prefix to use for data generated by that test
*/
public ContentName getTestNamespace(String testName) {
return ContentName.fromNative(_testNamespace, testName); }
/**
* Helper method to build child names for a specific test.
*/
public ContentName getTestChildName(String testName, String childName) {
return ContentName.fromNative(_testNamespace, new String[]{testName, childName});
}
/**
* Get the timestamp used for this test run. All data is gathered under the same timestamp.
* @return the timestamp
*/
public CCNTime getTestTime() { return _testTime; }
}
|
package com.redpois0n.panels;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.LayoutStyle.ComponentPlacement;
import com.redpois0n.Util;
import com.redpois0n.crypto.Crypto;
@SuppressWarnings("serial")
public class Panel3Encryption extends PanelBase {
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField cbKey;
private JRadioButton rdbtnEncryptResourcesAnd;
private JRadioButton rdbtnEncryptClassesresources;
private JCheckBox chckbxDefaultKey;
public Panel3Encryption() {
super("Encryption");
rdbtnEncryptClassesresources = new JRadioButton("Encrypt classes (Resources will be in .jar)");
buttonGroup.add(rdbtnEncryptClassesresources);
rdbtnEncryptClassesresources.setSelected(true);
rdbtnEncryptResourcesAnd = new JRadioButton("Encrypt resources and classes");
buttonGroup.add(rdbtnEncryptResourcesAnd);
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
JLabel lblEncryptionKey = new JLabel("Encryption key");
cbKey = new JTextField();
cbKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
update();
}
});
cbKey.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent arg0) {
update();
}
});
cbKey.setEditable(true);
cbKey.setText(Util.randomString(Crypto.KEY_LENGTH));
chckbxDefaultKey = new JCheckBox("Default key");
chckbxDefaultKey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cbKey.setEnabled(!chckbxDefaultKey.isSelected());
}
});
JToolBar toolBar_1 = new JToolBar();
toolBar_1.setFloatable(false);
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(30)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(rdbtnEncryptClassesresources)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblEncryptionKey)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(chckbxDefaultKey)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(toolBar_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(rdbtnEncryptResourcesAnd, Alignment.LEADING))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(toolBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(cbKey, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE))))
.addContainerGap(191, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(18)
.addComponent(rdbtnEncryptClassesresources)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(rdbtnEncryptResourcesAnd)
.addComponent(toolBar, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblEncryptionKey)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(cbKey, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(toolBar_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(chckbxDefaultKey, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(26, Short.MAX_VALUE))
);
JButton button_2 = new JButton("");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cbKey.setText(Util.randomString(Crypto.KEY_LENGTH));
update();
}
});
button_2.setIcon(new ImageIcon(Panel3Encryption.class.getResource("/com/redpois0n/icons/update.png")));
button_2.setToolTipText("Random");
toolBar_1.add(button_2);
JButton button = new JButton("");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "If you are encrypting ALL resources, the encrypted program\n" +
"cant access Class.getResource() because you cant get an URL from a object in memory that is not written to disk.\n\n" +
"Only do this if the program does not use that method", "jCrypt", JOptionPane.WARNING_MESSAGE);
}
});
button.setIcon(new ImageIcon(Panel3Encryption.class.getResource("/com/redpois0n/icons/exclamation-circle-frame.png")));
toolBar.add(button);
setLayout(groupLayout);
update();
}
public String getKey() {
return chckbxDefaultKey.isSelected() ? null : cbKey.getText().trim();
}
public boolean shouldEncryptAll() {
return rdbtnEncryptResourcesAnd.isSelected();
}
public void update() {
String text = cbKey.getText();
if (text.length() == Crypto.KEY_LENGTH) {
cbKey.setBackground(Color.green);
} else {
cbKey.setBackground(Color.red);
}
}
}
|
package net.katsuster.strview.util;
/**
* <p>
*
* </p>
*/
public interface Named {
/**
* <p>
*
* </p>
*
* <p>
* Class.getCanonicalName()
*
* </p>
*
* @return
*/
public String getTypeName();
/**
* <p>
*
* </p>
*
* @return
*/
public String getName();
/**
* <p>
*
* </p>
*
* @param n
*/
public void setName(String n);
}
|
package net.time4j;
import net.time4j.base.MathUtils;
import net.time4j.engine.Normalizer;
import net.time4j.engine.TimePoint;
import net.time4j.engine.TimeSpan;
/**
* <p>Represents the most common time units on an ISO-8601-conforming
* analogue clock counting the scale ticks. </p>
*
* @author Meno Hochschild
*/
/*[deutsch]
* <p>Repräsentiert die meistgebrächlichen Zeiteinheiten einer
* ISO-konformen Uhrzeit, entsprechend den Skalenstrichen auf einer
* analogen Uhr. </p>
*
* @author Meno Hochschild
*/
public enum ClockUnit
implements IsoTimeUnit {
/** Time unit "hours" (symbol H) */
/*[deutsch] Zeiteinheit "Stunden" (Symbol H) */
HOURS() {
@Override
public char getSymbol() {
return 'H';
}
@Override
public double getLength() {
return 3600.0;
}
},
/** Time unit "minutes" (symbol M) */
/*[deutsch] Zeiteinheit "Minuten" (Symbol M) */
MINUTES() {
@Override
public char getSymbol() {
return 'M';
}
@Override
public double getLength() {
return 60.0;
}
},
/**
* <p>Time unit "seconds" (symbol S) according to the
* position of the second pointer on an analogue clock. </p>
*
* <p>This unit is NOT the SI-second. </p>
*
* @see SI
*/
/*[deutsch]
* <p>Zeiteinheit "Sekunden" (Symbol S) entsprechend der
* Stellung des Sekundenzeigers auf einer analogen Uhr. </p>
*
* <p>Diese Zeiteinheit ist nicht die SI-Sekunde. </p>
*
* @see SI
*/
SECONDS() {
@Override
public char getSymbol() {
return 'S';
}
@Override
public double getLength() {
return 1.0;
}
},
/** Time unit "milliseconds" (symbol 3) */
/*[deutsch] Zeiteinheit "Millisekunden" (Symbol 3) */
MILLIS() {
@Override
public char getSymbol() {
return '3';
}
@Override
public double getLength() {
return 1.0 / 1_000;
}
},
/** Time unit "microseconds" (symbol 6) */
/*[deutsch] Zeiteinheit "Mikrosekunden" (Symbol 6) */
MICROS() {
@Override
public char getSymbol() {
return '6';
}
@Override
public double getLength() {
return 1.0 / 1_000_000;
}
},
/** Time unit "nanoseconds" (symbol 9) */
/*[deutsch] Zeiteinheit "Nanosekunden" (Symbol 9) */
NANOS() {
@Override
public char getSymbol() {
return '9';
}
@Override
public double getLength() {
return 1.0 / 1_000_000_000;
}
};
// Standard-Umrechnungsfaktoren
private static final long[] FACTORS = {
1L, 60L, 3_600L, 3_600_000L, 3_600_000_000L, 3_600_000_000_000L
};
/**
* <p>Calculates the temporal distance between given wall times
* in this unit. </p>
*
* @param <T> generic type of time point
* @param start starting time
* @param end ending time
* @return duration as count of this unit
*/
/*[deutsch]
* <p>Ermittelt den zeitlichen Abstand zwischen den angegebenen
* Zeitangaben gemessen in dieser Einheit. </p>
*
* @param <T> generic type of time point
* @param start starting time
* @param end ending time
* @return duration as count of this unit
*/
public <T extends TimePoint<? super ClockUnit, T>> long between(
T start,
T end
) {
return start.until(end, this);
}
/**
* <p>Converts the given duration to a temporal amount measured in
* this unit. </p>
*
* <p>Conversions from more precise to less precise units are usually
* associated with a loss of information. For example the conversion
* of <tt>999</tt> milliseconds results to <tt>0</tt> seconds. In reverse,
* the conversion of less precise to more precise units can result in
* a numerical overflow. </p>
*
* <p>Example: In order to convert 44 minutes to milliseconds, the
* expression {@code ClockUnit.MILLIS.convert(44L, ClockUnit.MINUTES)}
* is applied. Note: If hours or minutes are to be converted then
* UTC-leapseconds will be ignored that is a minute has here always
* 60 seconds. </p>
*
* @param sourceDuration amount of duration to be converted
* @param sourceUnit time unit of duration to be converted
* @return converted duration expressed in this unit
* @throws ArithmeticException in case of long overflow
*/
/*[deutsch]
* <p>Konvertiert die angegebene Zeitdauer in einen Betrag gezählt
* in dieser Zeiteinheit. </p>
*
* <p>Konversionen von genaueren zu weniger genauen Zeiteinheiten
* führen im allgemeinen zu Verlusten an Information. Zum Beispiel
* wird die Konversion von <tt>999</tt> Millisekunden <tt>0</tt> Sekunden
* ergeben. Umgekehrt kann die Konversion von groben zu feinen Einheiten
* zu einem Überlauf führen. </p>
*
* <p>Beispiel: Um 44 Minuten zu Millisekunden zu konvertieren, wird der
* Ausdruck {@code ClockUnit.MILLIS.convert(44L, ClockUnit.MINUTES)}
* angewandt. Zu beachten: Sind auch Minuten und Stunden zu konvertieren,
* dann werden UTC-Schaltsekunden nicht berücksichtigt, d.h., eine
* Minute hat hier immer genau 60 Sekunden. </p>
*
* @param sourceDuration amount of duration to be converted
* @param sourceUnit time unit of duration to be converted
* @return converted duration expressed in this unit
* @throws ArithmeticException in case of long overflow
*/
public long convert(
long sourceDuration,
ClockUnit sourceUnit
) {
if (sourceDuration == 0) {
return 0L;
}
int o1 = this.ordinal();
int o2 = sourceUnit.ordinal();
if (o1 == o2) {
return sourceDuration;
} else if (o1 > o2) {
return MathUtils.safeMultiply(
sourceDuration,
FACTORS[o1] / FACTORS[o2]
);
} else {
long factor = FACTORS[o2] / FACTORS[o1];
return (sourceDuration / factor); // possible truncation
}
}
/**
* <p>Converts the given duration to an amount in this unit and performs
* any necessary truncation if needed. </p>
*
* @param duration temporal amount in clock units to be converted
* @return count of this unit representing given duration
* @since 1.2
*/
/*[deutsch]
* <p>Konvertiert die angegebene Dauer zu einer Anzahl von Zeiteinheiten
* dieser Instanz und rundet bei Bedarf. </p>
*
* @param duration temporal amount in clock units to be converted
* @return count of this unit representing given duration
* @since 1.2
*/
public long convert(TimeSpan<? extends ClockUnit> duration) {
if (duration.isEmpty()) {
return 0;
}
long total = 0;
ClockUnit smallest = null;
for (int i = duration.getTotalLength().size() - 1; i >= 0; i
TimeSpan.Item<? extends ClockUnit> item =
duration.getTotalLength().get(i);
ClockUnit unit = item.getUnit();
if (smallest == null) {
smallest = unit;
total = item.getAmount();
} else {
total =
MathUtils.safeAdd(
total,
smallest.convert(item.getAmount(), unit));
}
}
if (duration.isNegative()) {
total = MathUtils.safeNegate(total);
}
return this.convert(total, smallest); // possibly lossy
}
/**
* <p>Yields a normalizer which converts a given duration in another
* duration with only this clock unit. </p>
*
* @return normalizer
* @since 1.2
* @see #convert(TimeSpan)
*/
/*[deutsch]
* <p>Liefert einen Normalisierer, der eine Dauer in eine andere Dauer nur mit dieser
* Zeiteinheit konvertiert. </p>
*
* @return normalizer
* @since 1.2
* @see #convert(TimeSpan)
*/
public Normalizer<ClockUnit> only() {
return ClockNormalizer.ofOnlyMode(this);
}
/**
* <p>Yields a normalizer which converts a given duration in another
* duration with smaller units truncated. </p>
*
* @return normalizer
* @since 3.0
*/
/*[deutsch]
* <p>Liefert einen Normalisierer, der eine Dauer in eine andere Dauer so
* konvertiert, daß Dauerelemente mit kleineren Zeiteinheiten
* abgeschnitten werden. </p>
*
* @return normalizer
* @since 3.0
*/
public Normalizer<ClockUnit> truncated() {
return ClockNormalizer.ofTruncateMode(this);
}
/**
* <p>Yields a normalizer which converts a given duration in another
* normalized duration with smaller units truncated and this unit rounded. </p>
*
* <p>This normalizer is a combination of {@code Duration.STD_CLOCK_PERIOD},
* {@code truncated()} and a special half-up rounding. Example: </p>
*
* <pre>
* Duration<ClockUnit> timePeriod = Duration.ofClockUnits(4, 55, 90);
* System.out.println(timePeriod.with(ClockUnit.MINUTES.rounded()));
* // output: P4H57M
* </pre>
*
* @return normalizer
* @since 3.0
* @see Duration#STD_CLOCK_PERIOD
*/
/*[deutsch]
* <p>Liefert einen Normalisierer, der eine Dauer in eine andere normalisierte Dauer so
* konvertiert, daß Dauerelemente mit kleineren Zeiteinheiten abgeschnitten werden
* und diese Zeiteinheit gerundet wird. </p>
*
* <p>Dieser Normalisierer ist eine Kombination aus {@code Duration.STD_CLOCK_PERIOD},
* {@code truncated()} und einer kaufmännischen Rundung. Beispiel: </p>
*
* <pre>
* Duration<ClockUnit> timePeriod = Duration.ofClockUnits(4, 55, 90);
* System.out.println(timePeriod.with(ClockUnit.MINUTES.rounded()));
* // Ausgabe: P4H57M
* </pre>
*
* @return normalizer
* @since 3.0
* @see Duration#STD_CLOCK_PERIOD
*/
public Normalizer<ClockUnit> rounded() {
return ClockNormalizer.ofRoundingMode(this);
}
/**
* <p>A wall time unit is never calendrical. </p>
*
* @return {@code false}
*/
/*[deutsch]
* <p>Eine Uhrzeiteinheit ist nicht kalendarisch. </p>
*
* @return {@code false}
*/
@Override
public boolean isCalendrical() {
return false;
}
}
|
package com.github.nsnjson;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.*;
import org.junit.*;
public class DriverTest extends AbstractFormatTest {
@Test
public void processTestNull() {
shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation());
}
@Test
public void processTestNumberInt() {
NumericNode value = getNumberInt();
shouldBeConsistencyWhenGivenNumber(value, getNumberIntPresentation(value));
}
@Test
public void processTestNumberLong() {
NumericNode value = getNumberLong();
shouldBeConsistencyWhenGivenNumber(value, getNumberLongPresentation(value));
}
@Test
public void processTestNumberDouble() {
NumericNode value = getNumberDouble();
shouldBeConsistencyWhenGivenNumber(value, getNumberDoublePresentation(value));
}
@Test
public void processTestEmptyString() {
TextNode value = getEmptyString();
shouldBeConsistencyWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestString() {
TextNode value = getString();
shouldBeConsistencyWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestBooleanTrue() {
BooleanNode value = getBooleanTrue();
shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestBooleanFalse() {
BooleanNode value = getBooleanFalse();
shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestEmptyArray() {
shouldBeConsistencyWhenGivenArray(getEmptyArray(), getEmptyArrayPresentation());
}
@Test
public void processTestArray() {
ArrayNode array = getArray();
shouldBeConsistencyWhenGivenArray(array, getArrayPresentation(array));
}
@Test
public void processTestEmptyObject() {
shouldBeConsistencyWhenGivenObject(getEmptyObject(), getEmptyObjectPresentation());
}
@Test
public void processObject() {
ObjectNode object = getObject();
shouldBeConsistencyWhenGivenObject(object, getObjectPresentation(object));
}
private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenString(TextNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenBoolean(BooleanNode value, ObjectNode presentation) {
assertConsistency(value, presentation);
}
private void shouldBeConsistencyWhenGivenArray(ArrayNode array, ObjectNode presentation) {
assertConsistency(array, presentation);
}
private void shouldBeConsistencyWhenGivenObject(ObjectNode object, ObjectNode presentation) {
assertConsistency(object, presentation);
}
private static void assertConsistency(JsonNode value, ObjectNode presentation) {
assertConsistencyByEncoding(value);
assertConsistencyByDecoding(presentation);
}
private static void assertConsistencyByEncoding(JsonNode value) {
Assert.assertEquals(value, Driver.decode(Driver.encode(value)));
}
private static void assertConsistencyByDecoding(ObjectNode presentation) {
Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation)));
}
}
|
package com.rabriel.gwt;
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.rabriel.gwt.GivenWhenThen.given;
import static junit.framework.TestCase.assertEquals;
public class HappyFlowTest {
@Test
public void testPassedValueisMatchedGivenWhen(){
int passedIntValue = 22;
String passedStringValue = "Test Value";
given(passedIntValue).when("testing passed int value in 'when'",
receivedValue -> { assertEquals("given passed int value should match when received value",
passedIntValue, (int) receivedValue); return true; });
given(passedStringValue).when("testing passed string value in 'when'",
receivedValue -> { assertEquals("given passed string value should match when received value",
passedStringValue, receivedValue); return true; });
}
@Test
public void testPassedValueIsMatchedWhenThen(){
String whenValue = "Test Value";
given(null)
.when(whenReceivedValue -> whenValue)
.then("testing passed string value in 'then'",thenReceivedValue ->
{ assertEquals("when passed value should match then received value",whenValue, thenReceivedValue); });
}
@Test
public void basicFlowTest(){
given(1)
.when("multiplying by 2", givenValue -> 2*givenValue)
.then("value should be even", whenValue -> whenValue%2 == 0);
}
@Test
public void multiTypeFlowTest(){
LocalDateTime localDateTime = LocalDateTime.now();
DayOfWeek expectedDay = localDateTime.getDayOfWeek();
given(localDateTime)
.when("retrieving current day", date -> date.getDayOfWeek())
.then("days should match", day -> expectedDay == day);
}
@Test
public void assertFlowTest(){
Integer primeNumber = 17;
given(primeNumber)
.when("finding dividers naively", number -> IntStream.range(1, number+1)
.boxed().filter(value -> number%value == 0).collect(Collectors.toList()))
.then("days should match", dividers -> {
assertEquals("should have two dividers", 2, dividers.size());
assertEquals("first divider should be 1", 1, (int) dividers.get(0));
assertEquals(String.format("first divider should be %d", primeNumber), primeNumber, dividers.get(1));
});
}
}
|
package com.sixtyfour.test;
import com.sixtyfour.cbmnative.TermHelper;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.elements.Variable;
import com.sixtyfour.elements.commands.Command;
import com.sixtyfour.elements.functions.Function;
import com.sixtyfour.parser.Line;
import com.sixtyfour.parser.Parser;
import com.sixtyfour.parser.Term;
import com.sixtyfour.parser.TermEnhancer;
import com.sixtyfour.system.Machine;
/**
* Basic tests for the parser.
*/
public class ParserTest {
private static CompilerConfig config = new CompilerConfig();
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
testArrayAccess();
testLineNumber();
testCommands();
testTermCompletion();
testTermCreation();
testComplexFunctions();
testLogic();
testPowerOf();
testAbs();
testStuff();
testConstants();
testAnd();
testAnd2();
testMinusPower();
testSin();
testNumberExt1();
testBrackets();
testLogicBrackets();
testSimilarity();
testNot();
testMidStrAnd();
}
private static void testMidStrAnd() {
System.out.println("testMidStrAnd");
Machine machine = new Machine();
String term = "mid$(str$(cand15),2)";
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
term = "a$=\"\" and peek(56320)=127>2";
s = TermEnhancer.addBrackets(term);
System.out.println(s);
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
term = "a$(cand15, sin(cand15))=\"\" and peek(56320)=127";
s = TermEnhancer.addBrackets(term);
System.out.println(s);
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
term = "str$(cand15)=\"\" and peek(56320)=127";
s = TermEnhancer.addBrackets(term);
System.out.println(s);
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
term = "mid$(a$,c and 15, b(2,3) and 3)";
s = TermEnhancer.addBrackets(term);
System.out.println(s);
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
}
private static void testNot() {
System.out.println("testNot");
Machine machine = new Machine();
String term = "not(i>5 or i<12)";
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
}
private static void testSimilarity() {
System.out.println("testSimilarity");
Machine machine = new Machine();
String term = "A/B";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("lin: " + TermHelper.linearize(res.getInitial(), true));
term = "INT(A/B)";
wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res1 = Parser.getTerm(config, term, machine, false, true);
Term res2 = Parser.getTerm(config, term, machine, false, true);
System.out.println(res1);
System.out.println(res2);
System.out.println("lin1: " + TermHelper.linearize(res1.getInitial(), true));
System.out.println("lin2: " + TermHelper.linearize(res2.getInitial(), true));
System.out.println("res1==res1: " + res1.equals(res1));
System.out.println("res1==res2: " + res1.equals(res2));
System.out.println("res==res1: " + res.equals(res1));
System.out.println("res2==res: " + res2.equals(res));
term = "RND(0)";
wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
res1 = Parser.getTerm(config, term, machine, false, true);
res2 = Parser.getTerm(config, term, machine, false, true);
System.out.println(res1);
System.out.println(res2);
System.out.println("lin1: " + TermHelper.linearize(res1.getInitial(), true));
System.out.println("lin2: " + TermHelper.linearize(res2.getInitial(), true));
System.out.println("res1==res1: " + res1.equals(res1));
System.out.println("res1==res2: " + res1.equals(res2));
System.out.println("res==res1: " + res.equals(res1));
System.out.println("res2==res: " + res2.equals(res));
term = "INT(A/B+5+SIN(8))";
wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
res1 = Parser.getTerm(config, term, machine, false, true);
res2 = Parser.getTerm(config, term, machine, false, true);
System.out.println(res1);
System.out.println(res2);
System.out.println("lin1: " + TermHelper.linearize(res1.getInitial(), true));
System.out.println("lin2: " + TermHelper.linearize(res2.getInitial(), true));
System.out.println("res1==res1: " + res1.equals(res1));
System.out.println("res1==res2: " + res1.equals(res2));
System.out.println("res==res1: " + res.equals(res1));
System.out.println("res2==res: " + res2.equals(res));
term = "A/B+5+SIN(8)";
wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
res1 = Parser.getTerm(config, term, machine, false, true);
System.out.println(res2);
res2 = ((Function) res2.getLeft()).getTerm();
System.out.println(res1);
System.out.println(res2);
System.out.println("lin1: " + TermHelper.linearize(res1.getInitial(), true));
System.out.println("lin2: " + TermHelper.linearize(res2.getInitial(), true));
System.out.println("res1==res1: " + res1.equals(res1));
System.out.println("res1==res2: " + res1.equals(res2));
System.out.println("res==res1: " + res.equals(res1));
System.out.println("res2==res: " + res2.equals(res));
}
private static void testLogicBrackets() {
System.out.println("testLogicBrackets");
String term = "u or 4 +56-23 or z=160 or l>1 and l<10 and z(2,3*4)=32";
System.out.println("Before: " + term);
String s = TermEnhancer.addBrackets(term);
System.out.println("After:" + s);
}
private static void testBrackets() {
System.out.println("testBrackets");
String term = "646,(bg&15)*16+(fg&15)";
System.out.println("Before: " + term);
String s = TermEnhancer.addBrackets(term);
System.out.println("After:" + s);
}
private static void testNumberExt1() {
System.out.println("testNumberExt1");
Machine machine = new Machine();
String term = "$252525+%1010110";
config.setNonDecimalNumbersAware(true);
System.out.println("Before: " + term);
term = TermEnhancer.handleNonDecimalNumbers(config, term);
System.out.println("After: " + term);
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(t.eval(machine));
}
private static void testSin() {
System.out.println("testSin");
Machine machine = new Machine();
String term = "sin(23)--23";
// String term = "sin(23) blah";
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(t.eval(machine));
}
private static void testConstants() {
System.out.println("testConstants");
Machine machine = new Machine();
String term = "(int(int(4.4+5*2.2)+5.6)) and (8+4)";
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(t.eval(machine));
}
private static void testMinusPower() {
System.out.println("testMinusPower");
String term = "2+-(32-30)^10";
String s = TermEnhancer.addBrackets(term);
System.out.println(s);
Machine machine = new Machine();
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(t.eval(machine));
term = "2*-3^2e1";
// term="2*-3/3*+2^2";
// term="(2*-(1*(2^2)))";
s = TermEnhancer.addBrackets(term);
System.out.println(s);
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(t.eval(machine));
}
private static void testArrayAccess() {
System.out.println("testArrayAccess");
String term = "10*b(1,1)";
Machine machine = new Machine();
Term t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(TermEnhancer.addBrackets(term));
System.out.println();
term = "10+b(1,1)";
t = Parser.getTerm(config, term, machine, false, true);
System.out.println(t);
System.out.println(TermEnhancer.addBrackets(term));
System.out.println();
term = "a=a*2+4+b(1,1)";
t = Parser.getTerm(config, term, machine, true, true);
System.out.println(t);
System.out.println(t.getOperator());
System.out.println(t.eval(machine));
System.out.println(TermEnhancer.addBrackets(term));
}
/**
* Test stuff.
*/
private static void testAnd() {
System.out.println("testAnd");
Machine machine = new Machine();
machine.add(new Variable("A", 23));
machine.add(new Variable("B", 41));
String term = "(a>68andb)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
private static void testAnd2() {
System.out.println("testAnd2");
Machine machine = new Machine();
machine.add(new Variable("A", 124));
machine.add(new Variable("B", 3));
String term = "(aand255-bor255+2*b)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println("Added brackets: " + wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
private static void testStuff() {
System.out.println("testStuff");
Machine machine = new Machine();
machine.add(new Variable("A", 23));
machine.add(new Variable("B", 41));
machine.add(new Variable("D", 123));
machine.add(new Variable("F", 141));
machine.add(new Variable("G", 3));
machine.add(new Variable("Z", 1));
machine.add(new Variable("T", 11));
machine.add(new Variable("R", 21));
machine.add(new Variable("P", 55));
machine.add(new Variable("U", 22));
machine.add(new Variable("O", 45));
machine.add(new Variable("I", 67));
String term = "a * b * (-c*f+(t*r+-f*(g-z)-f*g/z^4)) + abs(-(d*u))*(p+(o*i*z))*z+u";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
float a = 23;
float b = 41;
float c = 0;
float d = 123;
float f = 141;
float g = 3;
float z = 1;
float t = 11;
float r = 21;
float p = 55;
float u = 22;
float o = 45;
float i = 67;
double rr = a * b * (-c * f + (t * r + -f * (g - z) - f * g / Math.pow(z, 4)))
+ Math.abs(-(d * u)) * (p + (o * i * z)) * z + u;
System.out.println("Real result: " + rr);
}
/**
* Test abs.
*/
private static void testAbs() {
System.out.println("testAbs");
Machine machine = new Machine();
machine.add(new Variable("Z", 23));
machine.add(new Variable("P", 41));
String term = "(ABS(Z-P)-2)*(ABS(Z-P)-18)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
/**
* Test power of.
*/
private static void testPowerOf() {
System.out.println("testPowerOf");
Machine machine = new Machine();
machine.add(new Variable("X1", 122));
machine.add(new Variable("X", 100));
machine.add(new Variable("Y", 113));
machine.add(new Variable("X1", 110));
machine.add(new Variable("Y", 214));
machine.add(new Variable("Y1", 210));
// String term="((x1-x)^2+(y1-y)^2+(z1-z)^2)";
String term = "((x1-x)^2+(y1-y)^2+(z1-z)^2)^(1/2)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
/**
* Test logic.
*/
private static void testLogic() {
System.out.println("testLogic");
Machine machine = new Machine();
machine.add(new Variable("A%", 5));
machine.add(new Variable("B%", 32));
String term = "NOT 1 OR NOT (110+10)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
/**
* Test complex functions.
*/
private static void testComplexFunctions() {
System.out.println("testComplexFunctions");
Machine machine = new Machine();
machine.add(new Variable("A$", "abcdefghijklmnopqrstuvwxyz"));
machine.add(new Variable("B$", "test"));
machine.add(new Variable("A", 1));
String term = "\"hallo\"+\" \"+mid$(A$+a$,1*5+3*5,13)+\" \"+mid$(\"1234567\", 3)+\" \"+mid$(B$+\"hallo\", 1+1+(1*1), 5)+\" \"+mid$(B$+\"hallo\", 1+2+(1*1)-a)";
String wbres = TermEnhancer.addBrackets(term);
System.out.println(wbres);
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
}
/**
* Test term creation.
*/
private static void testTermCreation() {
System.out.println("testTermCreation");
Machine machine = new Machine();
machine.add(new Variable("A", 5));
machine.add(new Variable("B", 5.6f));
machine.add(new Variable("C", 14));
machine.add(new Variable("Z", 12));
machine.add(new Variable("U", 1.4));
machine.add(new Variable("K", -2));
machine.add(new Variable("D", 3));
machine.add(new Variable("I", 4.1234));
String term = "(a^z * (b + c / (z+-sin(u+z*k))) * d)/cos(i) + cos(-88)";
// String term="sin(-1)";
Term res = Parser.getTerm(config, term, machine, false, true);
System.out.println(res);
System.out.println("Value: " + res.eval(machine));
System.out.println(((5f * ((5.6f + (14f / (12f + (-1f * Math.sin((1.4f + (12f * -2f))))))) * 3f))
/ (Math.cos((4.1234f)) + Math.cos(88f))));
// term =
// "a * b * (-c*f+(t*r+-f*(g-z)-f*g/z^4)) + -(d*u)*(p+(o*i*z))*z+u";
// res = Lexer.getTerm(term, memory);
// System.out.println(res);
}
/**
* Test term completion.
*/
private static void testTermCompletion() {
System.out.println("testTermCompletion");
String term = "a ++++++ b + c *
String res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * b + c * d * -2";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "f-18*a * b * -c + d";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * b * c * d";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * b * -c + -d";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a + b - c + d^e*r";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * b * (-c*f+(t*r+-f*(g-z)-f*g/z^4)) + -(d*u)*(p+(o*i*z))*z+u";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a + (b + c / (z+u))";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * (b + c / (z+-u))";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "a * (b + c / (z+-sin(u+z*k))) * d/cos(i) + (cos(88)+(a*(-b)))";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "\"ha a*b*c+d llo \"+\"welt!\"";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
term = "+++++++\"ha a*b*c+d llo \"+++++++\"welt!\"";
res = TermEnhancer.addBrackets(term);
System.out.println(term + " is actually " + res);
}
/**
* Test commands.
*/
private static void testCommands() {
System.out.println("testCommands");
String test = getSimpleLine();
Command com = Parser.getCommand(Line.getLine(test).getLine());
System.out.println("Command is: " + com);
}
/**
* Test line number.
*/
private static void testLineNumber() {
System.out.println("testLineNumber");
String test = getSimpleLine();
Line line = Line.getLine(test);
System.out.println("Line number is: " + line.getNumber());
test = test.replace(" ", "").replace("10", "65500");
line = Line.getLine(test);
System.out.println("Line number is: " + line.getNumber());
}
/**
* Gets the simple line.
*
* @return the simple line
*/
private static String getSimpleLine() {
return "10 PRINT\"Hello World\"";
}
}
|
package de.teiesti.postie;
import org.junit.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class PostmanTest {
private static Postman alice;
private static Postman bob;
@BeforeClass
public static void setup() {
Thread createAlice = new Thread() {
@Override
public void run() {
try {
Socket aliceSocket = new ServerSocket(2804).accept();
alice = new Postman(aliceSocket, Integer.class);
} catch (IOException e) {
e.printStackTrace();
fail("could not create alice");
}
}
};
createAlice.start();
try {
Socket bobSocket = new Socket(InetAddress.getLocalHost(), 2804);
bob = new Postman(bobSocket, Integer.class);
} catch (IOException e) {
e.printStackTrace();
fail("could not create bob");
}
try {
createAlice.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test(timeout = 500)
public void simplexSendTest() {
bob.send(42);
assertThat((Integer) alice.receive(), is(42));
}
@Test(timeout=500)
public void halfDuplexSendTest() {
bob.send(1234);
assertThat((Integer) alice.receive(), is(1234));
alice.send(4321);
assertThat((Integer) bob.receive(), is(4321));
}
@Test(timeout = 500)
public void fullDuplexSendTest() {
bob.send(1);
alice.send(2);
assertThat((Integer) bob.receive(), is(2));
assertThat((Integer) alice.receive(), is(1));
}
@Test(timeout = 500)
public void multiSendTest() {
for (int i = 0 ; i < 1024; i++)
bob.send(i);
for (int i = 0; i < 1024; i++)
assertThat((Integer) alice.receive(), is(i));
}
@AfterClass
public static void cleanup() throws Exception {
alice.close();
bob.close();
}
}
|
package io.bitsquare.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
// TODO route over tor
public class HttpClient {
private final String baseUrl;
public HttpClient(String baseUrl) {
this.baseUrl = baseUrl;
}
public String requestWithGET(String param) throws IOException, HttpException {
HttpURLConnection connection = null;
try {
URL url = new URL(baseUrl + param);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10_000);
connection.setReadTimeout(10_000);
if (connection.getResponseCode() == 200) {
return convertInputStreamToString(connection.getInputStream());
} else {
String error = convertInputStreamToString(connection.getErrorStream());
connection.getErrorStream().close();
throw new HttpException(error);
}
} finally {
if (connection != null)
connection.getInputStream().close();
}
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
@Override
public String toString() {
return "HttpClient{" +
"baseUrl='" + baseUrl + '\'' +
'}';
}
}
|
package innovimax.mixthem;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.exceptions.MixException;
import java.io.*;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.theories.*;
import org.junit.runner.RunWith;
public class GenericTest {
@Test
public final void parameter() throws MixException, FileNotFoundException, IOException {
MixThem.setLogging(Level.FINE);
int testId = 1;
boolean result = true;
RuleRuns ruleRuns = new RuleRuns();
while (true) {
MixThem.LOGGER.info("TEST N° " + testId);
String prefix = "test" + String.format("%03d", testId) +"_";
URL url1 = getClass().getResource(prefix + "file1.txt");
URL url2 = getClass().getResource(prefix + "file2.txt");
MixThem.LOGGER.fine("--> URL 1 (" + prefix + "file1.txt"+") : " + url1);
MixThem.LOGGER.fine("--> URL 2 (" + prefix + "file2.txt"+") : " + url2);
if( url1 == null || url2 == null) break;
for(Rule rule : Rule.values()) {
String resource = prefix+"output-"+ rule.getExtension()+".txt";
URL url = getClass().getResource(resource);
MixThem.LOGGER.info(" RULE " + rule + " (" + (rule.isImplemented() ? "" : "NOT ") + "IMPLEMENTED)");
MixThem.LOGGER.fine(" --> Resource (" + resource + ") : " + url);
if (rule.isImplemented() && url != null) {
List<RuleRun> runs = ruleRuns.getRuns(rule);
for (RuleRun run : runs) {
if (run.accept(testId)) {
boolean res = check(new File(url1.getFile()), new File(url2.getFile()), new File(url.getFile()), rule, run.getParams());
MixThem.LOGGER.info(" RUN " + (res ? "PASS" : "FAIL") + " WITH PARAMS " + run.getParams().toString());
result &= res;
}
}
}
}
testId++;
}
Assert.assertTrue(result);
}
private final static boolean check(File file1, File file2, File expected, Rule rule, List<String> params) throws MixException, FileNotFoundException, IOException {
ByteArrayOutputStream baos_rule = new ByteArrayOutputStream();
MixThem mixThem = new MixThem(file1, file2, baos_rule);
mixThem.process(rule, params);
//mixThem = new MixThem(file1, file2, System.out);
//mixThem.process(rule, params);
return checkFileEquals(expected, baos_rule.toByteArray());
}
private static boolean checkFileEquals(File fileExpected, byte[] result) throws FileNotFoundException, IOException {
FileInputStream fisExpected = new FileInputStream(fileExpected);
int c;
int offset = 0;
while ((c = fisExpected.read()) != -1) {
if (offset >= result.length) return false;
int d = result[offset++];
if (c != d) return false;
}
if (offset > result.length) return false;
return true;
}
}
|
package innovimax.mixthem;
import innovimax.mixthem.arguments.FileMode;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.io.InputResource;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.theories.*;
import org.junit.runner.RunWith;
public class GenericTest {
@Test
public final void testCharRules() throws MixException, FileNotFoundException, IOException, NumberFormatException {
testRules(FileMode.CHAR);
}
@Test
public final void testBytesRules() throws MixException, FileNotFoundException, IOException, NumberFormatException {
testRules(FileMode.BYTE);
}
private final void testRules(final FileMode fileMode) throws MixException, FileNotFoundException, IOException, NumberFormatException {
MixThem.setLogging(Level.FINE);
int testId = 0;
final List<String> failed = new ArrayList<String>();
final Set<Integer> locks = getTestLocks();
boolean result = true;
while (true) {
testId++;
MixThem.LOGGER.info("TEST [" + fileMode.getName().toUpperCase() + "] N° " + testId + "***********************************************************");
final String prefix = "test" + String.format("%03d", testId) +"_";
final List<URL> urlF = new ArrayList<URL>();
int index = 1;
while (true) {
final URL url = getClass().getResource(prefix + "file" + index + ".txt");
if (url != null) {
urlF.add(url);
index++;
} else {
break;
}
}
if( urlF.size() < 2) break;
if (locks.contains(Integer.valueOf(testId))) {
MixThem.LOGGER.info("Locked!!!");
continue;
}
for (int i=0; i < urlF.size(); i++) {
MixThem.LOGGER.info("File " + (i+1) + ": " + urlF.get(i));
}
for(Rule rule : Rule.values()) {
if (rule.isImplemented() && rule.acceptFileMode(fileMode)) {
String paramsFile = prefix + "params-" + rule.getExtension() + ".txt";
URL urlP = getClass().getResource(paramsFile);
List<RuleRun> runs = RuleRuns.getRuns(rule, urlP);
for (RuleRun run : runs) {
String resultFile = prefix + "output-" + rule.getExtension();
if (run.hasSuffix()) {
resultFile += "-" + run.getSuffix();
}
resultFile += ".txt";
URL urlR = getClass().getResource(resultFile);
if (urlR == null && run.hasSuffix()) {
resultFile = prefix + "output-" + rule.getExtension() + ".txt";
urlR = getClass().getResource(resultFile);
}
if (urlR != null) {
MixThem.LOGGER.info("
if (urlP != null) {
MixThem.LOGGER.info("Params file : " + urlP);
}
MixThem.LOGGER.info("Result file : " + urlR);
MixThem.LOGGER.info("
boolean res = check(urlF, urlR, fileMode, rule, run.getParams());
MixThem.LOGGER.info("Run " + (res ? "pass" : "FAIL") + " with params " + run.getParams().toString());
result &= res;
if (!res) {
failed.add(Integer.toString(testId));
}
}
}
}
}
}
MixThem.LOGGER.info("*********************************************************************");
MixThem.LOGGER.info("FAILED [" + fileMode.getName().toUpperCase() + "] TESTS : " + (failed.size() > 0 ? failed.toString() : "None"));
MixThem.LOGGER.info("LOCKED [" + fileMode.getName().toUpperCase() + "] TESTS : " + locks.toString());
MixThem.LOGGER.info("*********************************************************************");
Assert.assertTrue(result);
}
private final static boolean check(final List<URL> filesURL, final URL resultURL, final FileMode fileMode, final Rule rule, final Map<RuleParam, ParamValue> params) throws MixException, FileNotFoundException, IOException {
MixThem.LOGGER.info("Run and check result...");
final List<InputResource> inputs = new ArrayList<InputResource>();
for (URL url : filesURL) {
inputs.add(InputResource.createFile(new File(url.getFile())));
}
final ByteArrayOutputStream baos_rule = new ByteArrayOutputStream();
MixThem mixThem = new MixThem(inputs, baos_rule);
mixThem.process(fileMode, rule, params);
MixThem.LOGGER.info("Run and print result...");
mixThem = new MixThem(inputs, System.out);
mixThem.process(fileMode, rule, params);
final File result = new File(resultURL.getFile());
return checkFileEquals(result, baos_rule.toByteArray());
}
private static boolean checkFileEquals(final File fileExpected, final byte[] result) throws FileNotFoundException, IOException {
FileInputStream fisExpected = new FileInputStream(fileExpected);
int c;
int last = -1;
int offset = 0;
while ((c = fisExpected.read()) != -1) {
last = c;
if (offset >= result.length) {
offset++;
continue;
}
int d = result[offset++];
if (c != d) return false;
}
if (offset < result.length) {
// result is longer than expected
return false;
} else if (offset-1 > result.length) {
// result is smaller than expected
return false;
} else if (offset-1 == result.length && last != 10) {
// result is one char smaller than expected and last char expected isn't CR
return false;
}
return true;
}
private Set<Integer> getTestLocks() {
final Set<Integer> locks = new HashSet<Integer>();
try {
final URL url = getClass().getResource("test_locks.txt");
if (url != null) {
final File file = new File(url.getFile());
final BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);
final List<String> ids = Arrays.asList(reader.readLine().split(" "));
for (String id : ids) {
try {
locks.add(Integer.valueOf(id));
} catch (NumberFormatException ignored) {}
}
}
} catch (IOException ignored) {}
return locks;
}
}
|
package io.scif.writing;
import io.scif.config.SCIFIOConfig;
import io.scif.img.ImgIOException;
import io.scif.img.ImgOpener;
import io.scif.io.location.TestImgLocation;
import java.io.IOException;
import net.imagej.ImgPlus;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.scijava.io.location.FileLocation;
public class ICSFormatTest extends AbstractSyntheticWriterTest {
private static ImgOpener opener;
@BeforeClass
public static void createOpener() {
opener = new ImgOpener();
}
@AfterClass
public static void disposeOpener() {
opener.context().dispose();
}
public ICSFormatTest() {
super(".ics");
}
@Test
public void testWriting_uint8() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
final ImgPlus<?> sourceImg2 = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y", "C", "Time").lengths(100,
100, 3, 3).build()).get(0);
testWriting(sourceImg2);
final ImgPlus<?> sourceImg3 = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y", "Channel", "Z", "Time")
.lengths(100, 100, 3, 10, 13).build()).get(0);
testWriting(sourceImg3);
final ImgPlus<?> sourceImg4 = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y", "C", "Z", "T").lengths(100,
100, 3, 3, 3).build()).get(0);
testWriting(sourceImg4);
final ImgPlus<?> sourceImg5 = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y", "Z", "Custom").lengths(100,
100, 3, 3).build()).get(0);
testWriting(sourceImg5);
final ImgPlus<?> sourceImg6 = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint8").axes("X", "Y").lengths(100, 100).build()).get(0);
testWriting(sourceImg6);
}
@Test
public void testWriting_int8() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("int8").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testWriting_int16() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("int16").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testWriting_uint16() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint16").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testWriting_int32() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("int32").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testWriting_uint32() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("uint32").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testWriting_float() throws IOException {
final ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder().name(
"testimg").pixelType("float").axes("X", "Y", "C").lengths(100, 100, 3)
.build()).get(0);
testWriting(sourceImg);
}
@Test
public void testSuccessfulOverwrite() throws IOException {
final SCIFIOConfig config = new SCIFIOConfig().writerSetFailIfOverwriting(
false);
FileLocation overwritten = testOverwritingBehavior(config);
opener.openImgs(overwritten);
}
}
|
package io.usethesource.vallang;
import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.Stream;
import io.usethesource.vallang.impl.persistent.ValueFactory;
import io.usethesource.vallang.io.binary.message.IValueReader;
import io.usethesource.vallang.type.TypeStore;
public class Setup {
public static Iterable<? extends Object> valueFactories() {
final String propertyName = String.format("%s.%s", Setup.class.getName(), "valueFactory");
final String propertyValue = System.getProperty(propertyName, "REFERENCE,PERSISTENT");
final IValueFactory[] valueFactories =
Stream.of(propertyValue.split(",")).map(String::trim).map(ValueFactoryEnum::valueOf)
.map(ValueFactoryEnum::getInstance).toArray(IValueFactory[]::new);
return Arrays.asList(valueFactories);
}
/**
* Allocates new {@link TypeStore} environments that are used within {@link IValueReader}.
*
* Type stores are used as encapsulated namespaces for types. The supplier creates a fresh type
* store environment, to avoid name clashes when nesting types / values.
*/
public static final Supplier<TypeStore> TYPE_STORE_SUPPLIER = () -> {
TypeStore typeStore = new TypeStore();
// typeStore.declareAbstractDataType(RascalValueFactory.Type);
// typeStore.declareConstructor(RascalValueFactory.Type_Reified);
// typeStore.declareAbstractDataType(RascalValueFactory.ADTforType);
return typeStore;
};
private enum ValueFactoryEnum {
REFERENCE {
@Override
public IValueFactory getInstance() {
return io.usethesource.vallang.impl.reference.ValueFactory.getInstance();
}
},
PERSISTENT {
@Override
public IValueFactory getInstance() {
return ValueFactory.getInstance();
}
};
public abstract IValueFactory getInstance();
}
}
|
package javaslang.collection;
import static javaslang.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import javaslang.Requirements.UnsatisfiedRequirementException;
import org.junit.Test;
public class ListTest {
// -- head
@Test
public void shouldThrowWhenHeadOnEmptyList() {
assertThat(() -> EmptyList.instance().head()).isThrowing(
UnsupportedOperationException.class, "head of empty list");
}
@Test
public void shouldReturnHeadOfNonEmptyList() {
final Integer actual = List.of(1, 2, 3).head();
assertThat(actual).isEqualTo(1);
}
// -- tail
@Test
public void shouldThrowWhenTailOnEmptyList() {
assertThat(() -> EmptyList.instance().tail()).isThrowing(
UnsupportedOperationException.class, "tail of empty list");
}
@Test
public void shouldReturnTailOfNonEmptyList() {
final List<Integer> actual = List.of(1, 2, 3).tail();
final List<Integer> expected = List.of(2, 3);
assertThat(actual).isEqualTo(expected);
}
// -- isEmpty
@Test
public void shouldRecognizeEmptyList() {
assertThat(List.empty().isEmpty()).isTrue();
}
@Test
public void shouldRecognizeNonEmptyList() {
assertThat(List.of(1).isEmpty()).isFalse();
}
// -- reverse
@Test
public void shouldReverseEmptyList() {
assertThat(List.empty().reverse()).isEqualTo(List.empty());
}
@Test
public void shouldReverseNonEmptyList() {
assertThat(List.of(1, 2, 3).reverse()).isEqualTo(List.of(3, 2, 1));
}
// -- size
@Test
public void shouldComputeSizeOfEmptyList() {
assertThat(List.empty().size()).isEqualTo(0);
}
@Test
public void shouldComputeSizeOfNonEmptyList() {
assertThat(List.of(1, 2, 3).size()).isEqualTo(3);
}
// -- append
@Test
public void shouldAppendElementToEmptyList() {
final List<Integer> actual = List.<Integer> empty().append(1);
final List<Integer> expected = List.of(1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendElementToNonEmptyList() {
final List<Integer> actual = List.of(1).append(2);
final List<Integer> expected = List.of(1, 2);
assertThat(actual).isEqualTo(expected);
}
// -- appendAll
@Test
public void shouldThrowOnAppendAllOfNull() {
assertThat(() -> List.empty().appendAll(null)).isThrowing(
UnsatisfiedRequirementException.class, "elements is null");
}
@Test
public void shouldAppendAllEmptyListToEmptyList() {
final List<Object> actual = List.empty().appendAll(List.empty());
final List<Object> expected = List.empty();
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendAllNonEmptyListToEmptyList() {
final List<Integer> actual = List.<Integer> empty().appendAll(List.of(1, 2, 3));
final List<Integer> expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendAllEmptyListToNonEmptyList() {
final List<Integer> actual = List.of(1, 2, 3).appendAll(List.empty());
final List<Integer> expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldAppendAllNonEmptyListToNonEmptyList() {
final List<Integer> actual = List.of(1, 2, 3).appendAll(List.of(4, 5, 6));
final List<Integer> expected = List.of(1, 2, 3, 4, 5, 6);
assertThat(actual).isEqualTo(expected);
}
// -- prepend
@Test
public void shouldPrependElementToEmptyList() {
final List<Integer> actual = List.<Integer> empty().prepend(1);
final List<Integer> expected = List.of(1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldPrependElementToNonEmptyList() {
final List<Integer> actual = List.of(2).prepend(1);
final List<Integer> expected = List.of(1, 2);
assertThat(actual).isEqualTo(expected);
}
// -- prependAll
@Test
public void shouldThrowOnPrependAllOfNull() {
assertThat(() -> List.empty().prependAll(null)).isThrowing(
UnsatisfiedRequirementException.class, "elements is null");
}
@Test
public void shouldPrependAllEmptyListToEmptyList() {
final List<Integer> actual = List.<Integer> empty().prependAll(List.empty());
final List<Integer> expected = List.empty();
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldPrependAllEmptyListToNonEmptyList() {
final List<Integer> actual = List.of(1, 2, 3).prependAll(List.empty());
final List<Integer> expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldPrependAllNonEmptyListToEmptyList() {
final List<Integer> actual = List.<Integer> empty().prependAll(List.of(1, 2, 3));
final List<Integer> expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldPrependAllNonEmptyListToNonEmptyList() {
final List<Integer> actual = List.of(4, 5, 6).prependAll(List.of(1, 2, 3));
final List<Integer> expected = List.of(1, 2, 3, 4, 5, 6);
assertThat(actual).isEqualTo(expected);
}
// -- insert
@Test
public void shouldInsertIntoEmptyList() {
final List<Integer> actual = List.<Integer> empty().insert(0, 1);
final List<Integer> expected = List.of(1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertInFrontOfElement() {
final List<Integer> actual = List.of(4).insert(0, 1);
final List<Integer> expected = List.of(1, 4);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertBehindOfElement() {
final List<Integer> actual = List.of(4).insert(1, 1);
final List<Integer> expected = List.of(4, 1);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertIntoList() {
final List<Integer> actual = List.of(1, 2, 3).insert(2, 4);
final List<Integer> expected = List.of(1, 2, 4, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldThrowOnInsertWithNegativeIndex() {
assertThat(() -> List.empty().insert(-1, null)).isThrowing(IndexOutOfBoundsException.class,
"insert(-1, e)");
}
@Test
public void shouldThrowOnInsertWhenExceedingUpperBound() {
assertThat(() -> List.empty().insert(1, null)).isThrowing(IndexOutOfBoundsException.class,
"insert(1, e) on list of size 0");
}
// -- insertAll
@Test
public void shouldInserAlltIntoEmptyList() {
final List<Integer> actual = List.<Integer> empty().insertAll(0, List.of(1, 2, 3));
final List<Integer> expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertAllInFrontOfElement() {
final List<Integer> actual = List.of(4).insertAll(0, List.of(1, 2, 3));
final List<Integer> expected = List.of(1, 2, 3, 4);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertAllBehindOfElement() {
final List<Integer> actual = List.of(4).insertAll(1, List.of(1, 2, 3));
final List<Integer> expected = List.of(4, 1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldInsertAllIntoList() {
final List<Integer> actual = List.of(1, 2, 3).insertAll(2, List.of(4, 5));
final List<Integer> expected = List.of(1, 2, 4, 5, 3);
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldThrowOnInsertAllWithEmptyList() {
assertThat(() -> List.empty().insertAll(0, null)).isThrowing(
UnsatisfiedRequirementException.class, "elements is null");
}
@Test
public void shouldThrowOnInsertAllWithNegativeIndex() {
assertThat(() -> List.empty().insertAll(-1, List.empty())).isThrowing(
IndexOutOfBoundsException.class, "insertAll(-1, elements)");
}
@Test
public void shouldThrowOnInsertAllWhenExceedingUpperBound() {
assertThat(() -> List.empty().insertAll(1, List.empty())).isThrowing(
IndexOutOfBoundsException.class, "insertAll(1, elements) on list of size 0");
}
// -- remove
@Test
public void shouldRemoveElementFromEmptyList() {
assertThat(List.empty().remove(null)).isEqualTo(List.empty());
}
@Test
public void shouldRemoveFirstElement() {
assertThat(List.of(1, 2, 3).remove(1)).isEqualTo(List.of(2, 3));
}
@Test
public void shouldRemoveLastElement() {
assertThat(List.of(1, 2, 3).remove(3)).isEqualTo(List.of(1, 2));
}
@Test
public void shouldRemoveInnerElement() {
assertThat(List.of(1, 2, 3).remove(2)).isEqualTo(List.of(1, 3));
}
@Test
public void shouldRemoveNonExistingElement() {
assertThat(List.of(1, 2, 3).remove(4)).isEqualTo(List.of(1, 2, 3));
}
// -- removeAll
@Test
public void shouldRemoveAllElementsFromEmptyList() {
assertThat(List.empty().removeAll(List.of(1, 2, 3))).isEqualTo(List.empty());
}
@Test
public void shouldRemoveAllExistingElementsFromNonEmptyList() {
assertThat(List.of(1, 2, 3, 1, 2, 3).removeAll(List.of(1, 2))).isEqualTo(List.of(3, 3));
}
@Test
public void shouldNotRemoveAllNonExistingElementsFromNonEmptyList() {
assertThat(List.of(1, 2, 3).removeAll(List.of(4, 5))).isEqualTo(List.of(1, 2, 3));
}
// -- retainAll
@Test
public void shouldRetainAllElementsFromEmptyList() {
assertThat(List.empty().retainAll(List.of(1, 2, 3))).isEqualTo(List.empty());
}
@Test
public void shouldRetainAllExistingElementsFromNonEmptyList() {
assertThat(List.of(1, 2, 3, 1, 2, 3).retainAll(List.of(1, 2))).isEqualTo(
List.of(1, 2, 1, 2));
}
@Test
public void shouldNotRetainAllNonExistingElementsFromNonEmptyList() {
assertThat(List.of(1, 2, 3).retainAll(List.of(4, 5))).isEqualTo(List.empty());
}
// -- replaceAll
@Test
public void shouldReplaceAllElementsOfEmptyList() {
assertThat(List.<Integer> empty().replaceAll(i -> i + 1)).isEqualTo(List.empty());
}
@Test
public void shouldReplaceAllElementsOfNonEmptyList() {
assertThat(List.of(1, 2, 3).replaceAll(i -> i + 1)).isEqualTo(List.of(2, 3, 4));
}
// -- clear
@Test
public void shouldClearEmptyList() {
assertThat(List.empty().clear()).isEqualTo(List.empty());
}
@Test
public void shouldClearNonEmptyList() {
assertThat(List.of(1, 2, 3).clear()).isEqualTo(List.empty());
}
// -- contains
@Test
public void shouldRecognizeEmptyListContainsNoElement() {
final boolean actual = List.empty().contains(null);
assertThat(actual).isFalse();
}
@Test
public void shouldRecognizeNonEmptyListDoesNotContainElement() {
final boolean actual = List.of(1, 2, 3).contains(0);
assertThat(actual).isFalse();
}
@Test
public void shouldRecognizeNonEmptyListDoesContainElement() {
final boolean actual = List.of(1, 2, 3).contains(2);
assertThat(actual).isTrue();
}
// -- containsAll
@Test
public void shouldRecognizeEmptyListNotContainsAllElements() {
final boolean actual = List.empty().containsAll(List.of(1, 2, 3));
assertThat(actual).isFalse();
}
@Test
public void shouldRecognizeNonEmptyListNotContainsAllOverlappingElements() {
final boolean actual = List.of(1, 2, 3).containsAll(List.of(2, 3, 4));
assertThat(actual).isFalse();
}
@Test
public void shouldRecognizeNonEmptyListContainsAllOnSelf() {
final boolean actual = List.of(1, 2, 3).containsAll(List.of(1, 2, 3));
assertThat(actual).isTrue();
}
// -- indexOf
@Test
public void shouldNotFindIndexOfElementWhenListIsEmpty() {
assertThat(List.empty().indexOf(1)).isEqualTo(-1);
}
@Test
public void shouldFindIndexOfFirstElement() {
assertThat(List.of(1, 2, 3).indexOf(1)).isEqualTo(0);
}
@Test
public void shouldFindIndexOfInnerElement() {
assertThat(List.of(1, 2, 3).indexOf(2)).isEqualTo(1);
}
@Test
public void shouldFindIndexOfLastElement() {
assertThat(List.of(1, 2, 3).indexOf(3)).isEqualTo(2);
}
// -- lastIndexOf
@Test
public void shouldNotFindLastIndexOfElementWhenListIsEmpty() {
assertThat(List.empty().lastIndexOf(1)).isEqualTo(-1);
}
@Test
public void shouldFindLastIndexOfElement() {
assertThat(List.of(1, 2, 3, 1, 2, 3).lastIndexOf(1)).isEqualTo(3);
}
// -- get
@Test
public void shouldThrowWhenGetWithNegativeIndexOnEmptyList() {
assertThat(() -> List.empty().get(-1)).isThrowing(IndexOutOfBoundsException.class,
"get(-1) on empty list");
}
@Test
public void shouldThrowWhenGetWithNegativeIndexOnNonEmptyList() {
assertThat(() -> List.of(1).get(-1)).isThrowing(IndexOutOfBoundsException.class, "get(-1)");
}
@Test
public void shouldThrowWhenGetOnEmptyList() {
assertThat(() -> List.empty().get(0)).isThrowing(IndexOutOfBoundsException.class,
"get(0) on empty list");
}
@Test
public void shouldThrowWhenGetWithTooBigIndexOnNonEmptyList() {
assertThat(() -> List.of(1).get(1)).isThrowing(IndexOutOfBoundsException.class,
"get(1) on list of size 1");
}
@Test
public void shouldGetFirstElement() {
assertThat(List.of(1, 2, 3).get(0)).isEqualTo(1);
}
@Test
public void shouldGetLastElement() {
assertThat(List.of(1, 2, 3).get(2)).isEqualTo(3);
}
// -- set
@Test
public void shouldThrowWhenSetWithNegativeIndexOnEmptyList() {
assertThat(() -> List.empty().set(-1, null)).isThrowing(IndexOutOfBoundsException.class,
"set(-1, e) on empty list");
}
@Test
public void shouldThrowWhenSetWithNegativeIndexOnNonEmptyList() {
assertThat(() -> List.of(1).set(-1, 2)).isThrowing(IndexOutOfBoundsException.class,
"set(-1, e)");
}
@Test
public void shouldThrowWhenSetOnEmptyList() {
assertThat(() -> List.empty().set(0, null)).isThrowing(IndexOutOfBoundsException.class,
"set(0, e) on empty list");
}
@Test
public void shouldThrowWhenSetWithTooBigIndexOnNonEmptyList() {
assertThat(() -> List.of(1).set(1, 2)).isThrowing(IndexOutOfBoundsException.class,
"set(1, e) on list of size 1");
}
@Test
public void shouldSetFirstElement() {
assertThat(List.of(1, 2, 3).set(0, 4)).isEqualTo(List.of(4, 2, 3));
}
@Test
public void shouldSetLastElement() {
assertThat(List.of(1, 2, 3).set(2, 4)).isEqualTo(List.of(1, 2, 4));
}
// -- sublist(beginIndex)
@Test
public void shouldReturnEmptyListWhenSublistFrom0OnEmptyList() {
final List<Integer> actual = List.<Integer> empty().sublist(0);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldReturnIdentityWhenSublistFrom0OnNonEmptyList() {
final List<Integer> actual = List.of(1).sublist(0);
assertThat(actual).isEqualTo(List.of(1));
}
@Test
public void shouldReturnEmptyListWhenSublistFrom1OnListOf1() {
final List<Integer> actual = List.of(1).sublist(1);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldReturnSublistWhenIndexIsWithinRange() {
final List<Integer> actual = List.of(1, 2, 3).sublist(1);
assertThat(actual).isEqualTo(List.of(2, 3));
}
@Test
public void shouldReturnEmptyListWhenSublistBeginningWithSize() {
final List<Integer> actual = List.of(1, 2, 3).sublist(3);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldThrowWhenSublist0OnEmptyList() {
assertThat(() -> List.<Integer> empty().sublist(1)).isThrowing(
IndexOutOfBoundsException.class, "sublist(1) on list of size 0");
}
@Test
public void shouldThrowWhenSublistWithOutOfLowerBound() {
assertThat(() -> List.of(1, 2, 3).sublist(-1)).isThrowing(IndexOutOfBoundsException.class,
"sublist(-1)");
}
@Test
public void shouldThrowWhenSublistWithOutOfUpperBound() {
assertThat(() -> List.of(1, 2, 3).sublist(4)).isThrowing(IndexOutOfBoundsException.class,
"sublist(4) on list of size 3");
}
// -- sublist(beginIndex, endIndex)
@Test
public void shouldReturnEmptyListWhenSublistFrom0To0OnEmptyList() {
final List<Integer> actual = List.<Integer> empty().sublist(0, 0);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldReturnEmptyListWhenSublistFrom0To0OnNonEmptyList() {
final List<Integer> actual = List.of(1).sublist(0, 0);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldReturnListWithFirstElementWhenSublistFrom0To1OnNonEmptyList() {
final List<Integer> actual = List.of(1).sublist(0, 1);
assertThat(actual).isEqualTo(List.of(1));
}
@Test
public void shouldReturnEmptyListWhenSublistFrom1To1OnNonEmptyList() {
final List<Integer> actual = List.of(1).sublist(1, 1);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldReturnSublistWhenIndicesAreWithinRange() {
final List<Integer> actual = List.of(1, 2, 3).sublist(1, 3);
assertThat(actual).isEqualTo(List.of(2, 3));
}
@Test
public void shouldReturnEmptyListWhenIndicesBothAreUpperBound() {
final List<Integer> actual = List.of(1, 2, 3).sublist(3, 3);
assertThat(actual).isEqualTo(List.empty());
}
@Test
public void shouldThrowOnSublistWhenEndIndexIsGreaterThanBeginIndex() {
assertThat(() -> List.of(1, 2, 3).sublist(1, 0)).isThrowing(
IndexOutOfBoundsException.class, "sublist(1, 0) on list of size 3");
}
@Test
public void shouldThrowOnSublistWhenBeginIndexExceedsLowerBound() {
assertThat(() -> List.of(1, 2, 3).sublist(-1, 2)).isThrowing(
IndexOutOfBoundsException.class, "sublist(-1, 2) on list of size 3");
}
@Test
public void shouldThrowOnSublistWhenEndIndexExceedsUpperBound() {
assertThat(() -> List.of(1, 2, 3).sublist(1, 4)).isThrowing(
IndexOutOfBoundsException.class, "sublist(1, 4) on list of size 3");
}
// -- drop
@Test
public void shouldDropNoneOnEmptyList() {
assertThat(List.empty().drop(1)).isEqualTo(List.empty());
}
@Test
public void shouldDropNoneIfCountIsNegative() {
assertThat(List.of(1, 2, 3).drop(-1)).isEqualTo(List.of(1, 2, 3));
}
@Test
public void shouldDropAsExpectedIfCountIsLessThanSize() {
assertThat(List.of(1, 2, 3).drop(2)).isEqualTo(List.of(3));
}
@Test
public void shouldDropAllIfCountExceedsSize() {
assertThat(List.of(1, 2, 3).drop(4)).isEqualTo(List.empty());
}
// -- take
@Test
public void shouldTakeNoneOnEmptyList() {
assertThat(List.empty().take(1)).isEqualTo(List.empty());
}
@Test
public void shouldTakeNoneIfCountIsNegative() {
assertThat(List.of(1, 2, 3).take(-1)).isEqualTo(List.empty());
}
@Test
public void shouldTakeAsExpectedIfCountIsLessThanSize() {
assertThat(List.of(1, 2, 3).take(2)).isEqualTo(List.of(1, 2));
}
@Test
public void shouldTakeAllIfCountExceedsSize() {
assertThat(List.of(1, 2, 3).take(4)).isEqualTo(List.of(1, 2, 3));
}
// -- toArray
@Test
public void shouldConvertEmptyListToArray() {
assertThat(List.<Integer> empty().toArray()).isEqualTo(new Integer[] {});
}
@Test
public void shouldConvertNonEmptyListToArray() {
assertThat(List.of(1, 2, 3).toArray()).isEqualTo(new Integer[] { 1, 2, 3 });
}
// -- toArray(E[])
@Test
public void shouldConvertEmptyListGivenEmptyArray() {
final Integer[] actual = List.<Integer> empty().toArray(new Integer[] {});
final Integer[] expected = new Integer[] {};
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldConvertEmptyListGivenNonEmptyArray() {
final Integer[] array = List.<Integer> empty().toArray(new Integer[] { 9, 9, 9 });
final Integer[] expected = new Integer[] { null, 9, 9 };
assertThat(array).isEqualTo(expected);
}
@Test
public void shouldConvertNonEmptyListToGivenArrayIfSizeIsSmaller() {
final Integer[] array = List.of(1, 2).toArray(new Integer[] { 9, 9, 9 });
final Integer[] expected = new Integer[] { 1, 2, null };
assertThat(array).isEqualTo(expected);
}
@Test
public void shouldConvertNonEmptyListToGivenArrayIfSizeIsEqual() {
final Integer[] actual = List.of(1, 2, 3).toArray(new Integer[] { 9, 9, 9 });
final Integer[] expected = new Integer[] { 1, 2, 3 };
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldConvertNonEmptyListToGivenArrayIfSizeIsBigger() {
final Integer[] array = List.of(1, 2, 3, 4).toArray(new Integer[] { 9, 9, 9 });
final Integer[] expected = new Integer[] { 1, 2, 3, 4 };
assertThat(array).isEqualTo(expected);
}
// -- toArrayList
@Test
public void shouldConvertEmptyListToArrayList() {
assertThat(List.<Integer> empty().toArrayList()).isEqualTo(new ArrayList<Integer>());
}
@Test
public void shouldConvertNonEmptyListToArrayList() {
assertThat(List.of(1, 2, 3).toArrayList()).isEqualTo(Arrays.asList(1, 2, 3));
}
// -- sort
@Test
public void shouldSortEmptyList() {
assertThat(List.empty().sort()).isEqualTo(List.empty());
}
@Test
public void shouldSortNonEmptyList() {
assertThat(List.of(3, 4, 1, 2).sort()).isEqualTo(List.of(1, 2, 3, 4));
}
// -- sort(Comparator)
@Test
public void shouldSortEmptyListUsingComparator() {
assertThat(List.<Integer> empty().sort((i, j) -> j - i)).isEqualTo(List.empty());
}
@Test
public void shouldSortNonEmptyListUsingComparator() {
assertThat(List.of(3, 4, 1, 2).sort((i, j) -> j - i)).isEqualTo(List.of(4, 3, 2, 1));
}
// -- stream
@Test
public void shouldStreamAndCollectEmptyList() {
assertThat(List.empty().stream().collect(List.collector())).isEqualTo(List.empty());
}
@Test
public void shouldStreamAndCollectNonEmptyList() {
assertThat(List.of(1, 2, 3).stream().collect(List.collector())).isEqualTo(List.of(1, 2, 3));
}
// -- parallelStream
@Test
public void shouldParallelStreamAndCollectEmptyList() {
assertThat(List.empty().parallelStream().collect(List.collector())).isEqualTo(List.empty());
}
@Test
public void shouldParallelStreamAndCollectNonEmptyList() {
assertThat(List.of(1, 2, 3).parallelStream().collect(List.collector())).isEqualTo(
List.of(1, 2, 3));
}
// -- spliterator
@Test
public void shouldSplitEmptyList() {
final java.util.List<Integer> actual = new java.util.ArrayList<>();
List.<Integer> empty().spliterator().forEachRemaining(i -> actual.add(i));
assertThat(actual).isEqualTo(Arrays.asList());
}
@Test
public void shouldSplitNonEmptyList() {
final java.util.List<Integer> actual = new java.util.ArrayList<>();
List.of(1, 2, 3).spliterator().forEachRemaining(i -> actual.add(i));
assertThat(actual).isEqualTo(Arrays.asList(1, 2, 3));
}
@Test
public void shouldHaveImmutableSpliterator() {
assertThat(List.of(1, 2, 3).spliterator().characteristics() & Spliterator.IMMUTABLE)
.isNotZero();
}
@Test
public void shouldHaveOrderedSpliterator() {
assertThat(List.of(1, 2, 3).spliterator().characteristics() & Spliterator.ORDERED)
.isNotZero();
}
@Test
public void shouldHaveSizedSpliterator() {
assertThat(List.of(1, 2, 3).spliterator().characteristics() & Spliterator.SIZED)
.isNotZero();
}
@Test
public void shouldReturnSizeWhenSpliterator() {
assertThat(List.of(1, 2, 3).spliterator().getExactSizeIfKnown()).isEqualTo(3);
}
// -- iterator
@Test
public void shouldNotHasNextWhenEmptyListIterator() {
assertThat(List.empty().iterator().hasNext()).isFalse();
}
@Test
public void shouldThrowOnNextWhenEmptyListIterator() {
assertThat(() -> List.empty().iterator().next()).isThrowing(NoSuchElementException.class,
null);
}
@Test
public void shouldIterateFirstElementOfNonEmptyList() {
assertThat(List.of(1, 2, 3).iterator().next()).isEqualTo(1);
}
@Test
public void shouldFullyIterateNonEmptyList() {
int actual = -1;
for (Iterator<Integer> iter = List.of(1, 2, 3).iterator(); iter.hasNext(); actual = iter
.next())
;
assertThat(actual).isEqualTo(3);
}
// -- iterator(int)
@Test
public void shouldThrowWhenEmptyListIteratorStartingAtIndex() {
assertThat(() -> {
List.empty().iterator(1);
}).isThrowing(IndexOutOfBoundsException.class, "sublist(1) on list of size 0");
}
@Test
public void shouldIterateFirstElementOfNonEmptyListStartingAtIndex() {
assertThat(List.of(1, 2, 3).iterator(1).next()).isEqualTo(2);
}
@Test
public void shouldFullyIterateNonEmptyListStartingAtIndex() {
int actual = -1;
for (Iterator<Integer> iter = List.of(1, 2, 3).iterator(1); iter.hasNext(); actual = iter
.next())
;
assertThat(actual).isEqualTo(3);
}
// -- equals
@Test
public void shouldRecognizeEqualityOfEmptyLists() {
assertThat(List.empty().equals(List.empty())).isTrue();
}
@Test
public void shouldRecognizeEqualityOfNonEmptyLists() {
assertThat(List.of(1, 2, 3).equals(List.of(1, 2, 3))).isTrue();
}
@Test
public void shouldRecognizeNonEqualityOfListsOfSameSize() {
assertThat(List.of(1, 2, 3).equals(List.of(1, 2, 4))).isFalse();
}
@Test
public void shouldRecognizeNonEqualityOfListsOfDifferentSize() {
assertThat(List.of(1, 2, 3).equals(List.of(1, 2))).isFalse();
}
// -- hashCode
@Test
public void shouldCalculateHashCodeOfEmptyList() {
assertThat(List.empty().hashCode()).isEqualTo(1);
}
@Test
public void shouldCalculateHashCodeOfNonEmptyList() {
assertThat(List.of(1, 2, 3).hashCode()).isEqualTo(31 * (31 * (31 * 1 + 1) + 2) + 3);
}
// -- toString
@Test
public void shouldStringifyEmptyList() {
assertThat(List.empty().toString()).isEqualTo("()");
}
@Test
public void shouldStringifyNonEmptyList() {
assertThat(List.of(1, 2, 3).toString()).isEqualTo("(1, 2, 3)");
}
// -- List.empty()
@Test
public void shouldCreateEmptyList() {
assertThat(List.empty()).isEqualTo(EmptyList.instance());
}
// -- List.of(T, T...)
@Test
public void shouldCreateListOfElements() {
final List<Object> actual = List.of(1, 2);
final List<Object> expected = new LinearList<>(1, new LinearList<>(2, EmptyList.instance()));
assertThat(actual).isEqualTo(expected);
}
// -- List.of(Iterable)
@Test
public void shouldCreateListOfIterable() {
final java.util.List<Integer> arrayList = Arrays.asList(1, 2, 3);
assertThat(List.of(arrayList)).isEqualTo(List.of(1, 2, 3));
}
// -- Serializable interface
@Test
public void shouldSerializeDeserializeEmptyList() throws Exception {
final Object actual = deserialize(serialize(List.empty()));
final Object expected = List.empty();
assertThat(actual).isEqualTo(expected);
}
@Test
public void shouldPreserveSingletonInstanceOnDeserialization() throws Exception {
final boolean actual = deserialize(serialize(List.empty())) == List.empty();
assertThat(actual).isTrue();
}
@Test
public void shouldSerializeDeserializeNonEmptyList() throws Exception {
final Object actual = deserialize(serialize(List.of(1, 2, 3)));
final Object expected = List.of(1, 2, 3);
assertThat(actual).isEqualTo(expected);
}
private static byte[] serialize(Object obj) throws IOException {
try (ByteArrayOutputStream buf = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(buf)) {
stream.writeObject(obj);
return buf.toByteArray();
}
}
private static Object deserialize(byte[] objectData) throws ClassNotFoundException, IOException {
try (ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(objectData))) {
return stream.readObject();
}
}
}
|
package net.imagej.ops;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import io.scif.img.IO;
import java.net.URL;
import java.util.Iterator;
import java.util.Random;
import net.imglib2.Cursor;
import net.imglib2.FinalInterval;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.img.basictypeaccess.array.FloatArray;
import net.imglib2.img.cell.CellImg;
import net.imglib2.img.cell.CellImgFactory;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import org.junit.After;
import org.junit.Before;
import org.scijava.Context;
import org.scijava.cache.CacheService;
import org.scijava.plugin.Parameter;
/**
* Base class for {@link Op} unit testing.
* <p>
* <i>All</i> {@link Op} unit tests need to have an {@link OpService} instance.
* Following the DRY principle, we should implement it only once. Here.
* </p>
*
* @author Johannes Schindelin
* @author Curtis Rueden
*/
public abstract class AbstractOpTest {
@Parameter
protected Context context;
@Parameter
protected OpService ops;
@Parameter
protected OpMatchingService matcher;
/** Subclasses can override to create a context with different services. */
protected Context createContext() {
return new Context(OpService.class, OpMatchingService.class,
CacheService.class);
}
/** Sets up a SciJava context with {@link OpService}. */
@Before
public void setUp() {
createContext().inject(this);
}
/**
* Disposes of the {@link OpService} that was initialized in {@link #setUp()}.
*/
@After
public synchronized void cleanUp() {
if (context != null) {
context.dispose();
context = null;
ops = null;
matcher = null;
}
}
private int seed;
private int pseudoRandom() {
return seed = 3170425 * seed + 132102;
}
public ArrayImg<ByteType, ByteArray> generateByteArrayTestImg(
final boolean fill, final long... dims)
{
final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(
dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (byte) pseudoRandom();
}
}
return ArrayImgs.bytes(array, dims);
}
public ArrayImg<UnsignedByteType, ByteArray> generateUnsignedByteArrayTestImg(
final boolean fill, final long... dims)
{
final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(
dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (byte) pseudoRandom();
}
}
return ArrayImgs.unsignedBytes(array, dims);
}
public CellImg<ByteType, ?> generateByteTestCellImg(final boolean fill,
final long... dims)
{
final CellImg<ByteType, ?> img = new CellImgFactory<ByteType>().create(dims,
new ByteType());
if (fill) {
final Cursor<ByteType> c = img.cursor();
while (c.hasNext())
c.next().set((byte) pseudoRandom());
}
return img;
}
public CellImg<ByteType, ?> generateByteTestCellImg(final boolean fill,
final int[] cellDims, final long... dims)
{
final CellImg<ByteType, ?> img = new CellImgFactory<ByteType>(cellDims)
.create(dims, new ByteType());
if (fill) {
final Cursor<ByteType> c = img.cursor();
while (c.hasNext())
c.next().set((byte) pseudoRandom());
}
return img;
}
public Img<UnsignedByteType>
generateRandomlyFilledUnsignedByteTestImgWithSeed(final long[] dims,
final long tempSeed)
{
final Img<UnsignedByteType> img = ArrayImgs.unsignedBytes(dims);
final Random rand = new Random(tempSeed);
final Cursor<UnsignedByteType> cursor = img.cursor();
while (cursor.hasNext()) {
cursor.next().set(rand.nextInt((int) img.firstElement().getMaxValue()));
}
return img;
}
public ArrayImg<FloatType, FloatArray> generateFloatArrayTestImg(
final boolean fill, final long... dims)
{
final float[] array = new float[(int) Intervals.numElements(
new FinalInterval(dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (float) pseudoRandom() / (float) Integer.MAX_VALUE;
}
}
return ArrayImgs.floats(array, dims);
}
public Img<FloatType> openFloatImg(final String resourcePath) {
return openFloatImg(getClass(), resourcePath);
}
public static Img<FloatType> openFloatImg(final Class<?> c,
final String resourcePath)
{
final URL url = c.getResource(resourcePath);
return IO.openFloatImgs(url.getPath()).get(0).getImg();
}
public static Img<UnsignedByteType> openUnsignedByteType(final Class<?> c,
final String resourcePath)
{
final URL url = c.getResource(resourcePath);
return IO.openUnsignedByteImgs(url.getPath()).get(0).getImg();
}
public <T> void assertIterationsEqual(final Iterable<T> expected,
final Iterable<T> actual)
{
final Iterator<T> e = expected.iterator();
final Iterator<T> a = actual.iterator();
while (e.hasNext()) {
assertTrue("Fewer elements than expected", a.hasNext());
assertEquals(e.next(), a.next());
}
assertFalse("More elements than expected", a.hasNext());
}
public static class NoOp extends AbstractOp {
@Override
public void run() {
// NB: No implementation needed.
}
}
}
|
package org.jsoup.select;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import static org.junit.Assert.*;
/**
Tests that the selector selects correctly.
@author Jonathan Hedley, jonathan@hedley.net */
public class SelectorTest {
@Test public void testByTag() {
Elements els = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("div");
assertEquals(3, els.size());
assertEquals("1", els.get(0).id());
assertEquals("2", els.get(1).id());
assertEquals("3", els.get(2).id());
Elements none = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("span");
assertEquals(0, none.size());
}
@Test public void testById() {
Elements els = Jsoup.parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>").select("#foo");
assertEquals(1, els.size());
assertEquals("Hello", els.get(0).text());
Elements none = Jsoup.parse("<div id=1></div>").select("#foo");
assertEquals(0, none.size());
}
@Test public void testByClass() {
Elements els = Jsoup.parse("<p id=0 class='one two'><p id=1 class='one'><p id=2 class='two'>").select("p.one");
assertEquals(2, els.size());
assertEquals("0", els.get(0).id());
assertEquals("1", els.get(1).id());
Elements none = Jsoup.parse("<div class='one'></div>").select(".foo");
assertEquals(0, none.size());
Elements els2 = Jsoup.parse("<div class='one-two'></div>").select(".one-two");
assertEquals(1, els2.size());
}
@Test public void testByAttribute() {
String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Bam /><div title=SLAM /><div />";
Document doc = Jsoup.parse(h);
Elements withTitle = doc.select("[title]");
assertEquals(4, withTitle.size());
Elements foo = doc.select("[title=foo]");
assertEquals(1, foo.size());
Elements not = doc.select("div[title!=bar]");
assertEquals(5, not.size());
assertEquals("Foo", not.first().attr("title"));
Elements starts = doc.select("[title^=ba]");
assertEquals(2, starts.size());
assertEquals("Bar", starts.first().attr("title"));
assertEquals("Bam", starts.last().attr("title"));
Elements ends = doc.select("[title$=am]");
assertEquals(2, ends.size());
assertEquals("Bam", ends.first().attr("title"));
assertEquals("SLAM", ends.last().attr("title"));
Elements contains = doc.select("[title*=a]");
assertEquals(3, contains.size());
assertEquals("Bar", contains.first().attr("title"));
assertEquals("SLAM", contains.last().attr("title"));
}
@Test public void testByAttributeRegex() {
Document doc = Jsoup.parse("<p><img src=foo.png id=1><img src=bar.jpg id=2><img src=qux.JPEG id=3><img src=old.gif><img></p>");
Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g)]");
assertEquals(3, imgs.size());
assertEquals("1", imgs.get(0).id());
assertEquals("2", imgs.get(1).id());
assertEquals("3", imgs.get(2).id());
}
@Test public void testAllElements() {
String h = "<div><p>Hello</p><p><b>there</b></p></div>";
Document doc = Jsoup.parse(h);
Elements allDoc = doc.select("*");
Elements allUnderDiv = doc.select("div *");
assertEquals(8, allDoc.size());
assertEquals(3, allUnderDiv.size());
assertEquals("p", allUnderDiv.first().tagName());
}
@Test public void testAllWithClass() {
String h = "<p class=first>One<p class=first>Two<p>Three";
Document doc = Jsoup.parse(h);
Elements ps = doc.select("*.first");
assertEquals(2, ps.size());
}
@Test public void testGroupOr() {
String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>";
Document doc = Jsoup.parse(h);
Elements els = doc.select("p,div,[title]");
assertEquals(5, els.size());
assertEquals("p", els.get(0).tagName());
assertEquals("div", els.get(1).tagName());
assertEquals("foo", els.get(1).attr("title"));
assertEquals("div", els.get(2).tagName());
assertEquals("bar", els.get(2).attr("title"));
assertEquals("div", els.get(3).tagName());
assertTrue(els.get(3).attr("title").length() == 0); // missing attributes come back as empty string
assertFalse(els.get(3).hasAttr("title"));
assertEquals("span", els.get(4).tagName());
}
@Test public void testGroupOrAttribute() {
String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />";
Elements els = Jsoup.parse(h).select("[id],[title=foo]");
assertEquals(3, els.size());
assertEquals("1", els.get(0).id());
assertEquals("2", els.get(1).id());
assertEquals("foo", els.get(2).attr("title"));
}
@Test public void descendant() {
String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>";
Document doc = Jsoup.parse(h);
Elements els = doc.select(".head p");
assertEquals(2, els.size());
assertEquals("Hello", els.get(0).text());
assertEquals("There", els.get(1).text());
Elements p = doc.select("p.first");
assertEquals(1, p.size());
assertEquals("Hello", p.get(0).text());
Elements empty = doc.select("p .first"); // self, not descend, should not match
assertEquals(0, empty.size());
}
@Test public void and() {
String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div";
Document doc = Jsoup.parse(h);
Elements div = doc.select("div.foo");
assertEquals(1, div.size());
assertEquals("div", div.first().tagName());
Elements p = doc.select("div .foo"); // space indicates like "div *.foo"
assertEquals(1, p.size());
assertEquals("p", p.first().tagName());
Elements div2 = doc.select("div#1.foo.bar[title=bar][name=qux]"); // very specific!
assertEquals(1, div2.size());
assertEquals("div", div2.first().tagName());
Elements p2 = doc.select("div *.foo"); // space indicates like "div *.foo"
assertEquals(1, p2.size());
assertEquals("p", p2.first().tagName());
}
@Test public void deeperDescendant() {
String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>";
Elements els = Jsoup.parse(h).select("div p .first");
assertEquals(1, els.size());
assertEquals("Hello", els.first().text());
assertEquals("span", els.first().tagName());
}
@Test public void parentChildElement() {
String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>";
Document doc = Jsoup.parse(h);
Elements divs = doc.select("div > div");
assertEquals(2, divs.size());
assertEquals("2", divs.get(0).id()); // 2 is child of 1
assertEquals("3", divs.get(1).id()); // 3 is child of 2
Elements div2 = doc.select("div#1 > div");
assertEquals(1, div2.size());
assertEquals("2", div2.get(0).id());
}
@Test public void parentWithClassChild() {
String h = "<h1 class=foo><a href=1 /></h1><h1 class=foo><a href=2 class=bar /></h1><h1><a href=3 /></h1>";
Document doc = Jsoup.parse(h);
Elements allAs = doc.select("h1 > a");
assertEquals(3, allAs.size());
assertEquals("a", allAs.first().tagName());
Elements fooAs = doc.select("h1.foo > a");
assertEquals(2, fooAs.size());
assertEquals("a", fooAs.first().tagName());
Elements barAs = doc.select("h1.foo > a.bar");
assertEquals(1, barAs.size());
}
@Test public void parentChildStar() {
String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>";
Document doc = Jsoup.parse(h);
Elements divChilds = doc.select("div > *");
assertEquals(3, divChilds.size());
assertEquals("p", divChilds.get(0).tagName());
assertEquals("p", divChilds.get(1).tagName());
assertEquals("span", divChilds.get(2).tagName());
}
@Test public void multiChildDescent() {
String h = "<div id=foo><h1 class=bar><a href=http://example.com/>One</a></h1></div>";
Document doc = Jsoup.parse(h);
Elements els = doc.select("div#foo > h1.bar > a[href*=example]");
assertEquals(1, els.size());
assertEquals("a", els.first().tagName());
}
@Test public void caseInsensitive() {
String h = "<dIv tItle=bAr><div>"; // mixed case so a simple toLowerCase() on value doesn't catch
Document doc = Jsoup.parse(h);
assertEquals(2, doc.select("DIV").size());
assertEquals(1, doc.select("DIV[TITLE]").size());
assertEquals(1, doc.select("DIV[TITLE=BAR]").size());
assertEquals(0, doc.select("DIV[TITLE=BARBARELLA").size());
}
@Test public void adjacentSiblings() {
String h = "<ol><li>One<li>Two<li>Three</ol>";
Document doc = Jsoup.parse(h);
Elements sibs = doc.select("li + li");
assertEquals(2, sibs.size());
assertEquals("Two", sibs.get(0).text());
assertEquals("Three", sibs.get(1).text());
}
@Test public void adjacentSiblingsWithId() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = Jsoup.parse(h);
Elements sibs = doc.select("li#1 + li#2");
assertEquals(1, sibs.size());
assertEquals("Two", sibs.get(0).text());
}
@Test public void notAdjacent() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = Jsoup.parse(h);
Elements sibs = doc.select("li#1 + li#3");
assertEquals(0, sibs.size());
}
@Test public void mixCombinator() {
String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>";
Document doc = Jsoup.parse(h);
Elements sibs = doc.select("body > div.foo li + li");
assertEquals(2, sibs.size());
assertEquals("Two", sibs.get(0).text());
assertEquals("Three", sibs.get(1).text());
}
@Test public void mixCombinatorGroup() {
String h = "<div class=foo><ol><li>One<li>Two<li>Three</ol></div>";
Document doc = Jsoup.parse(h);
Elements els = doc.select(".foo > ol, ol > li + li");
assertEquals(3, els.size());
assertEquals("ol", els.get(0).tagName());
assertEquals("Two", els.get(1).text());
assertEquals("Three", els.get(2).text());
}
@Test public void generalSiblings() {
String h = "<ol><li id=1>One<li id=2>Two<li id=3>Three</ol>";
Document doc = Jsoup.parse(h);
Elements els = doc.select("#1 ~ #3");
assertEquals(1, els.size());
assertEquals("Three", els.first().text());
}
// for http://github.com/jhy/jsoup/issues#issue/10
@Test public void testCharactersInIdAndClass() {
// using CSS spec for identifiers (id and class): a-z0-9, -, _. NOT . (which is OK in html spec, but not css)
String h = "<div><p id='a1-foo_bar'>One</p><p class='b2-qux_bif'>Two</p></div>";
Document doc = Jsoup.parse(h);
Element el1 = doc.getElementById("a1-foo_bar");
assertEquals("One", el1.text());
Element el2 = doc.getElementsByClass("b2-qux_bif").first();
assertEquals("Two", el2.text());
Element el3 = doc.select("#a1-foo_bar").first();
assertEquals("One", el3.text());
Element el4 = doc.select(".b2-qux_bif").first();
assertEquals("Two", el4.text());
}
// for http://github.com/jhy/jsoup/issues#issue/13
@Test public void testSupportsLeadingCombinator() {
String h = "<div><p><span>One</span><span>Two</span></p></div>";
Document doc = Jsoup.parse(h);
Element p = doc.select("div > p").first();
Elements spans = p.select("> span");
assertEquals(2, spans.size());
assertEquals("One", spans.first().text());
// make sure doesn't get nested
h = "<div id=1><div id=2><div id=3></div></div></div>";
doc = Jsoup.parse(h);
Element div = doc.select("div").select(" > div").first();
assertEquals("2", div.id());
}
@Test public void testPseudoLessThan() {
Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>");
Elements ps = doc.select("div p:lt(2)");
assertEquals(3, ps.size());
assertEquals("One", ps.get(0).text());
assertEquals("Two", ps.get(1).text());
assertEquals("Four", ps.get(2).text());
}
@Test public void testPseudoGreaterThan() {
Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</p></div><div><p>Four</p>");
Elements ps = doc.select("div p:gt(0)");
assertEquals(2, ps.size());
assertEquals("Two", ps.get(0).text());
assertEquals("Three", ps.get(1).text());
}
@Test public void testPseudoEquals() {
Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>");
Elements ps = doc.select("div p:eq(0)");
assertEquals(2, ps.size());
assertEquals("One", ps.get(0).text());
assertEquals("Four", ps.get(1).text());
Elements ps2 = doc.select("div:eq(0) p:eq(0)");
assertEquals(1, ps2.size());
assertEquals("One", ps2.get(0).text());
assertEquals("p", ps2.get(0).tagName());
}
@Test public void testPseudoBetween() {
Document doc = Jsoup.parse("<div><p>One</p><p>Two</p><p>Three</>p></div><div><p>Four</p>");
Elements ps = doc.select("div p:gt(0):lt(2)");
assertEquals(1, ps.size());
assertEquals("Two", ps.get(0).text());
}
@Test public void testPseudoCombined() {
Document doc = Jsoup.parse("<div class='foo'><p>One</p><p>Two</p></div><div><p>Three</p><p>Four</p></div>");
Elements ps = doc.select("div.foo p:gt(0)");
assertEquals(1, ps.size());
assertEquals("Two", ps.get(0).text());
}
@Test public void testPseudoHas() {
Document doc = Jsoup.parse("<div id=0><p><span>Hello</span></p></div> <div id=1><span class=foo>There</span></div> <div id=2><p>Not</p></div>");
Elements divs1 = doc.select("div:has(span)");
assertEquals(2, divs1.size());
assertEquals("0", divs1.get(0).id());
assertEquals("1", divs1.get(1).id());
Elements divs2 = doc.select("div:has([class]");
assertEquals(1, divs2.size());
assertEquals("1", divs2.get(0).id());
Elements divs3 = doc.select("div:has(span, p)");
assertEquals(3, divs3.size());
assertEquals("0", divs3.get(0).id());
assertEquals("1", divs3.get(1).id());
assertEquals("2", divs3.get(2).id());
}
@Test public void testNestedHas() {
Document doc = Jsoup.parse("<div><p><span>One</span></p></div> <div><p>Two</p></div>");
Elements divs = doc.select("div:has(p:has(span))");
assertEquals(1, divs.size());
assertEquals("One", divs.first().text());
// test matches in has
divs = doc.select("div:has(p:matches((?i)two))");
assertEquals(1, divs.size());
assertEquals("div", divs.first().tagName());
assertEquals("Two", divs.first().text());
// test contains in has
divs = doc.select("div:has(p:contains(two))");
assertEquals(1, divs.size());
assertEquals("div", divs.first().tagName());
assertEquals("Two", divs.first().text());
}
@Test public void testPseudoContains() {
Document doc = Jsoup.parse("<div><p>The Rain.</p> <p class=light>The <i>rain</i>.</p> <p>Rain, the.</p></div>");
Elements ps1 = doc.select("p:contains(Rain)");
assertEquals(3, ps1.size());
Elements ps2 = doc.select("p:contains(the rain)");
assertEquals(2, ps2.size());
assertEquals("The Rain.", ps2.first().html());
assertEquals("The <i>rain</i>.", ps2.last().html());
Elements ps3 = doc.select("p:contains(the Rain):has(i)");
assertEquals(1, ps3.size());
assertEquals("light", ps3.first().className());
}
@Test public void testPsuedoContainsWithParentheses() {
Document doc = Jsoup.parse("<div><p id=1>This (is good)</p><p id=2>This is bad)</p>");
Elements ps1 = doc.select("p:contains(this (is good))");
assertEquals(1, ps1.size());
assertEquals("1", ps1.first().id());
Elements ps2 = doc.select("p:contains(this is bad\\))");
assertEquals(1, ps2.size());
assertEquals("2", ps2.first().id());
}
@Test public void testMatches() {
Document doc = Jsoup.parse("<p id=1>The <i>Rain</i></p> <p id=2>There are 99 bottles.</p> <p id=3>Harder (this)</p> <p id=4>Rain</p>");
Elements p1 = doc.select("p:matches(The rain)"); // no match, case sensitive
assertEquals(0, p1.size());
Elements p2 = doc.select("p:matches((?i)the rain)"); // case insense. should include root, html, body
assertEquals(1, p2.size());
assertEquals("1", p2.first().id());
Elements p4 = doc.select("p:matches((?i)^rain$)"); // bounding
assertEquals(1, p4.size());
assertEquals("4", p4.first().id());
Elements p5 = doc.select("p:matches(\\d+)");
assertEquals(1, p5.size());
assertEquals("2", p5.first().id());
Elements p6 = doc.select("p:matches(\\w+\\s+\\(\\w+\\))"); // test bracket matching
assertEquals(1, p6.size());
assertEquals("3", p6.first().id());
Elements p7 = doc.select("p:matches((?i)the):has(i)"); // multi
assertEquals(1, p7.size());
assertEquals("1", p7.first().id());
}
}
|
package org.lantern;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.File;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.util.Arrays;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.lantern.proxy.CertTrackingSslEngineSource;
import org.lantern.proxy.GiveModeProxy;
import org.lantern.state.Model;
import org.lantern.util.LanternHostNameVerifier;
import org.littleshoot.proxy.SslEngineSource;
import org.littleshoot.proxy.impl.NetworkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tests running a fallback proxy based on the current code base with a client
* that hits that proxy.
*/
public class FallbackProxyTest {
private Logger log = LoggerFactory.getLogger(getClass());
private static final int SERVER_PORT = LanternUtils.randomPort();
private static String originalFallbackKeystorePath;
// We have to make sure to clean up the keystore path to avoid affecting
// other tests when tests are run together.
@BeforeClass
public static void setUpClass() {
originalFallbackKeystorePath = LanternUtils.getFallbackKeystorePath();
// This is the keystore that's used on the server side -- a test
// dummy of littleproxy_keystore.jks that's used in production.
LanternUtils.setFallbackKeystorePath("src/test/resources/test.jks");
}
@AfterClass
public static void tearDownClass() {
LanternUtils.setFallbackKeystorePath(originalFallbackKeystorePath);
LanternUtils.setFallbackProxy(false);
}
@Test
public void testFallback() throws Exception {
//System.setProperty("javax.net.debug", "all");
//System.setProperty("javax.net.debug", "ssl");
Launcher.configureCipherSuites();
final File temp = new File(SystemUtils.getJavaIoTmpDir(),
String.valueOf(RandomUtils.nextLong()));
FileUtils.forceDeleteOnExit(temp);
final LanternKeyStoreManager ksm =
new LanternKeyStoreManager(temp);
ksm.start();
final LanternTrustStore trustStore = new LanternTrustStore(ksm);
final String testId = "test@gmail.com/somejidresource";
ksm.getBase64Cert(testId);
// This adds the dummy test certificate to the trust store on the
// client side to ensure it will trust our test proxy.
addTestCertToTrustStore(trustStore);
// This runs a give mode proxy that's identical to the fallback servers
// running in production except it uses a different keystore, so
// will send different keys to the client side (see comments above on
// using a test keystore).
final GiveModeProxy give = startGiveModeProxy(trustStore, ksm);
try {
log.debug("Connecting on port: {}", SERVER_PORT);
if (!LanternUtils.waitForServer(
NetworkUtils.getLocalHost().getHostAddress(), SERVER_PORT, 4000)) {
fail("Could not get server on expected port?");
}
final LanternSocketsUtil util = new LanternSocketsUtil(null, trustStore);
final DefaultHttpClient httpClient = new DefaultHttpClient();
// We prefer this one because this way the client can advertise a more
// typical set of suites, and the server can choose.
final SSLSocketFactory clientFactory = util.newTlsSocketFactoryJavaCipherSuites();
//final SSLSocketFactory client = util.newTlsSocketFactory(IceConfig.getCipherSuites());
final HttpHost proxy = new HttpHost(NetworkUtils.getLocalHost().getHostAddress(), SERVER_PORT, "https");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
final org.apache.http.conn.ssl.SSLSocketFactory socketFactory =
new org.apache.http.conn.ssl.SSLSocketFactory(clientFactory,
new LanternHostNameVerifier(proxy)) {
@Override
protected void prepareSocket(final SSLSocket socket) throws IOException {
// This is necessary because calls to the Google auth
// library that wraps an HTTP client apparently
// can corrupt the set cipher suites, causing
// "no cipher suites in common". To reproduce:
// 1) Run on Java 6 (might fail on 7 too, but not sure)
// 2) Disable the setEnabledCipherSuites call below
// 3) Run DefaultXmppHandlerTest followed by
// FallbackProxyTest in the same suite,for example
// "TestsThatFailTogether.java" as of this writing.
final String[] suites = clientFactory.getDefaultCipherSuites();
log.debug("Default suites are: {}", Arrays.asList(suites));
socket.setEnabledCipherSuites(suites);
}
};
final Scheme sch = new Scheme("https", 443, socketFactory);
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
hitSite(httpClient, "https:
// Just make sure there's nothing that pops up with making a second
// request.
hitSite(httpClient, "https:
} finally {
give.stop();
ksm.stop();
}
}
private final String LITTLEPROXY_TEST =
"
+"MIIFXDCCA0SgAwIBAgIEUjzSKDANBgkqhkiG9w0BAQUFADBwMRAwDgYDVQQGEwdV\n"
+"bmtub3duMRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYD\n"
+"VQQKEwdVbmtub3duMRAwDgYDVQQLEwdVbmtub3duMRQwEgYDVQQDEwtsaXR0bGVw\n"
+"cm94eTAeFw0xMzA5MjAyMjU0MzJaFw0xMzEyMTkyMjU0MzJaMHAxEDAOBgNVBAYT\n"
+"B1Vua25vd24xEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB1Vua25vd24xEDAO\n"
+"BgNVBAoTB1Vua25vd24xEDAOBgNVBAsTB1Vua25vd24xFDASBgNVBAMTC2xpdHRs\n"
+"ZXByb3h5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgH7wyJ7Sgyvt\n"
+"plEj0jyaCJG5SDOJAqVu5BP4kE0SaY5Zt8JRHKYSt2J9Yn2DmNaTIT3L7y1SgwjD\n"
+"exzo1bv1SA0yP0D+JsKWd21Aum/isroeMtqUBl39phEA1KhPXCgGbufhPmgkBcK+\n"
+"2HSTIapqWec5JizIZdz7x566om98gNPj7cDHLqSeaJ/VymrHZebddEDJhDtnE3SD\n"
+"t7Ed76IYBjX6DMkLHpIghXz7S4ZaQ6Jo/hCQyxg152rTvfLSgzVxp15xd5H4EoIE\n"
+"m36Lnuqxge2WXzUUqYeJSkDKD3JdwhnRqPyCMxBXgtr6hkb9cqh2WzuzN1a8G1cO\n"
+"JzWJK6kZRxHw5Mv2cMI4YuLRusbmzBTisaRLEKXI41S3Oj7IwmtKUNxYYEMoYJhr\n"
+"CGxHK+Fn+bXTjNY2SwG/ABeOcHSQVJbJdnR+plnp0Yt9nm3+Lgl9Fex5d3O7EqRR\n"
+"rdSDq4+0dJTbauUuJoXurV/HrkzKh1lnNLjWKJLqo3V622bfjOhQ6Xm4Ox48SIig\n"
+"ODCpcdBCxXTIXq9re0RBXg+FgGYvijWtI4RuQdUwD7kgjEoCaRWXuz0acbh2Vkhi\n"
+"BQ8hMIpfSZ9am0nmnUFodDioYDR4bAplQSqHCxaLi5pJxgU9GrF/xeAAnIaqX4oZ\n"
+"GS1t653V457K0n5yQ0VwrjxNiIFNbqkCAwEAATANBgkqhkiG9w0BAQUFAAOCAgEA\n"
+"biJGSf8MByu5inBXH07yoJ1gAOepTRfAmIKH328esfGuxvtoznxntcaKeRNCHEUB\n"
+"m9YqHwp+iQjbwXFhY8Es2bQ+lXtiA4N4Z7Smq3jX7n/u+hODUJvahyUQf4iMvqIX\n"
+"u4ngUBn4LyoXaF9TXlIJ/nfdLp8ciGL9m5G4tUDeCPsNDxZSfQw+xxgm76DgePDM\n"
+"EBU1iJpkyAg4MQGvC+kXMLIb036URpAdNn2w1kJeTZUj7HRT8a7VhuzmldLyAvJS\n"
+"uukHdhlc7H4DVwVG1OlqGYyOcCQ4TchWOGvZ0JoTxsMcrn/hw939eYBMpk3c4nS8\n"
+"kBn1lx4zr9Qio34SHvarfs0ycYIrG8Q04T+EOfSuoN04hoVwphJcuoJlyQdOE+b2\n"
+"goJLuepl96YePCJzPJt4WaYgv5+CqmgrroidlnHynQeiSX5I0aXRlenLfKVs3EOe\n"
+"HeoJRhVlADTyUIWZQMb80Xrd8xGE4Kxy2Hzs5H9VbOAZXh+ke7LYkfwdZi7t129n\n"
+"vL1nAeS2qCELSLf+qkK0KGyQpfGF/IDButXK4peHaf3sT0a9iR9g5cxH+DG42W3w\n"
+"GXGZicHUSZltUqbgxnue0gmXSaqke43cR+hlDRqqN+iqGazxnj8qgUqiaVWoC4jL\n"
+"WhwHlCXlqQCgBRRgJG4XD8mUCiln605LmlLd8WLLdYU=\n"
+"
private void addTestCertToTrustStore(final LanternTrustStore trustStore)
throws CertificateException, KeyStoreException {
trustStore.addCert("littleproxy", LITTLEPROXY_TEST);
}
private void hitSite(DefaultHttpClient httpClient, final String url)
throws Exception {
final HttpGet get = new HttpGet(url);
try {
log.debug("About to execute get!");
final HttpResponse response = httpClient.execute(get);
final StatusLine line = response.getStatusLine();
log.debug("Got response status: {}", line);
final HttpEntity entity = response.getEntity();
final String body = IOUtils.toString(entity.getContent());
EntityUtils.consume(entity);
log.debug("GOT RESPONSE BODY FOR EMAIL:\n"+body);
final int code = line.getStatusCode();
if (code < 200 || code > 299) {
log.error("OAuth error?\n"+line);
fail("Could not get response?");
}
} finally {
get.reset();
}
}
private GiveModeProxy startGiveModeProxy(final LanternTrustStore trustStore,
final LanternKeyStoreManager keyStoreManager) {
LanternUtils.setFallbackProxy(true);
final Model model = new Model();
model.getSettings().setServerPort(SERVER_PORT);
final SslEngineSource sslEngineSource =
new CertTrackingSslEngineSource(trustStore, keyStoreManager);
PeerFactory peerFactory = mock(PeerFactory.class);
final ClientStats stats = mock(ClientStats.class);
final GiveModeProxy proxy =
new GiveModeProxy(stats, model, sslEngineSource, peerFactory);
proxy.start();
return proxy;
}
}
|
package se.lth.cs.connect;
import org.junit.Rule;
import org.junit.Test;
import com.jayway.restassured.response.Response;
import ro.pippo.test.PippoRule;
import ro.pippo.test.PippoTest;
public class TestUserAPI extends PippoTest {
@Rule
public PippoRule pippoRule = new PippoRule(new Connect());
@Test
public void testAccessDenied() {
// These routes require an active session => requests should be denied
// Status code 401 => all is ok (expected)
// Any other code means that we have an error somewhere.
when().get("/v1/account/login").then().statusCode(401);
when().get("/v1/account/collections").then().statusCode(401);
when().get("/v1/account/self").then().statusCode(401);
when().post("/v1/account/logout").then().statusCode(401);
when().post("/v1/account/delete").then().statusCode(401);
when().post("/v1/account/change-password").then().statusCode(401);
when().get("/v1/account/invites").then().statusCode(401);
when().get("/v1/account/dat12asm@student.lu.se").then().statusCode(401);
}
@Test
public void testLifecycle() {
// This test case is not very important, but it showcases how to
// (re)use a session for multiple queries and how to create post
// requests with data.
Response reg = given().
param("email", "test@serptest.test").
param("passw", "hejsanhoppsan").
post("/v1/account/register");
reg.then().
statusCode(200);
given().
cookie("JSESSIONID", reg.getCookie("JSESSIONID")).
when().
post("/v1/account/logout").
then().
statusCode(200);
Response login = given().
param("email", "test@serptest.test").
param("passw", "hejsanhoppsan").
post("/v1/account/login");
reg.then().
statusCode(200);
given().
cookie("JSESSIONID", login.getCookie("JSESSIONID")).
when().
post("/v1/account/delete").
then().
statusCode(200);
}
}
|
package seedu.doist.testutil;
import java.util.Date;
import seedu.doist.model.tag.UniqueTagList;
import seedu.doist.model.task.Description;
import seedu.doist.model.task.FinishedStatus;
import seedu.doist.model.task.Priority;
import seedu.doist.model.task.ReadOnlyTask;
/**
* A mutable person object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private Description desc;
private Priority priority;
private FinishedStatus finishedStatus;
private UniqueTagList tags;
private Date startDate;
private Date endDate;
public TestTask() {
tags = new UniqueTagList();
finishedStatus = new FinishedStatus();
priority = new Priority();
startDate = endDate = null;
}
/**
* Creates a copy of {@code taskToCopy}.
*/
public TestTask(TestTask taskToCopy) {
this.desc = taskToCopy.getDescription();
this.priority = taskToCopy.getPriority();
this.finishedStatus = taskToCopy.getFinishedStatus();
this.tags = taskToCopy.getTags();
}
public void setName(Description desc) {
this.desc = desc;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public void setFinishedStatus(boolean isFinished) {
this.finishedStatus.setIsFinished(isFinished);
}
public void setTags(UniqueTagList tags) {
this.tags = tags;
}
@Override
public Description getDescription() {
return desc;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
public FinishedStatus getFinishedStatus() {
return finishedStatus;
}
@Override
public Date getStartDate() {
return startDate;
}
@Override
public Date getEndDate() {
return endDate;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add " + this.getDescription().desc + " ");
sb.append("\\as " + this.getPriority().toString());
if (!this.getTags().isEmpty()) {
sb.append("\\under");
this.getTags().asObservableList().stream().forEach(s -> sb.append(" " + s.tagName));
}
return sb.toString();
}
}
|
package com.openxc.messages;
import java.util.Map;
import android.os.Parcel;
import com.google.common.base.Objects;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
public class NamedVehicleMessage extends VehicleMessage {
private String mName;
public NamedVehicleMessage(String name) {
this(name, null);
}
public NamedVehicleMessage(Map<String, Object> values) {
super(values);
mName = (String)getValuesMap().remove(NAME_KEY);
}
public NamedVehicleMessage(String name, Map<String, Object> values) {
super(values);
mName = name;
}
public NamedVehicleMessage(Long timestamp, String name, Map<String, Object> values) {
super(timestamp, values);
mName = name;
}
public String getName() {
return mName;
}
@Override
public boolean equals(Object obj) {
if(obj == null || !super.equals(obj)) {
return false;
}
final NamedVehicleMessage other = (NamedVehicleMessage) obj;
return super.equals(other) && mName.equals(other.mName);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("timestamp", getTimestamp())
.add("name", getName())
.add("values", getValuesMap())
.toString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeString(getName());
}
@Override
protected void readFromParcel(Parcel in) {
super.readFromParcel(in);
mName = in.readString();
}
private NamedVehicleMessage(Parcel in)
throws UnrecognizedMeasurementTypeException {
this();
readFromParcel(in);
}
protected NamedVehicleMessage() { }
}
|
package gleem.linalg.open;
import gleem.linalg.Rotf;
import gleem.linalg.Vec3f;
import javax.media.opengl.GL;
/**
* Slerp implementation that can handle rotation, scaling and transformation.
*
* @author Marc Streit
*/
public class Slerp {
private Rotf quatResult;
private Vec3f translationResult;
private Vec3f scaleResult;
public Slerp() {
quatResult = new Rotf();
}
public Transform interpolate(Transform transformOrigin,
Transform transformDestination, float delta) {
translationResult = interpolate(transformOrigin.getTranslation(),
transformDestination.getTranslation(), delta);
scaleResult = interpolate(transformOrigin.getScale(),
transformDestination.getScale(), delta);
// Return the interpolated quaternion
quatResult = slerp(transformOrigin.getRotation(), transformDestination
.getRotation(), delta);
Transform resultTransform = new Transform();
resultTransform.setTranslation(translationResult);
resultTransform.setScale(scaleResult);
resultTransform.setRotation(quatResult);
return resultTransform;
}
public void applySlerp(final GL gl, final Transform transform,
boolean bIgnoreZRotation) {
Vec3f translation = transform.getTranslation();
Vec3f scale = transform.getScale();
Vec3f axis = new Vec3f();
float fAngle = transform.getRotation().get(axis);
// Subtract 1.5 for slerping around the views center point
// gl.glTranslatef(translation.x() - 1.5f, translation.y() - 1.5f,
// translation.z());
gl.glTranslatef(translation.x(), translation.y(), translation.z());
gl.glScalef(scale.x(), scale.y(), scale.z());
float fZRot = 0;
if (!bIgnoreZRotation)
fZRot = axis.z();
gl.glRotatef(Vec3f.convertRadiant2Grad(fAngle), axis.x(), axis.y(),
fZRot);
}
// /**
// * <code>slerp</code> sets this quaternion's value as an interpolation
// * between two other quaternions.
// *
// * @param q1
// * the first quaternion.
// * @param q2
// * the second quaternion.
// * @param t
// * the amount to interpolate between the two quaternions.
// */
// protected Rotf slerp(Rotf q1, Rotf q2, float t) {
// Rotf quatResult = new Rotf();
// // Create a local quaternion to store the interpolated quaternion
// if (q1.getX() == q2.getX() && q1.getY() == q2.getY() && q1.getZ() ==
// q2.getZ() && q1.getAngle() == q2.getAngle()) {
// quatResult.set(q1);
// return quatResult;
// float result = (q1.getX() * q2.getX()) + (q1.getY() * q2.getY()) +
// (q1.getZ() * q2.getZ())
// + (q1.getAngle() * q2.getAngle());
// if (result < 0.0f) {
// // Negate the second quaternion and the result of the dot product
// q2.setX(-q2.getX());
// q2.setY(-q2.getY());
// q2.setZ(-q2.getZ());
// q2.setAngle(-q2.getAngle());
// result = -result;
// // Set the first and second scale for the interpolation
// float scale0 = 1 - t;
// float scale1 = t;
// // Check if the angle between the 2 quaternions was big enough to
// // warrant such calculations
// if ((1 - result) > 0.1f) {// Get the angle between the 2 quaternions,
// // and then store the sin() of that angle
// float theta = (float) Math.acos(result);
// float invSinTheta = (float) (1f / Math.sin(theta));
// // Calculate the scale for q1 and q2, according to the angle and
// // it's sine value
// scale0 = (float) (Math.sin((1 - t) * theta) * invSinTheta);
// scale1 = (float) (Math.sin((t * theta)) * invSinTheta);
// // Calculate the x, y, z and w values for the quaternion by using a
// // special
// // form of linear interpolation for quaternions.
// quatResult.setX((scale0 * q1.getX()) + (scale1 * q2.getX()));
// quatResult.setY((scale0 * q1.getY()) + (scale1 * q2.getY()));
// quatResult.setZ((scale0 * q1.getZ()) + (scale1 * q2.getZ()));
// quatResult.setAngle((scale0 * q1.getAngle()) + (scale1 * q2.getAngle()));
// // Return the interpolated quaternion
// return quatResult;
/**
* <code>slerp</code> sets this quaternion's value as an interpolation
* between two other quaternions.
*
* @param q1
* the first quaternion.
* @param q2
* the second quaternion.
* @param t
* the amount to interpolate between the two quaternions.
*/
protected Rotf slerp(Rotf q1, Rotf q2, float t) {
Rotf quatResult = new Rotf();
Vec3f vecQ1Axis = new Vec3f();
float fQ1Angle = q1.get(vecQ1Axis);
Vec3f vecQ2Axis = new Vec3f();
float fQ2Angle = q2.get(vecQ2Axis);
// Create a local quaternion to store the interpolated quaternion
if (vecQ1Axis.x() == vecQ2Axis.x() && vecQ1Axis.y() == vecQ2Axis.y()
&& vecQ1Axis.z() == vecQ2Axis.z() && fQ1Angle == fQ2Angle) {
quatResult.set(q1);
return quatResult;
}
float result = vecQ1Axis.x() * vecQ2Axis.x() + vecQ1Axis.y()
* vecQ2Axis.y() + vecQ1Axis.z() * vecQ2Axis.z() + fQ1Angle
* fQ2Angle;
if (result < 0.0f) {
// Negate the second quaternion and the result of the dot product
q2.set(new Vec3f(-vecQ2Axis.x(), -vecQ2Axis.y(), -vecQ2Axis.z()),
-fQ2Angle);
fQ2Angle = q2.get(vecQ2Axis);
result = -result;
}
// Set the first and second scale for the interpolation
float scale0 = 1 - t;
float scale1 = t;
// Check if the angle between the 2 quaternions was big enough to
// warrant such calculations
if (1 - result > 0.1f) {// Get the angle between the 2 quaternions,
// and then store the sin() of that angle
float theta = (float) Math.acos(result);
float invSinTheta = (float) (1f / Math.sin(theta));
// Calculate the scale for q1 and q2, according to the angle and
// it's sine value
scale0 = (float) (Math.sin((1 - t) * theta) * invSinTheta);
scale1 = (float) (Math.sin((t * theta)) * invSinTheta);
}
// Calculate the x, y, z and w values for the quaternion by using a
// special
// form of linear interpolation for quaternions.
quatResult.set(new Vec3f(scale0 * vecQ1Axis.x() + scale1
* vecQ2Axis.x(), scale0 * vecQ1Axis.y() + scale1
* vecQ2Axis.y(), scale0 * vecQ1Axis.z() + scale1
* vecQ2Axis.z()), scale0 * fQ1Angle + scale1 * fQ2Angle);
// Return the interpolated quaternion
return quatResult;
}
/**
* Sets this vector to the interpolation by changeAmnt from beginVec to
* finalVec this=(1-changeAmnt)*beginVec + changeAmnt * finalVec
*
* @param beginVec
* the begin vector (changeAmnt=0)
* @param finalVec
* The final vector to interpolate towards
* @param changeAmnt
* An amount between 0.0 - 1.0 representing a percentage change
* from beginVec towards finalVec
*/
public Vec3f interpolate(Vec3f beginVec, Vec3f finalVec, float changeAmnt) {
Vec3f result = new Vec3f();
result
.setX((1 - changeAmnt) * beginVec.x() + changeAmnt
* finalVec.x());
result
.setY((1 - changeAmnt) * beginVec.y() + changeAmnt
* finalVec.y());
result
.setZ((1 - changeAmnt) * beginVec.z() + changeAmnt
* finalVec.z());
return result;
}
public Vec3f getTranslationResult() {
return translationResult;
}
public Vec3f getScaleResult() {
return scaleResult;
}
}
|
package islam.adhanalarm;
import net.sourceforge.jitl.Method;
import net.sourceforge.jitl.Rounding;
import uz.efir.muazzin.R;
/**
* TODO: delete this class
*/
public class CONSTANT {
public static final String[][] CALCULATION_METHOD_COUNTRY_CODES = new String[][]{
/** METHOD_EGYPT_SURVEY: Africa, Syria, Iraq, Lebanon, Malaysia, Parts of the USA **/
new String[]{
// Africa
"AGO", "BDI", "BEN", "BFA", "BWA", "CAF", "CIV", "CMR", "COG", "COM", "CPV", "DJI", "DZA", "EGY", "ERI", "ESH", "ETH", "GAB", "GHA", "GIN", "GMB", "GNB", "GNQ", "KEN", "LBR", "LBY", "LSO", "MAR", "MDG", "MLI", "MOZ", "MRT", "MUS", "MWI", "MYT", "NAM", "NER", "NGA", "REU", "RWA", "SDN", "SEN", "SLE", "SOM", "STP", "SWZ", "SYC", "TCD", "TGO", "TUN", "TZA", "UGA", "ZAF", "ZAR", "ZWB", "ZWE",
// Syria, Iraq, Lebanon, Malaysia
"IRQ", "LBN", "MYS", "SYR"
},
new String[]{},
/** METHOD_KARACHI_HANAF: Pakistan, Bangladesh, India, Afghanistan, Parts of Europe **/
new String[]{"AFG", "BGD", "IND", "PAK"},
/** METHOD_NORTH_AMERICA: Parts of the USA, Canada, Parts of the UK **/
new String[]{"USA", "CAN"},
/** METHOD_MUSLIM_LEAGUE: Europe, The Far East, Parts of the USA **/
new String[]{
// Europe
"AND", "AUT", "BEL", "DNK", "FIN", "FRA", "DEU", "GIB", "IRL", "ITA", "LIE", "LUX", "MCO", "NLD", "NOR", "PRT", "SMR", "ESP", "SWE", "CHE", "GBR", "VAT",
// Far East
"CHN", "JPN", "KOR", "PRK", "TWN"
},
/** METHOD_UMM_ALQURRA: The Arabian Peninsula **/
new String[]{"BHR", "KWT", "OMN", "QAT", "SAU", "YEM"},
new String[]{}
};
public static final Method[] CALCULATION_METHODS = new Method[]{Method.EGYPT_SURVEY, Method.KARACHI_SHAF, Method.KARACHI_HANAF, Method.NORTH_AMERICA, Method.MUSLIM_LEAGUE, Method.UMM_ALQURRA, Method.FIXED_ISHAA};
public static final short DEFAULT_CALCULATION_METHOD = 5; // UMM_ALQURRA
public static final short FAJR = 0, SUNRISE = 1, DHUHR = 2, ASR = 3, MAGHRIB = 4, ISHAA = 5, NEXT_FAJR = 6; // Notification Times
public static int[] TIME_NAMES = new int[]{R.string.fajr, R.string.sunrise, R.string.dhuhr, R.string.asr, R.string.maghrib, R.string.ishaa, R.string.next_fajr};
public static final short NOTIFICATION_NONE = 0, NOTIFICATION_DEFAULT = 1, NOTIFICATION_PLAY = 2, NOTIFICATION_CUSTOM = 3; // Notification Methods
public static final Rounding[] ROUNDING_METHODS = new Rounding[]{Rounding.NONE, Rounding.NORMAL, Rounding.SPECIAL, Rounding.AGRESSIVE};
public static final short DEFAULT_ROUNDING_INDEX = 2; // Special
public static final String EXTRA_ACTUAL_TIME = "extra_actual_time";
public static final String EXTRA_TIME_INDEX = "extra_time_index";
private CONSTANT() {
// Private constructor to enforce un-instantiability.
}
}
|
package wyrw.util;
import java.util.ArrayList;
import java.util.Arrays;
import wyautl.core.Automaton;
import wyautl.util.BinaryMatrix;
import static wyautl.core.Automata.*;
/**
* <p>
* Responsible for efficiently ensuring an automaton remains properly minimised
* and compacted after a rewrite operation has occurred. Rewrites can result in
* the presence of multiple equivalent states, though not always. For example,
* consider this automaton:
* </p>
*
* <pre>
* Or
* / \
* And And
* | |
* "X" "Y"
* </pre>
*
* <p>
* Now, suppose we rewrite state "X" to "Y", then their parent nodes become
* equivalent and should be merged. The purpose of this algorithm is to do this
* efficiently without traversing the entire automaton.
* </p>
*
* <p>
* The algorithm works by firstly maintaining the set of "parents" for each
* state. That is the set of states for which this state is a direct child.
* Since automata are directed graphs states can multiple parents (i.e. unlike
* trees, where each node has exactly one parent). Since we expect relatively
* few parents for each state, an array is used for this purpose.
* </p>
* <p>
* Given knowledge of the parents for each state, the algorithm can now
* efficiently determine the "cone" of states which could be equivalent after a
* rewrite. Specifically, the parents of the states involved in the rewrite are
* candidates for equivalence. Furthermore, if they are equivalent then their
* parents are candidates for being equivalent and so on, until we fail to find
* an equivalent pair of parents or we reach a root state.
* </p>
* <p>
* <b>NOTE</b>: this algorithm should eventually be properly integrated with the
* Automaton data structure. At this stage, I have avoided doing this simply
* because of the work involved in doing it.
* </p>
*
* @author David J. Pearce
*
*/
public class IncrementalAutomatonMinimiser {
/**
* The automaton for which the incremental information is being maintained.
*/
private final Automaton automaton;
/**
* This represents the set of parents for each state in the automaton. This
* is a list because we will need to expand it as the automaton increases in
* size (which it likely will as rewrites occur).
*/
private final ArrayList<ParentInfo> parents;
public IncrementalAutomatonMinimiser(Automaton automaton) {
this.automaton = automaton;
this.parents = determineParents(automaton);
}
/**
* <p>
* Update the automaton after a successful rewrite has occurred. The goal
* here is to ensure: 1) the automaton remains in minimised form; 2) that
* all unreachable states are nullified; 3) that the parents information is
* up-to-date.
* </p>
* <p>
* To ensure the automaton remains in minimised form, we need to collapse
* any states which have been rendered equivalent by the rewrite. By
* definition, these states must be parents of the two states involved in
* the rewrite. There are two cases to consider. If the rewrite is to a
* fresh state, then we are guaranteed that no equivalent states are
* generated. On the otherhand, if the rewrite is to an existing state, then
* there is potential for equivalent states to arise. In both cases, we must
* first update the parents of those states involved.
* </p>
*
* @param from
* @param to
*/
public void rewrite(int from, int to, int pivot) {
if(to > Automaton.K_VOID) {
ParentInfo fromParents = parents.get(from);
expandParents();
// Copy parents to target state
rewriteParents(from, to);
// Eliminate all states made unreachable
eliminateUnreachableState(from);
// Eliminate unreachable states above pivot
eliminateUnreachableAbovePivot(pivot);
checkParentsInvariant();
// Second, collapse any equivalent vertices
// TODO: only collapse if target state is new?
collapseEquivalentParents(from, to, fromParents);
// TODO: resize to first unused slot above pivot; this should help
// prevent the automaton grow too quickly.
} else {
eliminateUnreachableState(from);
}
checkParentsInvariant();
// NOTE: what about fresh states added which were immediately
// unreachable. For example, they were added to implement a check. We
// could eliminate these by compacting "above the pivot".
}
public void substitute(int source, int from, int to) {
}
/**
* <p>
* The given state has become unreachable. Therefore, we need to recursively
* eliminate any children of this state which are also eliminated as a
* result. To do this, we remove this state from the parents set of its
* children. If any of those children now have an empty set of parents, then
* we recursively eliminate them as well
* </p>
* <p>
* <b>NOTE:</b> The major problem with this algorithm is, likely many
* garbage collection algorithms, that it does not guarantee to eliminate
* all unreachable states. In particular, no state involved in a cycle will
* be reclaimed as it will always have at least one parent. <i>At this
* stage, it remains to determine how best to resolve this problem. One
* solution maybe to record the "dominator" for each state. That way, you
* could tell whether a state which was unreachable dominated a child and,
* hence, it too was unreachable.</i>
* </p>
*
* @param parent
* Index of the state in question.
*/
private void eliminateUnreachableState(int parent) {
// FIXME: figure out solution for cycles (see above).
Automaton.State state = automaton.get(parent);
// First, check whether state already removed
if (state != null) {
// Second, physically remove the state in question
automaton.set(parent, null);
parents.set(parent, null);
// Third, update parental information for any children
switch (state.kind) {
case Automaton.K_BOOL:
case Automaton.K_INT:
case Automaton.K_REAL:
case Automaton.K_STRING:
// no children
return;
case Automaton.K_LIST:
case Automaton.K_SET:
case Automaton.K_BAG: {
// lots of children :)
Automaton.Collection c = (Automaton.Collection) state;
for (int i = 0; i != c.size(); ++i) {
int child = c.get(i);
if(child > Automaton.K_VOID) {
ParentInfo pinfo = parents.get(child);
pinfo.removeAll(parent);
if (pinfo.size() == 0 && !isRoot(child)) {
// this state is now unreachable as well
eliminateUnreachableState(child);
}
}
}
return;
}
default:
// terms
Automaton.Term t = (Automaton.Term) state;
int child = t.contents;
if(child > Automaton.K_VOID) {
ParentInfo pinfo = parents.get(child);
pinfo.removeAll(parent);
if (pinfo.size() == 0 && !isRoot(child)) {
// this state is now unreachable as well
eliminateUnreachableState(child);
}
}
}
}
}
private boolean isRoot(int index) {
int nRoots = automaton.nRoots();
for(int i=0;i!=nRoots;++i) {
if(automaton.getRoot(i) == index) {
return true;
}
}
return false;
}
private void eliminateUnreachableAbovePivot(int pivot) {
for(int i=pivot;i!=automaton.nStates();++i) {
Automaton.State s = automaton.get(i);
if(s != null && parents.get(i) == null) {
automaton.set(i, null);
}
}
}
private void rewriteParents(int from, int to) {
ParentInfo fromParents = parents.get(from);
ParentInfo toParents = parents.get(to);
if(toParents == null) {
parents.set(to, fromParents);
addParentToChildren(to);
} else {
toParents.addAll(fromParents);
}
parents.set(from, null);
}
private void addParent(int parent, int child) {
ParentInfo pinfo = parents.get(child);
if(pinfo == null) {
// This is a fresh state
pinfo = new ParentInfo(1);
parents.set(child, pinfo);
addParentToChildren(child);
}
pinfo.add(parent);
}
/**
* Add a given state as a parent for all its children. The assumption is
* that this state would be fresh.
*
* @param child
*/
private void addParentToChildren(int child) {
Automaton.State state = automaton.get(child);
switch (state.kind) {
case Automaton.K_BOOL:
case Automaton.K_INT:
case Automaton.K_REAL:
case Automaton.K_STRING:
// no children
break;
case Automaton.K_LIST:
case Automaton.K_SET:
case Automaton.K_BAG: {
// lots of children :)
Automaton.Collection c = (Automaton.Collection) state;
for (int i = 0; i != c.size(); ++i) {
int grandChild = c.get(i);
if(grandChild > Automaton.K_VOID) {
addParent(child,grandChild);
}
}
break;
}
default:
// terms
Automaton.Term t = (Automaton.Term) state;
int grandChild = t.contents;
if(grandChild > Automaton.K_VOID) {
addParent(child,grandChild);
}
}
}
/**
* Ensure there are enough entries in the parents array after a rewrite has occurred.
*/
private void expandParents() {
int size = parents.size();
int nStates = automaton.nStates();
while(size < nStates) {
parents.add(null);
size = size + 1;
}
}
/**
* <p>
* Given two states, collapse any parents which are now equivalent. To do
* this, we compare each parent from the first state against all from the
* second, etc. Whenever an equivalent pairing is found we must then explore
* those parents of the pairing, etc.
* </p>
* <p>
* The algorithm works using a worklist containing candidates pairs which
* should be explored. The algorithm also maintains the set of states now
* determined as equivalent. This is necessary when comparing two states to
* determine if they are equivalent, as their equivalence may depend on two
* child states which were previously determined as equivalent. Furthermore,
* in the end, we need to determine which states to actually collapse.
* </p>
* <p>
* <b>NOTE:</b> the algorithm potential does more work than necessary. This
* is because it can end up retesting some candidate pairs more than once,
* though this is perhaps a rather unusual case to encounter. To avoid this,
* we could additionally record candidate pairs which are shown *not* to be
* equivalent (but, actually, this might fail if children are subsequently
* found to be equivalent).
* </p>
*
* @param from
* @param to
* @param fromParents
*/
private void collapseEquivalentParents(int from, int to, ParentInfo fromParents) {
ParentInfo toParents = parents.get(to);
// FIXME: the following operations are linear (or worse) in the size of the
// automaton. Therefore, we want to eliminate this by using a more compact representation.
IntStack worklist = new IntStack(2 * (fromParents.size * toParents.size));
BinaryMatrix equivs = initialiseEquivalences();
// First, determine all potentially equivalent parents (if any)
addCandidatesToWorklist(worklist,equivs,fromParents,toParents);
// Second, iterate until all equivalences are determined. When an
// equivalent is found recursively explore their parents.
while (worklist.size > 0) {
to = worklist.pop();
from = worklist.pop();
if (!equivs.get(from, to) && equivalent(automaton, equivs, from, to)) {
equivs.set(from, to, true);
addCandidatesToWorklist(worklist, equivs, parents.get(from), parents.get(to));
}
}
// Third, collapse all states now determined to be equivalent.
collapseEquivalences(equivs);
}
private BinaryMatrix initialiseEquivalences() {
BinaryMatrix equivs = new BinaryMatrix(automaton.nStates(),automaton.nStates(),false);
for(int i=0;i!=automaton.nStates();++i) {
equivs.set(i, i, true);
}
return equivs;
}
private void addCandidatesToWorklist(IntStack worklist, BinaryMatrix equivs, ParentInfo fromParents,
ParentInfo toParents) {
int[] from_parents = fromParents.parents;
int[] to_parents = toParents.parents;
for (int i = 0; i != fromParents.size; ++i) {
int from_parent = from_parents[i];
Automaton.State from_state = automaton.get(from_parent);
for (int j = 0; j != toParents.size; ++j) {
int to_parent = to_parents[j];
Automaton.State to_state = automaton.get(to_parent);
if (!equivs.get(from_parent, to_parent) && from_state.kind == to_state.kind) {
// Only add candidates which could actually be the same.
// This is a simple optimisation which should reduce work
// considerably.
worklist.push(from_parent);
worklist.push(to_parent);
}
}
}
}
/**
* <p>
* Collapse all states which are determined to be equivalent together. This
* modifies the automaton in a potentially destructive fashion. The main
* objective is to do this in time proportional to the number of equivalent
* states (roughly speaking) rather than in time proportional to the size of
* the automaton. This function does not compact the automaton, however.
* Hence, there will be states remaining which are "null".
* </p>
* <p>
* To collapse a set of equivalent states, we must remap their parent states
* to now refer to the set's representative state. We must also update the
* parent references for any child states. Finally, we delete (i.e. set to
* null) any states which equivalent to some other representative.
* </p>
*
* @param equivs
*/
private void collapseEquivalences(BinaryMatrix equivs) {
// FIXME: these operations are all linear in size of automaton!
int[] mapping = new int[automaton.nStates()];
// Determine representative states for all equivalence classes. In other
// words, for any set of equivalent states, determine which one of them
// is to be the "representative" which remains.
determineRepresentativeStates(automaton,equivs,mapping);
// Collapse all equivalence classes to a single state. Thus, the
// representative for each class remains and all references to members of
// that class are redirected to the representative.
collapseEquivalenceClasses(automaton,mapping);
// Finally, update the parent links for all vertices and delete those
// records for states which are eliminated.
int nStates = automaton.nStates();
for (int i = 0; i != nStates; ++i) {
if(mapping[i] != i) {
// This state has be subsumed by another state which was the
// representative for its equivalence class. Therefore, the
// state must now be unreachable.
parents.set(i, null);
} else {
ParentInfo pinfo = parents.get(i);
if(pinfo != null) {
// This state is the unique representative for its equivalence
// class. Therefore, retain it whilst remapping all of its
// references appropriately.
pinfo.remap(mapping);
}
}
}
}
/**
* Check that every parent of a state has that state as a child. This is the
* fundamental invariant which should be maintained by the parents array.
*/
private void checkParentsInvariant() {
for(int i=0;i!=parents.size();++i) {
ParentInfo pinfo = parents.get(i);
if(pinfo != null) {
for(int j=0;j!=pinfo.size();++j) {
int parent = pinfo.get(j);
checkIsChildOf(parent,i);
}
}
}
}
/**
* Check that one state is a child of another
*/
private void checkIsChildOf(int parent, int child) {
Automaton.State state = automaton.get(parent);
if(state != null) {
switch (state.kind) {
case Automaton.K_BOOL:
case Automaton.K_INT:
case Automaton.K_REAL:
case Automaton.K_STRING:
// no children
break;
case Automaton.K_LIST:
case Automaton.K_SET:
case Automaton.K_BAG: {
// lots of children :)
Automaton.Collection c = (Automaton.Collection) state;
if(c.contains(child)) {
return;
}
break;
}
default:
// terms
Automaton.Term t = (Automaton.Term) state;
if(t.contents == child) {
return;
}
}
}
throw new RuntimeException("*** INVALID PARENTS INVARIANT: " + child + " NOT CHILD OF " + parent);
}
/**
* Compute the parents for each state in the automaton from scratch. This is
* done using several linear traversals over the states to minimise the
* amount of memory churn and ensure linear time.
*
* @param automaton
* @return
*/
private static ArrayList<ParentInfo> determineParents(Automaton automaton) {
int[] counts = new int[automaton.nStates()];
// first, visit all nodes
for (int i = 0; i != automaton.nStates(); ++i) {
updateParentCounts(automaton.get(i),i,counts);
}
ArrayList<ParentInfo> parents = new ArrayList<ParentInfo>();
for (int i = 0; i != automaton.nStates(); ++i) {
parents.add(new ParentInfo(counts[i]));
}
for (int i = 0; i != automaton.nStates(); ++i) {
updateParents(automaton.get(i),i,parents);
}
return parents;
}
private static void updateParentCounts(Automaton.State state, int parent, int[] counts) {
switch(state.kind) {
case Automaton.K_BOOL:
case Automaton.K_INT:
case Automaton.K_REAL:
case Automaton.K_STRING:
return;
case Automaton.K_LIST:
case Automaton.K_SET:
case Automaton.K_BAG: {
Automaton.Collection c = (Automaton.Collection) state;
for(int i=0;i!=c.size();++i) {
int child = c.get(i);
if(child > Automaton.K_VOID) {
counts[child]++;
}
}
break;
}
default:
// terms
Automaton.Term t = (Automaton.Term) state;
int child = t.contents;
if(child > Automaton.K_VOID) {
counts[child]++;
}
}
}
private static void updateParents(Automaton.State state, int parent, ArrayList<ParentInfo> parents) {
switch(state.kind) {
case Automaton.K_BOOL:
case Automaton.K_INT:
case Automaton.K_REAL:
case Automaton.K_STRING:
return;
case Automaton.K_LIST:
case Automaton.K_SET:
case Automaton.K_BAG: {
Automaton.Collection c = (Automaton.Collection) state;
for(int i=0;i!=c.size();++i) {
int child = c.get(i);
if(child > Automaton.K_VOID) {
parents.get(child).add(parent);
}
}
break;
}
default:
// terms
Automaton.Term t = (Automaton.Term) state;
int child = t.contents;
if(child > Automaton.K_VOID) {
parents.get(child).add(parent);
}
}
}
/**
* A simple data structure for representing the parent information. This
* could be made more interesting, for example, by using a sorted array. Or,
* perhaps, a compressed bitset.
*
* @author David J. Pearce
*
*/
private static final class ParentInfo {
private int[] parents;
private int size;
public ParentInfo(int capacity) {
this.parents = new int[capacity];
this.size = 0;
}
public int size() {
return size;
}
public int get(int index) {
return parents[index];
}
public void add(int parent) {
int index = indexOf(parents,size,parent);
if(index == -1) {
ensureCapacity((size+1)*1);
parents[size++] = parent;
}
}
public void addAll(ParentInfo pinfo) {
int pinfo_size = pinfo.size;
ensureCapacity(size+pinfo_size);
for(int i=0;i!=pinfo_size;++i) {
int parent = pinfo.parents[i];
if(indexOf(parents,size,parent) == -1) {
parents[size++] = parent;
}
}
}
public void removeAll(int parent) {
int index;
// FIXME: this could be optimised
while ((index = indexOf(parents, size, parent)) != -1) {
System.arraycopy(parents, index + 1, parents, index, size - (index + 1));
size = size - 1;
}
}
public void remap(int[] mapping) {
for (int i = 0; i != size; ++i) {
parents[i] = mapping[parents[i]];
}
}
public void replace(int from, int to) {
int j = indexOf(parents,size,to);
if(j == -1) {
for(int i=0;i!=size;++i) {
if(parents[i] == from) {
parents[i] = to;
}
}
} else {
removeAll(from);
}
}
public boolean contains(int parent) {
return indexOf(parents,size,parent) != -1;
}
public String toString() {
String r = "";
for(int i=0;i!=size;++i) {
if(i != 0) { r += ","; }
r = r + i;
}
return "{" + r + "}";
}
private void ensureCapacity(int capacity) {
if(parents.length < capacity) {
parents = Arrays.copyOf(parents, capacity);
}
}
private static int indexOf(int[] array, int size, int element) {
for(int i=0;i!=size;++i) {
if(array[i] == element) {
return i;
}
}
return -1;
}
}
}
|
package joliex.io;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.parser.XSOMParser;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;
import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.jap.JapURLConnection;
import jolie.runtime.AndJarDeps;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.embedding.RequestResponse;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author Fabrizio Montesi
*/
@AndJarDeps({"jolie-xml.jar","xsom.jar"})
public class FileService extends JavaService
{
private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
private FileTypeMap fileTypeMap = FileTypeMap.getDefaultFileTypeMap();
public FileService()
{
super();
documentBuilderFactory.setIgnoringElementContentWhitespace( true );
}
@RequestResponse
public void setMimeTypeFile( String filename )
throws FaultException
{
try {
fileTypeMap = new MimetypesFileTypeMap( filename );
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
}
private static void readBase64IntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
value.setValue( encoder.encode( buffer ) );
}
private static void readBinaryIntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
value.setValue( new ByteArray( buffer ) );
}
private void readXMLIntoValue( InputStream istream, Value value )
throws IOException
{
try {
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new InputStreamReader( istream ) );
Document doc = builder.parse( src );
value = value.getFirstChild( doc.getDocumentElement().getNodeName() );
jolie.xml.XmlUtils.documentToValue( doc, value );
} catch( ParserConfigurationException e ) {
throw new IOException( e );
} catch( SAXException e ) {
throw new IOException( e );
}
}
private static void readTextIntoValue( InputStream istream, long size, Value value )
throws IOException
{
byte[] buffer = new byte[ (int)size ];
istream.read( buffer );
istream.close();
value.setValue( new String( buffer ) );
}
public Value readFile( Value request )
throws FaultException
{
Value filenameValue = request.getFirstChild( "filename" );
Value retValue = Value.create();
String format = request.getFirstChild( "format" ).strValue();
File file = new File( filenameValue.strValue() );
InputStream istream = null;
long size;
try {
if ( file.exists() ) {
istream = new FileInputStream( file );
size = file.length();
} else {
URL fileURL = interpreter().getClassLoader().findResource( filenameValue.strValue() );
if ( fileURL != null && fileURL.getProtocol().equals( "jap" ) ) {
URLConnection conn = fileURL.openConnection();
if ( conn instanceof JapURLConnection ) {
JapURLConnection jarConn = (JapURLConnection)conn;
size = jarConn.getEntrySize();
if ( size < 0 ) {
throw new IOException( "File dimension is negative for file " + fileURL.toString() );
}
istream = jarConn.getInputStream();
} else {
throw new FileNotFoundException( filenameValue.strValue() );
}
} else {
throw new FileNotFoundException( filenameValue.strValue() );
}
}
istream = new BufferedInputStream( istream );
try {
if ( "base64".equals( format ) ) {
readBase64IntoValue( istream, size, retValue );
} else if ( "binary".equals( format ) ) {
readBinaryIntoValue( istream, size, retValue );
} else if ( "xml".equals( format ) ) {
readXMLIntoValue( istream, retValue );
} else {
readTextIntoValue( istream, size, retValue );
}
} finally {
istream.close();
}
} catch( FileNotFoundException e ) {
throw new FaultException( "FileNotFound" );
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
return retValue;
}
public String getMimeType( String filename )
throws FaultException
{
File file = new File( filename );
if ( file.exists() == false ) {
throw new FaultException( "FileNotFound" );
}
return fileTypeMap.getContentType( file );
}
public String getServiceDirectory()
{
String dir = null;
try {
dir = interpreter().programDirectory().getCanonicalPath();
} catch( IOException e ) {
e.printStackTrace();
}
if ( dir == null || dir.isEmpty() ) {
dir = ".";
}
return dir;
}
public String getFileSeparator()
{
return jolie.lang.Constants.fileSeparator;
}
private void writeXML( File file, Value value, boolean append, String schemaFilename )
throws IOException
{
if ( value.children().isEmpty() ) {
return; // TODO: perhaps we should erase the content of the file before returning.
}
String rootName = value.children().keySet().iterator().next();
try {
XSType type = null;
if ( schemaFilename != null ) {
try {
XSOMParser parser = new XSOMParser();
parser.parse( schemaFilename );
XSSchemaSet schemaSet = parser.getResult();
if ( schemaSet != null ) {
type = schemaSet.getElementDecl( "", rootName ).getType();
}
} catch( SAXException e ) {
throw new IOException( e );
}
}
Document doc = documentBuilderFactory.newDocumentBuilder().newDocument();
if ( type == null ) {
jolie.xml.XmlUtils.valueToDocument(
value.getFirstChild( rootName ),
rootName,
doc
);
} else {
jolie.xml.XmlUtils.valueToDocument(
value.getFirstChild( rootName ),
rootName,
doc,
type
);
}
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
Writer writer = new FileWriter( file, append );
StreamResult result = new StreamResult( writer );
transformer.transform( new DOMSource( doc ), result );
} catch( ParserConfigurationException e ) {
throw new IOException( e );
} catch( TransformerConfigurationException e ) {
throw new IOException( e );
} catch( TransformerException e ) {
throw new IOException( e );
}
}
private static void writeBinary( File file, Value value, boolean append )
throws IOException
{
FileOutputStream os = new FileOutputStream( file, append );
os.write( value.byteArrayValue().getBytes() );
os.flush();
os.close();
}
private static void writeText( File file, Value value, boolean append )
throws IOException
{
FileWriter writer = new FileWriter( file, append );
writer.write( value.strValue() );
writer.flush();
writer.close();
}
@RequestResponse
public void writeFile( Value request )
throws FaultException
{
boolean append = false;
Value content = request.getFirstChild( "content" );
String format = request.getFirstChild( "format" ).strValue();
File file = new File( request.getFirstChild( "filename" ).strValue() );
if ( request.getFirstChild( "append" ).intValue() > 0 ) {
append = true;
}
try {
if ( "text".equals( format ) ) {
writeText( file, content, append );
} else if ( "binary".equals( format ) ) {
writeBinary( file, content, append );
} else if ( "xml".equals( format ) ) {
String schemaFilename = null;
if ( request.getFirstChild( "format" ).hasChildren( "schema" ) ) {
schemaFilename = request.getFirstChild( "format" ).getFirstChild( "schema" ).strValue();
}
writeXML( file, content, append, schemaFilename );
} else if ( format.isEmpty() ) {
if ( content.isByteArray() ) {
writeBinary( file, content, append );
} else {
writeText( file, content, append );
}
}
} catch( IOException e ) {
throw new FaultException( "IOException", e );
}
}
public Boolean delete( Value request )
{
String filename = request.strValue();
boolean isRegex = request.getFirstChild( "isRegex" ).intValue() > 0;
boolean ret = true;
if ( isRegex ) {
File dir = new File( filename ).getAbsoluteFile().getParentFile();
String[] files = dir.list( new ListFilter( filename ) );
if ( files != null ) {
for( String file : files ) {
new File( file ).delete();
}
}
} else {
if ( new File( filename ).delete() == false ) {
ret = false;
}
}
return ret;
}
@RequestResponse
public void rename( Value request )
throws FaultException
{
String filename = request.getFirstChild( "filename" ).strValue();
String toFilename = request.getFirstChild( "to" ).strValue();
if ( new File( filename ).renameTo( new File( toFilename ) ) == false ) {
throw new FaultException( "IOException" );
}
}
public Value list( Value request )
{
File dir = new File( request.getFirstChild( "directory" ).strValue() );
String[] files = dir.list( new ListFilter( request.getFirstChild( "regex" ).strValue() ) );
Value response = Value.create();
if ( files != null ) {
ValueVector results = response.getChildren( "result" );
for( String file : files ) {
results.add( Value.create( file ) );
}
}
return response;
}
private static class ListFilter implements FilenameFilter
{
final private Pattern pattern;
public ListFilter( String regex )
{
this.pattern = Pattern.compile( regex );
}
public boolean accept( File file, String name )
{
return pattern.matcher( name ).matches();
}
}
}
|
package org.jpos.util;
import org.jpos.core.Configurable;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import org.jpos.util.BlockingQueue.Closed;
import org.jpos.util.NameRegistrar.NotFoundException;
import java.io.PrintStream;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Implements a ThreadPool with the ability to run simple Runnable
* tasks as well as Jobs (supervised Runnable tasks)
* @since 1.1
* @author apr@cs.com.uy
* @deprecated Used Executor framework
*/
public class ThreadPool extends ThreadGroup implements LogSource, Loggeable, Configurable, ThreadPoolMBean {
private static AtomicInteger poolNumber = new AtomicInteger(0);
private static AtomicInteger threadNumber = new AtomicInteger(0);
private int maxPoolSize = 1;
private int available;
private int running = 0;
private int active = 0;
private BlockingQueue pool = new BlockingQueue();
private Logger logger;
private String realm;
private int jobs = 0;
private final String namePrefix;
public static final int DEFAULT_MAX_THREADS = 100;
public interface Supervised {
boolean expired();
}
private class PooledThread extends Thread {
Object currentJob = null;
public PooledThread() {
super (ThreadPool.this,
ThreadPool.this.namePrefix + ".PooledThread-" + threadNumber.getAndIncrement());
setDaemon(true);
}
public void run () {
String name = getName();
try {
while (pool.ready()) {
Object job = pool.dequeue();
if (job instanceof Runnable) {
setName (name + "-running");
synchronized (this) {
currentJob = job;
}
try {
active++;
((Runnable) job).run();
setName (name + "-idle");
} catch (Throwable t) {
setName (name + "-idle-"+t.getMessage());
}
synchronized (this) {
currentJob = null;
available++;
active
}
} else {
synchronized (this) {
currentJob = null;
available++;
}
}
}
} catch (InterruptedException e) {
if (logger != null) {
Logger.log(new LogEvent(ThreadPool.this, e.getMessage()));
}
} catch (Closed e) {
if (logger != null) {
Logger.log(new LogEvent(ThreadPool.this, e.getMessage()));
}
}
}
public synchronized void supervise () {
if (currentJob != null && currentJob instanceof Supervised && ((Supervised)currentJob).expired())
this.interrupt();
}
}
/**
* @param poolSize starting pool size
* @param maxPoolSize maximum number of threads on this pool
*/
public ThreadPool (int poolSize, int maxPoolSize) {
this(poolSize, maxPoolSize, "ThreadPool");
}
/**
* @param name pool name
* @param poolSize starting pool size
* @param maxPoolSize maximum number of threads on this pool
*/
public ThreadPool (int poolSize, int maxPoolSize, String name) {
super(name + "-" + poolNumber.getAndIncrement());
this.maxPoolSize = maxPoolSize > 0 ? maxPoolSize : DEFAULT_MAX_THREADS ;
this.available = this.maxPoolSize;
this.namePrefix = name;
init (poolSize);
}
private void init(int poolSize){
while (running < Math.min (poolSize > 0 ? poolSize : 1, maxPoolSize)) {
running++;
new PooledThread().start();
}
}
/**
* Default constructor for ThreadPool
*/
public ThreadPool () {
this(1, DEFAULT_MAX_THREADS);
}
public void close () {
pool.close();
}
public synchronized void execute(Runnable action) throws Closed {
if (!pool.ready())
throw new Closed();
if (++jobs % this.maxPoolSize == 0 || pool.consumerCount() <= 0)
supervise();
if (running < maxPoolSize && pool.consumerDeficit() >= 0) {
new PooledThread().start();
running++;
}
available
pool.enqueue (action);
}
public void dump (PrintStream p, String indent) {
String inner = indent + " ";
p.println (indent + "<thread-pool name=\""+getName()+"\">");
if (!pool.ready())
p.println (inner + "<closed/>");
p.println (inner + "<jobs>" + getJobCount() + "</jobs>");
p.println (inner + "<size>" + getPoolSize() + "</size>");
p.println (inner + "<max>" + getMaxPoolSize() + "</max>");
p.println (inner + "<active>" + getActiveCount() + "</active>");
p.println (inner + "<idle>" + getIdleCount() + "</idle>");
p.println (inner + "<active>" + getActiveCount() + "</active>");
p.println (inner + "<pending>" + getPendingCount() + "</pending>");
p.println (indent + "</thread-pool>");
}
/**
* @return number of jobs processed by this pool
*/
public int getJobCount () {
return jobs;
}
/**
* @return number of running threads
*/
public int getPoolSize () {
return running;
}
/**
* @return max number of active threads allowed
*/
public int getMaxPoolSize () {
return maxPoolSize;
}
/**
* @return number of active threads
*/
public int getActiveCount () {
return active;
}
/**
* @return number of idle threads
*/
public int getIdleCount () {
return pool.consumerCount ();
}
/**
* @return number of available threads
*/
synchronized public int getAvailableCount () {
return available;
}
/**
* @return number of Pending jobs
*/
public int getPendingCount () {
return pool.pending ();
}
public void supervise () {
Thread[] t = new Thread[maxPoolSize];
int cnt = enumerate (t);
for (int i=0; i<cnt; i++)
if (t[i] instanceof PooledThread)
((PooledThread) t[i]).supervise();
}
public void setLogger (Logger logger, String realm) {
this.logger = logger;
this.realm = realm;
}
public String getRealm () {
return realm;
}
public Logger getLogger() {
return logger;
}
/**
* @param cfg Configuration object
* @throws ConfigurationException
*/
public void setConfiguration(Configuration cfg) throws ConfigurationException {
maxPoolSize = cfg.getInt("max-size", DEFAULT_MAX_THREADS);
init (cfg.getInt("initial-size"));
}
/**
* Retrieves a thread pool from NameRegistrar given its name, unique identifier.
*
* @param name Name of the thread pool to retrieve, must be the same as the name property of the thread-pool tag in the QSP config file
* @throws NotFoundException thrown when there is not a thread-pool registered under this name.
* @return returns the retrieved instance of thread pool
*/
public static ThreadPool getThreadPool(java.lang.String name) throws NotFoundException {
return (ThreadPool)NameRegistrar.get("thread.pool." + name);
}
}
|
// ExtractFlexMetdata.java
import java.io.File;
import java.io.FileWriter;
import loci.common.RandomAccessInputStream;
import loci.formats.TiffTools;
/** Convenience method to extract the metadat from all the Flex files present in a directory. */
public class ExtractFlexMetdata {
public static void main(String[] args) throws Exception {
File dir;
if (args.length != 1 || !(dir=new File(args[0])).canRead()) {
System.out.println("Usage: java ExtractFlexMetdata dir");
return;
}
for(File file:dir.listFiles()) {
if(file.getName().endsWith(".flex")){
String id=file.getPath();
int dot = id.lastIndexOf(".");
String outId = (dot >= 0 ? id.substring(0, dot) : id) + ".xml";
String xml = (String) TiffTools.getIFDValue(TiffTools.getIFDs(new RandomAccessInputStream(id))[0],
65200, true, String.class);
FileWriter writer =new FileWriter(new File(outId));
writer.write(xml);
writer.close();
System.out.println("Writing header of: "+id);
}
}
System.out.println("Done");
}
}
|
package view.enums;
import model.component.movement.Position;
public enum DefaultStrings {
DEFAULT_LANGUAGE("english"),
EVENT_EDITOR_NAME("EditorEvent"),
GUI_IMAGES("resources/images"),
DEFAULT_ICON("resources/guiImages/default_icon.png"),
ENTITY_EDITOR_NAME("EditorEntity"),
ENVIRONMENT_EDITOR_NAME("EditorEnvironment"),
LANG_LOC("languages/"),
COMPONENT_LOC("propertyFiles/componentLocations"),
SCRIPTS_LOC("propertyFiles/scriptLocations"),
CREATE_LOC("resources/createdGames/"),
TEMPLATE_BUNDLE_LOC("templates/"),
POSITION_COMP_NAME(Position.class.getName()),
XML(".xml"),
CSS_LOCATION("resources/cssFiles/"),
MAIN_CSS("darktheme.css"),
RHONDU("resources/testing/RhonduSmithwick.JPG"),
THEME("finalCountdown.mp3"),
MUSIC("resources/music/"),
SOUNDFX("resources/soundfx/"),
METADATA_LOC("/metadata.xml"),
ENTITIES_LOC("/entities.xml"),
LEVELS_LOC("/levels/"),
TEMP_LIST("_templatelist"),
DEF_NAME("DefaultName"),
GUI_RESOURCES("guiObject/guiComponents"),
GUI_FACTORY("guiObject/GuiObjectFactory"),
TEMPLATE_LANG("-templates"),
TEMPLATE_DIREC_LOC("resources/templates"),
RESOURCES("resources/"),
COMPONENTS("-components"),
PROPERTIES("-properties"),
ANIMATION_LOC("resources/spriteProperties/");
private final String content;
/**
* creates default for string str
*
* @param str default string
*/
DefaultStrings(String str) {
this.content = str;
}
/**
* returns default string
*
* @return default string for enum
*/
public String getDefault() {
return this.content;
}
}
|
package vacsys;
/**
* System to regulate treatment to patients based on a number of criteria
*/
public class VacSys {
VacSysHeap priorityQueue;
/**
* Create a system with an empty priority queue
*/
public VacSys() {
priorityQueue = new VacSysHeap();
}
/**
* Create a system loaded with requests from a batch file
*
* @param filename batch file
*/
public VacSys(String filename) {
// TODO Create a system loaded with requests from the batch le given by lename
}
/**
* Add a new request to the system
*
* @param name of the new patient
* @param age of the new patient
* @param zip of the new patient
* @return successful?
*/
public boolean insert(String name, int age, String zip) {
return priorityQueue.add(new Patient(name, age, zip));
}
/**
* Remove the next request from the system
*
* @return Comma-Delimited String on Patient Fields name, age, zip
*/
public String remove() {
// TODO Remove the next request from the system
return "";
}
/**
* Remove num requests and store them in a CSV format
*
* @param num of records to save
* @param filename to save in
* @return
*/
public boolean remove(int num, String filename) {
// TODO Remove num requests and store them in a CSV format in filename
return false;
}
}
|
package web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import web.struct.Personne;
@WebServlet("/servlet/profil")
public class ServletProfil extends HttpServlet {
static final String NOM = "kwin";
static final String MDP = "moi";
static final String URL = "jdbc:postgresql://kwinserv.ddns.net:22042/MeetNRoll";
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
if (session.getAttribute("personne") == null)
res.sendRedirect("../login.html");
Personne p = ((Personne) session.getAttribute("personne"));
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM joueurs where login='" + p.getLogin() + "';";
out.println("<!DOCTYPE html>" + "<html lang=\"fr\">" + "<head>"
+ " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
+ " <meta http-equiv='X-UA-Compatible' content='IE=edge'>"
+ " <meta name='viewport' content='width=device-width, initial-scale=1'>"
+ " <link rel=\"stylesheet\" href=\"StyleDevoir.css\" />" + "<title>Meet'N'Role: Profil</title>"
+ "</head>" + "<body>" + "<h1>Profil</h1>"
// login
+ "<h2>" + p.getLogin() + "</h2>"
// nom
+ "<p>" + p.getNom() + "</p>"
// Prenom
+ "<p>" + p.getPrenom() + "</p>" + "<table>");
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(URL, NOM, MDP);
stmt = con.createStatement();
System.out.println(req.getParameter("add") == null);
if (req.getParameter("add") != null && req.getParameter("add").length() > 1) {
System.out.println(
"insert into joueurs values('" + p.getLogin() + "','" + req.getParameter("add") + "');");
stmt.execute("insert into joueurs values('" + p.getLogin() + "','" + req.getParameter("add") + "');");
res.sendRedirect("profil");
}
<<<<<<< HEAD
if (req.getParameter("del") != null && req.getParameter("del").length() > 1) {
System.out.println("delete from joueurs where type='" + req.getParameter("del") + "';");
stmt.execute("delete from joueurs where type='" + req.getParameter("del") + "';");
=======
if (req.getParameter("del") != null && req.getParameter("del").length()>1) {
System.out.println("delete from joueurs where type='"+req.getParameter("del") + "';");
stmt.execute("delete from joueurs where login='"+p.getLogin()+"' and type='"+req.getParameter("del") + "';");
>>>> 854455125ce87796fa26076fc2c492d7799fe8aa
res.sendRedirect("profil");
}
rs = stmt.executeQuery(sql);
out.println("<center><table>");
out.println("<th>JDR favoris</th>");
while (rs.next())
out.println("<tr><td><a href =profil?del=" + rs.getString(2) + ">" + fromMatch(rs.getString(2))
+ "</td></tr>");
out.println("</table>");
sql = "select * from jeux where type not in (select type from joueurs where login ='" + p.getLogin()
+ "');";
rs = stmt.executeQuery(sql);
out.println("<table>");
out.println("<th> JDR DISPONIBLES </th>");
while (rs.next())
out.println("<tr><td><a href=profil?add=" + rs.getString(1) + ">" + fromMatch(rs.getString(1))
+ "</a></td></tr>");
out.println("</table></center>");
out.println("<a href=../modifProfil.jsp> Modifier le profil</a>");
out.println("</body></html>");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
}
}
}
private String fromMatch(String str) {
String rez = "";
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == '_')
rez += " ";
else
rez += str.charAt(i);
return rez;
}
}
|
package at.chaosfield.packupdate;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.lang.Override;
import java.lang.String;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FxController {
@FXML
private Label status;
@FXML
private ProgressBar progress;
private List<String> parameters;
private Stage primaryStage;
public void setMain(PackUpdate main) {
this.primaryStage = main.primaryStage;
this.parameters = main.getParameters().getRaw();
Task updater = new Task<List<String>>() {
@Override
protected List<String> call() {
class ErrorLog extends ArrayList<String> {
@Override
public boolean add(String e) {
System.out.println(e);
return super.add(e);
}
}
List<String> ret = new ErrorLog();
HashMap<String, String[]> updated = new HashMap<>();
HashMap<String, String[]> updateables = null;
try {
updateables = FileManager.getAvailableUpdates(parameters.get(0), parameters.get(2) + File.separator + parameters.get(1));
updateMessage("To Update: " + updateables.size());
} catch (IOException e) {
ret.add("[PackUpdate] Downloading \"" + parameters.get(0) + "\" failed.");
e.printStackTrace();
}
if (updateables != null) {
int current = 0;
updateProgress(current, updateables.size());
final String modsPath = parameters.get(2) + File.separator + "mods" + File.separator;
final String configPath = parameters.get(2) + File.separator + "config";
final String resourcePacksPath = parameters.get(2) + File.separator + "resources" + File.separator;
final String resourcesPath = parameters.get(2);
for (Map.Entry<String, String[]> entry : updateables.entrySet()) {
updateMessage("Updating " + entry.getKey());
switch (entry.getValue()[3]) {
case "mod":
if (!entry.getValue()[2].equals("")) { //If URL is not empty -> download new Version
try {
FileManager.downloadFile(entry.getValue()[2], modsPath + entry.getKey() + "-" + entry.getValue()[0] + ".jar");
} catch (IOException e) {
ret.add("[" + entry.getKey() + "] " + "Download failed.");
continue;
}
if (!entry.getValue()[1].equals("")) //If old version exists delete it
if (!FileManager.deleteLocalFile(modsPath + entry.getKey() + "-" + entry.getValue()[1] + ".jar")) {
ret.add("[" + entry.getKey() + "] " + "Warning: Deletion of file " + entry.getKey() + "-" + entry.getValue()[1] + ".jar failed.\n" +
"Either someone touched the mod's file manually or this is a bug.");
//continue;
}
} else {
if (!FileManager.deleteLocalFile(modsPath + entry.getKey() + "-" + entry.getValue()[1] + ".jar")) {
ret.add("[" + entry.getKey() + "] " + "Warning: Deletion of file " + entry.getKey() + "-" + entry.getValue()[1] + ".jar failed.\n" +
"Either someone touched the mod's file manually or this is a bug.");
//continue;
}
}
break;
case "resourcepack":
if (!entry.getValue()[2].equals("")) { //If URL is not empty -> download new Version
try {
FileManager.downloadFile(entry.getValue()[2], resourcePacksPath + entry.getKey() + "-" + entry.getValue()[0] + ".jar");
} catch (IOException e) {
ret.add("[" + entry.getKey() + "] " + "Download failed.");
continue;
}
if (!entry.getValue()[1].equals("")) //If old version exists delete it
if (!FileManager.deleteLocalFile(resourcePacksPath + entry.getKey() + "-" + entry.getValue()[1] + ".zip")) {
ret.add("[" + entry.getKey() + "] " + "Warning: Deletion of file " + entry.getKey() + "-" + entry.getValue()[1] + ".zip failed.\n" +
"Either someone touched the resource pack's file manually or this is a bug.");
//continue;
}
} else {
if (!FileManager.deleteLocalFile(resourcePacksPath + entry.getKey() + "-" + entry.getValue()[1] + ".zip")) {
ret.add("[" + entry.getKey() + "] " + "Warning: Deletion of file " + entry.getKey() + "-" + entry.getValue()[1] + ".zip failed.\n" +
"Either someone touched the resource pack's file manually or this is a bug.");
//continue;
}
}
break;
case "config":
if (!entry.getValue()[2].equals("")) { //If URL is not empty -> download new Version
if (!FileManager.deleteLocalFolderContents(configPath)) { //delete current config files
ret.add("[" + entry.getKey() + "] " + "Either deleting the config folder's content or creating an empty config folder failed.");
continue;
}
try {
FileManager.downloadFile(entry.getValue()[2], configPath + File.separator + entry.getKey() + "-" + entry.getValue()[0] + ".zip");
} catch (IOException e) {
ret.add("[" + entry.getKey() + "] " + "Download failed.");
continue;
}
if (!FileManager.unzipLocalFile(configPath + File.separator + entry.getKey() + "-" + entry.getValue()[0] + ".zip", configPath + File.separator)) {
ret.add("[" + entry.getKey() + "] " + "Unpack failed: The zip file seems to be corrupted.");
continue;
}
} else {
if (!FileManager.deleteLocalFolderContents(configPath)) {
ret.add("[" + entry.getKey() + "] " + "Either deleting the config folder's content or creating an empty config folder failed.");
continue;
}
}
break;
case "resources":
if (!entry.getValue()[2].equals("")) { //If URL is not empty -> download new Version
if (!FileManager.deleteLocalFolderContents(resourcesPath + File.separator + "resources")) { //delete current config files
ret.add("[" + entry.getKey() + "] " + "Either deleting the resources folder's content or creating an empty resources folder failed.");
continue;
}
if (!FileManager.deleteLocalFolderContents(resourcesPath + File.separator + "scripts")) {
ret.add("[" + entry.getKey() + "] " + "Either deleting the scripts folder's content or creating an empty scripts folder failed.");
continue;
}
try {
FileManager.downloadFile(entry.getValue()[2], resourcesPath + File.separator + "resources" + File.separator + entry.getKey() + "-" + entry.getValue()[0] + ".zip");
} catch (IOException e) {
ret.add("[" + entry.getKey() + "] " + "Download failed.");
continue;
}
if (!FileManager.unzipLocalFile(resourcesPath + File.separator + "resources" + File.separator + entry.getKey() + "-" + entry.getValue()[0] + ".zip", resourcesPath + File.separator)) {
ret.add("[" + entry.getKey() + "] " + "Unpack failed: The zip file seems to be corrupted.");
continue;
}
} else {
if (!FileManager.deleteLocalFolderContents(resourcesPath + File.separator + "resources")) {
ret.add("[" + entry.getKey() + "] " + "Either deleting the resources folder's content or creating an empty resources folder failed.");
continue;
}
if (!FileManager.deleteLocalFolderContents(resourcesPath + File.separator + "scripts")) {
ret.add("[" + entry.getKey() + "] " + "Either deleting the scripts folder's content or creating an empty scripts folder failed.");
continue;
}
}
break;
default:
}
updated.put(entry.getKey(), entry.getValue());
current++;
updateProgress(current, updateables.size());
System.out.println("Successfully updated " + entry.getKey());
}
}
if(!FileManager.writeLocalConfig(updated, parameters.get(2) + File.separator + parameters.get(1)))
ret.add("[PackInfo]" + "Error writing " + parameters.get(1));
return ret;
}
};
progress.progressProperty().bind(updater.progressProperty());
status.textProperty().bind(updater.messageProperty());
updater.setOnSucceeded(t -> {
List<String> returnValue = (List<String>) updater.getValue();
if (returnValue.size() > 0) {
main.errorAlert(returnValue);
}
primaryStage.close();
});
new Thread(updater).start();
}
}
|
package org.cejug.business;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.cejug.entity.Properties;
import org.cejug.entity.*;
import org.cejug.event.entity.Event;
import org.cejug.util.EntitySupport;
import org.cejug.util.TextUtils;
/**
* Centralizes the posting of all email messages sent by the system and manage
* the history of those messages. Each kind of message has a method, which can
* be involked from different parts of the business logic.
* @author Hildeberto Mendonca
*/
@Stateless
@LocalBean
public class MessengerBsn {
@PersistenceContext
private EntityManager em;
@Resource(name = "mail/jug")
private Session mailSession;
@EJB
private MessageTemplateBsn messageTemplateBsn;
@EJB
private ApplicationPropertyBsn applicationPropertyBsn;
static final Logger logger = Logger.getLogger("org.cejug.business.MessengerBsn");
public HistoricalMessage findHistoricalMessage(String id) {
if(id != null)
return em.find(HistoricalMessage.class, id);
else
return null;
}
public List<HistoricalMessage> findHistoricalMessageByRecipient(UserAccount recipient) {
List<HistoricalMessage> messages = em.createQuery("select hm from HistoricalMessage hm where hm.recipient = :userAccount order by hm.dateSent desc")
.setParameter("userAccount", recipient)
.getResultList();
return messages;
}
public HistoricalMessage saveHistoricalMessage(HistoricalMessage message) {
if(message.getId() == null || message.getId().isEmpty()) {
message.setId(EntitySupport.generateEntityId());
em.persist(message);
return message;
}
else {
return em.merge(message);
}
}
public void removeHistoricalMessage(String id) {
HistoricalMessage messageHistory = findHistoricalMessage(id);
if(messageHistory != null)
em.remove(messageHistory);
}
/**
* If the application is configured to send emails, it creates a email message
* based on the message template. The message is saved in the history and an
* attempt to send the message is done. If successful the historical message
* is set as sent, otherwise the message is set as not sent and new attempts
* will be carried out later until the sessage is successfully sent.
* @param recipients The list of users for who the message will be sent.
* @param messageTemplate The template of the message to be sent.
*/
public void sendEmailMessage(List<UserAccount> recipients, MessageTemplate messageTemplate) throws MessagingException {
ApplicationProperty appProp = applicationPropertyBsn.findApplicationProperty(Properties.SEND_EMAILS);
if(appProp.sendEmailsEnabled()) {
EmailMessage emailMessage;
HistoricalMessage historicalMessage;
MessagingException messagingException = null;
for(UserAccount recipient: recipients) {
emailMessage = new EmailMessage();
emailMessage.setRecipient(recipient);
emailMessage.setSubject(messageTemplate.getTitle());
emailMessage.setBody(messageTemplate.getBody());
historicalMessage = new HistoricalMessage(emailMessage);
historicalMessage = saveHistoricalMessage(historicalMessage);
try {
Transport.send(emailMessage.createMimeMessage(mailSession));
historicalMessage.setMessageSent(Boolean.TRUE);
historicalMessage.setDateSent(Calendar.getInstance().getTime());
}
catch(MessagingException me) {
historicalMessage.setMessageSent(Boolean.FALSE);
messagingException = me;
}
}
if(messagingException != null)
throw messagingException;
}
}
public void sendEmailMessage(UserAccount recipient, MessageTemplate messageTemplate) throws MessagingException {
List<UserAccount> recipients = new ArrayList<UserAccount>();
recipients.add(recipient);
sendEmailMessage(recipients, messageTemplate);
}
public void sendEmailConfirmationRequest(UserAccount userAccount, String serverAddress) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("E3F122DCC87D42248872878412B34CEE");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("serverAddress", serverAddress);
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("userAccount.confirmationCode", userAccount.getConfirmationCode());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the mail confirmation. The registration was not finalized.", me);
}
}
public void sendWelcomeMessage(UserAccount userAccount) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("47DEE5C2E0E14F8BA4605F3126FBFAF4");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.firstName", userAccount.getFirstName());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the deactivation reason to user "+ userAccount.getPostingEmail(), me);
}
}
public void sendNewMemberAlertMessage(UserAccount userAccount, List<UserAccount> leaders) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("0D6F96382D91454F8155A720F3326F1B");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.fullName", userAccount.getFullName());
values.put("userAccount.registrationDate", userAccount.getRegistrationDate());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(leaders, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending alert to administrators about the registration of "+ userAccount.getPostingEmail(), me);
}
}
public void sendDeactivationReason(UserAccount userAccount) {
MessageTemplate messageTemplate;
if(userAccount.getDeactivationType() == DeactivationType.ADMINISTRATIVE) {
messageTemplate = messageTemplateBsn.findMessageTemplate("03BD6F3ACE4C48BD8660411FC8673DB4");
}
else {
messageTemplate = messageTemplateBsn.findMessageTemplate("IKWMAJSNDOE3F122DCC87D4224887287");
}
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("userAccount.deactivationReason", userAccount.getDeactivationReason());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the deactivation reason to user "+ userAccount.getPostingEmail(), me);
}
}
public void sendDeactivationAlertMessage(UserAccount userAccount, List<UserAccount> leaders) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("0D6F96382IKEJSUIWOK5A720F3326F1B");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.fullName", userAccount.getFullName());
values.put("userAccount.deactivationReason", userAccount.getDeactivationReason());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(leaders, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the deactivation reason from "+ userAccount.getPostingEmail() +" to leaders.", me);
}
}
public void sendConfirmationCode(UserAccount userAccount, String serverAddress) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("67BE6BEBE45945D29109A8D6CD878344");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("serverAddress", serverAddress);
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("userAccount.confirmationCode", userAccount.getConfirmationCode());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the mail confirmation. The registration was not finalized.", me);
}
}
/**
* Sends a email to the user that requested to change his/her email address,
* asking him/her to confirm the request by clicking on the informed link. If
* the user successfully click on the link it means that his/her email address
* is valid since he/she could receive the email message successfully.
* @param userAccount the user who wants to change his/her email address.
* @param serverAddress the URL of the server where the application is deployed.
* it will be used to build the URL that the user will click to validate his/her
* email address.
*/
public void sendEmailVerificationRequest(UserAccount userAccount, String serverAddress) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("KJZISKQBE45945D29109A8D6C92IZJ89");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("serverAddress", serverAddress);
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("userAccount.email", userAccount.getEmail());
values.put("userAccount.unverifiedEmail", userAccount.getUnverifiedEmail());
values.put("userAccount.confirmationCode", userAccount.getConfirmationCode());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the mail confirmation. The registration was not finalized.", me);
}
}
public void sendGroupAssignmentAlert(UserAccount userAccount, AccessGroup accessGroup) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("09JDIIE82O39IDIDOSJCHXUDJJXHCKP0");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("accessGroup.name", accessGroup.getName());
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the group assignment alert to "+ userAccount.getFullName(), me);
}
}
public void sendConfirmationEventAttendance(UserAccount userAccount, Event event, String dateFormat, String timeFormat, String timezone) {
MessageTemplate messageTemplate = messageTemplateBsn.findMessageTemplate("KJDIEJKHFHSDJDUWJHAJSNFNFJHDJSLE");
em.detach(messageTemplate);
Map<String, Object> values = new HashMap<String, Object>();
values.put("userAccount.firstName", userAccount.getFirstName());
values.put("event.name", event.getName());
values.put("event.venue", event.getVenue().getName());
values.put("event.startDate", TextUtils.getFormattedDate(event.getStartDate(), dateFormat));
values.put("event.startTime", TextUtils.getFormattedTime(event.getStartTime(), timeFormat, timezone));
values.put("event.endTime", TextUtils.getFormattedTime(event.getEndTime(), timeFormat, timezone));
messageTemplate.replaceVariablesByValues(values);
try {
sendEmailMessage(userAccount, messageTemplate);
}
catch(MessagingException me) {
logger.log(Level.WARNING, "Error when sending the confirmation of event attendance to user "+ userAccount.getPostingEmail(), me);
}
}
}
|
package be.ibridge.kettle.trans.step;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.w3c.dom.Node;
import be.ibridge.kettle.cluster.ClusterSchema;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.GUIPositionInterface;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Point;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.SharedObjectBase;
import be.ibridge.kettle.core.SharedObjectInterface;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepLoaderException;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.repository.Repository;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
/**
* This class contains everything that is needed to define a step.
*
* @since 27-mei-2003
* @author Matt
*
*/
public class StepMeta extends SharedObjectBase implements Cloneable, Comparable, GUIPositionInterface, SharedObjectInterface
{
public static final String XML_TAG = "step";
private String stepid; // --> StepPlugin.id
private String stepname;
private StepMetaInterface stepMetaInterface;
private boolean selected;
private boolean distributes;
private int copies;
private Point location;
private boolean drawstep;
private String description;
private boolean terminator;
private StepPartitioningMeta stepPartitioningMeta;
private ClusterSchema clusterSchema;
private String clusterSchemaName; // temporary to resolve later.
private StepErrorMeta stepErrorMeta;
// private LogWriter log;
private long id;
/**
* @param stepid The ID of the step: this is derived information, you can also use the constructor without stepid.
* This constructor will be deprecated soon.
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepname, stepMetaInterface);
if (this.stepid==null) this.stepid = stepid;
}
/**
* @param stepname The name of the new step
* @param stepMetaInterface The step metadata interface to use (TextFileInputMeta, etc)
*/
public StepMeta(String stepname, StepMetaInterface stepMetaInterface)
{
if (stepMetaInterface!=null)
{
this.stepid = StepLoader.getInstance().getStepPluginID(stepMetaInterface);
}
this.stepname = stepname;
this.stepMetaInterface = stepMetaInterface;
selected = false;
distributes = true;
copies = 1;
location = new Point(0,0);
drawstep = false;
description = null;
stepPartitioningMeta = new StepPartitioningMeta();
clusterSchema = null; // non selected by default.
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param stepid
* @param stepname
* @param stepMetaInterface
*/
public StepMeta(LogWriter log, String stepid, String stepname, StepMetaInterface stepMetaInterface)
{
this(stepid, stepname, stepMetaInterface);
}
public StepMeta()
{
this((String)null, (String)null, (StepMetaInterface)null);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
*/
public StepMeta(LogWriter log)
{
this();
}
public String getXML()
{
StringBuffer retval=new StringBuffer(200); //$NON-NLS-1$
retval.append(" <").append(XML_TAG).append('>').append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("name", getName()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("type", getStepID()) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("description", description) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("distribute", distributes) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("copies", copies) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append( stepPartitioningMeta.getXML() );
retval.append( stepMetaInterface.getXML() );
retval.append(" ").append(XMLHandler.addTagValue("cluster_schema", clusterSchema==null?"":clusterSchema.getName()));
retval.append(" <GUI>").append(Const.CR); //$NON-NLS-1$
retval.append(" <xloc>").append(location.x).append("</xloc>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <yloc>").append(location.y).append("</yloc>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <draw>").append((drawstep?"Y":"N")).append("</draw>").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
retval.append(" </GUI>").append(Const.CR); //$NON-NLS-1$
retval.append(" </"+XML_TAG+">").append(Const.CR).append(Const.CR); //$NON-NLS-1$
return retval.toString();
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(LogWriter log, Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this(stepnode, databases, counters);
}
/**
* Read the step data from XML
*
* @param stepnode The XML step node.
* @param databases A list of databases
* @param counters A hashtable with all defined counters.
*
*/
public StepMeta(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException
{
this();
LogWriter log = LogWriter.getInstance();
StepLoader steploader = StepLoader.getInstance();
try
{
stepname = XMLHandler.getTagValue(stepnode, "name"); //$NON-NLS-1$
stepid = XMLHandler.getTagValue(stepnode, "type"); //$NON-NLS-1$
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.LookingForTheRightStepNode",stepname)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// Create a new StepMetaInterface object...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
// Load the specifics from XML...
if (stepMetaInterface!=null)
{
stepMetaInterface.loadXML(stepnode, databases, counters);
}
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.SpecificLoadedStep",stepname)); //$NON-NLS-1$ //$NON-NLS-2$
/* Handle info general to all step types...*/
description = XMLHandler.getTagValue(stepnode, "description"); //$NON-NLS-1$
copies = Const.toInt(XMLHandler.getTagValue(stepnode, "copies"), 1); //$NON-NLS-1$
String sdistri = XMLHandler.getTagValue(stepnode, "distribute"); //$NON-NLS-1$
distributes = "Y".equalsIgnoreCase(sdistri); //$NON-NLS-1$
if (sdistri==null) distributes=true; // default=distribute
// Handle GUI information: location & drawstep?
String xloc, yloc;
int x,y;
xloc=XMLHandler.getTagValue(stepnode, "GUI", "xloc"); //$NON-NLS-1$ //$NON-NLS-2$
yloc=XMLHandler.getTagValue(stepnode, "GUI", "yloc"); //$NON-NLS-1$ //$NON-NLS-2$
try{ x=Integer.parseInt(xloc); } catch(Exception e) { x=0; }
try{ y=Integer.parseInt(yloc); } catch(Exception e) { y=0; }
location=new Point(x,y);
drawstep = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "GUI", "draw")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// The partitioning information?
Node partNode = XMLHandler.getSubNode(stepnode, "partitioning");
stepPartitioningMeta = new StepPartitioningMeta(partNode);
clusterSchemaName = XMLHandler.getTagValue(stepnode, "cluster_schema"); // resolve to clusterSchema later
log.logDebug("StepMeta()", Messages.getString("StepMeta.Log.EndOfReadXML")); //$NON-NLS-1$ //$NON-NLS-2$
}
catch(Exception e)
{
throw new KettleXMLException(Messages.getString("StepMeta.Exception.UnableToLoadStepInfo"), e); //$NON-NLS-1$
}
}
/**
* Resolves the name of the cluster loaded from XML/Repository to the correct clusterSchema object
* @param clusterSchemas The list of clusterSchemas to reference.
*/
public void setClusterSchemaAfterLoading(List clusterSchemas)
{
if (clusterSchemaName==null) return;
for (int i=0;i<clusterSchemas.size();i++)
{
ClusterSchema look = (ClusterSchema) clusterSchemas.get(i);
if (look.getName().equals(clusterSchemaName)) clusterSchema=look;
}
}
public long getID()
{
return id;
}
public void setID(long id)
{
this.id = id;
}
/**
* See wether or not the step is drawn on the canvas.
*
* @return True if the step is drawn on the canvas.
*/
public boolean isDrawn()
{
return drawstep;
}
/**
* See wether or not the step is drawn on the canvas.
* Same as isDrawn(), but needed for findMethod(StepMeta, drawstep)
* called by StringSearcher.findMetaData(). Otherwise findMethod() returns
* be.ibridge.kettle.trans.step.StepMeta.drawStep() instead of isDrawn().
* @return True if the step is drawn on the canvas.
*/
public boolean isDrawStep()
{
return drawstep;
}
/**
* Sets the draw attribute of the step so that it will be drawn on the canvas.
*
* @param draw True if you want the step to show itself on the canvas, False if you don't.
*/
public void setDraw(boolean draw)
{
drawstep=draw;
setChanged();
}
/**
* Sets the number of parallel copies that this step will be launched with.
*
* @param c The number of copies.
*/
public void setCopies(int c)
{
if (copies!=c) setChanged();
copies=c;
}
public int getCopies()
{
// If the step is partitioned, that's going to determine the number of copies, nothing else...
if (isPartitioned() && getStepPartitioningMeta().getPartitionSchema()!=null)
{
String[] partitionIDs = getStepPartitioningMeta().getPartitionSchema().getPartitionIDs();
if (partitionIDs!=null && partitionIDs.length>0) // these are the partitions the step can "reach"
{
return partitionIDs.length;
}
}
return copies;
}
public void drawStep()
{
setDraw(true);
setChanged();
}
public void hideStep()
{
setDraw(false);
setChanged();
}
/**
* Two steps are equal if their names are equal.
* @return true if the two steps are equal.
*/
public boolean equals(Object obj)
{
if (obj==null) return false;
StepMeta stepMeta = (StepMeta)obj;
return getName().equalsIgnoreCase(stepMeta.getName());
}
public int hashCode()
{
return stepname.hashCode();
}
public int compareTo(Object o)
{
return toString().compareTo(((StepMeta)o).toString());
}
public boolean hasChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
return bsi!=null?bsi.hasChanged():false;
}
public void setChanged(boolean ch)
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged(ch);
}
public void setChanged()
{
BaseStepMeta bsi = (BaseStepMeta)this.getStepMetaInterface();
if (bsi!=null) bsi.setChanged();
}
public boolean chosesTargetSteps()
{
if (getStepMetaInterface()!=null)
{
return getStepMetaInterface().getTargetSteps()!=null;
}
return false;
}
public Object clone()
{
StepMeta stepMeta = new StepMeta();
stepMeta.replaceMeta(this);
stepMeta.setID(-1L);
return stepMeta;
}
public void replaceMeta(StepMeta stepMeta)
{
this.stepid = stepMeta.stepid; // --> StepPlugin.id
this.stepname = stepMeta.stepname;
if (stepMeta.stepMetaInterface!=null)
{
this.stepMetaInterface = (StepMetaInterface) stepMeta.stepMetaInterface.clone();
}
else
{
this.stepMetaInterface = null;
}
this.selected = stepMeta.selected;
this.distributes = stepMeta.distributes;
this.copies = stepMeta.copies;
if (stepMeta.location!=null)
{
this.location = new Point(stepMeta.location.x, stepMeta.location.y);
}
else
{
this.location = null;
}
this.drawstep = stepMeta.drawstep;
this.description = stepMeta.description;
this.terminator = stepMeta.terminator;
if (stepMeta.stepPartitioningMeta!=null)
{
this.stepPartitioningMeta = (StepPartitioningMeta) stepMeta.stepPartitioningMeta.clone();
}
else
{
this.stepPartitioningMeta = null;
}
if (stepMeta.clusterSchema!=null)
{
this.clusterSchema = (ClusterSchema) stepMeta.clusterSchema.clone();
}
else
{
this.clusterSchema = null;
}
this.clusterSchemaName = stepMeta.clusterSchemaName; // temporary to resolve later.
// this.setShared(stepMeta.isShared());
this.id = stepMeta.getID();
this.setChanged(true);
}
public StepMetaInterface getStepMetaInterface()
{
return stepMetaInterface;
}
public String getStepID()
{
return stepid;
}
/*
public String getStepTypeDesc()
{
return BaseStep.type_desc[steptype];
}
*/
public String getName()
{
return stepname;
}
public void setName(String sname)
{
stepname=sname;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description=description;
}
public void setSelected(boolean sel)
{
selected=sel;
}
public void flipSelected()
{
selected=!selected;
}
public boolean isSelected()
{
return selected;
}
public void setTerminator()
{
setTerminator(true);
}
public void setTerminator(boolean t)
{
terminator = t;
}
public boolean hasTerminator()
{
return terminator;
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
* @param log
* @param id_step
*/
public StepMeta(LogWriter log, long id_step)
{
this((String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
public StepMeta(long id_step)
{
this((String)null, (String)null, (StepMetaInterface)null);
setID(id_step);
}
/**
* @deprecated The logging is now a singlton, use the constructor without it.
*
* @param log
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(LogWriter log, Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this(rep, id_step, databases, counters, partitionSchemas);
}
/**
* Create a new step by loading the metadata from the specified repository.
* @param rep
* @param id_step
* @param databases
* @param counters
* @param partitionSchemas
* @throws KettleException
*/
public StepMeta(Repository rep, long id_step, ArrayList databases, Hashtable counters, List partitionSchemas) throws KettleException
{
this();
StepLoader steploader = StepLoader.getInstance();
try
{
Row r = rep.getStep(id_step);
if (r!=null)
{
setID(id_step);
stepname = r.searchValue("NAME").getString(); //$NON-NLS-1$
//System.out.println("stepname = "+stepname);
description = r.searchValue("DESCRIPTION").getString(); //$NON-NLS-1$
//System.out.println("description = "+description);
long id_step_type = r.searchValue("ID_STEP_TYPE").getInteger(); //$NON-NLS-1$
//System.out.println("id_step_type = "+id_step_type);
Row steptyperow = rep.getStepType(id_step_type);
stepid = steptyperow.searchValue("CODE").getString(); //$NON-NLS-1$
distributes = r.searchValue("DISTRIBUTE").getBoolean(); //$NON-NLS-1$
copies = (int)r.searchValue("COPIES").getInteger(); //$NON-NLS-1$
int x = (int)r.searchValue("GUI_LOCATION_X").getInteger(); //$NON-NLS-1$
int y = (int)r.searchValue("GUI_LOCATION_Y").getInteger(); //$NON-NLS-1$
location = new Point(x,y);
drawstep = r.searchValue("GUI_DRAW").getBoolean(); //$NON-NLS-1$
// Generate the appropriate class...
StepPlugin sp = steploader.findStepPluginWithID(stepid);
if (sp!=null)
{
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
}
else
{
throw new KettleStepLoaderException(Messages.getString("StepMeta.Exception.UnableToLoadClass",stepid+Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
stepMetaInterface = BaseStep.getStepInfo(sp, steploader);
if (stepMetaInterface!=null)
{
// Read the step info from the repository!
stepMetaInterface.readRep(rep, getID(), databases, counters);
}
// Get the partitioning as well...
stepPartitioningMeta = new StepPartitioningMeta(rep, getID());
// Get the cluster schema name
clusterSchemaName = rep.getStepAttributeString(id_step, "cluster_schema");
}
else
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepInfoCouldNotBeFound",String.valueOf(id_step))); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("StepMeta.Exception.StepCouldNotBeLoaded",String.valueOf(getID())), dbe); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void saveRep(Repository rep, long id_transformation)
throws KettleException
{
LogWriter log = LogWriter.getInstance();
try
{
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveNewStep")); //$NON-NLS-1$
// Insert new Step in repository
setID(rep.insertStep( id_transformation,
getName(),
getDescription(),
getStepID(),
distributes,
copies,
getLocation()==null?-1:getLocation().x,
getLocation()==null?-1:getLocation().y,
isDrawn()
)
);
// Save partitioning selection for the step
stepPartitioningMeta.saveRep(rep, id_transformation, getID());
// The id_step is known, as well as the id_transformation
// This means we can now save the attributes of the step...
log.logDebug(toString(), Messages.getString("StepMeta.Log.SaveStepDetails")); //$NON-NLS-1$
stepMetaInterface.saveRep(rep, id_transformation, getID());
// Save the clustering schema that was chosen.
rep.saveStepAttribute(id_transformation, getID(), "cluster_schema", clusterSchema==null?"":clusterSchema.getName());
}
catch(KettleException e)
{
throw new KettleException(Messages.getString("StepMeta.Exception.UnableToSaveStepInfo",String.valueOf(id_transformation)), e); //$NON-NLS-1$
}
}
public void setLocation(int x, int y)
{
int nx = (x>=0?x:0);
int ny = (y>=0?y:0);
Point loc = new Point(nx,ny);
if (!loc.equals(location)) setChanged();
location=loc;
}
public void setLocation(Point loc)
{
if (loc!=null && !loc.equals(location)) setChanged();
location = loc;
}
public Point getLocation()
{
return location;
}
public void check(ArrayList remarks, Row prev, String input[], String output[], Row info)
{
stepMetaInterface.check(remarks, this, prev, input, output, info);
}
public String toString()
{
if (getName()==null) return getClass().getName();
return getName();
}
/**
* @return true is the step is partitioned
*/
public boolean isPartitioned()
{
return stepPartitioningMeta.isPartitioned();
}
/**
* @return the stepPartitioningMeta
*/
public StepPartitioningMeta getStepPartitioningMeta()
{
return stepPartitioningMeta;
}
/**
* @param stepPartitioningMeta the stepPartitioningMeta to set
*/
public void setStepPartitioningMeta(StepPartitioningMeta stepPartitioningMeta)
{
this.stepPartitioningMeta = stepPartitioningMeta;
}
/**
* @return the clusterSchema
*/
public ClusterSchema getClusterSchema()
{
return clusterSchema;
}
/**
* @param clusterSchema the clusterSchema to set
*/
public void setClusterSchema(ClusterSchema clusterSchema)
{
this.clusterSchema = clusterSchema;
}
/**
* @return the distributes
*/
public boolean isDistributes()
{
return distributes;
}
/**
* @param distributes the distributes to set
*/
public void setDistributes(boolean distributes)
{
this.distributes = distributes;
}
/**
* @return the StepErrorMeta error handling metadata for this step
*/
public StepErrorMeta getStepErrorMeta()
{
return stepErrorMeta;
}
/**
* @param stepErrorMeta the error handling metadata for this step
*/
public void setStepErrorMeta(StepErrorMeta stepErrorMeta)
{
this.stepErrorMeta = stepErrorMeta;
}
/**
* Find a step with the ID in a given ArrayList of steps
*
* @param steps The List of steps to search
* @param id The ID of the step
* @return The step if it was found, null if nothing was found
*/
public static final StepMeta findStep(List steps, long id)
{
if (steps == null) return null;
for (int i = 0; i < steps.size(); i++)
{
StepMeta stepMeta = (StepMeta) steps.get(i);
if (stepMeta.getID() == id) return stepMeta;
}
return null;
}
/**
* Find a step with its name in a given ArrayList of steps
*
* @param steps The List of steps to search
* @param stepname The name of the step
* @return The step if it was found, null if nothing was found
*/
public static final StepMeta findStep(List steps, String stepname)
{
if (steps == null) return null;
for (int i = 0; i < steps.size(); i++)
{
StepMeta stepMeta = (StepMeta) steps.get(i);
if (stepMeta.getName().equalsIgnoreCase(stepname)) return stepMeta;
}
return null;
}
public boolean supportsErrorHandling()
{
return stepMetaInterface.supportsErrorHandling();
}
/**
* @return if error handling is supported for this step, if error handling is defined and a target step is set
*/
public boolean isDoingErrorHandling()
{
return stepMetaInterface.supportsErrorHandling() &&
stepErrorMeta!=null &&
stepErrorMeta.getTargetStep()!=null &&
stepErrorMeta.isEnabled()
;
}
public boolean isSendingErrorRowsToStep(StepMeta targetStep)
{
return (isDoingErrorHandling() && stepErrorMeta.getTargetStep().equals(targetStep));
}
}
|
package beast.evolution.tree;
import java.io.PrintStream;
import beast.core.CalculationNode;
import beast.core.Description;
import beast.core.Function;
import beast.core.Input;
import beast.core.Input.Validate;
import beast.core.Loggable;
@Description("Logger to report height of a tree")
public class TreeHeightLogger extends CalculationNode implements Loggable, Function {
final public Input<Tree> treeInput = new Input<>("tree", "tree to report height for.", Validate.REQUIRED);
final public Input<Boolean> logLengthInput = new Input<>("logLength", "If true, tree length will be logged as well.", false);
@Override
public void initAndValidate() {
// nothing to do
}
@Override
public void init(PrintStream out) {
final Tree tree = treeInput.get();
if (getID() == null || getID().matches("\\s*")) {
out.print(tree.getID() + ".height\t");
} else {
out.print(getID() + "\t");
}
if (logLengthInput.get()) {
out.print(tree.getID() + ".treeLength\t");
}
}
@Override
public void log(int sample, PrintStream out) {
final Tree tree = treeInput.get();
out.print(tree.getRoot().getHeight() + "\t");
if (logLengthInput.get()) {
out.print(getLength(tree) + "\t");
}
}
private double getLength(Tree tree) {
double length = 0;
for (Node node : tree.getNodesAsArray()) {
if (!node.isRoot()) {
length += node.getLength();
}
}
return length;
}
@Override
public void close(PrintStream out) {
// nothing to do
}
@Override
public int getDimension() {
return 1;
}
@Override
public double getArrayValue() {
return treeInput.get().getRoot().getHeight();
}
@Override
public double getArrayValue(int dim) {
return treeInput.get().getRoot().getHeight();
}
}
|
package com.sometrik.framework;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.TreeSet;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
public class FWImageView extends ImageView implements NativeCommandHandler {
final static int RGB565 = 3;
final static int RGBA4 = 4;
final static int RGBA8 = 5;
final static int RGB8 = 6;
FrameWork frame;
ViewStyleManager normalStyle, activeStyle, currentStyle;
Bitmap ownedBitmap = null;
boolean imageRequestSent = false;
int currentWidth = 0, currentHeight = 0;
TreeSet<ImageData> images = new TreeSet<ImageData>();
public FWImageView(final FrameWork frame, int id) {
super(frame);
this.frame = frame;
this.setId(id);
this.setScaleType(ScaleType.CENTER_CROP); // needed for parallax scrolling
this.setClipToOutline(true);
this.setAdjustViewBounds(true);
this.setClickable(false);
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
}
@Override
public void addImageUrl(String url, int width, int height) {
String protocol = getProtocol(url);
if (protocol.equals("http") || protocol.equals("https")) {
images.add(new ImageData(width, height, url));
} else {
setImageFromAssets(url);
}
}
private String getProtocol(String filename) {
try {
URI uri = new URI(filename);
String scheme = uri.getScheme();
return scheme != null ? scheme : "asset";
} catch (URISyntaxException e) {
return "asset";
}
}
private void setImageFromAssets(String filename) {
deinitialize();
Bitmap bitmap = frame.bitmapCache.loadBitmap(filename);
setImageBitmap(bitmap);
invalidate();
}
@Override
public void onScreenOrientationChange(boolean isLandscape) { }
@Override
public void addChild(View view) { }
@Override
public void addOption(int optionId, String text) { }
@Override
public void addColumn(String text, int columnType) { }
@Override
public void addData(String text, int row, int column, int sheet) { }
@Override
public void setValue(String v) {
deinitialize();
images.clear();
String protocol = getProtocol(v);
if (protocol.equals("http") || protocol.equals("https")) {
addImageUrl(v, 0, 0);
if (currentWidth != 0 && currentHeight != 0) requestImage();
} else {
setImageFromAssets(v);
}
}
@Override
public void setValue(int v) { }
@Override
public void reshape(int value, int size) { }
@Override
public void setViewVisibility(boolean visible) { }
@Override
public void setStyle(Selector selector, String key, String value) {
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
if (normalStyle == currentStyle) normalStyle.apply(this);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
if (activeStyle == currentStyle) activeStyle.apply(this);
}
if (key.equals("scale")) {
if (value.equals("fit-start")) {
setScaleType(ScaleType.FIT_START);
} else if (value.equals("fit-end")) {
setScaleType(ScaleType.FIT_END);
} else if (value.equals("fit-center")) {
setScaleType(ScaleType.FIT_CENTER);
} else if (value.equals("center")) {
setScaleType(ScaleType.CENTER);
}
}
}
@Override
public void setError(boolean hasError, String errorText) { }
@Override
public void clear() {
deinitialize();
setImageBitmap(null);
images.clear();
}
@Override
public void flush() { }
@Override
public int getElementId() {
return getId();
}
@Override
public void setBitmap(Bitmap bitmap) {
releaseBitmap();
ownedBitmap = bitmap;
setImageBitmap(ownedBitmap);
}
@Override
public void reshape(int size) { }
private void releaseBitmap() {
if (ownedBitmap != null) {
ownedBitmap.recycle();
ownedBitmap = null;
}
}
private void cancelImageRequest() {
if (imageRequestSent) {
frame.cancelImageRequest(getElementId());
}
}
@Override
public void deinitialize() {
releaseBitmap();
cancelImageRequest();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
cancelImageRequest();
currentWidth = w;
currentHeight = h;
requestImage();
}
protected void requestImage() {
if (currentWidth > 0) {
if (!images.isEmpty()) {
ImageData img = getSuitable(currentWidth);
System.out.println("Sending image request for " + img.url);
imageRequestSent = true;
final float scale = getContext().getResources().getDisplayMetrics().density;
ImageData smallest = images.first();
if (false && smallest.width < img.width) {
frame.sendImageRequest(getElementId(), smallest.url, (int)(currentWidth / scale), 0, 0);
}
if (true) {
frame.sendImageRequest(getElementId(), img.url, (int)(currentWidth / scale), 0, RGB565);
}
} else {
frame.sendImageRequest(getElementId(), (int)(currentWidth / scale), (int)(currentHeight / scale), RGB565);
}
} else {
System.out.println("Unable to sent image request");
}
}
private ImageData getSuitable(int target_width) {
for (ImageData d : images) {
if (4 * d.width >= 3 * target_width) { // select image if it's at least 0.75 * target_width
return d;
}
}
if (!images.isEmpty()) {
return images.last();
} else {
return null;
}
}
private class ImageData implements Comparable<ImageData> {
public int width;
public int height;
public String url;
public ImageData(int width, int height, String url) {
this.width = width;
this.height = height;
this.url = url;
}
@Override
public int compareTo(ImageData other) {
return Integer.compare(width, other.width);
}
}
}
|
package com.artifex.mupdfdemo;
import java.io.InputStream;
import java.util.concurrent.Executor;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewAnimator;
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
public class MuPDFActivity extends Activity
{
/* The core rendering instance */
enum TopBarMode {Main, Search, Text, AnnotSelect, AnnotCreate, InkCreate};
private MuPDFCore core;
private String mFileName;
private MuPDFReaderView mDocView;
private View mButtonsView;
private boolean mButtonsVisible;
private EditText mPasswordView;
private TextView mFilenameView;
private SeekBar mPageSlider;
private int mPageSliderRes;
private TextView mPageNumberView;
private TextView mInfoView;
private ImageButton mSearchButton;
private ImageButton mReflowButton;
private ImageButton mSelectButton;
private ImageButton mCancelSelectButton;
private ImageButton mCopySelectButton;
private ImageButton mHighlightButton;
private ImageButton mUnderlineButton;
private ImageButton mStrikeOutButton;
private ImageButton mCancelButton;
private ImageButton mOutlineButton;
private ImageButton mDeleteButton;
private ImageButton mCancelDeleteButton;
private ImageButton mAnnotButton;
private ImageButton mCancelAnnotButton;
private ImageButton mInkButton;
private Button mSaveInkButton;
private ImageButton mCancelInkButton;
private ViewAnimator mTopBarSwitcher;
private ImageButton mLinkButton;
private TopBarMode mTopBarMode;
private ImageButton mSearchBack;
private ImageButton mSearchFwd;
private EditText mSearchText;
private SearchTask mSearchTask;
private AlertDialog.Builder mAlertBuilder;
private boolean mLinkHighlight = false;
private final Handler mHandler = new Handler();
private boolean mAlertsActive= false;
private boolean mReflow = false;
private AsyncTask<Void,Void,MuPDFAlert> mAlertTask;
private AlertDialog mAlertDialog;
public void createAlertWaiter() {
mAlertsActive = true;
// All mupdf library calls are performed on asynchronous tasks to avoid stalling
// the UI. Some calls can lead to javascript-invoked requests to display an
// alert dialog and collect a reply from the user. The task has to be blocked
// until the user's reply is received. This method creates an asynchronous task,
// the purpose of which is to wait of these requests and produce the dialog
// in response, while leaving the core blocked. When the dialog receives the
// user's response, it is sent to the core via replyToAlert, unblocking it.
// Another alert-waiting task is then created to pick up the next alert.
if (mAlertTask != null) {
mAlertTask.cancel(true);
mAlertTask = null;
}
if (mAlertDialog != null) {
mAlertDialog.cancel();
mAlertDialog = null;
}
mAlertTask = new AsyncTask<Void,Void,MuPDFAlert>() {
@Override
protected MuPDFAlert doInBackground(Void... arg0) {
if (!mAlertsActive)
return null;
return core.waitForAlert();
}
@Override
protected void onPostExecute(final MuPDFAlert result) {
// core.waitForAlert may return null when shutting down
if (result == null)
return;
final MuPDFAlert.ButtonPressed pressed[] = new MuPDFAlert.ButtonPressed[3];
for(int i = 0; i < 3; i++)
pressed[i] = MuPDFAlert.ButtonPressed.None;
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mAlertDialog = null;
if (mAlertsActive) {
int index = 0;
switch (which) {
case AlertDialog.BUTTON1: index=0; break;
case AlertDialog.BUTTON2: index=1; break;
case AlertDialog.BUTTON3: index=2; break;
}
result.buttonPressed = pressed[index];
// Send the user's response to the core, so that it can
// continue processing.
core.replyToAlert(result);
// Create another alert-waiter to pick up the next alert.
createAlertWaiter();
}
}
};
mAlertDialog = mAlertBuilder.create();
mAlertDialog.setTitle(result.title);
mAlertDialog.setMessage(result.message);
switch (result.iconType)
{
case Error:
break;
case Warning:
break;
case Question:
break;
case Status:
break;
}
switch (result.buttonGroupType)
{
case OkCancel:
mAlertDialog.setButton(AlertDialog.BUTTON2, "Cancel", listener);
pressed[1] = MuPDFAlert.ButtonPressed.Cancel;
case Ok:
mAlertDialog.setButton(AlertDialog.BUTTON1, "Ok", listener);
pressed[0] = MuPDFAlert.ButtonPressed.Ok;
break;
case YesNoCancel:
mAlertDialog.setButton(AlertDialog.BUTTON3, "Cancel", listener);
pressed[2] = MuPDFAlert.ButtonPressed.Cancel;
case YesNo:
mAlertDialog.setButton(AlertDialog.BUTTON1, "Yes", listener);
pressed[0] = MuPDFAlert.ButtonPressed.Yes;
mAlertDialog.setButton(AlertDialog.BUTTON2, "No", listener);
pressed[1] = MuPDFAlert.ButtonPressed.No;
break;
}
mAlertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mAlertDialog = null;
if (mAlertsActive) {
result.buttonPressed = MuPDFAlert.ButtonPressed.None;
core.replyToAlert(result);
createAlertWaiter();
}
}
});
mAlertDialog.show();
}
};
mAlertTask.executeOnExecutor(new ThreadPerTaskExecutor());
}
public void destroyAlertWaiter() {
mAlertsActive = false;
if (mAlertDialog != null) {
mAlertDialog.cancel();
mAlertDialog = null;
}
if (mAlertTask != null) {
mAlertTask.cancel(true);
mAlertTask = null;
}
}
private MuPDFCore openFile(String path)
{
int lastSlashPos = path.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1
? path
: path.substring(lastSlashPos+1));
System.out.println("Trying to open "+path);
try
{
core = new MuPDFCore(path);
// New file: drop the old outline data
OutlineActivityData.set(null);
}
catch (Exception e)
{
System.out.println(e);
return null;
}
return core;
}
private MuPDFCore openBuffer(byte buffer[])
{
System.out.println("Trying to open byte buffer");
try
{
core = new MuPDFCore(buffer);
// New file: drop the old outline data
OutlineActivityData.set(null);
}
catch (Exception e)
{
System.out.println(e);
return null;
}
return core;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAlertBuilder = new AlertDialog.Builder(this);
if (core == null) {
core = (MuPDFCore)getLastNonConfigurationInstance();
if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
mFileName = savedInstanceState.getString("FileName");
}
}
if (core == null) {
Intent intent = getIntent();
byte buffer[] = null;
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri.toString().startsWith("content:
// Handle view requests from the Transformer Prime's file manager
// Hopefully other file managers will use this same scheme, if not
// using explicit paths.
Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
if (cursor.moveToFirst()) {
String str = cursor.getString(0);
String failString = null;
if (str == null) {
try {
InputStream is = getContentResolver().openInputStream(uri);
int len = is.available();
buffer = new byte[len];
is.read(buffer, 0, len);
is.close();
}
catch (java.lang.OutOfMemoryError e)
{
System.out.println("Out of memory during buffer reading");
failString = e.toString();
}
catch (Exception e) {
failString = e.toString();
}
if (failString != null)
{
buffer = null;
Resources res = getResources();
AlertDialog alert = mAlertBuilder.create();
String contentFailure = res.getString(R.string.content_failure);
String openFailed = res.getString(R.string.open_failed);
setTitle(String.format(contentFailure, openFailed, failString));
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
} else {
uri = Uri.parse(str);
}
}
}
if (buffer != null) {
core = openBuffer(buffer);
} else {
core = openFile(Uri.decode(uri.getEncodedPath()));
}
SearchTaskResult.set(null);
if (core.countPages() == 0)
core = null;
}
if (core != null && core.needsPassword()) {
requestPassword(savedInstanceState);
return;
}
}
if (core == null)
{
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.open_failed);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
createUI(savedInstanceState);
}
public void requestPassword(final Bundle savedInstanceState) {
mPasswordView = new EditText(this);
mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
mPasswordView.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.enter_password);
alert.setView(mPasswordView);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (core.authenticatePassword(mPasswordView.getText().toString())) {
createUI(savedInstanceState);
} else {
requestPassword(savedInstanceState);
}
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
public void createUI(Bundle savedInstanceState) {
if (core == null)
return;
// Now create the UI.
// First create the document view
mDocView = new MuPDFReaderView(this) {
@Override
protected void onMoveToChild(int i) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d / %d", i + 1,
core.countPages()));
mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
mPageSlider.setProgress(i * mPageSliderRes);
super.onMoveToChild(i);
}
@Override
protected void onTapMainDocArea() {
if (!mButtonsVisible) {
showButtons();
} else {
hideButtons();
}
}
@Override
protected void onDocMotion() {
hideButtons();
}
@Override
protected void onHit(Hit item) {
switch (item) {
case Annotation:
showButtons();
mTopBarMode = TopBarMode.AnnotSelect;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
break;
case Widget:
case Nothing:
if (mTopBarMode == TopBarMode.AnnotSelect) {
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
break;
}
}
};
mDocView.setAdapter(new MuPDFPageAdapter(this, core));
mSearchTask = new SearchTask(this, core) {
@Override
protected void onTextFound(SearchTaskResult result) {
SearchTaskResult.set(result);
// Ask the ReaderView to move to the resulting page
mDocView.setDisplayedViewIndex(result.pageNumber);
// Make the ReaderView act on the change to SearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
};
// Make the buttons overlay, and store all its
// controls in variables
makeButtonsView();
// Set up the page slider
int smax = Math.max(core.countPages()-1,1);
mPageSliderRes = ((10 + smax - 1)/smax) * 2;
// Set the file-name text
mFilenameView.setText(mFileName);
// Activate the seekbar
mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
mDocView.setDisplayedViewIndex((seekBar.getProgress()+mPageSliderRes/2)/mPageSliderRes);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePageNumView((progress+mPageSliderRes/2)/mPageSliderRes);
}
});
// Activate the search-preparing button
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOn();
}
});
// Activate the reflow button
mReflowButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toggleReflow();
}
});
mAnnotButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mTopBarMode = TopBarMode.AnnotCreate;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
// Activate the select button
mSelectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDocView.setMode(MuPDFReaderView.Mode.Selecting);
mTopBarMode = TopBarMode.Text;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mCancelSelectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.deselectText();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.AnnotCreate;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mInkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDocView.setMode(MuPDFReaderView.Mode.Drawing);
mTopBarMode = TopBarMode.InkCreate;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mCancelInkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.cancelDraw();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.AnnotCreate;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mSaveInkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.saveDraw();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mCancelDeleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.deselectAnnotation();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mCancelAnnotButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
if (pageView != null)
pageView.deselectText();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
mCopySelectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean copied = false;
if (pageView != null)
copied = pageView.copySelection();
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
showInfo(copied?"Copied to clipboard":"No text selected");
}
});
mHighlightButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean success = false;
if (pageView != null)
success = pageView.markupSelection(Annotation.Type.HIGHLIGHT);
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
if (!success)
showInfo("No text selected");
}
});
mUnderlineButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean success = false;
if (pageView != null)
success = pageView.markupSelection(Annotation.Type.UNDERLINE);
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
if (!success)
showInfo("No text selected");
}
});
mStrikeOutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
boolean success = false;
if (pageView != null)
success = pageView.markupSelection(Annotation.Type.STRIKEOUT);
mDocView.setMode(MuPDFReaderView.Mode.Viewing);
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
if (!success)
showInfo("No text selected");
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOff();
}
});
// Search invoking buttons are disabled while there is no text specified
mSearchBack.setEnabled(false);
mSearchFwd.setEnabled(false);
mSearchBack.setColorFilter(Color.argb(255, 128, 128, 128));
mSearchFwd.setColorFilter(Color.argb(255, 128, 128, 128));
// React to interaction with the text widget
mSearchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
boolean haveText = s.toString().length() > 0;
mSearchBack.setEnabled(haveText);
mSearchFwd.setEnabled(haveText);
if (haveText) {
mSearchBack.setColorFilter(Color.argb(255, 255, 255, 255));
mSearchFwd.setColorFilter(Color.argb(255, 255, 255, 255));
} else {
mSearchBack.setColorFilter(Color.argb(255, 128, 128, 128));
mSearchFwd.setColorFilter(Color.argb(255, 128, 128, 128));
}
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchText.getText().toString().equals(SearchTaskResult.get().txt)) {
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
//React to Done button on keyboard
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
search(1);
return false;
}
});
mSearchText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
search(1);
return false;
}
});
// Activate search invoking buttons
mSearchBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(-1);
}
});
mSearchFwd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(1);
}
});
mLinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mLinkHighlight) {
mLinkButton.setColorFilter(Color.argb(0xFF, 255, 255, 255));
mLinkHighlight = false;
} else {
// LINK_COLOR tint
mLinkButton.setColorFilter(Color.argb(0xFF, 172, 114, 37));
mLinkHighlight = true;
}
// Inform pages of the change.
mDocView.setLinksEnabled(mLinkHighlight);
}
});
if (core.hasOutline()) {
mOutlineButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OutlineItem outline[] = core.getOutline();
if (outline != null) {
OutlineActivityData.get().items = outline;
Intent intent = new Intent(MuPDFActivity.this, OutlineActivity.class);
startActivityForResult(intent, 0);
}
}
});
} else {
mOutlineButton.setVisibility(View.GONE);
}
mDeleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View cv = mDocView.getDisplayedView();
if (cv != null)
((MuPDFView)cv).deleteSelectedAnnotation();
mTopBarMode = TopBarMode.Main;
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
});
// Reenstate last state if it was recorded
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
mDocView.setDisplayedViewIndex(prefs.getInt("page"+mFileName, 0));
if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
showButtons();
if(savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false))
searchModeOn();
if(savedInstanceState != null && savedInstanceState.getBoolean("ReflowMode", false))
reflowModeSet(true);
// Stick the document view and the buttons overlay into a parent view
RelativeLayout layout = new RelativeLayout(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode >= 0)
mDocView.setDisplayedViewIndex(resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
public Object onRetainNonConfigurationInstance()
{
MuPDFCore mycore = core;
core = null;
return mycore;
}
private void reflowModeSet(boolean reflow)
{
mReflow = reflow;
if (mReflow) {
mDocView.setAdapter(new MuPDFReflowAdapter(this, core));
mReflowButton.setColorFilter(Color.argb(0xFF, 172, 114, 37));
showInfo("Entering reflow mode");
} else {
mDocView.setAdapter(new MuPDFPageAdapter(this, core));
mReflowButton.setColorFilter(Color.argb(0xFF, 255, 255, 255));
showInfo("Exited reflow mode");
}
mDocView.refresh(mReflow);
}
private void toggleReflow() {
reflowModeSet(!mReflow);
showInfo(mReflow ? "Entering reflow mode" : "Leaving reflow mode");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFileName != null && mDocView != null) {
outState.putString("FileName", mFileName);
// Store current page in the prefs against the file name,
// so that we can pick it up each time the file is loaded
// Other info is needed only for screen-orientation change,
// so it can go in the bundle
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
if (!mButtonsVisible)
outState.putBoolean("ButtonsHidden", true);
if (mTopBarMode == TopBarMode.Search)
outState.putBoolean("SearchMode", true);
if (mReflow)
outState.putBoolean("ReflowMode", true);
}
@Override
protected void onPause() {
super.onPause();
if (mSearchTask != null)
mSearchTask.stop();
if (mFileName != null && mDocView != null) {
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
}
public void onDestroy()
{
if (core != null)
core.onDestroy();
if (mAlertTask != null) {
mAlertTask.cancel(true);
mAlertTask = null;
}
core = null;
super.onDestroy();
}
void showButtons() {
if (core == null)
return;
if (!mButtonsVisible) {
mButtonsVisible = true;
// Update page number text and slider
int index = mDocView.getDisplayedViewIndex();
updatePageNumView(index);
mPageSlider.setMax((core.countPages()-1)*mPageSliderRes);
mPageSlider.setProgress(index*mPageSliderRes);
if (mTopBarMode == TopBarMode.Search) {
mSearchText.requestFocus();
showKeyboard();
}
Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mTopBarSwitcher.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageSlider.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageNumberView.setVisibility(View.VISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void hideButtons() {
if (mButtonsVisible) {
mButtonsVisible = false;
hideKeyboard();
Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mTopBarSwitcher.setVisibility(View.INVISIBLE);
}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageNumberView.setVisibility(View.INVISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageSlider.setVisibility(View.INVISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void searchModeOn() {
if (mTopBarMode != TopBarMode.Search) {
mTopBarMode = TopBarMode.Search;
//Focus on EditTextWidget
mSearchText.requestFocus();
showKeyboard();
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
}
}
void searchModeOff() {
if (mTopBarMode == TopBarMode.Search) {
mTopBarMode = TopBarMode.Main;
hideKeyboard();
mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
SearchTaskResult.set(null);
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
}
void updatePageNumView(int index) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d / %d", index+1, core.countPages()));
}
private void showInfo(String message) {
mInfoView.setText(message);
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.info);
set.setTarget(mInfoView);
set.addListener(new Animator.AnimatorListener() {
public void onAnimationStart(Animator animation) {
mInfoView.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animator animation) {
}
public void onAnimationEnd(Animator animation) {
mInfoView.setVisibility(View.INVISIBLE);
}
public void onAnimationCancel(Animator animation) {
}
});
set.start();
} else {
mInfoView.setVisibility(View.VISIBLE);
mHandler.postDelayed(new Runnable() {
public void run() {
mInfoView.setVisibility(View.INVISIBLE);
}
}, 500);
}
}
void makeButtonsView() {
mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null);
mFilenameView = (TextView)mButtonsView.findViewById(R.id.docNameText);
mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider);
mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber);
mInfoView = (TextView)mButtonsView.findViewById(R.id.info);
mSearchButton = (ImageButton)mButtonsView.findViewById(R.id.searchButton);
mReflowButton = (ImageButton)mButtonsView.findViewById(R.id.reflowButton);
mSelectButton = (ImageButton)mButtonsView.findViewById(R.id.selectButton);
mCancelSelectButton = (ImageButton)mButtonsView.findViewById(R.id.cancelSelectButton);
mCopySelectButton = (ImageButton)mButtonsView.findViewById(R.id.copySelectButton);
mHighlightButton = (ImageButton)mButtonsView.findViewById(R.id.highlightButton);
mUnderlineButton = (ImageButton)mButtonsView.findViewById(R.id.underlineButton);
mStrikeOutButton = (ImageButton)mButtonsView.findViewById(R.id.strikeOutButton);
mCancelButton = (ImageButton)mButtonsView.findViewById(R.id.cancel);
mOutlineButton = (ImageButton)mButtonsView.findViewById(R.id.outlineButton);
mDeleteButton = (ImageButton)mButtonsView.findViewById(R.id.deleteButton);
mCancelDeleteButton = (ImageButton)mButtonsView.findViewById(R.id.cancelDeleteButton);
mAnnotButton = (ImageButton)mButtonsView.findViewById(R.id.annotButton);
mCancelAnnotButton = (ImageButton)mButtonsView.findViewById(R.id.cancelAnnotButton);
mInkButton = (ImageButton)mButtonsView.findViewById(R.id.inkButton);
mSaveInkButton = (Button)mButtonsView.findViewById(R.id.saveInkButton);
mCancelInkButton = (ImageButton)mButtonsView.findViewById(R.id.cancelInkButton);
mTopBarSwitcher = (ViewAnimator)mButtonsView.findViewById(R.id.switcher);
mSearchBack = (ImageButton)mButtonsView.findViewById(R.id.searchBack);
mSearchFwd = (ImageButton)mButtonsView.findViewById(R.id.searchForward);
mSearchText = (EditText)mButtonsView.findViewById(R.id.searchText);
mLinkButton = (ImageButton)mButtonsView.findViewById(R.id.linkButton);
mTopBarSwitcher.setVisibility(View.INVISIBLE);
mPageNumberView.setVisibility(View.INVISIBLE);
mInfoView.setVisibility(View.INVISIBLE);
mPageSlider.setVisibility(View.INVISIBLE);
}
void showKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(mSearchText, 0);
}
void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
}
void search(int direction) {
hideKeyboard();
int displayPage = mDocView.getDisplayedViewIndex();
SearchTaskResult r = SearchTaskResult.get();
int searchPage = r != null ? r.pageNumber : -1;
mSearchTask.go(mSearchText.getText().toString(), direction, displayPage, searchPage);
}
@Override
public boolean onSearchRequested() {
if (mButtonsVisible && mTopBarMode == TopBarMode.Search) {
hideButtons();
} else {
showButtons();
searchModeOn();
}
return super.onSearchRequested();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (mButtonsVisible && mTopBarMode != TopBarMode.Search) {
hideButtons();
} else {
showButtons();
searchModeOff();
}
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onStart() {
if (core != null)
{
core.startAlerts();
createAlertWaiter();
}
super.onStart();
}
@Override
protected void onStop() {
if (core != null)
{
destroyAlertWaiter();
core.stopAlerts();
}
super.onStop();
}
@Override
public void onBackPressed() {
if (core.hasChanges()) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == AlertDialog.BUTTON_POSITIVE)
core.save();
finish();
}
};
AlertDialog alert = mAlertBuilder.create();
alert.setTitle("MuPDF");
alert.setMessage("Document has changes. Save them?");
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", listener);
alert.setButton(AlertDialog.BUTTON_NEGATIVE, "No", listener);
alert.show();
} else {
super.onBackPressed();
}
}
}
|
package com.cy.asap.android;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.cy.framework.MainGame;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new MainGame(), config);
}
}
|
package com.rho.rubyext;
import javax.microedition.location.*;
import com.rho.RhoClassFactory;
import com.rho.RhoConf;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.RhoThread;
import com.rho.net.NetResponse;
import com.xruby.runtime.lang.*;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.builtin.RubyArray;
import com.rho.net.NetRequest;
import com.rho.RhoRuby;
public class GeoLocation extends RhoThread{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("GeoLocation");
private static GeoLocation m_pInstance;
private LocationProvider m_lp = null;
private double m_lat = 0.0;
private double m_lon = 0.0;
private boolean m_bDetermined = false;
private long m_nDeterminedTime = 0;
private LocationListenerImpl m_locListener;
static private Object sync = new Object();
static private Object syncLP = new Object();
private boolean m_bInCallback = false;
private int m_nPingTimeoutSec = 0;
private final String errorStrDontSupport = "Location API doesn't support";
private final String errorStrLocationException= "Location could not be determined";
static class LocationListenerImpl implements LocationListener{
GeoLocation m_parent;
LocationListenerImpl(GeoLocation parent)
{
m_parent = parent;
}
public void locationUpdated(LocationProvider provider, Location location)
{
m_parent.m_bInCallback = true;
Coordinates coord = null;
try{
if ( location == null )
{
LOG.TRACE("GetLocation - locationUpdated: location is null.");
return;
}
if( !location.isValid() )
{
LOG.TRACE("GetLocation - locationUpdated: location invalid.");
return;
}
coord = location.getQualifiedCoordinates();
if(coord != null )
{
LOG.TRACE("GetLocation - latitude: " + Double.toString(m_parent.m_lat));
LOG.TRACE("GetLocation - longitude: " + Double.toString(m_parent.m_lon));
}else
LOG.TRACE("GetLocation - getQualifiedCoordinates: return null.");
}catch(Exception exc)
{
LOG.ERROR("locationUpdated failed.", exc);
}catch(Throwable exc)
{
LOG.ERROR("locationUpdated crashed.", exc);
}finally
{
if(coord != null )
m_parent.updateLocation(coord.getLatitude(), coord.getLongitude());
else
m_parent.onLocationError();
}
m_parent.m_bInCallback = false;
}
public void providerStateChanged(LocationProvider provider, int newState) {
if ( newState == LocationProvider.TEMPORARILY_UNAVAILABLE ){
LOG.TRACE("providerStateChanged: TEMPORARILY_UNAVAILABLE");
// m_bDetermined = false;
}else if ( newState == LocationProvider.OUT_OF_SERVICE ){
LOG.TRACE("providerStateChanged: OUT_OF_SERVICE");
// m_bDetermined = false;
}else
LOG.TRACE("providerStateChanged: " + newState);
}
}
public GeoLocation() {
super(new RhoClassFactory());
start(epLow);
}
int getPingTimeoutSec()
{
if (m_nPingTimeoutSec==0)
m_nPingTimeoutSec = getDefaultPingTimeoutSec();
return m_nPingTimeoutSec;
}
int getDefaultPingTimeoutSec()
{
int nPingTimeoutSec = RhoConf.getInstance().getInt("gps_ping_timeout_sec");
if (nPingTimeoutSec==0)
nPingTimeoutSec = 10;
return nPingTimeoutSec;
}
void setPingTimeoutSec( int nTimeout )
{
int nNewTimeout = nTimeout;
if (nNewTimeout == 0)
nNewTimeout = getDefaultPingTimeoutSec();
if ( nNewTimeout != m_nPingTimeoutSec)
{
m_nPingTimeoutSec = nNewTimeout;
stopWait();
}
}
public void run()
{
LOG.INFO( "Starting main routine..." );
while(!m_bStop)
{
if (!m_bStop)
checkAlive();
wait( 10*10000);
}
synchronized(sync)
{
try{
while(m_bInCallback)
sync.wait(100);
}catch(InterruptedException exc)
{}
}
synchronized(syncLP)
{
if ( m_lp != null ){
m_lp.setLocationListener(null, 0, 0, 0);
m_lp.reset();
}
}
LOG.INFO( "End main routine..." );
}
private void checkAlive(){
java.util.Date now = new java.util.Date();
long nNow = now.getTime();
boolean bErrorNotify = false;
boolean bReset = !m_bInCallback;//m_nDeterminedTime == 0 || ((nNow - m_nDeterminedTime)>1000*m_nResetTimeoutSec);
if ( bReset ){
try {
synchronized(syncLP)
{
if ( m_lp != null ){
if ( m_locListener != null )
{
LOG.TRACE("Reset LocationListener");
m_lp.reset();
m_lp.setLocationListener(null, 0,0, 0 );
m_locListener = null;
}
m_lp = null;
}
if ( getPingTimeoutSec() != -1 )
{
m_lp = LocationProvider.getInstance(null);
if ( m_lp != null ){
m_locListener = new LocationListenerImpl(this);
LOG.TRACE("setLocationListener");
m_lp.setLocationListener( m_locListener,
m_nDeterminedTime == 0 ? 1 : getPingTimeoutSec(), -1, -1);
m_nDeterminedTime = nNow;
}else
bErrorNotify = true;
}
}
}catch(Exception exc)
{
if ( m_lp != null )
LOG.INFO(errorStrLocationException + " : " + exc.getMessage());
else
LOG.INFO(errorStrDontSupport + " : " + exc.getMessage());
bErrorNotify = true;
}finally
{
if (bErrorNotify)
onLocationError();
}
}
}
private static class GeoNotification
{
String m_strUrl = "", m_strParams = "";
GeoNotification(String strUrl, String strParams)
{
m_strUrl = strUrl;
m_strParams = strParams;
}
void fire(boolean bError)
{
if (m_strUrl != null && m_strUrl.length() == 0)
return;
NetRequest netRequest = RhoClassFactory.createNetRequest();
try {
String strFullUrl = netRequest.resolveUrl(m_strUrl);
String strBody = "rho_callback=1";
if (bError && isAvailable() )
strBody += "&status=error&error_code=" + RhoRuby.ERR_GEOLOCATION;
else
strBody += "&status=ok";
strBody += "&available=" + (isAvailable() ? 1 : 0);
strBody += "&known_position=" + (isKnownPosition() ? 1 : 0);
strBody += "&latitude=" + GetLatitude();
strBody += "&longitude=" + GetLongitude();
if ( m_strParams != null && m_strParams.length() > 0 )
strBody += "&" + m_strParams;
NetResponse resp = netRequest.pushData( strFullUrl, strBody, null );
if ( !resp.isOK() )
LOG.ERROR( "Fire notification failed. Code: " + resp.getRespCode() + "; Error body: " + resp.getCharData() );
}catch(Exception exc)
{
LOG.ERROR("fire notification failed.", exc);
}
}
};
GeoNotification m_ViewNotify, m_Notify;
private void setViewNotification( String strUrl, String strParams, int nTimeout )
{
synchronized(sync)
{
m_ViewNotify = new GeoNotification(strUrl, strParams);
setPingTimeoutSec(nTimeout);
}
}
private void setNotification( String strUrl, String strParams, int nTimeout )
{
synchronized(sync)
{
m_Notify = new GeoNotification(strUrl, strParams);
setPingTimeoutSec(nTimeout);
}
}
private void onLocationError()
{
if ( m_Notify != null )
{
m_Notify.fire(true);
m_Notify = null;
}
if ( m_ViewNotify != null )
{
m_ViewNotify.fire(true);
m_ViewNotify = null;
}
}
private void updateLocation( double dLatitude, double dLongitude )
{
synchronized(sync)
{
boolean bNotify = m_lat != dLatitude || m_lon != dLongitude || m_bDetermined != true;
m_lat = dLatitude;
m_lon = dLongitude;
m_bDetermined = true;
java.util.Date now = new java.util.Date();
m_nDeterminedTime = now.getTime();
if ( bNotify && m_Notify != null )
{
m_Notify.fire(false);
m_Notify = null;
}
if ( bNotify && m_ViewNotify != null )
m_ViewNotify.fire(false);
}
}
public static void stop() {
if ( m_pInstance != null )
{
m_pInstance.stop(2);
m_pInstance = null;
}
}
public static void wakeUp() {
if ( m_pInstance != null )
m_pInstance.stopWait();
}
public static boolean isAvailable(){
synchronized(sync)
{
return m_pInstance != null && m_pInstance.m_lp != null;
}
}
public static double GetLatitude(){
startSelf();
synchronized(sync)
{
return m_pInstance.m_lat;
}
}
public static double GetLongitude(){
startSelf();
synchronized(sync)
{
return m_pInstance.m_lon;
}
}
public static boolean isKnownPosition(){
startSelf();
synchronized(sync)
{
return m_pInstance.m_bDetermined;
}
}
public static String getGeoLocationText()
{
String location = "";
if ( !isAvailable() )
location = "Unavailable;Unavailable;Unavailable";
else if( !isKnownPosition() )
location = "reading...;reading...;reading...";//<br/>" + GeoLocation.getLog();
else
{
double latitude = GetLatitude();
double longitude = GetLongitude();
location = String.valueOf(Math.abs(latitude)) + "f " +
(latitude < 0 ? "South" : "North") + ", " +
String.valueOf(Math.abs(longitude)) + "f " +
(longitude < 0 ? "West" : "East") + ";" +
String.valueOf(latitude) + ";" +
String.valueOf(longitude) + ";";
}
return location;
}
private static void startSelf() {
if ( m_pInstance == null )
m_pInstance = new GeoLocation();
}
public static void initMethods(RubyClass klass) {
klass.getSingletonClass().defineMethod("latitude", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
return ObjectFactory.createFloat(GetLatitude());
}catch(Exception e)
{
LOG.ERROR("latitude failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("longitude", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
return ObjectFactory.createFloat(GetLongitude());
}catch(Exception e)
{
LOG.ERROR("longitude failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("known_position?", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
return ObjectFactory.createBoolean(isKnownPosition());
}catch(Exception e)
{
LOG.ERROR("known_position? failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.getSingletonClass().defineMethod("set_view_notification", new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
if ( args.size() < 1 )
throw new RubyException(RubyRuntime.ArgumentErrorClass,
"in GeoLocation.set_view_notification: wrong number of arguments ( " + args.size() + " for " + 3 + " )");
try{
String url = args.get(0) != RubyConstant.QNIL ? args.get(0).toStr() : "";
String params = "";
int nTimeout = 0;
if ( args.size() > 1 )
params = args.get(1) != RubyConstant.QNIL ? args.get(1).toStr() : "";
if ( args.size() > 2 )
nTimeout = args.get(2) != RubyConstant.QNIL ? args.get(2).toInt() : -1;
if ( url != null && url.length() > 0 )
{
startSelf();
m_pInstance.setViewNotification(url, params, nTimeout);
}else if ( m_pInstance != null )
m_pInstance.setViewNotification(url, params, nTimeout);
}catch(Exception e)
{
LOG.ERROR("set_view_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.getSingletonClass().defineMethod("set_notification", new RubyVarArgMethod() {
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) {
if ( args.size() < 1 )
throw new RubyException(RubyRuntime.ArgumentErrorClass,
"in GeoLocation.set_view_notification: wrong number of arguments ( " + args.size() + " for " + 3 + " )");
try{
String url = args.get(0) != RubyConstant.QNIL ? args.get(0).toStr() : "";
String params = "";
int nTimeout = 0;
if ( args.size() > 1 )
params = args.get(1) != RubyConstant.QNIL ? args.get(1).toStr() : "";
if ( args.size() > 2 )
nTimeout = args.get(2) != RubyConstant.QNIL ? args.get(2).toInt() : -1;
if ( url != null && url.length() > 0 )
{
startSelf();
m_pInstance.setNotification(url, params, nTimeout);
}else if ( m_pInstance != null )
m_pInstance.setNotification(url, params, nTimeout);
}catch(Exception e)
{
LOG.ERROR("set_view_notification failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
}
}
|
package com.daxiang.android.utils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.view.View;
/**
*
*
* @author daxiang
* @date 2015-5-27
*
*/
public class BitmapUtils {
private static final String PNG = ".png";
private static final String JPEG = ".jpeg";
private static final String BMP = ".bmp";
private static final String GIF = ".gif";
/**
* SdCardPNG
*
* @param context
* @param src
* Bitmap
* @param fileName
* photo.png
* @return
*/
public static File saveAsFile(Context context, Bitmap src, String fileName) {
if (context == null || src == null) {
return null;
}
if (TextUtils.isEmpty(fileName)) {
fileName = System.currentTimeMillis() + PNG;
}
OutputStream stream = null;
File file = new File(FileUtils.getExternalFileDirs(context), fileName);
try {
stream = new BufferedOutputStream(new FileOutputStream(file));
src.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
src.recycle();
}
return file;
}
/**
*
*
* @param context
* @param uri
* @return
*/
public static String getRealFilePath(Context context, Uri uri) {
if (null == uri)
return null;
String scheme = uri.getScheme();
String data = null;
if (scheme == null)
data = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor = context.getContentResolver().query(uri, new String[] { ImageColumns.DATA }, null, null,
null);
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
}
return data;
}
/**
* Bitmap
*
* @param bmp
* Bitmap
* @param needRecycle
* Bitmaptruefalse
* @return
*/
public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Bitmap createCircleBitmap(Bitmap bitmap, int width, int height) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(width / 2, height / 2, width / 2, paint);
/**
* SRC_IN
*/
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, 0, 0, paint);
return target;
}
/**
* Bitmap
*
* @param file
* @param targetWidth
* @param targetHeight
* @return
*/
public static Bitmap decode(File file, int targetWidth, int targetHeight) {
if (file == null || !file.exists() || file.length() == 0) {
return null;
}
String pathName = file.getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
/*
* If set to a value > 1, requests the decoder to subsample the original
* image, returning a smaller image to save memory. The sample size is
* the number of pixels in either dimension that correspond to a single
* pixel in the decoded bitmap. For example, inSampleSize == 4 returns
* an image that is 1/4 the width/height of the original, and 1/16 the
* number of pixels. Any value <= 1 is treated the same as 1. Note: the
* decoder uses a final value based on powers of 2, any other value will
* be rounded down to the nearest power of 2.
*/
options.inSampleSize = computeImageSampleSize(options, targetWidth, targetHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pathName, options);
}
private static int computeImageSampleSize(Options options, int targetWidth, int targetHeight) {
return Math.max(options.outWidth / targetWidth, options.outHeight / targetHeight);
}
/**
* UIView
*
* @param width
*
* @param height
*
* @param view
* View
* @return
*/
public static Bitmap screenShot(int width, int height, View view) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
/**
*
*
* @param context
* @param file
*
* @param imageName
*
* @return truefalse
*/
public static boolean insertMediaStore(Context context, File file, String imageName) {
if (context == null || file == null || !file.exists()) {
return false;
}
if (TextUtils.isEmpty(imageName)) {
imageName = SystemClock.currentThreadTimeMillis() + PNG;
}
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), imageName, null);
// String imagePath =
// MediaStore.Images.Media.insertImage(getContentResolver(),
// bitmap, "", "");
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
}
|
package com.fsck.k9.mail.internet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.apache.james.mime4j.decoder.Base64InputStream;
import org.apache.james.mime4j.decoder.DecoderUtil;
import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
import android.util.Log;
import com.fsck.k9.k9;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;
public class MimeUtility {
public static String unfold(String s) {
if (s == null) {
return null;
}
return s.replaceAll("\r|\n", "");
}
public static String decode(String s) {
if (s == null) {
return null;
}
return DecoderUtil.decodeEncodedWords(s);
}
public static String unfoldAndDecode(String s) {
return decode(unfold(s));
}
// TODO implement proper foldAndEncode
public static String foldAndEncode(String s) {
return s;
}
/**
* Returns the named parameter of a header field. If name is null the first
* parameter is returned, or if there are no additional parameters in the
* field the entire field is returned. Otherwise the named parameter is
* searched for in a case insensitive fashion and returned. If the parameter
* cannot be found the method returns null.
*
* @param header
* @param name
* @return
*/
public static String getHeaderParameter(String header, String name) {
if (header == null) {
return null;
}
header = header.replaceAll("\r|\n", "");
String[] parts = header.split(";");
if (name == null) {
return parts[0];
}
for (String part : parts) {
if (part.trim().toLowerCase().startsWith(name.toLowerCase())) {
String parameter = part.split("=", 2)[1].trim();
if (parameter.startsWith("\"") && parameter.endsWith("\"")) {
return parameter.substring(1, parameter.length() - 1);
}
else {
return parameter;
}
}
}
return null;
}
public static Part findFirstPartByMimeType(Part part, String mimeType)
throws MessagingException {
if (part.getBody() instanceof Multipart) {
Multipart multipart = (Multipart)part.getBody();
for (int i = 0, count = multipart.getCount(); i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
Part ret = findFirstPartByMimeType(bodyPart, mimeType);
if (ret != null) {
return ret;
}
}
}
else if (part.getMimeType().equalsIgnoreCase(mimeType)) {
return part;
}
return null;
}
public static Part findPartByContentId(Part part, String contentId) throws Exception {
if (part.getBody() instanceof Multipart) {
Multipart multipart = (Multipart)part.getBody();
for (int i = 0, count = multipart.getCount(); i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
Part ret = findPartByContentId(bodyPart, contentId);
if (ret != null) {
return ret;
}
}
}
String[] header = part.getHeader("Content-ID");
if (header != null) {
for (String s : header) {
if (s.equals(contentId)) {
return part;
}
}
}
return null;
}
/**
* Reads the Part's body and returns a String based on any charset conversion that needed
* to be done.
* @param part
* @return
* @throws IOException
*/
public static String getTextFromPart(Part part) {
Charset mCharsetConverter;
try {
if (part != null && part.getBody() != null) {
InputStream in = part.getBody().getInputStream();
String mimeType = part.getMimeType();
/*
* Now we read the part into a buffer for further processing. Because
* the stream is now wrapped we'll remove any transfer encoding at this point.
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
byte[] bytes = out.toByteArray();
in.close();
out.close();
String charset = getHeaderParameter(part.getContentType(), "charset");
/*
* We've got a text part, so let's see if it needs to be processed further.
*/
if (charset != null) {
/*
* See if there is conversion from the MIME charset to the Java one.
*/
mCharsetConverter = Charset.forName(charset);
charset = mCharsetConverter.name();
}
if (charset != null) {
/*
* We've got a charset encoding, so decode using it.
*/
return new String(bytes, 0, bytes.length, charset);
}
else {
/*
* No encoding, so use us-ascii, which is the standard.
*/
return new String(bytes, 0, bytes.length, "ASCII");
}
}
}
}
catch (Exception e) {
/*
* If we are not able to process the body there's nothing we can do about it. Return
* null and let the upper layers handle the missing content.
*/
Log.e(k9.LOG_TAG, "Unable to getTextFromPart", e);
}
return null;
}
* * /*.
* @return
*/
public static boolean mimeTypeMatches(String mimeType, String matchAgainst) {
return mimeType.matches(matchAgainst.replaceAll("\\*", "\\.\\*"));
}
* as image/* or * /*.
* @return
*/
public static boolean mimeTypeMatches(String mimeType, String[] matchAgainst) {
for (String matchType : matchAgainst) {
if (mimeType.matches(matchType.replaceAll("\\*", "\\.\\*"))) {
return true;
}
}
return false;
}
/**
* Removes any content transfer encoding from the stream and returns a Body.
*/
public static Body decodeBody(InputStream in, String contentTransferEncoding)
throws IOException {
/*
* We'll remove any transfer encoding by wrapping the stream.
*/
if (contentTransferEncoding != null) {
contentTransferEncoding =
MimeUtility.getHeaderParameter(contentTransferEncoding, null);
if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
in = new QuotedPrintableInputStream(in);
}
else if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
in = new Base64InputStream(in);
}
}
BinaryTempFileBody tempBody = new BinaryTempFileBody();
OutputStream out = tempBody.getOutputStream();
IOUtils.copy(in, out);
out.close();
return tempBody;
}
/**
* An unfortunately named method that makes decisions about a Part (usually a Message)
* as to which of it's children will be "viewable" and which will be attachments.
* The method recursively sorts the viewables and attachments into seperate
* lists for further processing.
* @param part
* @param viewables
* @param attachments
* @throws MessagingException
*/
public static void collectParts(Part part, ArrayList<Part> viewables,
ArrayList<Part> attachments) throws MessagingException {
String disposition = part.getDisposition();
String dispositionType = null;
String dispositionFilename = null;
if (disposition != null) {
dispositionType = MimeUtility.getHeaderParameter(disposition, null);
dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename");
}
/*
* A best guess that this part is intended to be an attachment and not inline.
*/
boolean attachment = ("attachment".equalsIgnoreCase(dispositionType))
|| (dispositionFilename != null)
&& (!"inline".equalsIgnoreCase(dispositionType));
/*
* If the part is Multipart but not alternative it's either mixed or
* something we don't know about, which means we treat it as mixed
* per the spec. We just process it's pieces recursively.
*/
if (part.getBody() instanceof Multipart) {
Multipart mp = (Multipart)part.getBody();
for (int i = 0; i < mp.getCount(); i++) {
collectParts(mp.getBodyPart(i), viewables, attachments);
}
}
/*
* If the part is an embedded message we just continue to process
* it, pulling any viewables or attachments into the running list.
*/
else if (part.getBody() instanceof Message) {
Message message = (Message)part.getBody();
collectParts(message, viewables, attachments);
}
/*
* If the part is HTML and it got this far it's part of a mixed (et
* al) and should be rendered inline.
*/
else if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/html"))) {
viewables.add(part);
}
/*
* If the part is plain text and it got this far it's part of a
* mixed (et al) and should be rendered inline.
*/
else if ((!attachment) && (part.getMimeType().equalsIgnoreCase("text/plain"))) {
viewables.add(part);
}
/*
* Finally, if it's nothing else we will include it as an attachment.
*/
else {
attachments.add(part);
}
}
}
|
package com.github.fengtan.solrgui;
import org.apache.commons.lang3.ArrayUtils;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
// TODO mechanism to load / delete servers from config file.
public class SolrGUITab extends CTabItem {
private Table table;
private TableViewer tableViewer;
private SolrGUIServer server;
private SolrGUIServerSorter sorter;
public SolrGUITab(CTabFolder tabFolder, SolrGUIServer server) {
super(tabFolder, SWT.NONE, tabFolder.getItemCount());
this.server = server;
setText(server.getName());
setToolTipText(server.getURL().toString());
// Fill up tab.
Composite composite = new Composite(getParent(), SWT.BORDER);
createLayout(composite);
createTable(composite);
createTableViewer();
createButtons(composite);
setControl(composite);
// Set focus on this tab.
tabFolder.setSelection(this);
tabFolder.forceFocus();
}
private void createLayout(Composite composite) {
GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_BOTH);
composite.setLayoutData (gridData);
// Set numColumns to 3 for the buttons
GridLayout layout = new GridLayout(4, false);
layout.marginWidth = 4;
composite.setLayout(layout);
}
/**
* Create the Table
*/
private void createTable(Composite parent) {
int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
table = new Table(parent, style);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.grabExcessVerticalSpace = true;
gridData.horizontalSpan = 4;
table.setLayoutData(gridData);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumn column = new TableColumn(table, SWT.CENTER, 0);
// TODO Review tooltip + Changes vs Status (Ctrl+F) should be consistent
column.setText("Changes");
column.setToolTipText("Pending changes:\nClick on \"Commit\" to push to Solr\nClick on \"Revert\" to cancel changes");
column.setWidth(20);
for (final String field:server.getFields()) {
column = new TableColumn(table, SWT.LEFT);
column.setText(field);
// Add listener to column so documents are sorted when clicked.
column.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
sorter = new SolrGUIServerSorter(field);
tableViewer.setSorter(sorter); // TODO does sorting scale ?
}
});
column.pack();
}
}
/**
* Create the TableViewer
*/
private void createTableViewer() {
tableViewer = new TableViewer(table);
tableViewer.setUseHashlookup(true);
String[] columns = ArrayUtils.addAll(new String[]{"Status"}, server.getFields());
tableViewer.setColumnProperties(columns);
// Create the cell editors
CellEditor[] editors = new CellEditor[tableViewer.getColumnProperties().length];
TextCellEditor textEditor;
for (int i=0; i<editors.length; i++) {
textEditor = new TextCellEditor(table);
((Text) textEditor.getControl()).setTextLimit(60);
editors[i] = textEditor;
}
tableViewer.setCellEditors(editors);
// Set the cell modifier for the viewer
tableViewer.setCellModifier(new SolrGUICellModifier(server));
// Set the default sorter for the viewer.
// tableViewer.setSorter(sorter); // null-safe. TODO uncomment ?
tableViewer.setContentProvider(new SolrGUIContentProvider());
tableViewer.setLabelProvider(new SolrGUILabelProvider(server));
tableViewer.setInput(server);
}
@Override
public void dispose() {
tableViewer.getLabelProvider().dispose();
server.dispose();
super.dispose();
}
/**
* InnerClass that acts as a proxy for the SolrGUIServer
* providing content for the Table. It implements the ISolrGUIServerViewer
* interface since it must register changeListeners with the
* SolrGUIServer
*/
class SolrGUIContentProvider implements IStructuredContentProvider, ISolrGUIServerViewer {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
if (newInput != null) {
((SolrGUIServer) newInput).addChangeListener(this);
}
if (oldInput != null) {
((SolrGUIServer) oldInput).removeChangeListener(this);
}
}
public void dispose() {
server.removeChangeListener(this);
}
// Return the documents as an array of Objects
public Object[] getElements(Object parent) {
return server.getDocuments().toArray();
}
public void addDocument(SolrGUIDocument document) {
tableViewer.add(document);
}
public void removeDocument(SolrGUIDocument document) {
tableViewer.remove(document);
}
public void updateDocument(SolrGUIDocument document) {
tableViewer.update(document, null);
}
}
/**
* Add the "Add", "Delete" and "Commit" buttons
*
* @param composite the parent composite
*/
private void createButtons(Composite composite) {
// Create and configure the "Add" button
Button add = new Button(composite, SWT.PUSH | SWT.CENTER);
add.setText("Add");
GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
gridData.widthHint = 80;
add.setLayoutData(gridData);
add.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
server.addDocument();
}
});
// Create and configure the "Delete" button
Button delete = new Button(composite, SWT.PUSH | SWT.CENTER);
delete.setText("Delete");
gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
gridData.widthHint = 80;
delete.setLayoutData(gridData);
delete.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
SolrGUIDocument document = (SolrGUIDocument) ((IStructuredSelection) tableViewer.getSelection()).getFirstElement();
if (document != null) {
server.removeDocument(document);
}
}
});
// Create and configure the "Clone" button
Button clone = new Button(composite, SWT.PUSH | SWT.CENTER);
clone.setText("Clone");
gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
gridData.widthHint = 80;
clone.setLayoutData(gridData);
clone.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
SolrGUIDocument document = (SolrGUIDocument) ((IStructuredSelection) tableViewer.getSelection()).getFirstElement();
if (document != null) {
// TODO Cloning generate remote exception
server.addDocument(document.clone());
}
}
});
// Create and configure the "Commit" button.
Button commit = new Button(composite, SWT.PUSH | SWT.CENTER);
commit.setText("Commit");
gridData = new GridData (GridData.HORIZONTAL_ALIGN_END);
gridData.widthHint = 80;
commit.setLayoutData(gridData);
commit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
server.commit();
tableViewer.refresh();
}
});
}
}
|
package yi.report;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import yi.pdf.YiPdfColor;
import yi.pdf.YiPdfFile;
import yi.pdf.YiPdfFont;
import yi.pdf.YiPdfTag;
import yi.pdf.font.YiPdfJGothicFont;
public class MyLayoutContext {
YiPdfFile pdfFile;
Map<String, String> nowStyle = new HashMap<String, String>();
Map<String, String> nowStyleDiff;
Stack<Map<String, String>> styleStack = new Stack<Map<String,String>>();
MyLayoutBlock nowBlock;
MyLayoutLine nowLine;
YiPdfTag nowTag;
YiPdfTag nowLineTag;
MyLayoutContext(YiPdfFile pdfFile) {
this.pdfFile = pdfFile;
nowTag = pdfFile.getDocument();
}
Stack<YiPdfTag> tagStack = new Stack<YiPdfTag>();
void pushPdfTag(YiPdfTag tag) {
tagStack.push(nowTag);
nowTag = tag;
clearLineTag();
}
void popPdfTag() {
nowTag = tagStack.pop();
clearLineTag();
}
YiPdfTag getNowTag() {
return nowTag;
}
YiPdfTag getLineTag() {
if(nowLineTag==null) {
nowLineTag = nowTag.makeChild("P");
}
return nowLineTag;
}
void clearLineTag() {
nowLineTag = null;
}
void pushStyle(Map<String, String> style) {
nowStyleDiff = style;
styleStack.push(nowStyle);
if(style!=null) {
nowStyle = new HashMap<String, String>(nowStyle);
nowStyle.putAll(style);
}
}
void popStyle() {
nowStyle = styleStack.pop();
}
MyLayoutBlock getNowBlock() {
if(nowBlock==null) {
nowBlock = MyLayoutBlock.createPageRoot(nowStyle);
}
return nowBlock;
}
Stack<MyLayoutBlock> blockStack;
void pushNewBlock() {
blockStack.push(getNowBlock());
nowBlock = MyLayoutBlock.createChildBlock();
}
void popBlock() {
MyLayoutBlock childBlock = nowBlock;
nowBlock = blockStack.pop();
nowBlock.addBlock(childBlock);
assert(false) : "TODO: MyLayoutContext.popBlock()";
}
void clearNowBlock() throws IOException {
clearNowLine();
if(nowBlock!=null) {
assert(nowBlock.isPageRoot()) : "pageRootnowBlockclear";
nowBlock.drawPage(pdfFile);
nowBlock = null;
}
}
MyLayoutLine getNowLine() {
if(nowLine==null) {
double lineWidth = getNowBlock().getLineWidth();
nowLine = new MyLayoutLine(lineWidth);
}
return nowLine;
}
boolean fourceBlockFlag = true;
void clearNowLine() throws IOException {
if(nowLine!=null) {
while(true) {
boolean f = getNowBlock().addLine(nowLine, fourceBlockFlag);
if(!f) {
MyLayoutLine hold = nowLine;
nowLine = null;
clearNowBlock();
nowLine = hold;
fourceBlockFlag = true;
}
else {
fourceBlockFlag = false;
break;
}
}
nowLine = null;
}
}
YiPdfFont dummyFont = new YiPdfJGothicFont();
YiPdfFont getNowFont() {
return dummyFont;
//assert(false) : "TODO: MyLayoutContext.getNowFont()";
}
double getNowFontSize() {
String str = nowStyle.get("font-size");
if(str==null) {
return 10.5;
}
return MyUtil.evalUnit(str);
//assert(false) : "TODO: MyLayoutContext.getNowFontSize()";
}
private YiPdfColor getNowFontColor() {
String str = nowStyle.get("font-color");
if(str==null) {
return new YiPdfColor(0, 0, 0);
}
return MyUtil.evalColor(str);
//assert(false) : "TODO: MyLayoutContext.getNowFontColor()";
}
public void writeText(String text) throws IOException {
YiPdfFont font = getNowFont();
YiPdfColor color = getNowFontColor();
double fontSize = getNowFontSize();
int len = text.length();
int pos = 0;
while(pos<len) {
MyLayoutLine nLine = getNowLine();
double maxTravel = nLine.getRemainingTravel();
MyQuartet<Integer, String, Boolean, Double> q = formattingText(font, fontSize, text, maxTravel, pos);
assert(pos!=q.first);
pos = q.first;
String str = q.second;
boolean brFlag = q.third;
double totalTravel = q.fourth;
nLine.addInline(new MyLayoutInlineText(font, fontSize, color, str, totalTravel, getLineTag()));
if(brFlag) {
writeNewLine();
}
}
}
String tabooPrefix = "";
String tabooSuffix = "";
public MyQuartet<Integer, String, Boolean, Double> formattingText(YiPdfFont font, double fontSize, String text, double maxTravel, int stPos) {
int maxTravelInt = (int)((maxTravel * 1000) / fontSize);
int len = text.length();
int totalTravel = 0;
int reservedTravel = -1;
int reservedPos = -1;
char beforeCh = 0;
boolean brFlag = false;
int pos;
for(pos = stPos; pos < len; ++pos) {
char ch = text.charAt(pos);
if(ch=='\n') {
pos += 1;
brFlag = true;
break;
}
else if(ch==' ') {
reservedPos = pos + 1;
reservedTravel = totalTravel;
}
else if((ch<0 || 128<=ch) && tabooPrefix.indexOf(ch)<0 && tabooSuffix.indexOf(beforeCh)<0) {
reservedPos = pos;
reservedTravel = totalTravel;
}
int travel = font.getTravel(ch);
if(maxTravelInt < totalTravel + travel) {
if(reservedPos==-1) {
if(pos==stPos) {
pos += 1;
totalTravel += travel;
}
}
else {
pos = reservedPos;
totalTravel = reservedTravel;
if(pos==stPos) {
pos += 1;
totalTravel += travel;
}
}
brFlag = true;
break;
}
totalTravel += travel;
beforeCh = ch;
}
String str = text.substring(stPos, pos);
return new MyQuartet<Integer, String, Boolean, Double>(pos, str, brFlag, (fontSize * totalTravel) / 1000);
}
public void writeBr() throws IOException {
getNowLine().addBlankText(getNowFont(), getNowFontSize(), getLineTag());
clearLineTag();
writeNewLine();
}
public void writeNewLine() throws IOException {
clearNowLine();
}
}
|
package controllers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import org.openrdf.rio.RDFFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import models.Article;
import models.Chapter;
import models.Proceeding;
import models.ResearchData;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import services.XmlUtils;
import services.ZettelRegister;
import services.ZettelRegisterEntry;
import views.html.*;
import play.libs.ws.*;
/**
* @author Jan Schnasse
*
*/
public class ZettelController extends Controller {
@Inject
play.data.FormFactory formFactory;
@Inject
WSClient ws;
/**
* @return the start page
*/
public CompletionStage<Result> index() {
CompletableFuture<Result> future = new CompletableFuture<>();
future.complete(ok(index.render("Zettel")));
return future;
}
/**
* @param all a path
* @return a header for all routes when ask with HTTP OPTIONS
*/
public CompletionStage<Result> corsforall(String all) {
CompletableFuture<Result> future = new CompletableFuture<>();
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods",
"POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
future.complete(ok());
return future;
}
/**
* @param id if null list all available forms otherwise render the requested
* form.
* @param format ask for certain format. supports xml,ntriples and json
* @param documentId your personal id for the document you want to create form
* data for
* @param topicId the topic id is used by our regal-drupal to find the actual
* documentId. You can probably ignore this.
* @return a list of available forms or if present the form with a certain id.
*
*/
public CompletionStage<Result> getForms(String id, String format,
String documentId, String topicId) {
setHeaders();
CompletableFuture<Result> future = new CompletableFuture<>();
Result result = null;
if (id == null)
result = listForms();
else {
ZettelRegister zettelRegister = new ZettelRegister();
ZettelRegisterEntry zettel = zettelRegister.get(id);
result = renderForm(zettel, format, documentId, topicId);
}
future.complete(result);
return future;
}
/**
* @param id the id of the form the POST data is send to.
* @param format ask for certain format. supports xml,ntriples and json
* @param documentId your personal id for the document you want to create form
* data for
* @param topicId the topic id is used by our regal-drupal to find the actual
* documentId. You can probably ignore this.
* @return if posted with accept:application/json return json-ld
* representation of the data. In all other cases return an html
* formular.
*/
public CompletionStage<Result> postForm(String id, String format,
String documentId, String topicId) {
setHeaders();
Result result = null;
ZettelRegister zettelRegister = new ZettelRegister();
CompletableFuture<Result> future = new CompletableFuture<>();
ZettelRegisterEntry zettel = zettelRegister.get(id);
Form<?> form = bindToForm(zettel);
result = renderForm(format, documentId, topicId, zettel, form);
future.complete(result);
return future;
}
/**
* @param format ask for certain format. supports xml,ntriples and json
* @param documentId your personal id for the document you want to create form
* data for
* @param topicId the topic id is used by our regal-drupal to find the actual
* documentId. You can probably ignore this.
* @return a client demo
*/
public CompletionStage<Result> client(String format, String id,
String documentId, String topicId) {
CompletableFuture<Result> future = new CompletableFuture<>();
future
.complete(ok(client.render("Zettel", format, id, documentId, topicId)));
return future;
}
private static Result renderForm(String format, String documentId,
String topicId, ZettelRegisterEntry zettel, Form<?> form) {
Result result;
if (form.hasErrors()) {
if (request().accepts("text/html")) {
result = badRequest(zettel.render(form, format, documentId, topicId));
} else {
result = badRequest(form.errorsAsJson()).as("application/json");
}
} else {
if (request().accepts("text/html")) {
result = ok(zettel.render(form, format, documentId, topicId));
} else {
result = ok(form.get().toString()).as("application/json");
}
}
return result;
}
private Form<?> bindToForm(ZettelRegisterEntry zettel) {
Form<?> form = null;
if ("application/rdf+xml".equals(request().contentType().get())) {
form = loadRdf(XmlUtils.docToString(request().body().asXml()), zettel);
form.bindFromRequest();
} else {
form = formFactory.form(zettel.getModel().getClass()).bindFromRequest();
}
return form;
}
private Form<?> loadRdf(String asText, ZettelRegisterEntry zettel) {
try (InputStream in = new ByteArrayInputStream(asText.getBytes("utf-8"))) {
String id = zettel.getId();
if (ResearchData.id.equals(id)) {
return formFactory.form(ResearchData.class).fill((ResearchData) zettel
.getModel().deserializeFromRdf(in, RDFFormat.RDFXML));
} else if (Article.id.equals(id)) {
return formFactory.form(Article.class).fill((Article) zettel.getModel()
.deserializeFromRdf(in, RDFFormat.RDFXML));
} else if (Proceeding.id.equals(id)) {
return formFactory.form(Proceeding.class).fill((Proceeding) zettel
.getModel().deserializeFromRdf(in, RDFFormat.RDFXML));
} else if (Chapter.id.equals(id)) {
return formFactory.form(Chapter.class).fill((Chapter) zettel.getModel()
.deserializeFromRdf(in, RDFFormat.RDFXML));
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void setHeaders() {
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
}
private static Result listForms() {
ZettelRegister zettelRegister = new ZettelRegister();
List<String> formList = zettelRegister.getIds();
return ok(forms.render(formList));
}
private Result renderForm(ZettelRegisterEntry zettel, String format,
String documentId, String topicId) {
Form<?> form = formFactory.form(zettel.getModel().getClass());
return ok(zettel.render(form, format, documentId, topicId));
}
/**
* @param q the query will be redirected to geonames
* @return the response from api.geonames.org
*/
public CompletionStage<Result> geoSearch(String q) {
String geoNamesUrl = "http://api.geonames.org/searchJSON";
WSRequest request = ws.url(geoNamesUrl);
WSRequest complexRequest =
request.setRequestTimeout(1000).setQueryParameter("q", q)
.setQueryParameter("username", "epublishinghbz");
return complexRequest.setFollowRedirects(true).get()
.thenApply(response -> ok(response.asJson()));
}
public CompletionStage<Result> orcidSearch(String q) {
String orcidUrl = "http://pub.orcid.org/search/orcid-bio";
WSRequest request = ws.url(orcidUrl);
WSRequest complexRequest =
request.setRequestTimeout(1000).setQueryParameter("q", q);
return complexRequest.setFollowRedirects(true).get()
.thenApply(response -> ok(response.asJson()));
}
public CompletionStage<Result> orcidAutocomplete(String q) {
final String[] callback =
request() == null || request().queryString() == null ? null
: request().queryString().get("callback");
String orcidUrl = "http://pub.orcid.org/search/orcid-bio";
WSRequest request = ws.url(orcidUrl);
WSRequest complexRequest = request.setHeader("accept", "application/json")
.setRequestTimeout(5000).setQueryParameter("q", q);
return complexRequest.setFollowRedirects(true).get().thenApply(response -> {
JsonNode hits =
response.asJson().at("/orcid-search-results/orcid-search-result");
List<Map<String, String>> result = new ArrayList<>();
hits.forEach((hit) -> {
String label = hit
.at("/orcid-profile/orcid-bio/personal-details/family-name/value")
.asText()
+ ", "
+ hit
.at("/orcid-profile/orcid-bio/personal-details/given-names/value")
.asText();
String id = hit.at("/orcid-profile/orcid-identifier/uri").asText();
Map<String, String> m = new HashMap<>();
m.put("label", label);
m.put("value", id);
result.add(m);
});
String searchResult = json(result);
String myResponse = callback != null
? String.format("%s(%s)", callback[0], searchResult)
: searchResult;
return ok(myResponse);
});
}
private static String json(Object obj) {
try {
StringWriter w = new StringWriter();
new ObjectMapper().writeValue(w, obj);
String result = w.toString();
return result;
} catch (Exception e) {
play.Logger.error("", e);
return "{\"message\":\"error\"}";
}
}
}
|
package com.jefftharris.passwdsafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.pwsafe.lib.file.PwsFile;
import org.pwsafe.lib.file.PwsFileFactory;
import org.pwsafe.lib.file.PwsFileV3;
import org.pwsafe.lib.file.PwsRecord;
import org.pwsafe.lib.file.PwsRecordV3;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
public class PasswdSafe extends ExpandableListActivity {
private static final String TAG = "PasswdSafe";
private static final int DIALOG_GET_PASSWD = 0;
private static final String GROUP = "group";
private static final String TITLE = "title";
private static final String RECORD = "record";
public static final String INTENT = "com.jefftharris.passwdsafe.action.VIEW";
private LoadFileData itsFileData = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate bundle:" + savedInstanceState + ", intent:" +
getIntent() + ", data:" + itsFileData);
if (itsFileData == null) {
showDialog(DIALOG_GET_PASSWD);
} else {
showFileData();
}
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy()
{
Log.i(TAG, "onDestroy");
super.onDestroy();
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause()
{
Log.i(TAG, "onPause");
super.onPause();
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume()
{
Log.i(TAG, "onResume");
super.onResume();
}
/* (non-Javadoc)
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState)
{
Log.i(TAG, "onSaveInstanceState state:" + outState);
super.onSaveInstanceState(outState);
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Log.i(TAG, "onCreateDialog id:" + id);
Dialog dialog = null;
switch (id) {
case DIALOG_GET_PASSWD:
{
LayoutInflater factory = LayoutInflater.from(this);
final View passwdView =
factory.inflate(R.layout.passwd_entry, null);
// TODO: click Ok when enter pressed
AlertDialog.Builder alert = new AlertDialog.Builder(this)
.setTitle("Enter Password")
.setMessage("Password:")
.setView(passwdView)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,
int which)
{
EditText passwdInput = (EditText) passwdView
.findViewById(R.id.passwd_edit);
PasswdSafe.this.removeDialog(DIALOG_GET_PASSWD);
showFile(passwdInput.getText().toString());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,
int which)
{
PasswdSafe.this.finish();
}
});
dialog = alert.create();
break;
}
}
return dialog;
}
/* (non-Javadoc)
* @see android.app.ExpandableListActivity#onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long)
*/
@Override
public boolean onChildClick(ExpandableListView parent,
View v,
int groupPosition,
int childPosition,
long id)
{
ArrayList<HashMap<String, Object>> groupChildren =
itsFileData.itsChildData.get(groupPosition);
HashMap<String, Object> child = groupChildren.get(childPosition);
Log.i(TAG, "selected child:" + child.get(TITLE));
return true;
}
private void showFile(String passwd)
{
Intent intent = getIntent();
final ProgressDialog progress =
ProgressDialog.show(this, "", "Loading...", true);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
if (msg.what == LoadFileThread.RESULT_DATA) {
itsFileData = (LoadFileData)msg.obj;
showFileData();
} else {
Exception e = (Exception)msg.obj;
new AlertDialog.Builder(PasswdSafe.this)
.setMessage(e.toString())
.setCancelable(false)
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
PasswdSafe.this.finish();
}
})
.show();
}
}
};
LoadFileThread thr = new LoadFileThread(intent.getData().getPath(),
new StringBuilder(passwd),
handler);
thr.start();
}
private void showFileData()
{
ExpandableListAdapter adapter =
new SimpleExpandableListAdapter(PasswdSafe.this,
itsFileData.itsGroupData,
android.R.layout.simple_expandable_list_item_1,
new String[] { GROUP },
new int[] { android.R.id.text1 },
itsFileData.itsChildData,
android.R.layout.simple_expandable_list_item_1,
new String[] { TITLE },
new int[] { android.R.id.text1 });
setListAdapter(adapter);
Log.i(TAG, "adapter set");
}
private static final String getGroup(PwsRecord rec, PwsFile file)
{
switch (file.getFileVersionMajor()) {
case PwsFileV3.VERSION:
return rec.getField(PwsRecordV3.GROUP).toString();
default:
return "TODO";
}
}
private static final String getTitle(PwsRecord rec, PwsFile file)
{
switch (file.getFileVersionMajor()) {
case PwsFileV3.VERSION:
return rec.getField(PwsRecordV3.TITLE).toString();
default:
return "TODO";
}
}
private static final class LoadFileData
{
public final PwsFile itsPwsFile;
public final ArrayList<Map<String, String>> itsGroupData;
public final ArrayList<ArrayList<HashMap<String, Object>>> itsChildData;
public LoadFileData(PwsFile pwsFile,
ArrayList<Map<String, String>> groupData,
ArrayList<ArrayList<HashMap<String, Object>>> childData)
{
itsPwsFile = pwsFile;
itsGroupData = groupData;
itsChildData = childData;
}
}
private static final class LoadFileThread extends Thread
{
private final String itsFile;
private StringBuilder itsPasswd;
private final Handler itsMsgHandler;
public static final int RESULT_DATA = 0;
public static final int RESULT_EXCEPTION = 1;
public LoadFileThread(String file,
StringBuilder passwd,
Handler msgHandler) {
itsFile = file;
itsPasswd = passwd;
itsMsgHandler = msgHandler;
}
@Override
public void run() {
LoadFileData data = null;
Exception resultException = null;
try {
// TODO: on pause, close file, clear password, etc.
// TODO: Remember last file used somewhere?
Log.i(TAG, "before load file");
PwsFile pwsfile = PwsFileFactory.loadFile(itsFile, itsPasswd);
itsPasswd = null;
Log.i(TAG, "after load file");
ArrayList<Map<String, String>> groupData =
new ArrayList<Map<String, String>>();
ArrayList<ArrayList<HashMap<String, Object>>> childData =
new ArrayList<ArrayList<HashMap<String, Object>>>();
TreeMap<String, ArrayList<PwsRecord>> recsByGroup =
new TreeMap<String, ArrayList<PwsRecord>>();
Iterator<PwsRecord> recIter = pwsfile.getRecords();
while (recIter.hasNext()) {
PwsRecord rec = recIter.next();
String group = getGroup(rec, pwsfile);
ArrayList<PwsRecord> groupList = recsByGroup.get(group);
if (groupList == null) {
groupList = new ArrayList<PwsRecord>();
recsByGroup.put(group, groupList);
}
groupList.add(rec);
}
Log.i(TAG, "groups sorted");
RecordMapComparator comp = new RecordMapComparator();
for (Map.Entry<String, ArrayList<PwsRecord>> entry :
recsByGroup.entrySet()) {
Log.i(TAG, "process group:" + entry.getKey());
Map<String, String> groupInfo =
Collections.singletonMap(GROUP, entry.getKey());
groupData.add(groupInfo);
ArrayList<HashMap<String, Object>> children =
new ArrayList<HashMap<String, Object>>();
for (PwsRecord rec : entry.getValue()) {
HashMap<String, Object> recInfo = new HashMap<String, Object>();
recInfo.put(TITLE, getTitle(rec, pwsfile));
recInfo.put(RECORD, rec);
children.add(recInfo);
}
Collections.sort(children, comp);
childData.add(children);
}
Log.i(TAG, "adapter data created");
data = new LoadFileData(pwsfile, groupData, childData);
} catch (Exception e) {
Log.e(TAG, "Exception", e);
resultException = e;
}
Message msg;
if (data != null) {
msg = Message.obtain(itsMsgHandler, RESULT_DATA, data);
} else {
msg = Message.obtain(itsMsgHandler, RESULT_EXCEPTION,
resultException);
}
itsMsgHandler.sendMessage(msg);
}
}
private static final class RecordMapComparator implements
Comparator<HashMap<String, Object>>
{
public int compare(HashMap<String, Object> arg0,
HashMap<String, Object> arg1)
{
String title0 = arg0.get(TITLE).toString();
String title1 = arg1.get(TITLE).toString();
return title0.compareTo(title1);
}
}
}
|
package jade.imtp.leap.nio;
//#J2ME_EXCLUDE_FILE
import jade.core.FrontEnd;
import jade.core.BackEnd;
import jade.core.BackEndContainer;
import jade.core.BEConnectionManager;
import jade.core.Profile;
import jade.core.ProfileException;
import jade.core.IMTPException;
import jade.imtp.leap.MicroSkeleton;
import jade.imtp.leap.BackEndSkel;
import jade.imtp.leap.FrontEndStub;
import jade.imtp.leap.Dispatcher;
import jade.imtp.leap.ICPException;
import jade.imtp.leap.JICP.JICPProtocol;
import jade.imtp.leap.JICP.JICPMediator;
import jade.imtp.leap.JICP.JICPMediatorManager;
import jade.imtp.leap.JICP.JICPPacket;
import jade.imtp.leap.JICP.Connection;
import jade.util.leap.Properties;
import jade.util.Logger;
import java.io.IOException;
import java.net.InetAddress;
/**
This class implements the BIFEDispatcher related BackEnd dispatcher
managable by an asynchronous JICPMediatorManager
@author Giovanni Caire - Telecom Italia LAB S.p.A.
*/
public class NIOBEDispatcher implements NIOMediator, BEConnectionManager, Dispatcher {
private static final long RESPONSE_TIMEOUT = 60000;
private long keepAliveTime;
private long lastReceivedTime;
private boolean active = true;
private boolean peerActive = true;
private JICPMediatorManager myMediatorManager;
private String myID;
private Properties myProperties;
private BackEndContainer myContainer = null;
protected InputManager inpManager;
protected OutputManager outManager;
private Logger myLogger = Logger.getMyLogger(getClass().getName());
/**
Retrieve the ID of this mediator. Returns null if this mediator
is not active
*/
public String getId() {
return (active ? myID : null);
}
/**
Retrieve the startup Properties for this NIOBEDispatcher.
*/
public Properties getProperties() {
return myProperties;
}
/**
Initialize this JICPMediator
*/
public void init(JICPMediatorManager mgr, String id, Properties props) throws ICPException {
myMediatorManager = mgr;
myID = id;
myProperties = props;
// Max disconnection time
long maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
try {
maxDisconnectionTime = Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
}
catch (Exception e) {
// Keep default
}
// Keep-alive time
keepAliveTime = JICPProtocol.DEFAULT_KEEP_ALIVE_TIME;
try {
keepAliveTime = Long.parseLong(props.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY));
}
catch (Exception e) {
// Keep default
}
// inpCnt
int inpCnt = 0;
try {
inpCnt = (Integer.parseInt(props.getProperty("lastsid")) + 1) & 0x0f;
}
catch (Exception e) {
// Keep default
}
// lastSid
int lastSid = 0x0f;
try {
lastSid = (byte) (Integer.parseInt(props.getProperty("outcnt")) -1);
if (lastSid < 0) {
lastSid = 0x0f;
}
}
catch (Exception e) {
// Keep default
}
FrontEndStub st = new FrontEndStub(this);
inpManager = new InputManager(inpCnt, st);
BackEndSkel sk = startBackEndContainer(props);
outManager = new OutputManager(lastSid, sk, maxDisconnectionTime);
}
protected final BackEndSkel startBackEndContainer(Properties props) throws ICPException {
try {
String nodeName = myID.replace(':', '_');
props.setProperty(Profile.CONTAINER_NAME, nodeName);
myContainer = new BackEndContainer(props, this);
if (!myContainer.connect()) {
throw new ICPException("BackEnd container failed to join the platform");
}
if(myLogger.isLoggable(Logger.CONFIG)) {
myLogger.log(Logger.CONFIG,"BackEndContainer "+myContainer.here().getName()+" successfully joined the platform");
}
return new BackEndSkel(myContainer);
}
catch (ProfileException pe) {
// should never happen
pe.printStackTrace();
throw new ICPException("Error creating profile");
}
}
// Local variable only used in the kill() method
private Object shutdownLock = new Object();
/**
Kill the above container.
This may be called by the JICPMediatorManager or when
a peer termination notification is received.
*/
public void kill() {
// Avoid killing the above container two times
synchronized (shutdownLock) {
if (active) {
active = false;
myContainer.shutDown();
}
}
}
/**
* Passes to this JICPMediator the connection opened by the mediated
* entity.
* This is called by the JICPServer this Mediator is attached to
* as soon as the mediated entity (re)connects.
* @param c the connection to the mediated entity
* @param pkt the packet that was sent by the mediated entity when
* opening this connection
* @param addr the address of the mediated entity
* @param port the local port used by the mediated entity
* @return an indication to the JICPMediatorManager to keep the
* connection open.
*/
public boolean handleIncomingConnection(Connection c, JICPPacket pkt, InetAddress addr, int port) {
// Update keep-alive info
lastReceivedTime = System.currentTimeMillis();
boolean inp = false;
byte[] data = pkt.getData();
if (data.length == 1) {
inp = (data[0] == 1);
}
if (inp) {
inpManager.setConnection(c);
if (myLogger.isLoggable(Logger.CONFIG)) {
myLogger.log(Logger.CONFIG, myID+": New INP Connection establishd");
}
((NIOJICPConnection) c).configureBlocking();
}
else {
outManager.setConnection(c);
if (myLogger.isLoggable(Logger.CONFIG)) {
myLogger.log(Logger.CONFIG, myID+": New OUT Connection establishd");
}
}
return true;
}
/**
Notify this NIOMediator that an error occurred on one of the
Connections it was using. This information is important since,
unlike normal mediators, a NIOMediator never reads packets from
connections on its own (the JICPMediatorManager always does that).
*/
public void handleConnectionError(Connection c, Exception e) {
if (active && peerActive) {
// Try assuming it is the input connection
try {
inpManager.checkConnection(c);
myLogger.log(Logger.INFO, myID+": IC Disconnection detected");
inpManager.resetConnection();
}
catch (ICPException icpe) {
// Then try assuming it is the output connection
try {
outManager.checkConnection(c);
myLogger.log(Logger.INFO, myID+": OC Disconnection detected");
outManager.resetConnection();
}
catch (ICPException icpe2) {
// Ignore it
}
}
}
}
/**
Passes to this mediator a JICPPacket received by the
JICPMediatorManager this mediator is attached to.
In a NIOMediator this should never be called.
*/
public JICPPacket handleJICPPacket(JICPPacket p, InetAddress addr, int port) throws ICPException {
throw new ICPException("Unexpected call");
}
/**
Overloaded version of the handleJICPPacket() method including
the <code>Connection</code> the incoming JICPPacket was received
from. This information is important since, unlike normal mediators,
a NIOMediator may not read packets from connections on its own (the
JICPMediatorManager does that in general).
*/
public JICPPacket handleJICPPacket(Connection c, JICPPacket pkt, InetAddress addr, int port) throws ICPException {
checkTerminatedInfo(pkt);
// Update keep-alive info
lastReceivedTime = System.currentTimeMillis();
byte type = pkt.getType();
if (type == JICPProtocol.COMMAND_TYPE) {
return outManager.handleCommand(c, pkt);
}
else if (type == JICPProtocol.KEEP_ALIVE_TYPE) {
return outManager.handleKeepAlive(c, pkt);
}
/* Asynch-reply
else if (type == JICPProtocol.RESPONSE_TYPE || type == JICPProtocol.ERROR_TYPE) {
inpManager.handleResponse(c, pkt);
return null;
}*/
else {
throw new ICPException("Unexpected packet type "+type);
}
}
/**
This is periodically called by the JICPMediatorManager and is
used by this NIOMediator to evaluate the elapsed time without
the need of a dedicated thread or timer.
*/
public final void tick(long currentTime) {
if (active) {
// 1) If there is a blocking read operation in place check the
// response timeout
inpManager.checkResponseTime(currentTime);
// 2) Evaluate the keep alive
if (keepAliveTime > 0) {
if ((currentTime - lastReceivedTime) > (keepAliveTime + RESPONSE_TIMEOUT)) {
// Missing keep-alive.
// The OUT connection is no longer valid
if (outManager.isConnected()) {
myLogger.log(Logger.WARNING, myID+": Missing keep-alive");
outManager.resetConnection();
}
// Check the INP connection. Since this method must return
// asap, does it in a separated Thread
if (inpManager.isConnected()) {
Thread t = new Thread() {
public void run() {
try {
JICPPacket pkt = new JICPPacket(JICPProtocol.KEEP_ALIVE_TYPE, JICPProtocol.DEFAULT_INFO, null);
inpManager.dispatch(pkt, false);
if(myLogger.isLoggable(Logger.CONFIG)) {
myLogger.log(Logger.CONFIG, myID+": IC valid");
}
}
catch (Exception e) {
// Just do nothing: the INP connection has been reset
}
}
};
t.start();
}
}
}
// 3) Evaluate the max disconnection time
if (outManager.checkMaxDisconnectionTime(currentTime)) {
myLogger.log(Logger.SEVERE, myID+": Max disconnection time expired.");
// Consider as if the FrontEnd has terminated spontaneously -->
// Kill the above container (this will also kill this NIOBEDispatcher).
kill();
}
}
}
// BEConnectionManager interface implementation
/**
Return a stub of the remote FrontEnd that is connected to the
local BackEnd.
@param be The local BackEnd
@param props Additional (implementation dependent) connection
configuration properties.
@return A stub of the remote FrontEnd.
*/
public FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException {
return inpManager.getStub();
}
public void activateReplica(String addr, Properties props) throws IMTPException {
}
/**
Make this NIOBEDispatcher terminate.
*/
public void shutdown() {
active = false;
if(myLogger.isLoggable(Logger.INFO)) {
myLogger.log(Logger.INFO, myID+": shutting down");
}
// Deregister from the JICPServer
if (myID != null) {
myMediatorManager.deregisterMediator(myID);
}
inpManager.shutdown();
outManager.shutdown();
}
// Dispatcher interface implementation
public byte[] dispatch(byte[] payload, boolean flush) throws ICPException {
JICPPacket pkt = new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.DEFAULT_INFO, payload);
pkt = inpManager.dispatch(pkt, flush);
return pkt.getData();
}
/**
Inner class InputManager.
This class manages the delivery of commands to the FrontEnd
*/
protected class InputManager {
private Connection myConnection;
private boolean connectionRefreshed;
private boolean waitingForFlush;
private long readStartTime = -1;
private JICPPacket currentReply;
private Object dispatchLock = new Object();
private int inpCnt;
private FrontEndStub myStub;
InputManager(int c, FrontEndStub s) {
inpCnt = c;
myStub = s;
}
FrontEndStub getStub() {
return myStub;
}
synchronized void setConnection(Connection c) {
// Reset the old connection
resetConnection();
// Set the new connection
myConnection = c;
connectionRefreshed = true;
waitingForFlush = myStub.flush();
myContainer.notifyInputConnectionReady();
}
synchronized void resetConnection() {
// Close the connection if it was in place
if (myConnection != null) {
close(myConnection);
myConnection = null;
}
// Asynch-reply
// If there was someone waiting for a response on the
// connection notify it.
//notifyAll();
}
final void checkConnection(Connection c) throws ICPException {
if (c != myConnection) {
throw new ICPException("Wrong connection");
}
}
final boolean isConnected() {
return myConnection != null;
}
void shutdown() {
resetConnection();
}
/**
Dispatch a JICP command to the FE and get back a reply.
This method must NOT be executed in mutual exclusion with
setConnection() and resetConnection() since it performs a
blocking read operation --> It can't just be declared synchronized.
*/
final JICPPacket dispatch(JICPPacket pkt, boolean flush) throws ICPException {
synchronized (dispatchLock) {
synchronized (this) {
if ((!active) || (myConnection == null) || (waitingForFlush && (!flush))) {
// If we are waiting for flushed packets and the current packet
// is a normal (i.e. non-flushed) one, then throw an exception -->
// The packet will be put in the queue of packets to be flushed
System.out.println("
throw new ICPException("Unreachable");
}
waitingForFlush = false;
connectionRefreshed = false;
}
try {
pkt.setSessionID((byte) inpCnt);
if (myLogger.isLoggable(Logger.FINE)) {
myLogger.log(Logger.FINE, myID+": Sending command "+inpCnt+" to FE");
}
long start = System.currentTimeMillis();
myConnection.writePacket(pkt);
// Asynch-reply: JICPPacket reply = waitForReply(RESPONSE_TIMEOUT);
readStartTime = System.currentTimeMillis();
JICPPacket reply = myConnection.readPacket();
readStartTime = -1;
checkTerminatedInfo(reply);
System.out.println("peer active = "+peerActive);
lastReceivedTime = System.currentTimeMillis();
long end = lastReceivedTime;
if ((end - start) > 100) {
System.out.println("Dispatching time = "+(end-start));
}
if (myLogger.isLoggable(Logger.FINER)) {
myLogger.log(Logger.FINER, myID+": Received response "+inpCnt+" from FE");
}
if (reply.getType() == JICPProtocol.ERROR_TYPE) {
// Communication OK, but there was a JICP error on the peer
throw new ICPException(new String(pkt.getData()));
}
if (!peerActive) {
System.out.println("Calling shutdown()");
// This is the response to an exit command --> Suicide, without
// killing the above container since it is already dying.
NIOBEDispatcher.this.shutdown();
}
inpCnt = (inpCnt+1) & 0x0f;
return reply;
}
catch (NullPointerException npe) {
// This can happen if a resetConnection() occurs just before
// myConnection.writePacket()/readPacket() is called.
throw new ICPException("Connection reset.");
}
catch (IOException ioe) {
synchronized (this) {
if (myConnection != null && !connectionRefreshed) {
// There was an IO exception writing data to the connection
// --> reset the connection.
myLogger.log(Logger.WARNING,myID+": IOException IC. "+ioe);
resetConnection();
}
}
readStartTime = -1;
throw new ICPException("Dispatching error.", ioe);
}
}
}
public final void checkResponseTime(long currentTime) {
if (readStartTime > 0 && (currentTime - readStartTime) > RESPONSE_TIMEOUT) {
myLogger.log(Logger.WARNING,myID+": Response timeout expired.");
resetConnection();
}
}
} // END of inner class InputManager
/**
Inner class OutputManager
This class manages the reception of commands and keep-alive
packets from the FrontEnd.
This class also manages the maxDisconnectionTime, i.e. the remote
FrontEnd is considered dead if it cannot re-establish the
OUT connection within the maxDisconnectionTime.
*/
protected class OutputManager {
private Connection myConnection;
private JICPPacket lastResponse;
private int lastSid;
private BackEndSkel mySkel;
private long maxDisconnectionTime, expirationDeadline;
OutputManager(int n, BackEndSkel s, long t) {
lastSid = n;
mySkel = s;
maxDisconnectionTime = t;
}
synchronized void setConnection(Connection c) {
// Close the old connection if any
if (myConnection != null) {
close(myConnection);
}
// Set the new connection
myConnection = c;
}
synchronized void resetConnection() {
if (myConnection != null) {
expirationDeadline = System.currentTimeMillis() + maxDisconnectionTime;
close(myConnection);
}
myConnection = null;
}
final void checkConnection(Connection c) throws ICPException {
if (c != myConnection) {
throw new ICPException("Wrong connection");
}
}
final boolean isConnected() {
return (myConnection != null);
}
void shutdown() {
resetConnection();
}
final synchronized JICPPacket handleCommand(Connection c, JICPPacket cmd) throws ICPException {
checkConnection(c);
JICPPacket reply = null;
if (peerActive) {
byte sid = cmd.getSessionID();
if (sid == lastSid) {
myLogger.log(Logger.WARNING,myID+": Duplicated command from FE "+sid);
reply = lastResponse;
}
else {
if(myLogger.isLoggable(Logger.FINE)) {
myLogger.log(Logger.FINE, myID+": Received command "+sid+" from FE");
}
byte[] rspData = mySkel.handleCommand(cmd.getData());
if(myLogger.isLoggable(Logger.FINER)) {
myLogger.log(Logger.FINER, myID+": Command "+sid+" from FE served ");
}
reply = new JICPPacket(JICPProtocol.RESPONSE_TYPE, getReconnectInfo(), rspData);
reply.setSessionID(sid);
lastSid = sid;
lastResponse = reply;
}
}
else {
// The remote FrontEnd has terminated spontaneously -->
// Kill the above container (this will also kill this NIOBEDispatcher).
kill();
}
return reply;
}
synchronized JICPPacket handleKeepAlive(Connection c, JICPPacket command) throws ICPException {
checkConnection(c);
if(myLogger.isLoggable(Logger.FINEST)) {
myLogger.log(Logger.FINEST,myID+": Keep-alive received");
}
return new JICPPacket(JICPProtocol.RESPONSE_TYPE, getReconnectInfo(), null);
}
final synchronized boolean checkMaxDisconnectionTime(long currentTime) {
return (!isConnected()) && (currentTime > expirationDeadline);
}
private final byte getReconnectInfo() {
byte info = JICPProtocol.DEFAULT_INFO;
// If the inpConnection is null request the FrontEnd to reconnect
if (!inpManager.isConnected()) {
info |= JICPProtocol.RECONNECT_INFO;
}
return info;
}
} // END of inner class OutputManager
private final void checkTerminatedInfo(JICPPacket pkt) {
if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
peerActive = false;
if (myLogger.isLoggable(Logger.INFO)) {
myLogger.log(Logger.INFO, myID+": Peer termination notification received");
}
}
}
private void close(Connection c) {
try {
c.close();
}
catch (IOException ioe) {
}
}
}
|
package com.lamfire.chimaera;
import com.lamfire.chimaera.store.FireStore;
import com.lamfire.chimaera.store.leveldbstore.LDBFireStore;
import com.lamfire.chimaera.store.leveldbstore.LDBOptions;
import com.lamfire.chimaera.store.memstore.MemoryFireStore;
import com.lamfire.logger.Logger;
import com.lamfire.utils.FileUtils;
import com.lamfire.utils.FilenameUtils;
import org.iq80.leveldb.Options;
import java.io.IOException;
public class FireStoreFactory {
private static final Logger LOGGER = Logger.getLogger(FireStoreFactory.class);
public synchronized static FireStore makeFireStore(String name,ChimaeraOpts opts)throws IOException{
FireStore store = null;
if (opts != null && opts.isStoreOnDisk()) {
store = makeFireStoreWithLDB(name, opts);
} else {
store = makeFireStoreWithMemory(name);
}
return store;
}
public static FireStore makeFireStoreWithMemory(String name){
return new MemoryFireStore(name);
}
public synchronized static FireStore makeFireStoreWithLDB(String name,ChimaeraOpts opts) throws IOException {
if(!FileUtils.exists(opts.getDataDir())){
FileUtils.makeDirs(opts.getDataDir());
}
String storeDir = FilenameUtils.concat(opts.getDataDir(),name);
LDBOptions options = new LDBOptions();
options.cacheSize(opts.getCacheSize());
options.blockSize(opts.getBlockSize());
options.maxOpenFiles(opts.getMaxOpenFiles());
options.createIfMissing(true);
options.writeBufferSize(opts.getWriteBufferSize());
LDBFireStore store = new LDBFireStore(storeDir,name,options);
LOGGER.info("MAKE LDB STORE[" + name + "] :" + opts.getDataDir());
return store;
}
}
|
package com.mpu.spinv.engine.model;
import java.awt.Color;
import java.awt.Graphics;
import com.mpu.spinv.utils.AdvList;
import com.mpu.spinv.utils.Constants;
/**
* GameEntity.java
*
* @author Brendon Pagano
* @date 2017-08-08
*/
public class GameEntity extends GameObject {
/**
* A list of the object's animations.
*/
private final AdvList<Animation> animations;
/**
* The key identifier of the active animation.
*/
private String actAnimation;
/**
* The active animation. Currently playing if {@link GameEntity#visible} is
* true.
*/
private Animation animation;
/**
* In case there is no need for the object to have an animation, use a static
* sprite to draw instead.
*/
private Sprite staticSprite;
/**
* GameObject's constructor.
*
* @param x
* The x position of the object in the screen.
* @param y
* The y position of the object in the screen.
* @param visible
* Flag to determine if the object will begin visible or not.
*/
public GameEntity(int x, int y, boolean visible) {
super(x, y, 0, 0, visible);
// Default params
this.animations = new AdvList<Animation>();
this.animation = null;
this.actAnimation = null;
this.staticSprite = null;
}
public GameEntity(int x, int y, Sprite staticSprite, boolean visible) {
super(x, y, staticSprite.getWidth(), staticSprite.getHeight(), visible);
this.staticSprite = staticSprite;
// Default params
this.animations = new AdvList<Animation>();
this.animation = null;
this.actAnimation = null;
}
public GameEntity(int x, int y, Animation animation, boolean visible) {
super(x, y, animation.getSprite().getWidth(), animation.getSprite().getHeight(), visible);
// Default params
this.animations = new AdvList<Animation>();
this.animation = null;
this.actAnimation = null;
this.staticSprite = null;
// Setting the default animation
addAnimation("default", animation);
}
@Override
public boolean isGroup() {
return false;
}
@Override
public void update() {
super.update();
if (actAnimation != null)
animation.update();
}
@Override
public void draw(Graphics g) {
if (visible && (animation != null || staticSprite != null)) {
g.drawImage((actAnimation == null ? staticSprite.getSprite() : animation.getSprite()), x, y, null);
if (Constants.SHOW_ENTITIES_BORDERS) {
g.setColor(Color.GREEN);
g.drawRect(x, y, width, height);
}
}
}
/**
* Adds an animation into the GameObject's animations list.
*
* @param key
* the identifier of the animation to add.
* @param animation
* the animation object to be added.
*/
public void addAnimation(String key, Animation animation) {
if (!key.equals("")) {
animations.add(key, animation);
if (actAnimation == null) {
this.actAnimation = key;
this.animation = animation;
}
}
}
/**
* Set the active and playing animation to a new one.
*
* @param key
* the identifier of the animation to be set.
*/
public void setAnimation(String key) {
if (key == null) {
actAnimation = null;
animation = null;
} else if (animations.containsKey(key)) {
actAnimation = key;
animation = animations.get(key);
}
}
/**
* Removes an animation from the GameObject's animation list and returns the
* removed animation object.
*
* @param key
* the key identifier of the animation to be removed.
* @return the removed animation object.
*/
public Animation removeAnimation(String key) {
Animation animation = null;
if (animations.containsKey(key)) {
animation = animations.get(key);
animations.remove(key);
if (actAnimation.equals(key)) {
this.animation = null;
this.actAnimation = null;
}
}
return animation;
}
/**
* Starts playing the active animation.
*/
public void startAnimation() {
if (animation != null)
animation.start();
}
/**
* Pauses the active animation.
*/
public void pauseAnimation() {
if (animation != null)
animation.pause();
}
/**
* Restarts the active animation.
*/
public void restartAnimation() {
if (animation != null)
animation.restart();
}
/**
* Resets the active animation.
*/
public void resetAnimation() {
if (animation != null)
animation.reset();
}
public void resizeSprite(int width, int height) {
this.width = width;
this.height = height;
staticSprite.resizeSprite(width, height);
}
// Getters and Setters
public String getAnimationKey() {
return actAnimation;
}
public Animation getActiveAnimation() {
return animation;
}
public Sprite getStaticSprite() {
return staticSprite;
}
public void setStaticSprite(Sprite staticSprite) {
this.staticSprite = staticSprite;
this.width = staticSprite.getWidth();
this.height = staticSprite.getHeight();
}
/**
* Unsafe method to set GameEntity's width.
*
* @param width
* The new width to be set.
*/
protected void setWidth(int width) {
this.width = width;
}
/**
* Unsafe method to set GameEntity's height.
*
* @param height
* The new height to be set.
*/
protected void setHeight(int height) {
this.height = height;
}
}
|
package com.telmomenezes.synthetic.cli;
import java.io.BufferedWriter;
import java.io.FileWriter;
import org.apache.commons.cli.CommandLine;
import com.telmomenezes.synthetic.Net;
import com.telmomenezes.synthetic.evo.EvoDRMap2P;
import com.telmomenezes.synthetic.evo.EvoGen;
import com.telmomenezes.synthetic.evo.EvoStrategy;
import com.telmomenezes.synthetic.io.NetFileType;
public class Evolve extends Command {
@Override
public boolean run(CommandLine cline) {
// TODO: make configurable
long maxEffort = 1000 * 1000 * 5;
int generations = 1000;
if(!cline.hasOption("inet")) {
setErrorMessage("input network file must be specified");
return false;
}
if(!cline.hasOption("odir")) {
setErrorMessage("output directory must be specified");
return false;
}
String netfile = cline.getOptionValue("inet");
String outdir = cline.getOptionValue("odir");
EvoDRMap2P callbacks = new EvoDRMap2P(Net.load(netfile, NetFileType.SNAP), outdir, maxEffort);
EvoStrategy popGen = new EvoStrategy(1, 1, 1);
EvoGen evo = new EvoGen(popGen, callbacks, generations);
System.out.println("target net: " + netfile);
System.out.println(evo.infoString());
// write experiment params to file
try {
FileWriter fstream = new FileWriter(outdir + "/params.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(evo.infoString());
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
evo.run();
return true;
}
}
|
package edu.teco.dnd.eclipse;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.part.ViewPart;
public class DeployView extends ViewPart {
private Button createButton; // Button to create deployment - checkboxes for different deployments?
private Button deployButton; // Button to deploy deployment
private Table applications; // Table to show all applications by name.
// Optional functionality: click app - get information on app
private Table deployment; // Table to show created deployment
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout();
layout.numColumns = 3;
parent.setLayout(layout);
createApplicationTable(parent);
createCreateButton(parent);
Label label = new Label(parent, SWT.NONE);
label.setText("Deployment:");
label.pack();
createDeployButton(parent);
createDeploymentTable(parent);
TableItem item1 = new TableItem(applications, SWT.NONE);
item1.setText(0, "Under Construction.");
TableItem item = new TableItem(applications, SWT.NONE);
item.setText(0, "Will contain list of applications");
TableItem item2 = new TableItem(deployment, SWT.NONE);
item2.setText(0, "FunctionBlocks");
item2.setText(1, "Modules");
}
@Override
public void setFocus() {
}
private void createCreateButton(Composite parent){
createButton = new Button(parent, SWT.NONE);
createButton.setText("Create Deployment");
createButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display display = Display.getCurrent();
Shell shell = new Shell(display);
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText("Warning");
dialog.setMessage("No Deployment Algorithm available yet, still to be implemented");
dialog.open();
}
});
}
private void createDeployButton(Composite parent){
GridData data = new GridData();
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.BEGINNING;
deployButton = new Button(parent, SWT.NONE);
deployButton.setText("Deploy");
deployButton.setToolTipText("Submit the created deployment to deploy your application");
deployButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display display = Display.getCurrent();
Shell shell = new Shell(display);
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText("Warning");
dialog.setMessage("You have to create a possible deployment before deploying");
dialog.open();
}
});
deployButton.setLayoutData(data);
}
private void createApplicationTable(Composite parent){
GridData data = new GridData();
data.verticalSpan = 2;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.FILL;
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
applications = new Table(parent, SWT.NONE);
applications.setLinesVisible(true);
applications.setHeaderVisible(true);
applications.setLayoutData(data);
TableColumn column = new TableColumn(applications, SWT.None);
column.setText("Applications");
applications.getColumn(0).pack();
}
private void createDeploymentTable(Composite parent){
GridData data = new GridData();
data.verticalSpan = 1;
data.horizontalAlignment = SWT.FILL;
data.verticalAlignment = SWT.FILL;
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
deployment = new Table(parent, SWT.NONE);
deployment.setLinesVisible(true);
deployment.setHeaderVisible(true);
deployment.setLayoutData(data);
TableColumn column = new TableColumn(deployment, SWT.None);
column.setText("Function Block");
TableColumn column2 = new TableColumn(deployment, SWT.NONE);
column2.setText("Module");
deployment.getColumn(0).pack();
deployment.getColumn(1).pack();
}
}
|
package zab.atomics.bag;
import java.util.concurrent.atomic.AtomicLong;
/**
* An atomic, lock-free and wait-free storage of items. It can store up to 32 items.
*
* The bag may keep references to up to 32 items after they have been removed. Use it
* only for objects you do not expect to be garbage-collected.
*
* @author zlatinb
*
* @param <T> type of the items stored
*/
public class AtomicBag<T> {
private static final int FREE = 0;
private static final int CLAIM = 1;
private static final int FULL = 2;
private final Object[] storage = new Object[32];
private final AtomicLong state = new AtomicLong();
private static long freeMask(int i) {
long mask = 1 << (i << 1);
mask |= (mask << 1);
return ~mask;
}
private static long free(long state, int i) {
return state & freeMask(i);
}
private static long claim(long state, int i) {
long freed = free(state,i);
return freed | (CLAIM << (i <<1));
}
private static long full(long state, int i) {
long freed = free(state,i);
return freed | (FULL << (i <<1));
}
private static int get(long state, final int i) {
state &= (~freeMask(i));
return (int)(state >>> (i << 1));
}
/**
* @param item to store
* @return true if stored, false if there was no space.
*/
public boolean store(T item) {
// find a free slot
int slot;
while(true) {
final long s = state.get();
slot = -1;
for (int i = 0; i < 32; i++) {
if (get(s,i) != FREE)
continue;
slot = i;
break;
}
if (slot < 0)
return false;
// try to claim it
long claimState = claim(s,slot);
if (state.compareAndSet(s,claimState))
break;
}
// write
storage[slot] = item;
while(true) {
final long s = state.get();
long fullState = full(s,slot);
if (state.compareAndSet(s,fullState))
return true;
}
}
/**
* @param items to store in the bag
* @return how many were stored
*/
public int store(T[] items) {
return store(items, 0, items.length);
}
/**
* Bulk store operation. More efficient than calling
* store() multiple times.
*
* @param items to store
* @param start index within the array where to start
* @param num how many of them, starting at 0
* @return number actually stored
*/
public int store(final T[] items, final int start, int num) {
num = Math.min(32,num);
// find free slots
int slots, found;
while(true) {
slots = 0;
found = 0;
final long s = state.get();
long newState = s;
for(int i = 0; i<32 && num > found ;i++) {
if (get(s,i) == FREE) {
slots |= 1 << i;
newState = newState | claim(s, i);
found++;
}
}
if (found == 0)
return 0;
if (state.compareAndSet(s,newState))
break;
}
// store in slots
int stored = 0;
long storedMask = 0;
for (int i = 0; i < 32 && stored < found; i++) {
if ((slots & ( 1 << i)) == 0)
continue;
storage[i] = items[start + stored++];
storedMask = full(storedMask,i);
}
// update state
while(true) {
final long s = state.get();
if (state.compareAndSet(s,s | storedMask))
return found;
}
}
/**
* @return number of items in the bag
*/
public int size() {
final long s = state.get();
int size = 0;
for (int i = 0; i < 32; i++) {
if (get(s,i) == FULL)
size++;
}
return size;
}
/**
* @return an arbitrary item from the bag, null if empty
*/
@SuppressWarnings("unchecked")
public T remove() {
while(true) {
final long s = state.get();
int slot = -1;
for (int i = 0; i < 32; i++) {
if (get(s,i) != FULL)
continue;
slot = i;
break;
}
if (slot == -1)
return null;
T item = (T)storage[slot];
long newState = free(s,slot);
if (state.compareAndSet(s,newState))
return item;
}
}
/**
* Removes the items currently in the bag and puts them in the
* destination array, in arbitrary order.
*
* More efficient than calling remove() repeatedly.
*
* @param dest to store items
* @param start starting position within dest
* @param num up to how many to store
* @return number of items stored
*/
@SuppressWarnings("unchecked")
public int removeTo(final T[] dest, final int start, final int num) {
while(true) {
final long s = state.get();
long newState = s;
int idx = 0;
for(int i = 0; i < 32 && idx < num; i++) {
if (get(s,i) != FULL)
continue;
dest[start + idx++] = (T)storage[i];
newState = free(newState,i);
}
if (idx == 0)
return 0;
if (state.compareAndSet(s,newState))
return idx;
}
}
/**
* Removes the items currently in the bag and puts them in the
* destination array, in arbitrary order.
*
* More efficient than calling remove() repeatedly.
*
* @param dest to store items
* @return number of items stored
*/
public int removeTo(T[] dest) {
return removeTo(dest,0,dest.length);
}
}
|
//2005 -
import java.util.*;
public class ThatDelicateBalance {
public static double thatFunction(double num){
//The function?
double sum = 0.0;
for(double x = 0.0; x <= num; x++){
sum += Math.pow(3.0, x);
}
return sum;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int times = input.nextInt();
for(int i = 0; i < times; i++){
int initialWeight = input.nextInt();
int leftW = initialWeight;
int rightW = 0;
ArrayList<Integer> jValues = new ArrayList<Integer>();
for(int x = 0; x < 20; x++){
jValues.add(x);
}
ArrayList<Integer> basketR = new ArrayList<Integer>();
ArrayList<Integer> basketL = new ArrayList<Integer>();
while(true){
int w = leftW - rightW;
if(w == 0){
//solved
//TODO output
System.out.print(initialWeight + " ");
Collections.sort(basketR);
Collections.sort(basketL);
//TODOTODOTODOTODOTODOTODO
for(int x = 0; x < basketR.size(); x++){
System.out.print(basketR.get(x) + " ");
}
for(int x = 0; x < basketL.size(); x++){
System.out.print(basketL.get(x) + " ");
}
System.out.println();
}
for(int j = 0; j < jValues.size() - 1; j++){
if((thatfunction(jValues.get(j)) < Math.abs(w)) && thatfunction(jValues.get(j) + 1) > Math.abs(w)){//Fiddle with this
//We have the j we're looking for
//Place the weight 3^j into lighter basket
if(w > 0){
//right is lighter basket
rightW += Math.pow(3, j);
basketR.add(-1 * Math.pow(3, j));
jValues.remove(jValues.indexOf(j));
} else {
//left is lighter basket
leftW += Math.pow(3, j);
basketL.add(Math.pow(3, j));
jValues.remove(jValues.indexOf(j));
}
}
}
}//End while
}
}
}
|
package test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cz.sysnet.cites.IdentFactory;
import static org.junit.Assert.*;
public class testIdentFactory {
@Test
public void testCodeLength() {
IdentFactory identFactory = new IdentFactory();
String id = identFactory.getId();
assertTrue(id.length() == 12);
}
@Test
public void testPrefix() {
IdentFactory identFactory = new IdentFactory();
String id = identFactory.generateId("TEST");
assertTrue(id.startsWith("TES"));
}
@Before
public void beforeRun() {}
@After
public void afterRun() {}
}
|
package de.fhpotsdam.unfolding.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import processing.core.PVector;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.MultiFeature;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.data.ShapeFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
/**
* Basic geo-spatial utility methods.
*/
public class GeoUtils {
private static final double EARTH_RADIUS_KM = 6371.01;
/**
* Get distance in kilometers between two points on the earth. Using the great-circle distance formula with the
* approximated radius of a spherical earth.
*
* @param lat1
* Latitude of first point, in decimal degrees.
* @param lon1
* Longitude of first point, in decimal degrees.
* @param lat2
* Latitude of second point, in decimal degrees.
* @param lon2
* Longitude of second point, in decimal degrees.
* @return Distance in kilometers.
*/
public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lon1Rad = Math.toRadians(lon1);
double lat2Rad = Math.toRadians(lat2);
double lon2Rad = Math.toRadians(lon2);
double r = EARTH_RADIUS_KM;
return r
* Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(lon2Rad - lon1Rad));
}
/**
* Get distance in kilometers between two points on the earth. Using the great-circle distance formula with the
* approximated radius of a spherical earth.
*
* @param location1
* Location of first point
* @param location2
* Location of second point
* @return Distance in kilometers.
*/
public static double getDistance(Location location1, Location location2) {
return getDistance(location1.getLat(), location1.getLon(), location2.getLat(), location2.getLon());
}
/**
* Gets the location specified by a start location, a bearing, and a distance.
*
* @param location
* The start location.
* @param bearing
* The bearing in degrees.
* @param distance
* The distance in kilometers.
* @return The destination location.
*/
public static Location getDestinationLocation(Location location, float bearing, float distance) {
double lat1 = Math.toRadians(location.getLat());
double lon1 = Math.toRadians(location.getLon());
double r = EARTH_RADIUS_KM;
double b = Math.toRadians(bearing);
double lat2 = Math.asin(Math.sin(lat1) * Math.cos(distance / r) + Math.cos(lat1) * Math.sin(distance / r)
* Math.cos(b));
double lon2 = lon1
+ Math.atan2(Math.sin(b) * Math.sin(distance / r) * Math.cos(lat1),
Math.cos(distance / r) - Math.sin(lat1) * Math.sin(lat2));
lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;
float lat2d = (float) Math.toDegrees(lat2);
float lon2d = (float) Math.toDegrees(lon2);
return new Location(lat2d, lon2d);
}
/**
* Gets the angle between two locations.
*
* @param location1
* First location.
* @param location2
* Second location.
* @return The angle in radians.
*/
public static double getAngleBetween(Location location1, Location location2) {
double rlat1 = Math.toRadians(location1.getLat());
double rlat2 = Math.toRadians(location2.getLat());
double rlon1 = Math.toRadians(location1.getLon());
double rlon2 = Math.toRadians(location2.getLon());
double angle = (Math.atan2(Math.sin(rlon2 - rlon1) * Math.cos(rlat2),
Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(rlon2 - rlon1)) % (2 * Math.PI));
return angle;
}
/**
* Super simplistic method to convert a geo-position as a Location.
*/
public static Location getDecimal(Integer latDegrees, Integer latMinutes, Integer latSeconds, String latDirection,
Integer lonDegrees, Integer lonMinutes, Integer lonSeconds, String lonDirection) {
float lat = latDegrees + (latMinutes * 60 + latSeconds) / 3600;
if (latDirection.equals("S")) {
lat = -lat;
}
float lon = lonDegrees + (lonMinutes * 60 + lonSeconds) / 3600;
if (lonDirection.equals("W")) {
lon = -lon;
}
return new Location(lat, lon);
}
/**
* Returns the center of the locations.
*
* The returned location minimizes the sum of squared Euclidean distances between itself and each location in the
* list.
*
* @return The centroid location.
*/
public static Location getEuclideanCentroid(List<Location> locations) {
Location center = new Location(0, 0);
for (Location loc : locations) {
center.add(loc);
}
center.div((float) locations.size());
return center;
}
/**
* Returns the geometric center of the locations of a polygon.
*
* The returned location is the center of the polygon, unfazed by unbalanced vertices. (You probably want to use
* this algorithm, but check out {@link #getEuclideanCentroid(List)} for an alternative.)
*
* @return The centroid location.
*/
public static Location getCentroid(List<Location> originalVertices) {
List<Location> vertices = getClosedPolygon(originalVertices);
float cx = 0f, cy = 0f;
for (int i = 0; i < vertices.size() - 1; i++) {
PVector vi0 = vertices.get(i);
PVector vi1 = vertices.get(i + 1);
cx = cx + (vi0.x + vi1.x) * (vi0.x * vi1.y - vi0.y * vi1.x);
cy = cy + (vi0.y + vi1.y) * (vi0.x * vi1.y - vi0.y * vi1.x);
}
float area = getArea(vertices);
cx /= (6f * area);
cy /= (6f * area);
return new Location(cx, cy);
}
/**
* Returns a closed polygon with the last vertex the same as the first.
*
* @param originalVertices
* List of locations of original polygon.
* @return List of location of closed polygon.
*/
protected static List<Location> getClosedPolygon(List<Location> originalVertices) {
if (originalVertices.size() < 1
|| (originalVertices.get(0).equals(originalVertices.get(originalVertices.size() - 1)))) {
// Return unchanged, if only one point, or already closed
return originalVertices;
}
List<Location> vertices = new ArrayList<Location>(originalVertices.size() + 1);
for (int i = 0; i < originalVertices.size(); i++) {
vertices.add(new Location(0f, 0f));
}
Collections.copy(vertices, originalVertices);
if (vertices.size() > 1) {
if (!vertices.get(0).equals(vertices.get(vertices.size() - 1))) {
// Add first vertex on last position to close polygon
vertices.add(vertices.get(0));
}
}
return vertices;
}
/**
* Calculates the area of a polygon.
*
* @param vertices
* The vertices of the polygon.
* @return The area.
*/
protected static float getArea(List<Location> vertices) {
float sum = 0;
for (int i = 0; i < vertices.size() - 1; i++) {
PVector vi0 = vertices.get(i);
PVector vi1 = vertices.get(i + 1);
sum += (vi0.x * vi1.y - vi1.x * vi0.y);
}
return sum * 0.5f;
}
/**
* Calculates the area of a shape feature.
*
* @param feature
* The feature containing location vertices.
* @return The area.
*/
protected static float getArea(Feature feature) {
return getArea(GeoUtils.getLocations(feature));
}
/**
* Calculates the area of a shape marker.
* @param marker
* The marker containing location vertices.
* @return The area.
*/
protected static float getArea(Marker marker) {
return getArea(GeoUtils.getLocations(marker));
}
/**
* Gets the overall geometric center of all features.
*
* @param features
* A list of features.
* @return The centroid location.
*/
public static Location getCentroidFromFeatures(List<Feature> features) {
return GeoUtils.getCentroid(GeoUtils.getLocationsFromFeatures(features));
}
/**
* Returns the centroid of a feature. Returns the single location for a PointFeature, the geometric center for
* LineFeature and PolygonFeature, and — depending on the second parameter — either the overall
* geometric center of all features, or the geometric center of the largest feature in a MultiFeature.
*
* @param feature
* The feature to get the centroid for.
* @param useLargestForMulti
* Set to true if you want to use only the largest feature for {@link MultiFeature}s.
* @return The location of the geometric center.
*/
public static Location getCentroid(Feature feature, boolean useLargestForMulti) {
Location location = null;
switch (feature.getType()) {
case POINT:
location = ((PointFeature) feature).getLocation();
break;
case LINES:
case POLYGON:
location = GeoUtils.getCentroid(((ShapeFeature) feature).getLocations());
break;
case MULTI:
MultiFeature multiFeature = ((MultiFeature) feature);
if (useLargestForMulti) {
// Return centroid of largest feature
Feature largestFeature = getLargestFeature(multiFeature);
location = getCentroid(largestFeature);
} else {
// Return centroid of all features
List<Location> locations = new ArrayList<Location>();
for (Feature f : multiFeature.getFeatures()) {
Location l = getCentroid(f);
locations.add(l);
}
location = GeoUtils.getCentroid(locations);
}
break;
}
return location;
}
/**
* Returns the largest feature of a MultiFeature by area size.
*
* @param multiFeature
* The MultiFeature consisting of multiple features.
* @return The largest feature.
*/
public static Feature getLargestFeature(MultiFeature multiFeature) {
float largestArea = 0;
Feature largestFeature = null;
for (Feature f : multiFeature.getFeatures()) {
if (largestArea < getArea(f)) {
largestFeature = f;
largestArea = getArea(f);
}
}
return largestFeature;
}
public static Marker getLargestMarker(MultiMarker multiMarker) {
float largestArea = 0;
Marker largestMarker = null;
for (Marker f : multiMarker.getMarkers()) {
if (largestArea < getArea(f)) {
largestMarker = f;
largestArea = getArea(f);
}
}
return largestMarker;
}
/**
* Convenience method for {@link #getCentroid(Feature, boolean)}.
*/
public static Location getCentroid(Feature feature) {
return getCentroid(feature, false);
}
/**
* Returns all locations of all features.
*
* @param features
* A list of features.
* @return A list of locations.
*/
public static List<Location> getLocationsFromFeatures(List<Feature> features) {
List<Location> locations = new ArrayList<Location>();
for (Feature feature : features) {
locations.addAll(getLocations(feature));
}
return locations;
}
/**
* Returns all locations of a feature. That is a single location for a point, all locations for lines or polygons,
* and all locations of all features of a MultiFeature.
*
* @param feature
* The feature to get locations from.
* @return A list of locations.
*/
public static List<Location> getLocations(Feature feature) {
List<Location> locations = new ArrayList<Location>();
if (feature.getType() == Feature.FeatureType.POINT) {
PointFeature pf = (PointFeature) feature;
locations.add(pf.getLocation());
}
if (feature.getType() == Feature.FeatureType.LINES || feature.getType() == Feature.FeatureType.POLYGON) {
ShapeFeature sf = (ShapeFeature) feature;
locations.addAll(sf.getLocations());
}
if (feature.getType() == Feature.FeatureType.MULTI) {
MultiFeature multiFeature = (MultiFeature) feature;
for (Feature f : multiFeature.getFeatures()) {
locations.addAll(getLocations(f));
}
}
return locations;
}
/**
* Returns all locations of all markers.
*
* @param markers
* A list of markers.
* @return A list of locations.
*/
public static List<Location> getLocationsFromMarkers(List<Marker> markers) {
List<Location> locations = new ArrayList<Location>();
for (Marker marker : markers) {
locations.addAll(getLocations(marker));
}
return locations;
}
/**
* Returns all locations of a marker. That is a single location for a point, all locations for lines or polygons,
* and all locations of all markers of a MultiMarker.
*
* @param marker
* The marker to get locations from.
* @return A list of locations.
*/
public static List<Location> getLocations(Marker marker) {
List<Location> locations = new ArrayList<Location>();
if (marker instanceof MultiMarker) {
// recursive for multi
MultiMarker mm = (MultiMarker) marker;
for (Marker m : mm.getMarkers()) {
locations.addAll(getLocations(m));
}
} else if (marker instanceof AbstractShapeMarker) {
// line or polygon
AbstractShapeMarker sm = (AbstractShapeMarker) marker;
locations.addAll(sm.getLocations());
} else {
// default: point
locations.add(marker.getLocation());
}
return locations;
}
}
|
package de.onyxbits.pocketbandit;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.audio.*;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.actions.*;
import com.badlogic.gdx.scenes.scene2d.utils.*;
import com.badlogic.gdx.assets.*;
import com.badlogic.gdx.utils.*;
import com.badlogic.gdx.math.*;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
import de.onyxbits.bureauengine.*;
import de.onyxbits.bureauengine.screen.*;
/**
* Represents the actual game screen. This class also doubles as the config screen.
*/
public class GambleScreen extends BureauScreen implements EventListener {
/**
* 3x3 symbols packed into a single array. First reel goes from 0 to 2, second from 3 to 5 and
* third from 6 to 8. Symbols within a reel are potentially unordered.
*/
private Symbol[] reelSymbols = new Symbol[9];
/**
* For toggling the number of coins the player may bet in each game.
*/
private ImageButton[] bet = new ImageButton[3];
/**
* Amount of coins on hand
*/
private Label credits;
/**
* The lever used to spin the reels
*/
private Image knob;
/**
* How often the lever has been pulled.
*/
private Label turns;
/**
* Displays a message to the player
*/
private Label feedbackMessage;
/**
* Displays a symbol to the player
*/
private Image feedbackSymbol;
/**
* Groups feedbackMessage and feedbackSymbol
*/
private Group feedbackGroup;
/**
* Switch between game view and options view
*/
private ImageButton viewSwitch;
/**
* Mute music
*/
private ImageButton musicStatus;
/**
* Mute sound
*/
private ImageButton soundStatus;
/**
* Cash out and exit to the menu screen
*/
private ImageButton exit;
/**
* Config mode: select previous game variation
*/
private ImageButton previousVariation;
/**
* Config mode: select next game variation
*/
private ImageButton nextVariation;
/**
* Displays the name of the variation
*/
private Table deviceName;
/**
* Rules
*/
private Variation variation;
/**
* Game state
*/
private Player player;
/**
* Number of <code>Symbol</code>S in motion.
*/
private int spinning;
/**
* Symbols on the reel
*/
private Drawable[] symbols;
/**
* Symbols on the paytable
*/
private Drawable[] smallSymbols;
/**
* Container for the paytable
*/
private ScrollPane scrollTable;
/**
* Contains the actual automaton UI
*/
private Group deviceGroup = new Group();
/**
* Contains the name, paytable and menu buttons
*/
private Group infoGroup = new Group();
/**
* For <code>playSoundEffect()</code>
*/
protected static final int TRIGGERSOUND=0;
/**
* For <code>playSoundEffect()</code>
*/
protected static final int WINSOUND=1;
/**
* For <code>playSoundEffect()</code>
*/
protected static final int EJECTCOINSOUND=2;
/**
* For <code>playSoundEffect()</code>
*/
protected static final int REELSTOPSOUND=3;
private FadeOverScreen fadeOverScreen;
private Sound triggerSound;
private Sound winSound;
private Sound ejectCoinSound;
private Sound reelStopSound;
private static final AssetDescriptor[] ASSETS = {
new AssetDescriptor<TextureAtlas>("textures/gamblescreen.atlas",TextureAtlas.class),
new AssetDescriptor<Music>("music/Theme for Harold var 3.mp3",Music.class),
new AssetDescriptor<Sound>("sfx/Pellet Gun Pump-SoundBible.com-517750307.mp3",Sound.class),
new AssetDescriptor<Sound>("sfx/135936__bradwesson__collectcoin.ogg",Sound.class),
new AssetDescriptor<Sound>("sfx/56246__q-k__latch-04.ogg",Sound.class),
};
/**
* Construct a new Gamble/Options screen
* @param game reference to the game object
* @param player game state. May be null. If null, the gamble screen allows for selecting
* a variation.
* @param variation the game variant
*/
public GambleScreen(BureauGame game, Player player, Variation variation) {
super(game);
this.player = player;
this.variation=variation;
}
@Override
protected AssetDescriptor[] getAssets() {
return ASSETS;
}
public void readyScreen() {
this.stage = new Stage(320, 480, true,game.spriteBatch);
fadeOverScreen = new FadeOverScreen();
deviceGroup.setTransform(false);
triggerSound=game.assetManager.get("sfx/Pellet Gun Pump-SoundBible.com-517750307.mp3",Sound.class);
winSound=game.assetManager.get("sfx/135936__bradwesson__collectcoin.ogg",Sound.class);
reelStopSound=game.assetManager.get("sfx/56246__q-k__latch-04.ogg",Sound.class);
music = game.assetManager.get("music/Theme for Harold var 3.mp3",Music.class);
music.setLooping(true);
//FIXME: Do these two need to be dispose()d off?
TextureAtlas localAtlas =game.assetManager.get("textures/gamblescreen.atlas",TextureAtlas.class);
TextureAtlas globalAtlas =game.assetManager.get("textures/global.atlas",TextureAtlas.class);
Drawable up,down,checked; // Reusables for making buttons.
symbols=new Drawable[variation.symbolNames.length];
smallSymbols=new Drawable[variation.symbolNames.length];
Drawable backgroundImage = new NinePatchDrawable(new NinePatch(globalAtlas.findRegion("roundbox_grey"),8,8,8,8));
// Note: Ideally this would be done in renderBackground() without the use of actors. Unfortunately,
// something about the stage being larger than the physical screen seems to mess with the camera
TextureRegion background = localAtlas.findRegion("spr_background");
for (int x=-12;x<Gdx.graphics.getWidth();x+=background.getRegionWidth()) {
for (int y=-12;y<Gdx.graphics.getHeight();y+=background.getRegionHeight()) {
Image img = new Image(background);
img.setPosition(x,y);
stage.addActor(img);
}
}
for(int i=0;i<symbols.length;i++) {
symbols[i]=new TextureRegionDrawable(new TextureRegion(localAtlas.findRegion(variation.symbolNames[i])));
smallSymbols[i]=new TextureRegionDrawable(new TextureRegion(localAtlas.findRegion(variation.symbolNames[i])));
smallSymbols[i].setMinWidth(symbols[i].getMinWidth()/2);
smallSymbols[i].setMinHeight(symbols[i].getMinHeight()/2);
}
Image frontPanel = new Image(new TextureRegionDrawable(localAtlas.findRegion("spr_frontpanel")));
frontPanel.setPosition(19,61);
deviceGroup.addActor(frontPanel);
knob = new Image(localAtlas.findRegion("spr_knob"));
knob.setPosition(235,219);
KnobHandler handler = new KnobHandler(this,true,240,69);
knob.addListener(handler);
handler.restKnob(knob);
deviceGroup.addActor(knob);
ClippingGroup reelGroup = new ClippingGroup(new Rectangle(0,56,Gdx.graphics.getWidth(),87));
int[] initialFaces = variation.getInitialFaces();
int pos = 0;
for (int i=0;i<reelSymbols.length;i++) {
reelSymbols[i] = new Symbol(variation,symbols,initialFaces[i],i/3,this);
reelGroup.addActor(reelSymbols[i]);
if (i>0 && i%3==0) {
pos+=75;
}
reelSymbols[i].setPosition(pos, (i%3)*reelSymbols[0].getHeight());
}
reelGroup.setPosition(53,284);
deviceGroup.addActor(reelGroup);
Group coinGroup = new Group();
for (int i=0;i<bet.length;i++) {
up = new TextureRegionDrawable(localAtlas.findRegion("btn_bet_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_bet_down"));
checked = new TextureRegionDrawable(localAtlas.findRegion("btn_bet_checked"));
bet[i] = new ImageButton(up,down,checked);
bet[i].setPosition(0,3*bet[i].getHeight()-i*bet[i].getHeight());
bet[i].addListener(this);
coinGroup.addActor(bet[i]);
}
bet[0].setChecked(true);
coinGroup.setPosition(10,40);
deviceGroup.addActor(coinGroup);
Table statusBar = new Table(((SlotMachine)game).skin);
statusBar.setBackground(backgroundImage);
statusBar.setBounds(10,10,300,48);
if (player!=null) {
Image knobCount = new Image(new TextureRegionDrawable(localAtlas.findRegion("spr_turns")));
statusBar.add(knobCount).left();
turns = new Label("x 0",((SlotMachine)game).skin);
statusBar.add(turns).width(30).right().padLeft(5).padRight(20);
Image coinCount = new Image(new TextureRegionDrawable(localAtlas.findRegion("spr_cash")));
statusBar.add(coinCount);
credits = new Label("x "+player.credit,((SlotMachine)game).skin);
statusBar.add(credits).width(30).right().padLeft(5).padRight(20);
up = new TextureRegionDrawable(localAtlas.findRegion("btn_view_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_view_down"));
checked = new TextureRegionDrawable(localAtlas.findRegion("btn_view_checked"));
viewSwitch = new ImageButton(up,down,checked);
viewSwitch.addListener(this);
statusBar.add(viewSwitch).right();
}
else {
// Setup screen
up = new TextureRegionDrawable(localAtlas.findRegion("btn_left_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_left_down"));
previousVariation = new ImageButton(up,down);
previousVariation.addListener(this);
up = new TextureRegionDrawable(localAtlas.findRegion("btn_right_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_right_down"));
nextVariation = new ImageButton(up,down);
nextVariation.addListener(this);
statusBar.add(previousVariation).padRight(30);
statusBar.add("Select game").padRight(30);
statusBar.add(nextVariation);
}
stage.addActor(statusBar);
feedbackMessage = new Label("",((SlotMachine)game).skin);
feedbackSymbol = new Image(new TextureRegionDrawable(localAtlas.findRegion("spr_feedbackcoins")));
feedbackGroup = new Group();
feedbackGroup.addActor(feedbackMessage);
feedbackGroup.addActor(feedbackSymbol);
feedbackMessage.setPosition(10+feedbackSymbol.getWidth(),feedbackSymbol.getHeight()/2-feedbackMessage.getHeight()/2);
feedbackGroup.getColor().a=0;
deviceGroup.addActor(feedbackGroup);
deviceName = new Table(((SlotMachine)game).skin);
deviceName.setBackground(backgroundImage);
deviceName.add(variation.machineName);
deviceName.setBounds(10,422,300,48);
infoGroup.addActor(deviceName);
Table buttons = new Table();
buttons.setBounds(262,150,48,200);
buttons.setBackground(backgroundImage);
up = new TextureRegionDrawable(localAtlas.findRegion("btn_musicmuted_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_musicmuted_down"));
checked = new TextureRegionDrawable(localAtlas.findRegion("btn_musicmuted_checked"));
musicStatus = new ImageButton(up,down,checked);
musicStatus.setChecked(game.muteManager.isMusicMuted());
musicStatus.addListener(this);
up = new TextureRegionDrawable(localAtlas.findRegion("btn_soundmuted_up"));
down = new TextureRegionDrawable(localAtlas.findRegion("btn_soundmuted_down"));
checked = new TextureRegionDrawable(localAtlas.findRegion("btn_soundmuted_checked"));
soundStatus = new ImageButton(up,down,checked);
soundStatus.addListener(this);
up = new TextureRegionDrawable(globalAtlas.findRegion("btn_close_up"));
down = new TextureRegionDrawable(globalAtlas.findRegion("btn_close_down"));
exit = new ImageButton(up,down);
exit.addListener(this);
buttons.add(musicStatus).padBottom(20).row();
buttons.add(soundStatus).padBottom(20).row();
buttons.add(exit);
infoGroup.addActor(buttons);
scrollTable = new ScrollPane(null,((SlotMachine)game).skin);
setVariant(variation);
//scrollTable.setSize(244,360);
scrollTable.setOverscroll(true,true);
//scrollTable.setPosition(18,60);
scrollTable.setBounds(10,68,320-30-48,334);
if (player==null) {
// Use as setup screen
infoGroup.setPosition(0,0);
deviceGroup.setPosition(stage.getWidth(),0);
}
else {
infoGroup.setPosition(stage.getWidth(),0);
}
infoGroup.addActor(scrollTable);
stage.addActor(deviceGroup);
stage.addActor(infoGroup);
}
/**
* setup the info on the inforscreen
* @param variant the game to visualize
* @return a pay table.
*/
private void setVariant(Variation variant) {
Table paytable = new Table(((SlotMachine)game).skin);
for (int x=0;x<variant.paytable.length;x++) {
for (int y=0;y<variant.paytable[x].length-1;y++) {
if (variant.paytable[x][y]==-1) {
// Wild symbol == empty space
paytable.add().pad(2,2,2,2);
}
else {
Actor actor = new Image(smallSymbols[variant.paytable[x][y]]);
paytable.add(actor).pad(2,2,8,2);
}
}
paytable.add(" = ");
paytable.add(variant.paytable[x][3]+" coins").right();
paytable.row();
}
// Only show extra information on the setup screen, as the paytable visual is not desgined
// to keep in sync with dynamically updated information
if (player==null) {
Player tmp = new Player(variant);
paytable.add("- - - - - - - - - - - - - - - - -").colspan(5).center();
paytable.row();
paytable.add("Seed capital").colspan(4).left();
paytable.add(variant.seedCapital+" coins").right();
paytable.row();
paytable.add("On hand").colspan(4).left();
paytable.add(tmp.credit+" coins").right();
paytable.row();
paytable.add("Highscore").colspan(4).left();
paytable.add(tmp.highscore+" coins").right();
}
paytable.pack();
this.variation= variant;
scrollTable.setWidget(paytable);
deviceName.clear();
deviceName.add(variant.machineName);
}
@Override
public void dispose() {
super.dispose();
if (triggerSound!=null) triggerSound.dispose();
if (ejectCoinSound!=null) ejectCoinSound.dispose();
if (winSound!=null) winSound.dispose();
if (reelStopSound!=null) reelStopSound.dispose();
}
@Override
public void renderBackground(float delta) {
Gdx.gl.glClearColor(0.72f, 0.74f, 0.71f, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
/**
* Sum up the coins that are currently visible and checked.
* @return amount of coins bet.
*/
public int getBet() {
int ret=0;
for (int i=0;i<bet.length;i++) {
if (bet[i].isChecked() && bet[i].isVisible()) ret++;
}
return ret;
}
@Override
public boolean handle(Event event) {
if (! (event instanceof InputEvent)) return false;
InputEvent input = (InputEvent) event;
Actor actor = input.getListenerActor();
Vector2 coords = Vector2.tmp.set(input.getStageX(), input.getStageY());
event.getListenerActor().stageToLocalCoordinates(coords);
boolean isOver = actor.hit(coords.x,coords.y,true)!=null;
if (isOver && actor==viewSwitch && input.getType().equals(InputEvent.Type.touchUp)) {
if (viewSwitch.isChecked()) {
// Note: moveBy takes time in which the user may trigger another moveBy, potentially
// scrolling the viewport into empty space. As a workaround, make sure, that groups
// are where they are suppose to be before doing a relative movement.
deviceGroup.setX(0);
infoGroup.setX(stage.getWidth());
deviceGroup.addAction(Actions.moveBy(-stage.getWidth(),0,0.1f));
infoGroup.addAction(Actions.moveBy(-stage.getWidth(),0,0.1f));
}
else {
deviceGroup.setX(-stage.getWidth());
infoGroup.setX(0);
deviceGroup.addAction(Actions.moveBy(stage.getWidth(),0,0.1f));
infoGroup.addAction(Actions.moveBy(stage.getWidth(),0,0.1f));
}
}
if (isOver && actor==exit && input.getType().equals(InputEvent.Type.touchUp)) {
// NOTE: persisting should probably be done transparently in Player.win() ans Player.loose(),
// but im not compfortable with writing often on flash memory.
if (player!=null) player.persist();
fadeOverScreen.configure(game,this,new MenuScreen(game),1);
game.setScreen(fadeOverScreen);
}
if (isOver && actor==musicStatus && input.getType().equals(InputEvent.Type.touchUp)) {
game.muteManager.setMusicMuted(musicStatus.isChecked());
}
if (isOver && actor==soundStatus && input.getType().equals(InputEvent.Type.touchUp)) {
game.muteManager.setSoundMuted(soundStatus.isChecked());
}
if (isOver && actor==nextVariation && input.getType().equals(InputEvent.Type.touchUp)) {
setVariant(Variation.loadNextVariation());
}
if (isOver && actor==previousVariation && input.getType().equals(InputEvent.Type.touchUp)) {
setVariant(Variation.loadNextVariation());
}
return true;
}
/**
* Mark a <code>Symbol</code> as either in motion or at rest.
* @param symbol the <code>Symbol</code> in question.
* @param moving true if spinning, false at rest
*/
protected synchronized void inMotion(Symbol symbol, boolean moving) {
if (moving) spinning++;
else spinning
// Provide audible feedback for a stopping reel
if (symbol.isOnPayline() && !moving) {
player.payline[symbol.getReel()]=symbol.getFace();
playSoundEffect(REELSTOPSOUND);
}
// All reels stopped -> evaluate
if (spinning==0) {
// A round may be played without betting, so simulate a bet to find out for sure if the player
// won or lost.
if (variation.getPayout(1,player.payline)>0) {
int win = variation.getPayout(player.bet,player.payline);
// No bet -> no bling
if (win>0) {
feedbackMessage.setText("+ "+win);
// NOTE: Actions from static import
float centerPos = stage.getWidth()/2-(feedbackMessage.getWidth()+10+feedbackSymbol.getWidth())/2;
feedbackGroup.addAction(sequence(moveTo(centerPos,85),fadeIn(0.4f),moveBy(0,-50,1f),fadeOut(0.4f)));
playSoundEffect(WINSOUND);
}
// But it still counts towards the statistics
player.win(win);
}
else {
// Player lost the round
player.loose();
}
// Make sure, the player can not bet more coins than s/he has. NOTE: There is no explicit
// Game Over check. The player just runs into a dead end eventually from which on s/he can
// only play wagerless rounds. This is intended! The game design calls for free games as a
// means of skipping over (suspected) loosing rounds (strategy element).
// Since this allows the player to play forever by never betting, a Game Over screen would
// be meaningless.
for (int i=0;i<bet.length;i++) {
bet[i].setVisible(player.credit>i);
}
player.round++;
credits.setText("x "+player.credit);
turns.setText("x "+player.round);
}
}
/**
* Query if the reels are still in motion
* @return true if the reels are spinning
*/
public synchronized boolean isSpinning() {
return spinning!=0;
}
/**
* Start a new round.
* @param velocity how fast to spin the reels.
*/
public synchronized void newRound(int velocity) {
if (isSpinning()) return;
player.gamble(getBet());
credits.setText("x "+player.credit);
for (int i=0;i<reelSymbols.length;i++) {
reelSymbols[i].spin((1+i/3 )* 3 +velocity,velocity);
}
}
/**
* Trigger a sound effect
* @param which which sound effect to play
*/
protected void playSoundEffect(int which) {
if (game.muteManager.isSoundMuted()) return;
// FIXME: We should probably throttle the music volume a bit to make sfx more noticeable.
// Problem with that: Sound.play() only triggers the sound effect and returns immediately.
switch(which) {
case TRIGGERSOUND: {
triggerSound.play();
break;
}
case WINSOUND: {
winSound.play();
break;
}
case EJECTCOINSOUND: {
ejectCoinSound.play();
break;
}
case REELSTOPSOUND: {
reelStopSound.play();
break;
}
}
}
/**
* Try stopping the wheels. This may or may not succeed (skill element).
* Wheels are stopped from left to right.
*/
public synchronized void brakeWheels() {
switch (spinning) {
case 1:
case 2:
case 3: {
reelSymbols[6].handbrake();
reelSymbols[7].handbrake();
reelSymbols[8].handbrake();
break;
}
case 4:
case 5:
case 6: {
reelSymbols[3].handbrake();
reelSymbols[4].handbrake();
reelSymbols[5].handbrake();
break;
}
case 7:
case 8:
case 9: {
reelSymbols[0].handbrake();
reelSymbols[1].handbrake();
reelSymbols[2].handbrake();
break;
}
default: {
return;
}
}
}
}
|
package git4idea.history;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import git4idea.GitFormatException;
import git4idea.config.GitVersionSpecialty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>Parses the 'git log' output basing on the given number of options.
* Doesn't execute of prepare the command itself, performs only parsing.</p>
* <p>
* Usage:<ol>
* <li> Pass options you want to have in the output to the constructor using the {@link GitLogOption} enum constants.
* <li> Get the custom format pattern for 'git log' by calling {@link #getPretty()}
* <li> Call the command and retrieve the output.
* <li> Parse the output via {@link #parseLine(CharSequence)}(prefered), {@link #parse(CharSequence)} or {@link #parseOneRecord(CharSequence)}.
* Note that {@link #parseLine(CharSequence)} expects lines without line separators</ol></p>
* <p>Note that you may pass one set of options to the GitLogParser constructor and then execute git log with other set of options.
* In that case {@link #parse(CharSequence)} will likely fail with {@link GitFormatException}.
* Moreover you really <b>must</b> use {@link #getPretty()} to pass "--pretty=format" pattern to 'git log' -- otherwise the parser won't be able
* to parse output of 'git log' (because special separator characters are used for that).</p>
* <p>Commit records have the following format:
* <pre>
* RECORD_START (commit information, separated by ITEMS_SEPARATOR) RECORD_END \n (changed paths with statuses)?</pre>
* Example:
* <pre>
* 2c815939f45fbcfda9583f84b14fe9d393ada790<ITEMS_SEPARATOR>sample commit<RECORD_END>
* D a.txt</pre></p>
*
* @see GitLogRecord
*/
public class GitLogParser {
private static final Logger LOG = Logger.getInstance(GitLogParser.class);
// Single records begin with %x01%x01, end with %03%03. Items of commit information (hash, committer, subject, etc.) are separated by %x02%x02.
public static final String RECORD_START = "\u0001\u0001";
public static final String ITEMS_SEPARATOR = "\u0002\u0002";
public static final String RECORD_END = "\u0003\u0003";
private static final int INPUT_ERROR_MESSAGE_HEAD_LIMIT = 1000000; // limit the string by ~2mb
private static final int INPUT_ERROR_MESSAGE_TAIL_LIMIT = 100;
private final boolean mySupportsRawBody;
@NotNull private final String myPretty;
@NotNull private final OptionsParser myOptionsParser;
@NotNull private final PathsParser myPathsParser;
private boolean myIsInBody = true;
private GitLogParser(boolean supportsRawBody,
@NotNull NameStatus nameStatusOption,
@NotNull GitLogOption... options) {
myPretty = "--pretty=format:" + makeFormatFromOptions(options);
mySupportsRawBody = supportsRawBody;
myOptionsParser = new OptionsParser(options);
myPathsParser = new PathsParser(nameStatusOption);
}
public GitLogParser(@NotNull Project project,
@NotNull NameStatus nameStatus,
@NotNull GitLogOption... options) {
this(GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project), nameStatus, options);
}
public GitLogParser(@NotNull Project project,
@NotNull GitLogOption... options) {
this(project, NameStatus.NONE, options);
}
@NotNull
public List<GitLogRecord> parse(@NotNull CharSequence output) {
List<GitLogRecord> result = ContainerUtil.newArrayList();
List<CharSequence> lines = StringUtil.split(output, "\n", true, false);
for (CharSequence line : lines) {
try {
GitLogRecord record = parseLine(line);
if (record != null) {
result.add(record);
}
}
catch (GitFormatException e) {
clear();
LOG.error(e);
}
}
GitLogRecord record = finish();
if (record != null) result.add(record);
return result;
}
@Nullable
public GitLogRecord parseOneRecord(@NotNull CharSequence output) {
List<GitLogRecord> records = parse(output);
clear();
if (records.isEmpty()) return null;
return ContainerUtil.getFirstItem(records);
}
/**
* Expects a line without separator.
*/
@Nullable
public GitLogRecord parseLine(@NotNull CharSequence line) {
if (myPathsParser.expectsPaths()) {
return parseLineWithPaths(line);
}
return parseLineWithoutPaths(line);
}
@Nullable
private GitLogRecord parseLineWithPaths(@NotNull CharSequence line) {
if (myIsInBody) {
myIsInBody = !myOptionsParser.parseLine(line);
}
else {
if (CharArrayUtil.regionMatches(line, 0, RECORD_START)) {
GitLogRecord record = createRecord();
myIsInBody = !myOptionsParser.parseLine(line);
return record;
}
myPathsParser.parseLine(line);
}
return null;
}
@Nullable
private GitLogRecord parseLineWithoutPaths(@NotNull CharSequence line) {
if (myOptionsParser.parseLine(line)) {
return createRecord();
}
return null;
}
@Nullable
public GitLogRecord finish() {
if (myOptionsParser.isEmpty()) return null;
return createRecord();
}
@NotNull
private GitLogRecord createRecord() {
Map<GitLogOption, String> options = myOptionsParser.getResult();
myOptionsParser.clear();
List<GitLogStatusInfo> result = myPathsParser.getResult();
myPathsParser.clear();
myIsInBody = true;
return new GitLogRecord(options, result, mySupportsRawBody);
}
public void clear() {
myOptionsParser.clear();
myPathsParser.clear();
myIsInBody = true;
}
@NotNull
public String getPretty() {
return myPretty;
}
@NotNull
private static String makeFormatFromOptions(@NotNull GitLogOption[] options) {
Function<GitLogOption, String> function = option -> "%" + option.getPlaceholder();
return encodeForGit(RECORD_START) + StringUtil.join(options, function, encodeForGit(ITEMS_SEPARATOR)) + encodeForGit(RECORD_END);
}
@NotNull
private static String encodeForGit(@NotNull String line) {
StringBuilder encoded = new StringBuilder();
line.chars().forEachOrdered(c -> encoded.append("%x").append(String.format("%02x", c)));
return encoded.toString();
}
private static void throwGFE(@NotNull String message, @NotNull CharSequence line) {
throw new GitFormatException(message + " [" + getTruncatedEscapedOutput(line) + "]");
}
@NotNull
private static String getTruncatedEscapedOutput(@NotNull CharSequence line) {
String lineString;
String formatString = "%s...(%d more characters)...%s";
if (line.length() > INPUT_ERROR_MESSAGE_HEAD_LIMIT + INPUT_ERROR_MESSAGE_TAIL_LIMIT + formatString.length()) {
lineString = String.format(formatString, line.subSequence(0, INPUT_ERROR_MESSAGE_HEAD_LIMIT),
(line.length() - INPUT_ERROR_MESSAGE_HEAD_LIMIT - INPUT_ERROR_MESSAGE_TAIL_LIMIT),
line.subSequence(line.length() - INPUT_ERROR_MESSAGE_TAIL_LIMIT, line.length()));
}
else {
lineString = line.toString();
}
return StringUtil.escapeStringCharacters(lineString);
}
// --name-status or no flag
enum NameStatus {
/**
* No flag.
*/
NONE,
/**
* --name-status
*/
STATUS
}
/**
* Options which may be passed to 'git log --pretty=format:' as placeholders and then parsed from the result.
* These are the pieces of information about a commit which we want to get from 'git log'.
*/
enum GitLogOption {
HASH("H"), TREE("T"), COMMIT_TIME("ct"), AUTHOR_NAME("an"), AUTHOR_TIME("at"), AUTHOR_EMAIL("ae"), COMMITTER_NAME("cn"),
COMMITTER_EMAIL("ce"), SUBJECT("s"), BODY("b"), PARENTS("P"), REF_NAMES("d"), SHORT_REF_LOG_SELECTOR("gd"),
RAW_BODY("B");
private final String myPlaceholder;
GitLogOption(String placeholder) {
myPlaceholder = placeholder;
}
private String getPlaceholder() {
return myPlaceholder;
}
}
private static class OptionsParser {
@NotNull private final GitLogOption[] myOptions;
@NotNull private final PartialResult myResult = new PartialResult();
public OptionsParser(@NotNull GitLogOption[] options) {
myOptions = options;
}
public boolean parseLine(@NotNull CharSequence line) {
int offset = 0;
if (myResult.isEmpty()) {
if (!CharArrayUtil.regionMatches(line, offset, RECORD_START)) {
return false;
}
offset += RECORD_START.length();
}
while (offset < line.length()) {
if (atRecordEnd(line, offset)) {
myResult.finishItem();
if (myResult.getResult().size() != myOptions.length) {
throwGFE("Parsed incorrect options " + myResult.getResult() + " for " +
Arrays.toString(myOptions), line);
}
return true;
}
if (CharArrayUtil.regionMatches(line, offset, ITEMS_SEPARATOR)) {
myResult.finishItem();
offset += ITEMS_SEPARATOR.length();
}
else {
char c = line.charAt(offset);
myResult.append(c);
offset++;
}
}
myResult.append('\n');
return false;
}
private static boolean atRecordEnd(@NotNull CharSequence line, int offset) {
return (offset == line.length() - RECORD_END.length() && CharArrayUtil.regionMatches(line, offset, RECORD_END));
}
@NotNull
public Map<GitLogOption, String> getResult() {
return createOptions(myResult.getResult());
}
@NotNull
private Map<GitLogOption, String> createOptions(@NotNull List<String> options) {
Map<GitLogOption, String> optionsMap = new HashMap<>(options.size());
for (int index = 0; index < options.size(); index++) {
optionsMap.put(myOptions[index], options.get(index));
}
return optionsMap;
}
public void clear() {
myResult.clear();
}
public boolean isEmpty() {
return myResult.isEmpty();
}
}
private static class PathsParser {
@NotNull private final NameStatus myNameStatusOption;
@NotNull private List<GitLogStatusInfo> myStatuses = ContainerUtil.newArrayList();
public PathsParser(@NotNull NameStatus nameStatusOption) {
myNameStatusOption = nameStatusOption;
}
public void parseLine(@NotNull CharSequence line) {
if (line.length() == 0) return;
List<String> match = parsePathsLine(line);
if (match.isEmpty()) {
// ignore
}
else {
if (myNameStatusOption != NameStatus.STATUS) throwGFE("Status list not expected", line);
if (match.size() == 2) {
myStatuses.add(new GitLogStatusInfo(GitChangeType.fromString(match.get(0)), match.get(1), null));
}
else {
myStatuses.add(new GitLogStatusInfo(GitChangeType.fromString(match.get(0)), match.get(1), match.get(2)));
}
}
}
@NotNull
private static List<String> parsePathsLine(@NotNull CharSequence line) {
int offset = 0;
PartialResult result = new PartialResult();
while (offset < line.length()) {
if (atLineEnd(line, offset)) {
break;
}
char charAt = line.charAt(offset);
if (charAt == '\t') {
result.finishItem();
}
else {
result.append(charAt);
}
offset++;
}
result.finishItem();
return result.getResult();
}
private static boolean atLineEnd(@NotNull CharSequence line, int offset) {
while (offset < line.length() && (line.charAt(offset) == '\t' || line.charAt(offset) == ' ')) offset++;
if (offset == line.length() || (line.charAt(offset) == '\n' || line.charAt(offset) == '\r')) return true;
return false;
}
@NotNull
public List<GitLogStatusInfo> getResult() {
return myStatuses;
}
public void clear() {
myStatuses = ContainerUtil.newArrayList();
}
public boolean expectsPaths() {
return myNameStatusOption == NameStatus.STATUS;
}
}
private static class PartialResult {
@NotNull private List<String> myResult = ContainerUtil.newArrayList();
@NotNull private final StringBuilder myCurrentItem = new StringBuilder();
public void append(char c) {
myCurrentItem.append(c);
}
public void finishItem() {
myResult.add(myCurrentItem.toString());
myCurrentItem.setLength(0);
}
@NotNull
public List<String> getResult() {
return myResult;
}
public void clear() {
myCurrentItem.setLength(0);
myResult = ContainerUtil.newArrayList();
}
public boolean isEmpty() {
return myResult.isEmpty() && myCurrentItem.length() == 0;
}
}
}
|
package de.podfetcher.service;
import java.io.IOException;
import android.R;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import de.podfetcher.PodcastApp;
import de.podfetcher.activity.MediaplayerActivity;
import de.podfetcher.feed.Feed;
import de.podfetcher.feed.FeedItem;
import de.podfetcher.feed.FeedManager;
import de.podfetcher.feed.FeedMedia;
import de.podfetcher.receiver.MediaButtonReceiver;
import de.podfetcher.receiver.PlayerWidget;
/** Controls the MediaPlayer that plays a FeedMedia-file */
public class PlaybackService extends Service {
/** Logging tag */
private static final String TAG = "PlaybackService";
/** Contains the id of the media that was played last. */
public static final String PREF_LAST_PLAYED_ID = "de.podfetcher.preferences.lastPlayedId";
/** Contains the feed id of the last played item. */
public static final String PREF_LAST_PLAYED_FEED_ID = "de.podfetcher.preferences.lastPlayedFeedId";
/** True if last played media was streamed. */
public static final String PREF_LAST_IS_STREAM = "de.podfetcher.preferences.lastIsStream";
/** Contains the id of the FeedMedia object. */
public static final String EXTRA_MEDIA_ID = "extra.de.podfetcher.service.mediaId";
/** Contains the id of the Feed object of the FeedMedia. */
public static final String EXTRA_FEED_ID = "extra.de.podfetcher.service.feedId";
/** True if media should be streamed. */
public static final String EXTRA_SHOULD_STREAM = "extra.de.podfetcher.service.shouldStream";
/**
* True if playback should be started immediately after media has been
* prepared.
*/
public static final String EXTRA_START_WHEN_PREPARED = "extra.de.podfetcher.service.startWhenPrepared";
public static final String ACTION_PLAYER_STATUS_CHANGED = "action.de.podfetcher.service.playerStatusChanged";
public static final String ACTION_PLAYER_NOTIFICATION = "action.de.podfetcher.service.playerNotification";
public static final String EXTRA_NOTIFICATION_CODE = "extra.de.podfetcher.service.notificationCode";
public static final String EXTRA_NOTIFICATION_TYPE = "extra.de.podfetcher.service.notificationType";
public static final int NOTIFICATION_TYPE_ERROR = 0;
public static final int NOTIFICATION_TYPE_INFO = 1;
public static final int NOTIFICATION_TYPE_BUFFER_UPDATE = 2;
public static final int NOTIFICATION_TYPE_RELOAD = 3;
/** Is true if service is running. */
public static boolean isRunning = false;
private static final int NOTIFICATION_ID = 1;
private NotificationCompat.Builder notificationBuilder;
private AudioManager audioManager;
private ComponentName mediaButtonReceiver;
private MediaPlayer player;
private FeedMedia media;
private Feed feed;
/** True if media should be streamed (Extracted from Intent Extra) . */
private boolean shouldStream;
private boolean startWhenPrepared;
private boolean playingVideo;
private FeedManager manager;
private PlayerStatus status;
private PositionSaver positionSaver;
private WidgetUpdateWorker widgetUpdater;
private PlayerStatus statusBeforeSeek;
/** True if mediaplayer was paused because it lost audio focus temporarily */
private boolean pausedBecauseOfTransientAudiofocusLoss;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public PlaybackService getService() {
return PlaybackService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
pausedBecauseOfTransientAudiofocusLoss = false;
status = PlayerStatus.STOPPED;
Log.d(TAG, "Service created.");
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
manager = FeedManager.getInstance();
player = new MediaPlayer();
player.setOnPreparedListener(preparedListener);
player.setOnCompletionListener(completionListener);
player.setOnSeekCompleteListener(onSeekCompleteListener);
player.setOnErrorListener(onErrorListener);
player.setOnBufferingUpdateListener(onBufferingUpdateListener);
mediaButtonReceiver = new ComponentName(getPackageName(),
MediaButtonReceiver.class.getName());
audioManager.registerMediaButtonEventReceiver(mediaButtonReceiver);
registerReceiver(headsetDisconnected, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
unregisterReceiver(headsetDisconnected);
Log.d(TAG, "Service is about to be destroyed");
audioManager.unregisterMediaButtonEventReceiver(mediaButtonReceiver);
audioManager.abandonAudioFocus(audioFocusChangeListener);
player.release();
stopWidgetUpdater();
updateWidget();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final OnAudioFocusChangeListener audioFocusChangeListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
Log.d(TAG, "Lost audio focus");
pause(true);
stopSelf();
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.d(TAG, "Gained audio focus");
if (pausedBecauseOfTransientAudiofocusLoss) {
play();
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.d(TAG, "Lost audio focus temporarily. Ducking...");
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, 0);
pausedBecauseOfTransientAudiofocusLoss = true;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.d(TAG, "Lost audio focus temporarily. Pausing...");
pause(false);
pausedBecauseOfTransientAudiofocusLoss = true;
}
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1);
if (keycode != -1) {
Log.d(TAG, "Received media button event");
handleKeycode(keycode);
} else {
long mediaId = intent.getLongExtra(EXTRA_MEDIA_ID, -1);
long feedId = intent.getLongExtra(EXTRA_FEED_ID, -1);
boolean playbackType = intent.getBooleanExtra(EXTRA_SHOULD_STREAM,
true);
if (mediaId == -1 || feedId == -1) {
Log.e(TAG,
"Media ID or Feed ID wasn't provided to the Service.");
if (media == null || feed == null) {
stopSelf();
}
// Intent values appear to be valid
// check if already playing and playbackType is the same
} else if (media == null || mediaId != media.getId()
|| playbackType != shouldStream) {
pause(true);
player.reset();
if (media == null || mediaId != media.getId()) {
feed = manager.getFeed(feedId);
media = manager.getFeedMedia(mediaId, feed);
}
if (media != null) {
shouldStream = playbackType;
startWhenPrepared = intent.getBooleanExtra(
EXTRA_START_WHEN_PREPARED, false);
setupMediaplayer();
} else {
Log.e(TAG, "Media is null");
stopSelf();
}
} else if (media != null) {
if (status == PlayerStatus.PAUSED) {
play();
}
} else {
Log.w(TAG, "Something went wrong. Shutting down...");
stopSelf();
}
}
return Service.START_NOT_STICKY;
}
/** Handles media button events */
private void handleKeycode(int keycode) {
switch (keycode) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
if (status == PlayerStatus.PLAYING) {
pause(true);
} else if (status == PlayerStatus.PAUSED) {
play();
}
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
if (status == PlayerStatus.PAUSED) {
play();
}
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
if (status == PlayerStatus.PLAYING) {
pause(true);
}
break;
}
}
/**
* Called by a mediaplayer Activity as soon as it has prepared its
* mediaplayer.
*/
public void setVideoSurface(SurfaceHolder sh) {
Log.d(TAG, "Setting display");
player.setDisplay(null);
player.setDisplay(sh);
if (status == PlayerStatus.STOPPED
|| status == PlayerStatus.AWAITING_VIDEO_SURFACE) {
try {
if (shouldStream) {
player.setDataSource(media.getDownload_url());
setStatus(PlayerStatus.PREPARING);
player.prepareAsync();
} else {
player.setDataSource(media.getFile_url());
setStatus(PlayerStatus.PREPARING);
player.prepare();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** Called when the surface holder of the mediaplayer has to be changed. */
public void resetVideoSurface() {
positionSaver.cancel(true);
player.setDisplay(null);
player.reset();
player.release();
player = new MediaPlayer();
player.setOnPreparedListener(preparedListener);
player.setOnCompletionListener(completionListener);
player.setOnSeekCompleteListener(onSeekCompleteListener);
player.setOnErrorListener(onErrorListener);
player.setOnBufferingUpdateListener(onBufferingUpdateListener);
status = PlayerStatus.STOPPED;
setupMediaplayer();
}
/** Called after service has extracted the media it is supposed to play. */
private void setupMediaplayer() {
try {
if (media.getMime_type().startsWith("audio")) {
playingVideo = false;
if (shouldStream) {
player.setDataSource(media.getDownload_url());
setStatus(PlayerStatus.PREPARING);
player.prepareAsync();
} else {
player.setDataSource(media.getFile_url());
setStatus(PlayerStatus.PREPARING);
player.prepare();
}
} else if (media.getMime_type().startsWith("video")) {
playingVideo = true;
setStatus(PlayerStatus.AWAITING_VIDEO_SURFACE);
player.setScreenOnWhilePlaying(true);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setupPositionSaver() {
if (positionSaver == null) {
positionSaver = new PositionSaver() {
@Override
protected void onCancelled(Void result) {
super.onCancelled(result);
positionSaver = null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
positionSaver = null;
}
};
positionSaver.execute();
}
}
private MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Resource prepared");
mp.seekTo(media.getPosition());
setStatus(PlayerStatus.PREPARED);
if (startWhenPrepared) {
play();
}
}
};
private MediaPlayer.OnSeekCompleteListener onSeekCompleteListener = new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mp) {
if (status == PlayerStatus.SEEKING) {
setStatus(statusBeforeSeek);
}
}
};
private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
private static final String TAG = "PlaybackService.onErrorListener";
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.w(TAG, "An error has occured: " + what);
if (mp.isPlaying()) {
pause(true);
}
sendNotificationBroadcast(NOTIFICATION_TYPE_ERROR, what);
stopSelf();
return true;
}
};
private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "Playback completed");
// Save state
positionSaver.cancel(true);
media.setPosition(0);
manager.markItemRead(PlaybackService.this, media.getItem(), true);
boolean isInQueue = manager.isInQueue(media.getItem());
if (isInQueue) {
manager.removeQueueItem(PlaybackService.this, media.getItem());
}
manager.setFeedMedia(PlaybackService.this, media);
// Prepare for playing next item
boolean followQueue = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext())
.getBoolean(PodcastApp.PREF_FOLLOW_QUEUE, false);
FeedItem nextItem = manager.getFirstQueueItem();
if (isInQueue && followQueue && nextItem != null) {
Log.d(TAG, "Loading next item in queue");
media = nextItem.getMedia();
feed = nextItem.getFeed();
shouldStream = !media.isDownloaded();
resetVideoSurface();
sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0);
} else {
Log.d(TAG, "Stopping playback");
stopWidgetUpdater();
setStatus(PlayerStatus.STOPPED);
stopForeground(true);
}
}
};
private MediaPlayer.OnBufferingUpdateListener onBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_UPDATE, percent);
}
};
/**
* Saves the current position and pauses playback
*
* @param abandonFocus
* is true if the service should release audio focus
*/
public void pause(boolean abandonFocus) {
if (player.isPlaying()) {
Log.d(TAG, "Pausing playback.");
player.pause();
if (abandonFocus) {
audioManager.abandonAudioFocus(audioFocusChangeListener);
}
if (positionSaver != null) {
positionSaver.cancel(true);
}
saveCurrentPosition();
stopWidgetUpdater();
setStatus(PlayerStatus.PAUSED);
stopForeground(true);
}
}
/** Pauses playback and destroys service. Recommended for video playback. */
public void stop() {
pause(true);
stopSelf();
}
public void play() {
if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED
|| status == PlayerStatus.STOPPED) {
int focusGained = audioManager.requestAudioFocus(
audioFocusChangeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (focusGained == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d(TAG, "Audiofocus successfully requested");
Log.d(TAG, "Resuming/Starting playback");
SharedPreferences.Editor editor = getApplicationContext()
.getSharedPreferences(PodcastApp.PREF_NAME, 0).edit();
editor.putLong(PREF_LAST_PLAYED_ID, media.getId());
editor.putLong(PREF_LAST_PLAYED_FEED_ID, feed.getId());
editor.putBoolean(PREF_LAST_IS_STREAM, shouldStream);
editor.commit();
player.start();
player.seekTo((int) media.getPosition());
setStatus(PlayerStatus.PLAYING);
setupPositionSaver();
setupWidgetUpdater();
setupNotification();
pausedBecauseOfTransientAudiofocusLoss = false;
} else {
Log.d(TAG, "Failed to request Audiofocus");
}
}
}
private void setStatus(PlayerStatus newStatus) {
Log.d(TAG, "Setting status to " + newStatus);
status = newStatus;
sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED));
updateWidget();
}
private void sendNotificationBroadcast(int type, int code) {
Intent intent = new Intent(ACTION_PLAYER_NOTIFICATION);
intent.putExtra(EXTRA_NOTIFICATION_TYPE, type);
intent.putExtra(EXTRA_NOTIFICATION_CODE, code);
sendBroadcast(intent);
}
/** Prepares notification and starts the service in the foreground. */
private void setupNotification() {
PendingIntent pIntent = PendingIntent.getActivity(this, 0, new Intent(
this, MediaplayerActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap icon = BitmapFactory.decodeResource(null,
R.drawable.stat_notify_sdcard);
notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Mediaplayer Service")
.setContentText("Click here for more info").setOngoing(true)
.setContentIntent(pIntent).setLargeIcon(icon)
.setSmallIcon(R.drawable.stat_notify_sdcard);
startForeground(NOTIFICATION_ID, notificationBuilder.getNotification());
Log.d(TAG, "Notification set up");
}
/**
* Seek a specific position from the current position
*
* @param delta
* offset from current position (positive or negative)
* */
public void seekDelta(int delta) {
seek(player.getCurrentPosition() + delta);
}
public void seek(int i) {
Log.d(TAG, "Seeking position " + i);
if (shouldStream) {
statusBeforeSeek = status;
setStatus(PlayerStatus.SEEKING);
}
player.seekTo(i);
saveCurrentPosition();
}
/** Saves the current position of the media file to the DB */
private synchronized void saveCurrentPosition() {
Log.d(TAG, "Saving current position to " + player.getCurrentPosition());
media.setPosition(player.getCurrentPosition());
manager.setFeedMedia(this, media);
}
private void stopWidgetUpdater() {
if (widgetUpdater != null) {
widgetUpdater.cancel(true);
}
}
private void setupWidgetUpdater() {
if (widgetUpdater == null || widgetUpdater.isCancelled()) {
widgetUpdater = new WidgetUpdateWorker();
widgetUpdater.execute();
}
}
private void updateWidget() {
Log.d(TAG, "Sending widget update request");
PlaybackService.this.sendBroadcast(new Intent(
PlayerWidget.FORCE_WIDGET_UPDATE));
}
/**
* Pauses playback when the headset is disconnected and the preference is
* set
*/
private BroadcastReceiver headsetDisconnected = new BroadcastReceiver() {
private static final String TAG = "headsetDisconnected";
private static final int UNPLUGGED = 0;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if (state != -1) {
Log.d(TAG, "Headset plug event. State is " + state);
boolean pauseOnDisconnect = PreferenceManager
.getDefaultSharedPreferences(
getApplicationContext())
.getBoolean(
PodcastApp.PREF_PAUSE_ON_HEADSET_DISCONNECT,
false);
Log.d(TAG, "pauseOnDisconnect preference is "
+ pauseOnDisconnect);
if (state == UNPLUGGED && pauseOnDisconnect
&& status == PlayerStatus.PLAYING) {
Log.d(TAG,
"Pausing playback because headset was disconnected");
pause(true);
}
} else {
Log.e(TAG, "Received invalid ACTION_HEADSET_PLUG intent");
}
}
}
};
/** Periodically saves the position of the media file */
class PositionSaver extends AsyncTask<Void, Void, Void> {
private static final int WAITING_INTERVALL = 5000;
@Override
protected Void doInBackground(Void... params) {
while (!isCancelled() && player.isPlaying()) {
try {
Thread.sleep(WAITING_INTERVALL);
saveCurrentPosition();
} catch (InterruptedException e) {
Log.d(TAG,
"Thread was interrupted while waiting. Finishing now...");
return null;
} catch (IllegalStateException e) {
Log.d(TAG, "Player is in illegal state. Finishing now");
return null;
}
}
return null;
}
}
/** Notifies the player widget in the specified intervall */
class WidgetUpdateWorker extends AsyncTask<Void, Void, Void> {
private static final String TAG = "WidgetUpdateWorker";
private static final int NOTIFICATION_INTERVALL = 2000;
@Override
protected void onProgressUpdate(Void... values) {
updateWidget();
}
@Override
protected Void doInBackground(Void... params) {
while (PlaybackService.isRunning && !isCancelled()) {
publishProgress();
try {
Thread.sleep(NOTIFICATION_INTERVALL);
} catch (InterruptedException e) {
return null;
}
}
return null;
}
}
public boolean isPlayingVideo() {
return playingVideo;
}
public boolean isShouldStream() {
return shouldStream;
}
public PlayerStatus getStatus() {
return status;
}
public FeedMedia getMedia() {
return media;
}
public MediaPlayer getPlayer() {
return player;
}
}
|
package ch.epfl.sweng.project;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import ch.epfl.sweng.project.Model.CheckPoint;
import ch.epfl.sweng.project.Model.Track;
/**
* This class contains some UI methods used by multiple Fragment/Activity.
*/
public class UtilsUI {
/**
* Given the time in seconds convert it into a String with the format hh:mm:ss.
* If showHours is true always display the hours digit (also if they are 00), otherwise,
* if it is false, they are shown only if necessary (not if they are 00).
*
* @param time time to convert, in seconds
* @param showHours indicates whether the hours digit must always be shown or not
* @return time as a String formatted as hh:mm:ss
*/
public static String timeToString(int time, boolean showHours) {
if (time < 0) {
throw new IllegalArgumentException("Run/Challenge could not have a negative duration");
}
String toDisplay = "";
if (showHours || time >= 3600) {
toDisplay += String.format(Locale.getDefault(), "%02d:", TimeUnit.SECONDS.toHours(time));
}
toDisplay += String.format(Locale.getDefault(), "%02d:%02d",
TimeUnit.SECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(time)),
TimeUnit.SECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(time)));
return toDisplay;
}
/**
* Setup UI elements and gesture of the given GoogleMap. Used for recaps.
*
* @param googleMap map to setup
*/
public static void recapDisplayTrackSetupUI(GoogleMap googleMap) {
if (googleMap == null) {
throw new NullPointerException();
}
googleMap.setBuildingsEnabled(false);
googleMap.setIndoorEnabled(false);
googleMap.setTrafficEnabled(false);
UiSettings uiSettings = googleMap.getUiSettings();
uiSettings.setCompassEnabled(false);
uiSettings.setIndoorLevelPickerEnabled(false);
uiSettings.setMapToolbarEnabled(false);
uiSettings.setZoomControlsEnabled(false);
uiSettings.setMyLocationButtonEnabled(false);
}
/**
* Display the given Track on the given GoogleMap. The argument color indicates the desired color for
* the Track to be shown. Also takes care to center the camera on the displayed Track. Used for recaps
*
* @param track Track to be shown
* @param googleMap map where the Track must be shown
* @param color color for the Tarck to be shown
*/
public static void recapDisplayTrack(Track track, GoogleMap googleMap, int color) {
if(track == null || googleMap == null) {
throw new NullPointerException();
}
if (track.getTotalCheckPoints() != 0) {
// Build polyline and latitude, longitude bounds
PolylineOptions polylineOptions = new PolylineOptions();
List<CheckPoint> trackPoints = track.getCheckpoints();
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (CheckPoint checkPoint : trackPoints) {
LatLng latLng = new LatLng(checkPoint.getLatitude(), checkPoint.getLongitude());
polylineOptions.add(latLng);
builder.include(latLng);
}
googleMap.addPolyline(polylineOptions.color(color));
// Center camera on past run
LatLngBounds bounds = builder.build();
int padding = 40;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
googleMap.animateCamera(cameraUpdate);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.