answer stringlengths 17 10.2M |
|---|
package org.pentaho.di.repository;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.xml.XMLHandler;
import org.w3c.dom.Node;
public class BaseRepositoryMeta {
protected String id;
protected String name;
protected String description;
public BaseRepositoryMeta(String id) {
this.id = id;
}
/**
* @param id
* @param name
* @param description
*/
public BaseRepositoryMeta(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#loadXML(org.w3c.dom.Node, java.util.List)
*/
public void loadXML(Node repnode, List<DatabaseMeta> databases) throws KettleException
{
try
{
// Fix for PDI-2508: migrating from 3.2 to 4.0 causes NPE on startup.
id = Const.NVL(XMLHandler.getTagValue(repnode, "id"), id) ;
name = XMLHandler.getTagValue(repnode, "name") ;
description = XMLHandler.getTagValue(repnode, "description");
}
catch(Exception e)
{
throw new KettleException("Unable to load repository meta object", e);
}
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#getXML()
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(100);
retval.append(" ").append(XMLHandler.addTagValue("id", id));
retval.append(" ").append(XMLHandler.addTagValue("name", name));
retval.append(" ").append(XMLHandler.addTagValue("description", description));
return retval.toString();
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#getId()
*/
public String getId() {
return id;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#setId(java.lang.String)
*/
public void setId(String id) {
this.id = id;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#getName()
*/
public String getName() {
return name;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#setName(java.lang.String)
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#getDescription()
*/
public String getDescription() {
return description;
}
/* (non-Javadoc)
* @see org.pentaho.di.repository.RepositoryMeta#setDescription(java.lang.String)
*/
public void setDescription(String description) {
this.description = description;
}
} |
package org.trustsoft.slastic.control;
import java.io.File;
import java.util.Collection;
import kieker.common.logReader.IMonitoringRecordConsumer;
import kieker.common.logReader.filesystemReader.FilesystemReader;
import kieker.common.tools.logReplayer.ReplayDistributor;
import kieker.loganalysis.LogAnalysisInstance;
import kieker.loganalysis.datamodel.ExecutionSequence;
import kieker.loganalysis.plugins.DependencyGraphPlugin;
import kieker.loganalysis.recordConsumer.ExecutionSequenceRepositoryFiller;
import kieker.loganalysis.recordConsumer.MonitoringRecordTypeLogger;
import kieker.tpmon.core.TpmonController;
import kieker.tpmon.monitoringRecord.AbstractKiekerMonitoringRecord;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.trustsoft.slastic.control.recordConsumer.ResponseTimeAverageCalculator;
import org.trustsoft.slastic.control.recordConsumer.ResponseTimePlotter;
/**
* @author Andre van Hoorn
*/
public class SLAsticControl {
private static final Log log = LogFactory.getLog(SLAsticControl.class);
private static final TpmonController ctrlInst = TpmonController.getInstance();
private static final IMonitoringRecordConsumer logCons = new IMonitoringRecordConsumer() {
/** Anonymous consumer class that simply passes all records to the
* controller */
public String[] getRecordTypeSubscriptionList() {
return null; // consume all types
}
public void consumeMonitoringRecord(final AbstractKiekerMonitoringRecord monitoringRecord) {
ctrlInst.logMonitoringRecord(monitoringRecord);
}
public boolean execute() {
// do nothing, we are synchronous
return true;
}
public void terminate() {
ctrlInst.terminateMonitoring();
}
};
public static void main(String[] args){
log.info("Hi, this is SLAsticControl");
String inputDir = System.getProperty("inputDir");
if (inputDir == null || inputDir.length() == 0 || inputDir.equals("${inputDir}")) {
log.error("No input dir found!");
log.error("Provide an input dir as system property.");
log.error("Example to read all tpmon-* files from /tmp:\n" +
" ant -DinputDir=/tmp/ run-SLAsticControl ");
System.exit(1);
} else {
log.info("Reading all tpmon-* files from " + inputDir);
}
LogAnalysisInstance analysisInstance = new LogAnalysisInstance();
analysisInstance.addLogReader(new FilesystemReader(inputDir));
/* Dumps the record type ID */
analysisInstance.addConsumer(new MonitoringRecordTypeLogger());
/* Collects all executions */
// ExecutionSequenceRepositoryFiller seqRepConsumer = new ExecutionSequenceRepositoryFiller();
// analysisInstance.addConsumer(seqRepConsumer);
/* Dumps response times */
// ResponseTimePlotter rtPlotter = new ResponseTimePlotter();
// analysisInstance.addConsumer(rtPlotter);
ResponseTimeAverageCalculator rtac = new ResponseTimeAverageCalculator();
//IMonitoringRecordConsumer rtDistributorCons = new ReplayDistributor(7, rtac);
//analysisInstance.addConsumer(rtDistributorCons);
analysisInstance.addConsumer(rtac);
/* Replays traces in real time */
analysisInstance.run();
/* Example that plots a dependency graph */
/* generate dependency diagram */
// Collection<ExecutionSequence> seqEnum = seqRepConsumer.getExecutionSequenceRepository().repository.values();
// DependencyGraphPlugin.writeDotFromExecutionTraces(seqEnum, inputDir+File.separator+"/dependencyGraph.dot");
// log.info("Wrote dependency graph to file " + inputDir+File.separator+"/dependencyGraph.dot");
log.info("Bye, this was SLAsticControl");
System.exit(0);
}
} |
package cn.cerc.mis.ado;
import java.lang.reflect.Field;
import javax.persistence.Column;
import cn.cerc.db.core.DataRow;
import cn.cerc.db.core.DataRowState;
import cn.cerc.db.core.DataSet;
import cn.cerc.db.core.FieldMeta;
import cn.cerc.db.core.FieldMeta.FieldKind;
import cn.cerc.db.core.IHandle;
import cn.cerc.db.core.SqlQuery;
import cn.cerc.db.core.SqlServer;
import cn.cerc.db.core.Utils;
import cn.cerc.db.mysql.MysqlDatabase;
import cn.cerc.mis.core.IService;
import cn.cerc.mis.core.ServiceState;
public abstract class AdoTable implements IService {
public DataSet execute(IHandle handle, DataSet dataIn) {
DataRow headIn = dataIn.head();
for (Field field : this.getClass().getDeclaredFields()) {
Search search = field.getAnnotation(Search.class);
if (search != null && !headIn.has(field.getName()))
return new DataSet().setMessage(field.getName() + " can not be null");
}
if (dataIn.crud()) {
SqlQuery query = buildQuery(handle);
query.setJson(dataIn.json());
query.setStorage(true);
for (FieldMeta meta : dataIn.fields())
meta.setKind(FieldKind.Storage);
query.operator().setTable(Utils.findTable(this.getClass()));
query.operator().setOid(Utils.findOid(this.getClass(), MysqlDatabase.DefaultOID));
saveDelete(dataIn, query);
saveUpdate(dataIn, query);
saveInsert(dataIn, query);
}
SqlQuery query = buildQuery(handle);
open(dataIn, query);
// meta
query.fields().readDefine(this.getClass());
query.setMeta(true);
return query.disableStorage().setState(ServiceState.OK);
}
private SqlQuery buildQuery(IHandle handle) {
SqlServer sqlServer = this.getClass().getAnnotation(SqlServer.class);
if (sqlServer == null)
throw new RuntimeException("unknow sql server");
return EntityQuery.buildQuery(handle, this.getClass());
}
protected AdoTable open(DataSet dataIn, SqlQuery query) {
DataRow headIn = dataIn.head();
query.add("select * from %s", this.table());
query.add("where 1=1");
dataIn.head().remove("_sql_");
for (FieldMeta meta : dataIn.head().getFields()) {
if (!headIn.has(meta.code())) {
continue;
}
String value = Utils.safeString(headIn.getString(meta.code())).trim();
if (value.endsWith("*"))
query.add("and %s like '%s%%'", meta.code(), value.substring(0, value.length() - 1));
else if (!"*".equals(value))
query.add("and %s='%s'", meta.code(), value);
}
query.open();
return this;
}
protected void saveInsert(DataSet dataIn, SqlQuery query) {
for (DataRow row : dataIn) {
if (DataRowState.Insert == row.state()) {
checkFieldsNull(row);
try {
query.insertStorage(row);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
}
protected void saveUpdate(DataSet dataIn, SqlQuery query) {
String uid = Utils.findOid(this.getClass(), query.operator().oid());
for (DataRow row : dataIn) {
if (DataRowState.Update == row.state()) {
DataRow history = row.history();
if (!query.locate(uid, history.getString(uid)))
throw new RuntimeException("update fail");
checkFieldsNull(row);
try {
query.updateStorage(row);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
}
protected void saveDelete(DataSet dataIn, SqlQuery query) {
for (DataRow row : dataIn.garbage()) {
try {
for (FieldMeta meta : row.fields())
meta.setKind(FieldKind.Storage);
query.deleteStorage(row);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
protected void checkFieldsNull(DataRow row) {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
Column column = field.getAnnotation(Column.class);
if (column != null) {
if (!column.nullable() && !row.has(field.getName()))
throw new RuntimeException(field.getName() + " can not be null");
}
}
}
public String table() {
return Utils.findTable(this.getClass());
}
/**
*
*
* @param handle IHandle
*/
public void insertTimestamp(IHandle handle) {
}
/**
*
*
* @param handle IHandle
*/
public void updateTimestamp(IHandle handle) {
}
} |
package org.conscrypt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ConscryptTest {
/**
* This confirms that the version machinery is working.
*/
@Test
public void testVersionIsSensible() {
Conscrypt.Version version = Conscrypt.version();
assertNotNull(version);
// The version object should be a singleton
assertSame(version, Conscrypt.version());
assertTrue("Major version: " + version.major(), 1 <= version.major());
assertTrue("Minor version: " + version.minor(), 0 <= version.minor());
assertTrue("Patch version: " + version.patch(), 0 <= version.patch());
}
} |
package org.jtrim2.build;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import org.gradle.api.JavaVersion;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.TaskContainer;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.api.tasks.compile.CompileOptions;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.api.tasks.testing.Test;
public final class JTrimJavaBasePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
try {
applyUnsafe(project);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void applyUnsafe(Project project) throws Exception {
ProjectUtils.applyPlugin(project, JTrimBasePlugin.class);
ProjectUtils.applyPlugin(project, "java");
configureJava(project);
setupTravis(project);
project.afterEvaluate(this::afterEvaluate);
}
private void afterEvaluate(Project project) {
// We are setting this, so the pom.xml will be generated properly
System.setProperty("line.separator", "\n");
}
private void configureJava(Project project) {
JavaPluginConvention java = ProjectUtils.java(project);
JavaVersion javaVersion = JavaVersion.toVersion(ProjectUtils.getDependencyFor(project, "java"));
java.setSourceCompatibility(javaVersion);
java.setTargetCompatibility(javaVersion);
TaskContainer tasks = project.getTasks();
tasks.withType(JavaCompile.class, (compile) -> {
CompileOptions options = compile.getOptions();
options.setEncoding("UTF-8");
options.setCompilerArgs(Arrays.asList("-Xlint"));
});
Jar sourcesJar = tasks.create("sourcesJar", Jar.class, (Jar jar) -> {
jar.dependsOn("classes");
jar.setDescription("Creates a jar from the source files.");
jar.setClassifier("sources");
jar.from(java.getSourceSets().getByName("main").getAllSource());
});
Jar javadocJar = tasks.create("javadocJar", Jar.class, (Jar jar) -> {
jar.dependsOn("javadoc");
jar.setDescription("Creates a jar from the JavaDoc.");
jar.setClassifier("javadoc");
jar.from(((Javadoc)tasks.getByName("javadoc")).getDestinationDir());
});
project.artifacts((artifacts) -> {
artifacts.add("archives", tasks.getByName("jar"));
artifacts.add("archives", sourcesJar);
artifacts.add("archives", javadocJar);
});
setDefaultDependencies(project);
}
private void setDefaultDependencies(Project project) {
DependencyHandler dependencies = project.getDependencies();
dependencies.add("testCompile", ProjectUtils.getDependencyFor(project, "junit"));
dependencies.add("testCompile", ProjectUtils.getDependencyFor(project, "mockito"));
}
private void setupTravis(Project project) {
if (!project.hasProperty("printTestErrorXmls")) {
return;
}
project.getGradle().projectsEvaluated((gradle) -> {
Test test = (Test)project.getTasks().getByName("test");
test.setIgnoreFailures(true);
test.doLast((task) -> {
int numberOfFailures = 0;
File destination = test.getReports().getJunitXml().getDestination();
for (File file: destination.listFiles()) {
String nameLowerCase = file.getName().toLowerCase(Locale.ROOT);
if (nameLowerCase.startsWith("test-") && nameLowerCase.endsWith(".xml")) {
if (printIfFailing(file)) {
numberOfFailures++;
}
}
}
if (numberOfFailures > 0) {
throw new RuntimeException("There were ${numberOfFailures} failing test classes.");
}
});
});
}
private boolean printIfFailing(File file) {
try {
String content = BuildFileUtils.readTextFile(file.toPath(), Charset.defaultCharset());
if (content.contains("</failure>")) {
System.out.println("Failing test " + file.getName() + ":\n" + content + "\n\n");
return true;
}
} catch (IOException ex) {
// ignore silently
}
return false;
}
} |
package org.bedework.util.xml.diff;
import org.bedework.util.misc.Util;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.namespace.QName;
public class NodeDiff {
public static class DiffNode {
final List<Node> pathTo;
final NodeWrapper left;
final NodeWrapper right;
/** Attempt to do a comparison of the structure pointed to by
* left and right.
*
* NOTE: this may be an incomplete comparison. At the moment the
* emphasis is on flagging inequalities and attempting to show
* where. It remains to be seen how well it codes with added and
* deleted nodes.
*
* @param pathTo the left and/or right
* @param left node or null if right was added
* @param right node or null if left was added
*/
public DiffNode(final List<Node> pathTo,
final NodeWrapper left,
final NodeWrapper right) {
this.pathTo = pathTo;
this.left = left;
this.right = right;
}
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Path: ");
if (Util.isEmpty(pathTo)) {
sb.append("<empty>");
} else {
String delim = "";
for (final Node n: pathTo) {
sb.append(delim);
delim = " -> ";
sb.append(new QName(n.getNamespaceURI(), n.getLocalName()));
}
}
sb.append("\n");
sb.append("left: ");
outNw(sb, left);
sb.append("right: ");
outNw(sb, right);
return sb.toString();
}
private void outNw(final StringBuilder sb,
final NodeWrapper nw) {
if (left == null) {
sb.append("null ");
return;
}
sb.append(nw.getName());
sb.append(" ");
if (nw.hasContent()) {
sb.append(nw.getContent());
sb.append(" ");
}
}
}
/**
*
* @param left node to compare
* @param right node to compare
* @return a list of differing nodes at or below left and right
*/
public static List<DiffNode> diff(final Node left,
final Node right) {
return diff(new ArrayList<>(0), left, right);
}
/**
*
* @param pathTo the left and right
* @param left node to compare
* @param right node to compare
* @return a list of differing nodes at or below left and right
*/
public static List<DiffNode> diff(final List<Node> pathTo,
final Node left,
final Node right) {
if (left == null) {
if (right != null) {
return Collections.singletonList(
new DiffNode(pathTo, null, new NodeWrapper(right)));
}
return Collections.emptyList();
}
if (right == null) {
return Collections.singletonList(
new DiffNode(pathTo, new NodeWrapper(left), null));
}
// Both non-null
return diff(Collections.emptyList(),
new NodeWrapper(left),
new NodeWrapper(right));
}
/**
*
* @param pathTo the left and right
* @param leftNw node to compare
* @param rightNw node to compare
* @return a list of differing nodes at or below left and right
*/
public static List<DiffNode> diff(final List<Node> pathTo,
final NodeWrapper leftNw,
final NodeWrapper rightNw) {
final List<DiffNode> result = new ArrayList<>();
if (leftNw.compareTo(rightNw) == 0) {
return result;
}
// Do shallow compare - compares content.
if (leftNw.shallowCompare(rightNw) != 0) {
result.add(new DiffNode(pathTo, leftNw, rightNw));
return result;
}
final List<Node> npathTo = new ArrayList<>(pathTo);
npathTo.add(leftNw.getNode());
// Children may differ
List<NodeWrapper> leftChildren = leftNw.getChildWrappers();
List<NodeWrapper> rightChildren = rightNw.getChildWrappers();
if (Util.isEmpty(leftChildren)) {
if (!Util.isEmpty(rightChildren)) {
for (final NodeWrapper nw: rightChildren) {
result.add(new DiffNode(npathTo, null, nw));
}
}
return result;
}
if (Util.isEmpty(rightChildren)) {
for (final NodeWrapper nw: leftChildren) {
result.add(new DiffNode(npathTo, nw, null));
}
return result;
}
int lefti = 0;
int righti = 0;
doDiff:
do {
final NodeWrapper lnw = leftChildren.get(lefti);
final NodeWrapper rnw = rightChildren.get(righti);
if (lnw.equals(rnw)) {
lefti++;
righti++;
continue doDiff;
}
// See if there is a subsequent node in the right that matches
final List<DiffNode> skipped = new ArrayList<>();
int testi = righti + 1;
while (testi < rightChildren.size()) {
final NodeWrapper testnw = rightChildren.get(testi);
int cmp = lnw.compareTo(testnw);
if (cmp == 0) {
result.addAll(skipped);
righti = testi;
continue doDiff;
}
if (cmp > 0) {
break;
}
skipped.addAll(diff(npathTo, lnw, testnw));
testi++;
}
// Didn't find any. Try the other side
skipped.clear();
testi = lefti + 1;
while (testi < leftChildren.size()) {
final NodeWrapper testnw = leftChildren.get(testi);
int cmp = rnw.compareTo(testnw);
if (cmp == 0) {
// Node and subtrees match
result.addAll(skipped);
lefti = testi;
continue doDiff;
}
if (cmp > 0) {
break;
}
skipped.addAll(diff(npathTo, testnw, rnw));
testi++;
}
// No match either side.
if (lnw.shallowCompare(rnw) != 0) {
result.add(new DiffNode(npathTo, lnw, rnw));
} else {
// Element itself matches - must be the children
skipped.addAll(diff(npathTo, lnw, rnw));
}
lefti++;
righti++;
} while ((lefti < leftChildren.size()) &&
(righti < rightChildren.size()));
return result;
}
} |
package com.lin.view;
import java.util.*;
import java.awt.Desktop;;
import java.text.SimpleDateFormat;
import java.awt.Rectangle;
import javax.swing.event.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.application.Application;
import javafx.event.*;
import javafx.event.EventHandler;
import static javafx.geometry.HPos.RIGHT;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.input.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.collections.*;
import javafx.stage.*;
import javafx.geometry.*;
import javafx.scene.Parent;
import javafx.fxml.*;
import java.util.regex.*;
import javafx.concurrent.*;
import javafx.scene.effect.BoxBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.io.*;
import com.lin.database.*;
import com.lin.model.*;
import com.lin.util.*;
import com.lin.view.*;
public class Main extends Application {
// database
private List<User> users;
private List<Email> emails;
private EmailClientDB emailClientDB;
private String[] boxName = {"", "", "", ""};
private final Desktop desktop = Desktop.getDesktop();
private Scene scene;
// root node
private VBox vBox;
// menu node
private MenuBar menuBar;
private Menu setupMenu;
private CheckMenuItem onlyDownloadTop;
// recv menu
private Menu recvMenu;
private MenuItem allMailboxs;
private MenuItem specificMailbox;
// send menu
private Menu sendMenu;
private MenuItem commonMenuItem;
private MenuItem htmlMenuItem;
// split node
private SplitPane splitPane;
// user pane
private VBox userBox;
private TreeView<String> treeView;
private TreeItem<String> rootNode;
// email pane
private VBox emailBox;
private ListView<Email> listView;
private ObservableList<Email> listData;
// content pane
private VBox contentBox;
private HBox topBox;
private Label subjectLabel;
private HBox attachmentBox;
private Label attachmentLabel;
private Separator separator1;
private GridPane gridPane;
private Label fromLabel;
private Label fromText;
private Label toLabel;
private Label toText;
private Label ccLabel;
private Label ccText;
private Label dateLabel;
private Label dateText;
private Separator separator2;
private Label contentLabel;
private Separator separator3;
private HBox refwBox;
private Button reButton;
private Button fwButton;
private HBox attachmentsBox;
@Override
public void start(Stage primaryStage) {
initEmailClientDB(primaryStage);
initComponents(primaryStage);
initEvents(primaryStage);
}
private void initEmailClientDB(Stage primaryStage) {
try {
Class.forName("org.sqlite.JDBC");
} catch (Exception e) {
e.printStackTrace();
}
emailClientDB = EmailClientDB.getInstance();
users = emailClientDB.loadUsers();
emails = new ArrayList<> ();
listData = FXCollections.observableArrayList(emails);
}
private void initComponents(Stage primaryStage) {
// * root pane
vBox = new VBox();
// ** menu pane
menuBar = new MenuBar();
setupMenu = new Menu("");
onlyDownloadTop = new CheckMenuItem("");
setupMenu.getItems().addAll(onlyDownloadTop);
recvMenu = new Menu("");
allMailboxs = new MenuItem("");
specificMailbox = new MenuItem("");
recvMenu.getItems().addAll(allMailboxs, specificMailbox);
sendMenu = new Menu("");
commonMenuItem = new MenuItem("");
htmlMenuItem = new MenuItem("HTML");
sendMenu.getItems().addAll(commonMenuItem, htmlMenuItem);
menuBar.getMenus().addAll(setupMenu, recvMenu, sendMenu);
// ** split pane
splitPane = new SplitPane();
splitPane.setDividerPositions(0.25, 0.5);
userBox = new VBox();
rootNode = new TreeItem<> ("user@example.com");
rootNode.setExpanded(true);
for (User u : users) {
TreeItem<String> userNode = new TreeItem<> (u.getEmail_addr());
for(String s : boxName) {
Image image = new Image(getClass().getResourceAsStream(s + ".png"));
TreeItem<String> boxleaf = new TreeItem<> (s, new ImageView(image));
userNode.getChildren().add(boxleaf);
}
rootNode.getChildren().add(userNode);
}
treeView = new TreeView<> (rootNode);
treeView.setShowRoot(false);
VBox.setVgrow(treeView, Priority.ALWAYS);
userBox.getChildren().add(treeView);
emailBox = new VBox();
listView = new ListView<> ();
listView.setItems(listData);
listView.setCellFactory((ListView<Email> l) -> new MyListCell());
VBox.setVgrow(listView, Priority.ALWAYS);
emailBox.getChildren().add(listView);
contentBox = new VBox();
contentBox.setSpacing(8);
contentBox.setPadding(new Insets(8, 8, 8, 8));
topBox = new HBox();
subjectLabel = new Label("");
subjectLabel.setWrapText(true);
subjectLabel.setFont(new Font("Arial", 24));
topBox.getChildren().add(subjectLabel);
attachmentBox = new HBox();
attachmentBox.setAlignment(Pos.BOTTOM_RIGHT);
Image attachmentImage = new Image(getClass().getResourceAsStream(".png"));
attachmentLabel = new Label("", new ImageView(attachmentImage));
attachmentLabel.setWrapText(true);
attachmentLabel.setFont(new Font("Arial", 18));
attachmentBox.getChildren().add(attachmentLabel);
attachmentBox.setVisible(false);
HBox.setHgrow(attachmentBox, Priority.ALWAYS);
topBox.getChildren().add(attachmentBox);
contentBox.getChildren().add(topBox);
separator1 = new Separator();
contentBox.getChildren().add(separator1);
gridPane = new GridPane();
gridPane.setVgap(8);
fromLabel = new Label(": ");
fromLabel.setAlignment(Pos.TOP_LEFT);
fromLabel.setTextFill(Color.DARKGRAY);
GridPane.setConstraints(fromLabel, 0, 0);
fromText = new Label("1780615543@qq.com");
GridPane.setConstraints(fromText, 1, 0);
toLabel = new Label(": ");
toLabel.setAlignment(Pos.TOP_LEFT);
toLabel.setTextFill(Color.DARKGRAY);
GridPane.setConstraints(toLabel, 0, 1);
toText = new Label("abc_2020@sohu.com");
toText.setWrapText(true);
GridPane.setConstraints(toText, 1, 1);
ccLabel = new Label(": ");
ccLabel.setAlignment(Pos.TOP_LEFT);
ccLabel.setTextFill(Color.DARKGRAY);
GridPane.setConstraints(ccLabel, 0, 2);
ccText = new Label("15172323141@163.com");
ccText.setWrapText(true);
GridPane.setConstraints(ccText, 1, 2);
dateLabel = new Label(": ");
dateLabel.setTextFill(Color.DARKGRAY);
GridPane.setConstraints(dateLabel, 0, 3);
dateText = new Label("2017417 19:55");
GridPane.setConstraints(dateText, 1, 3);
gridPane.getChildren().addAll(fromLabel, fromText, toLabel, toText, ccLabel, ccText, dateLabel, dateText);
contentBox.getChildren().add(gridPane);
separator2 = new Separator();
contentBox.getChildren().add(separator2);
contentLabel = new Label("");
contentLabel.setWrapText(true);
contentLabel.setPadding(new Insets(0, 0, 8, 8));
contentBox.getChildren().add(contentLabel);
separator3 = new Separator();
contentBox.getChildren().add(separator3);
refwBox = new HBox();
refwBox.setSpacing(8);
refwBox.setAlignment(Pos.BOTTOM_RIGHT);
reButton = new Button("");
fwButton = new Button("");
refwBox.getChildren().addAll(reButton, fwButton);
contentBox.getChildren().add(refwBox);
// attachments box
attachmentsBox = new HBox();
attachmentsBox.setPadding(new Insets(8, 8, 8, 8));
attachmentsBox.setSpacing(12);
attachmentsBox.setAlignment(Pos.BOTTOM_LEFT);
attachmentsBox.setVisible(false);
VBox.setVgrow(attachmentsBox, Priority.ALWAYS);
contentBox.getChildren().add(attachmentsBox);
contentBox.setVisible(false);
splitPane.getItems().addAll(userBox, emailBox, contentBox);
VBox.setVgrow(splitPane, Priority.ALWAYS);
// add menuBar and splitPane to root pane
vBox.getChildren().addAll(menuBar, splitPane);
// add root pane to scene
scene = new Scene(vBox, 900, 600);
// set and show primary stage
primaryStage.setTitle("Email Client");
primaryStage.setScene(scene);
if (users.isEmpty()) {
new UserEdit(primaryStage, treeView, rootNode);
} else {
primaryStage.show();
}
}
private void initEvents(Stage primaryStage) {
allMailboxs.setOnAction((ActionEvent t)->{
LogUtil.i("allMailboxs has been click");
if(users.isEmpty()) {
return ;
}
ProgressDialog progressDialog = new ProgressDialog("");
Task<Void> progressTask = new Task<Void>(){
@Override
protected void succeeded() {
super.succeeded();
progressDialog.getCancelButton().setText("");
}
@Override
protected Void call() throws Exception {
users = emailClientDB.loadUsers();
for (User u : users) {
PopUtil.retrEmails(u, onlyDownloadTop.isSelected(), new PopCallbackListener() {
@Override
public void onConnect() {
LogUtil.i("on connect");
updateProgress(ProgressIndicator.INDETERMINATE_PROGRESS, ProgressIndicator.INDETERMINATE_PROGRESS);
updateTitle("");
updateMessage(u.getEmail_addr());
}
@Override
public void onCheck() {
LogUtil.i("on check");
updateTitle("");
updateMessage(u.getEmail_addr());
}
@Override
public void onDownLoad(long total_email_size, long download_email_size,
int total_email_count, int download_email_count,
long current_email_size, long current_download_size) {
LogUtil.i("on download");
if (onlyDownloadTop.isSelected()) {
updateProgress(download_email_size, total_email_size);
updateTitle("");
updateMessage(u.getEmail_addr() + " : " + total_email_count + " : " + download_email_count);
} else {
updateProgress(download_email_size, total_email_size);
updateTitle("");
updateMessage(u.getEmail_addr() + " : " + total_email_count + " : " + download_email_count);
}
}
@Override
public void onFinish() {
LogUtil.i("on finish");
updateProgress(100, 100);
updateTitle("");
}
@Override
public void onError() {
LogUtil.i("on error");
updateTitle("");
}
@Override
public boolean onCancel() {
LogUtil.i("on cancel");
updateTitle("");
return progressDialog.getCancel();
}
});
}
return null;
}
};
progressDialog.getProgress().progressProperty().bind(progressTask.progressProperty());
progressDialog.getMessageLabel().textProperty().bind(progressTask.messageProperty());
progressDialog.getTitleLabel().textProperty().bind(progressTask.titleProperty());
new Thread(progressTask).start();
});
specificMailbox.setOnAction((ActionEvent t)->{
LogUtil.i("specificMailbox has been click");
List<User> users = emailClientDB.loadUsers();
if (!users.isEmpty()) {
final ContextMenu contextMenu = new ContextMenu();
for (User u : users) {
MenuItem item = new MenuItem(u.getEmail_addr());
item.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
ProgressDialog progressDialog = new ProgressDialog(u.getEmail_addr());
Task<Void> progressTask = new Task<Void>(){
@Override
protected void succeeded() {
super.succeeded();
progressDialog.getCancelButton().setText("");
}
@Override
protected Void call() throws Exception {
PopUtil.retrEmails(u, onlyDownloadTop.isSelected(), new PopCallbackListener() {
@Override
public void onConnect() {
LogUtil.i("on connect");
updateTitle("");
updateMessage("");
}
@Override
public void onCheck() {
LogUtil.i("on check");
updateTitle("");
updateMessage("");
}
@Override
public void onDownLoad(long total_email_size, long download_email_size,
int total_email_count, int download_email_count,
long current_email_size, long current_download_size) {
LogUtil.i("on download");
if (onlyDownloadTop.isSelected()) {
updateProgress(download_email_count, total_email_count);
updateTitle("");
updateMessage(": " + total_email_count + " : " + download_email_count);
} else {
updateProgress(download_email_size, total_email_size);
updateTitle("");
updateMessage(": " + total_email_count + " : " + download_email_count);
}
}
@Override
public void onFinish() {
LogUtil.i("on finish");
updateProgress(100, 100);
updateTitle("");
}
@Override
public void onError() {
LogUtil.i("on error");
updateTitle("");
}
@Override
public boolean onCancel() {
LogUtil.i("on cancel");
updateTitle("");
return progressDialog.getCancel();
}
});
return null;
}
};
progressDialog.getProgress().progressProperty().bind(progressTask.progressProperty());
progressDialog.getMessageLabel().textProperty().bind(progressTask.messageProperty());
progressDialog.getTitleLabel().textProperty().bind(progressTask.titleProperty());
new Thread(progressTask).start();
}
});
contextMenu.getItems().add(item);
}
contextMenu.show(menuBar, primaryStage.getX() + 60, primaryStage.getY() + menuBar.getScene().getY() + menuBar.localToScene(0, 0).getX() + menuBar.getHeight());
contextMenu.setAutoHide(true);
}
});
// txt
commonMenuItem.setOnAction((ActionEvent t)->{
LogUtil.i("commonMenuItem has been click");
if(users.isEmpty()) {
return ;
}
SimpleDateFormat df = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
LogUtil.i(df.format(new Date()));// new Date()
new EmailEdit(df.format(new Date()).toString(), "txt");
});
// html
htmlMenuItem.setOnAction((ActionEvent t)->{
LogUtil.i("htmlMenuItem has been click");
if(users.isEmpty()) {
return ;
}
SimpleDateFormat df = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
LogUtil.i(df.format(new Date()));// new Date()
new EmailEdit(df.format(new Date()).toString(), "html");
});
treeView.setOnMouseClicked((MouseEvent me)->{
if (me.getButton() == MouseButton.SECONDARY) {
LogUtil.i("Mouse Click");
final ContextMenu contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("");
item1.setOnAction((ActionEvent ae)->{
if (treeView.getSelectionModel().getSelectedItem() == null) {
return;
}
String email_regex = "\\w+(\\.\\w+)*@(\\w)+((\\.\\w+)+)";
String treeItemValue = treeView.getSelectionModel().getSelectedItem().getValue();
Pattern p = Pattern.compile(email_regex);
Matcher m = p.matcher(treeItemValue);
if (m == null) {
return ;
}
if (!m.find()) {
LogUtil.i("Click box");
treeItemValue = treeView.getSelectionModel().getSelectedItem().getParent().getValue();
}
users = emailClientDB.loadUsers();
User user = null;
for (User u : users) {
if (u.getEmail_addr().equals(treeItemValue)) {
user = u;
break;
}
}
if (user == null) {
LogUtil.i("can't find user");
} else {
emailClientDB.deleteUser(user);
users = emailClientDB.loadUsers();
rootNode = new TreeItem<> ("user@example.com");
rootNode.setExpanded(true);
for (User u : users) {
TreeItem<String> userNode = new TreeItem<> (u.getEmail_addr());
for(String s : boxName) {
Image image = new Image(getClass().getResourceAsStream(s + ".png"));
TreeItem<String> boxleaf = new TreeItem<> (s, new ImageView(image));
userNode.getChildren().add(boxleaf);
}
rootNode.getChildren().add(userNode);
}
treeView.setRoot(rootNode);
}
});
MenuItem item2 = new MenuItem("");
item2.setOnAction((ActionEvent ae)->{
new UserEdit(primaryStage, treeView, rootNode);
});
contextMenu.getItems().addAll(item1, item2);
contextMenu.show(menuBar, me.getScreenX(), me.getScreenY());
contextMenu.setAutoHide(true);
} else {
if (treeView.getSelectionModel().getSelectedItem() == null) {
return ;
}
emails = new ArrayList<Email>();
String email_regex = "\\w+(\\.\\w+)*@(\\w)+((\\.\\w+)+)";
String treeItemValue = treeView.getSelectionModel().getSelectedItem().getValue();
Pattern p = Pattern.compile(email_regex);
Matcher m = p.matcher(treeItemValue);
if (m == null) {
return ;
}
if (!m.find()) {
LogUtil.i("Click box");
User user = null;
String treeNodeValue = treeView.getSelectionModel().getSelectedItem().getParent().getValue();
users = emailClientDB.loadUsers();
for (User u : users) {
if (u.getEmail_addr().equals(treeNodeValue)) {
user = u;
break;
}
}
if (user == null) {
LogUtil.i("can't find user");
} else {
LogUtil.i("find user");
emails = emailClientDB.loadEmails(user.getId(), treeItemValue);
}
}
Collections.sort(emails, new Comparator<Email>() {
public int compare(Email email0, Email email1) {
SimpleDateFormat df_old = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
SimpleDateFormat df_new = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
String d0 = null;
String d1 = null;
try {
d0 = df_new.format(df_old.parse(email0.getDate()));
d1 = df_new.format(df_old.parse(email1.getDate()));
} catch (Exception e) {
e.printStackTrace();
}
return d1.compareTo(d0);
}
});
listData = FXCollections.observableArrayList(emails);
listView.setItems(listData);
listView.setCellFactory((ListView<Email> l) -> new MyListCell());
contentBox.setVisible(false);
}
});
listView.getSelectionModel().selectedItemProperty().addListener(
(ObservableValue<? extends Email> ov, Email old_val, Email new_val) -> {
LogUtil.i("happen");
Email email = listView.getSelectionModel().getSelectedItem();
if (email == null) {
return ;
}
if (email.getContent().equals("onlyDownloadTop")) {
for (User user : users) {
if (user.getId() == email.getUserid()) {
LogUtil.i("download email detail");
ProgressDialog progressDialog = new ProgressDialog(email.getSubject());
Task<Void> progressTask = new Task<Void>(){
@Override
protected void succeeded() {
super.succeeded();
progressDialog.getCancelButton().setText("");
if (email.getAttachment_num() != 0) {
attachmentLabel.setText("" + email.getAttachment_num());
String attachments_path = "C:\\SimpleEmailClient\\attachments\\";
for (String s : email.getAttachment_list()) {
Image image = new Image(getClass().getResourceAsStream("_2.png"));
Label label = new Label(s, new ImageView(image));
label.setFont(new Font("Arial", 14));
label.setOnMouseClicked((MouseEvent me)->{
File file = new File(attachments_path + s);
if (file != null) {
try {
desktop.open(file);
} catch (Exception e) {
new CommonDialog("", "");
e.printStackTrace();
}
} else {
new CommonDialog("", "");
}
});
attachmentsBox.getChildren().add(label);
}
}
contentLabel.setText(email.getContent());
}
@Override
protected Void call() throws Exception {
PopUtil.sendRetrRequest(user, email, new PopCallbackListener() {
@Override
public void onConnect() {
LogUtil.i("on connect");
updateTitle("");
updateMessage("");
}
@Override
public void onCheck() {
LogUtil.i("on check");
updateTitle("");
updateMessage("");
}
@Override
public void onDownLoad(long total_email_size, long download_email_size,
int total_email_count, int download_email_count,
long current_email_size, long current_download_size) {
LogUtil.i("on download");
updateProgress(current_download_size, current_email_size);
updateTitle("");
if (current_email_size > 1024) {
updateMessage(": " + current_email_size / (1024) + "KB : " + current_download_size / (1024) + "KB");
} else {
updateMessage(": " + current_email_size + "B : " + current_download_size + "B");
}
}
@Override
public void onFinish() {
LogUtil.i("on finish");
updateProgress(100, 100);
updateTitle("");
}
@Override
public void onError() {
LogUtil.i("on error");
updateTitle("");
}
@Override
public boolean onCancel() {
LogUtil.i("on cancel");
updateTitle("");
return progressDialog.getCancel();
}
});
return null;
}
};
progressDialog.getProgress().progressProperty().bind(progressTask.progressProperty());
progressDialog.getMessageLabel().textProperty().bind(progressTask.messageProperty());
progressDialog.getTitleLabel().textProperty().bind(progressTask.titleProperty());
new Thread(progressTask).start();
}
}
}
subjectLabel.setText(email.getSubject());
fromText.setText(email.getFrom());
if (email.getAttachment_num() != 0) {
if (email.getAttachment_num() == -1) {
attachmentLabel.setText("");
} else {
attachmentLabel.setText("" + email.getAttachment_num());
}
attachmentBox.setVisible(true);
contentBox.getChildren().remove(attachmentsBox);
attachmentsBox = new HBox();
attachmentsBox.setPadding(new Insets(8, 8, 8, 8));
attachmentsBox.setSpacing(12);
attachmentsBox.setAlignment(Pos.BOTTOM_LEFT);
attachmentsBox.setVisible(false);
VBox.setVgrow(attachmentsBox, Priority.ALWAYS);
contentBox.getChildren().add(attachmentsBox);
attachmentsBox.setVisible(true);
String attachments_path = "C:\\SimpleEmailClient\\attachments\\";
for (String s : email.getAttachment_list()) {
Image image = new Image(getClass().getResourceAsStream("_2.png"));
Label label = new Label(s, new ImageView(image));
label.setFont(new Font("Arial", 14));
label.setOnMouseClicked((MouseEvent me)->{
File file = new File(attachments_path + s);
if (file != null) {
try {
desktop.open(file);
} catch (Exception e) {
new CommonDialog("", "");
e.printStackTrace();
}
} else {
new CommonDialog("", "");
}
});
attachmentsBox.getChildren().add(label);
}
} else {
attachmentLabel.setText("");
attachmentBox.setVisible(false);
attachmentsBox.setVisible(false);
}
String to = "";
for (String s : email.getTo_list()) {
to += s + ";";
}
toText.setText(to);
String cc = "";
for (String s : email.getCc_list()) {
cc += s + ";";
}
ccText.setText(cc);
String date = "";
SimpleDateFormat df_old = new SimpleDateFormat("EE, dd MMM yyyy kk:mm:ss Z", Locale.US);
SimpleDateFormat df_new = new SimpleDateFormat("yyyyMMdd kk:mm", Locale.US);
try {
date = df_new.format(df_old.parse(email.getDate()));
} catch (Exception e) {
e.printStackTrace();
}
dateText.setText(date);
contentLabel.setText(email.getContent());
contentBox.setVisible(true);
});
listView.setOnMouseClicked((MouseEvent me)->{
if (me.getButton() == MouseButton.SECONDARY) {
LogUtil.i("Mouse Click");
final ContextMenu contextMenu = new ContextMenu();
MenuItem item1 = new MenuItem("");
item1.setOnAction((ActionEvent ae)->{
Email email = listView.getSelectionModel().getSelectedItem();
listData.remove(email);
listView.setItems(listData);
listView.setCellFactory((ListView<Email> l) -> new MyListCell());
emailClientDB.deleteEmail(email);
LogUtil.i("");
contentBox.setVisible(false);
});
MenuItem item2 = new MenuItem("");
item2.setOnAction((ActionEvent ae)->{
Email email = listView.getSelectionModel().getSelectedItem();
for (User user : users) {
if (user.getId() == email.getUserid()) {
PopUtil.sendDeleRequest(user, email);
}
}
listData.remove(email);
listView.setItems(listData);
listView.setCellFactory((ListView<Email> l) -> new MyListCell());
emailClientDB.deleteEmail(email);
LogUtil.i("");
contentBox.setVisible(false);
});
MenuItem item3 = new MenuItem("");
item3.setOnAction((ActionEvent ae)->{
Email email = listView.getSelectionModel().getSelectedItem();
listData.remove(email);
listView.setItems(listData);
listView.setCellFactory((ListView<Email> l) -> new MyListCell());
emailClientDB.deleteEmail(email);
email.setInbox("");
emailClientDB.insertEmail(email);
LogUtil.i("");
contentBox.setVisible(false);
});
contextMenu.getItems().addAll(item1, item2, item3);
contextMenu.show(menuBar, me.getScreenX(), me.getScreenY());
contextMenu.setAutoHide(true);
}
});
reButton.setOnAction((ActionEvent ae)->{
SimpleDateFormat df = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
LogUtil.i(df.format(new Date()));// new Date()
Email email = listView.getSelectionModel().getSelectedItem();
new EmailEdit(df.format(new Date()).toString(), email, ": ", "txt");
});
fwButton.setOnAction((ActionEvent ae)->{
SimpleDateFormat df = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
LogUtil.i(df.format(new Date()));// new Date()
Email email = listView.getSelectionModel().getSelectedItem();
new EmailEdit(df.format(new Date()).toString(), email, ": ", "txt");
});
attachmentLabel.setOnMouseClicked((MouseEvent me)->{
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
String attachments_name = "C:\\SimpleEmailClient\\attachments";
fileChooser.setInitialDirectory(new File(attachments_name));
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) {
try {
desktop.open(selectedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
class MyListCell extends ListCell<Email> {
@Override
public void updateItem(Email item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
SimpleDateFormat df_old = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US);
SimpleDateFormat df_new = new SimpleDateFormat("MM-dd", Locale.US);
String from = item.getFrom();
String date = item.getDate();
String subject = item.getSubject();
from = from.split("@")[0];
try {
date = df_new.format(df_old.parse(item.getDate()));
} catch (Exception e) {
e.printStackTrace();
}
VBox root = new VBox();
root.setSpacing(4);
HBox hbox = new HBox();
Label fromLabel = new Label(from);
if (item.getAttachment_num() != 0) {
Image image = new Image(getClass().getResourceAsStream("_1.png"));
fromLabel.setGraphic(new ImageView(image));
fromLabel.setContentDisplay(ContentDisplay.RIGHT);
}
// fromLabel.setFont(new Font("System Bold", 16));
fromLabel.setFont(new Font("Lucida Bright Demibold Italic", 16));
fromLabel.setPrefWidth(140);
Label dateLabel = new Label(date);
dateLabel.setFont(new Font(16));
dateLabel.setPrefWidth(80);
hbox.getChildren().addAll(fromLabel, dateLabel);
Label subjectLabel = new Label(subject);
subjectLabel.setFont(new Font(14));
root.getChildren().add(hbox);
root.getChildren().add(subjectLabel);
setGraphic(root);
}
}
}
} |
package ch.openech.mj.edit;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import ch.openech.mj.autofill.DemoEnabled;
import ch.openech.mj.edit.form.IForm;
import ch.openech.mj.edit.validation.Indicator;
import ch.openech.mj.edit.validation.Validatable;
import ch.openech.mj.edit.validation.ValidationMessage;
import ch.openech.mj.edit.value.CloneHelper;
import ch.openech.mj.page.PageContext;
import ch.openech.mj.resources.ResourceAction;
import ch.openech.mj.resources.Resources;
import ch.openech.mj.toolkit.ClientToolkit;
import ch.openech.mj.toolkit.ConfirmDialogListener;
/**
* An <code>Editor</code> knows
* <UL>
* <LI>How to build the FormPanel containing FormField s
* <LI>How to load an Object
* <LI>How to validate the object
* <LI>How to save the object
* <LI>What additional Actions the Editor provides
* <LI>Its name (for Window Title oder Tab Title)
* </UL>
* @startuml
* [*] --> Started: start
* Started: Form is created
* CheckClose: User is asked if he\nbreally wants to cancel
* Finished: Form is null again
* Started --> CheckClose : cancel or\nclose Window
* CheckClose --> Started : cancel\naborted
* CheckClose --> Finished : cancel confirmed
* Finished --> Started : restart
* Started --> Save : save
* Save --> Finished : save
*
* @enduml
*
* @startuml sequence_editor.png
* == Starting ==
* EditorPage -> Editor: start
* Editor -> SpecificEditor: create Form
* Editor -> SpecificEditor: load or create Object
* Editor -> Form: set Object to Form
* == Editing ==
* Form -> Editor: fire change
* Editor -> Object: set value of Field
* Editor -> SpecificEditor: validate
* Editor -> Form: validate
* Editor -> Object: validate
* Editor -> Form: indicate
* Editor -> EditorPage: indicate
* == Finishing ==
* Editor -> SpecificEditor: save
* Editor -> EditorPage: fire finished
* @enduml
* @author Bruno
*
* @param <T>
* Class of the edited Object
*/
public abstract class Editor<T> {
private T original;
private IForm<T> form;
private SaveAction saveAction;
private EditorFinishedListener editorFinishedListener;
private Indicator indicator;
private boolean saveable = true;
private boolean userEdited;
private String followLink;
protected PageContext context;
// what to implement
protected abstract IForm<T> createForm();
/**
* Should load the object to be edited. Note: The object will be copied before
* changed by the editor
*
* @return null if newInstance() should be used
*/
protected T load() {
return null;
}
/**
* Override this method for a validation specific for this editor.
* (Implement Validatable on the object itself for a general validation
* on the object)
*
* @param object
* @param resultList
*/
protected void validate(T object, List<ValidationMessage> resultList){
// to be overwritten
}
protected abstract boolean save(T object) throws Exception;
protected boolean isSaveSynchron() {
return true;
}
public String getTitle() {
String resourceName = getClass().getSimpleName() + ".text";
return Resources.getString(resourceName);
}
public Action[] getActions() {
return new Action[] { cancelAction(), saveAction() };
}
protected Editor() {
}
public IForm<T> startEditor(PageContext context) {
if (form != null) {
throw new IllegalStateException();
}
this.context = context;
form = createForm();
original = load();
if (original != null) {
T copy = CloneHelper.clone(original);
form.setObject(copy);
} else {
T newInstance = newInstance();
form.setObject(newInstance);
}
form.setSaveAction(saveAction());
userEdited = false;
form.setChangeListener(new EditorChangeListener());
return form;
}
/**
* Override this method to preset values for the editor
*
* @return The object this editor should edit.
*/
protected T newInstance() {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) ch.openech.mj.util.GenericUtils.getGenericClass(Editor.this.getClass());
T newInstance = CloneHelper.newInstance(clazz);
return newInstance;
}
public final void setEditorFinishedListener(EditorFinishedListener editorFinishedListener) {
this.editorFinishedListener = editorFinishedListener;
}
public final void setIndicator(Indicator indicator) {
this.indicator = indicator;
}
/**
*
* Disposes the editor and calls the editorFinished Listener
*/
protected void finish() {
fireEditorFinished();
form = null;
}
public final boolean isFinished() {
return form == null;
}
private void fireEditorFinished() {
if (editorFinishedListener != null) {
editorFinishedListener.finished(followLink);
}
}
protected final void setFollowLink(String followLink) {
this.followLink = followLink;
}
protected final T getObject() {
return form.getObject();
}
protected final void save() {
if (saveable) {
if (isSaveSynchron()) {
doSave();
} else {
progress(0, 100);
new Thread(new Runnable() {
@Override
public void run() {
doSave();
}
}).start();
}
} else {
ClientToolkit.getToolkit().showNotification(form.getComponent(), "Abschluss nicht möglich.\n\nBitte Eingaben überprüfen.");
}
}
private void doSave() {
try {
T objectToSave;
if (original != null) {
objectToSave = original;
CloneHelper.deepCopy(getObject(), original);
} else {
objectToSave = getObject();
}
if (save(objectToSave)) {
finish();
}
} catch (Exception x) {
ClientToolkit.getToolkit().showNotification(form.getComponent(), "Abschluss fehlgeschlagen\n\n" + x.getLocalizedMessage());
}
}
public final void progress(int value, int maximum) {
if (editorFinishedListener != null) {
editorFinishedListener.progress(value, maximum);
}
}
private class EditorChangeListener implements ChangeListener {
public EditorChangeListener() {
update(getObject());
}
@Override
public void stateChanged(ChangeEvent e) {
userEdited = true;
update(getObject());
}
}
private void update(T object) {
List<ValidationMessage> validationResult = validate(object);
indicate(validationResult);
}
private List<ValidationMessage> validate(T object) {
List<ValidationMessage> validationResult = new ArrayList<ValidationMessage>();
if (object instanceof Validatable) {
Validatable validatable = (Validatable) object;
validatable.validate(validationResult);
}
form.validate(validationResult);
validate(object, validationResult);
return validationResult;
}
final void indicate(List<ValidationMessage> validationResult) {
saveable = validationResult.isEmpty();
form.setValidationMessages(validationResult);
saveAction.setValidationMessages(validationResult);
if (indicator != null) {
indicator.setValidationMessages(validationResult);
}
}
protected final boolean isSaveable() {
return saveable;
}
public final void checkedClose() {
if (!userEdited) {
finish();
} else if (isSaveable()) {
ConfirmDialogListener listener = new ConfirmDialogListener() {
@Override
public void onClose(int answer) {
if (answer == JOptionPane.YES_OPTION) {
// finish will be called at the end of save
save();
} else if (answer == JOptionPane.NO_OPTION) {
finish();
} else { // Cancel or Close
// do nothing
}
}
};
ClientToolkit.getToolkit().showConfirmDialog(form.getComponent(), "Sollen die aktuellen Eingaben gespeichert werden?", "Schliessen",
JOptionPane.YES_NO_CANCEL_OPTION, listener);
} else {
ConfirmDialogListener listener = new ConfirmDialogListener() {
@Override
public void onClose(int answer) {
if (answer == JOptionPane.YES_OPTION) {
finish();
} else { // No or Close
// do nothing
}
}
};
ClientToolkit.getToolkit().showConfirmDialog(form.getComponent(), "Die momentanen Eingaben sind nicht gültig\nund können daher nicht gespeichert werden.\n\nSollen sie verworfen werden?",
"Schliessen", JOptionPane.YES_NO_OPTION, listener);
}
}
protected final Action saveAction() {
if (saveAction == null) {
saveAction = new SaveAction("OkAction") {
@Override
public void actionPerformed(ActionEvent e) {
save();
}
};
}
return saveAction;
}
protected final Action cancelAction() {
return new ResourceAction("CancelAction") {
@Override
public void actionPerformed(ActionEvent e) {
finish();
}
};
}
protected final Action demoAction() {
return new ResourceAction("FillWithDemoDataAction") {
@Override
public void actionPerformed(ActionEvent e) {
fillWithDemoData();
}
};
}
public interface EditorFinishedListener {
public void progress(int value, int maximum);
public void finished(String followLink);
}
public void fillWithDemoData() {
if (form instanceof DemoEnabled) {
((DemoEnabled) form).fillWithDemoData();
}
}
} |
package rand;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public abstract class DataProvider<T> implements StreamStrategy {
protected final DataProducer<T> producer;
protected final RandomizerContext context;
private final int dataSize;
// Use LinkedHashMap to keep the original ordering.
private final LinkedHashMap<Integer, T> pointerMap;
/**
* Constructs a new random data provider with no registered data using the
* given data producer.
*
* @param context The randomizer context constructing this provider.
* @param producer The producer to use.
*/
public DataProvider(RandomizerContext context, DataProducer<T> producer) {
this.producer = producer;
this.context = context;
this.dataSize = producer.getDataSize();
this.pointerMap = new LinkedHashMap<>();
}
/**
* Registers a new data entry in the given byte stream at its current
* position, if it was not registered already.
*
* @param stream The byte stream to read from.
*/
protected final void registerData(ByteStream stream) {
int pointer = stream.getRealPosition();
if (this.pointerMap.containsKey(pointer) && dataSize > 0) {
stream.advance(this.producer.getDataSize());
} else {
T data = this.producer.readFromStream(stream);
this.context.status("Registered " + this.producer.getDataName() + " at "
+ "0x" + String.format("%06X", pointer));
this.pointerMap.put(pointer, data);
}
}
/**
* Randomizes all registered data with the given random number generator.
*
* @param rng The random number generator to use.
*/
public void randomize(Random rng) {
for (Map.Entry<Integer, T> entry : this.pointerMap.entrySet()) {
T data = entry.getValue();
randomizeData(rng, data, entry.getKey());
entry.setValue(data);
}
}
/**
* Randomizes the given data entry.
*
* @param rng The random number generator to use.
* @param data The data to randomize.
* @param position The position of the data to randomize.
*/
protected abstract void randomizeData(Random rng, T data, int position);
/**
* Writes all registered data to the given byte stream.
*
* @param stream The byte stream to write to.
*/
public void produce(ByteStream stream) {
for (Map.Entry<Integer, T> entry : this.pointerMap.entrySet()) {
stream.setRealPosition(entry.getKey());
produceData(stream, entry.getValue());
}
}
/**
* Writes the given data entry to the given byte stream.
*
* @param stream The byte stream to write to.
* @param data The data to write.
*/
protected void produceData(ByteStream stream, T data) {
this.producer.writeToStream(stream, data);
}
/**
* Gets all registered data.
*
* @return The collection of data.
*/
public List<T> allData() {
return new ArrayList<>(this.pointerMap.values());
}
/**
* Clears all registered data.
*/
public void clear() {
this.pointerMap.clear();
}
/**
* Reads data from the given byte stream and registers it.
*
* @param stream The ROM to read from.
*/
@Override
public void execute(ByteStream stream) {
registerData(stream);
}
} |
import sdljava.event.*;
public class GameStateCredits implements GameState
{
private Font font;
private boolean[] keys;
private int scroll;
private boolean doScroll;
private int scrollTimer;
private int lineHeight;
public void loadState()
{
scroll = 0;
scrollTimer = 0;
lineHeight = 0;
font = new Font("./data/gfx/font1.bmp", 7, 10, 1, 4);
keys = new boolean[6]; // left, right, up, down, accept, back
}
public void unloadState()
{
}
public void input()
{
keys[Input.KEY_LEFT] = Sdl.getInput(SDLKey.SDLK_LEFT);
keys[Input.KEY_RIGHT] = Sdl.getInput(SDLKey.SDLK_RIGHT);
keys[Input.KEY_UP] = Sdl.getInput(SDLKey.SDLK_UP);
keys[Input.KEY_DOWN] = Sdl.getInput(SDLKey.SDLK_DOWN);
// keys[Input.KEY_JUMP] = Sdl.getInput(SDLKey.SDLK_x);
// keys[Input.KEY_ATTACK] = Sdl.getInput(SDLKey.SDLK_z);
keys[Input.KEY_JUMP] = Sdl.getInput(SDLKey.SDLK_LCTRL);
keys[Input.KEY_ATTACK] = Sdl.getInput(SDLKey.SDLK_LALT);
}
public void logic()
{
input();
doScroll = true;
if (keys[Input.KEY_JUMP])
{
keys[Input.KEY_JUMP] = false;
Sdl.putInput(SDLKey.SDLK_LCTRL, keys[Input.KEY_JUMP]);
Program.game.changeState(GameStateEnum.STATE_MENU);
}
else if (keys[Input.KEY_UP])
{
doScroll = false;
scroll
}
else if (keys[Input.KEY_DOWN])
{
doScroll = false;
scroll++;
}
}
private int getLineHeight()
{
lineHeight += font.getH() + font.getLeading();
return lineHeight;
}
public void draw()
{
// Draw uniform background
try
{
Sdl.screen.fillRect(100);
}
catch (Exception e)
{
//todo
}
lineHeight = 0;
font.drawFloatingCentered("** Programming **", Sdl.SCREEN_HEIGHT - scroll, 1, 3);
getLineHeight();
font.drawCentered("Artur Rojek", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
getLineHeight();
getLineHeight();
font.drawFloatingCentered("** Graphics **", Sdl.SCREEN_HEIGHT - scroll + getLineHeight(), 1, 3);
getLineHeight();
font.drawCentered("Daniel Garcia", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
getLineHeight();
getLineHeight();
font.drawFloatingCentered("** Level design **", Sdl.SCREEN_HEIGHT - scroll + getLineHeight(), 1, 3);
getLineHeight();
font.drawCentered("Artur Rojek", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
getLineHeight();
getLineHeight();
font.drawFloatingCentered("** Special Thanks **", Sdl.SCREEN_HEIGHT - scroll + getLineHeight(), 1, 3);
getLineHeight();
font.drawCentered("Paul Cercueil", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
font.drawCentered("Andreas Bjerkeholt", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
font.drawCentered("Nebuleon", Sdl.SCREEN_HEIGHT - scroll + getLineHeight());
lineHeight += Sdl.SCREEN_HEIGHT;
font.drawFloatingCentered("Thank YOU for playing!", Sdl.SCREEN_HEIGHT - scroll + getLineHeight(), 1, 3);
if (doScroll && scrollTimer
{
scrollTimer = 3;
scroll++;
}
if (scroll > lineHeight + font.getH() + font.getLeading() + Sdl.SCREEN_HEIGHT)
{
scroll = 0;
}
else if (scroll < 0)
{
scroll = lineHeight + font.getH() + font.getLeading() + Sdl.SCREEN_HEIGHT;
}
Sdl.flip(Sdl.screen);
}
} |
package org.jpos.ee;
import java.util.List;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
public class SysConfigManager {
DB db;
String prefix = "";
public SysConfigManager() {
super();
db = new DB();
}
public SysConfigManager (DB db) {
super();
this.db = db;
}
public void setPrefix (String prefix) {
this.prefix = prefix;
}
public String getPrefix() {
return prefix;
}
public boolean hasProperty (String name) {
try {
if (prefix != null)
name = prefix + name;
SysConfig cfg = (SysConfig)
db.session().get (SysConfig.class, name);
return cfg != null;
} catch (ObjectNotFoundException e) {
// okay to happen
} catch (HibernateException e) {
db.getLog().warn (e);
}
return false;
}
public String get (String name, String defaultValue) {
try {
if (prefix != null)
name = prefix + name;
SysConfig cfg = (SysConfig) db.session().load (SysConfig.class, name);
return cfg.getValue();
} catch (ObjectNotFoundException e) {
// okay to happen
} catch (HibernateException e) {
db.getLog().warn (e);
}
return defaultValue;
}
public String[] getAll (String name) {
String[] values;
try {
if (prefix != null)
name = prefix + name;
Query query = db.session().createQuery (
"from sysconfig in class org.jpos.ee.SysConfig where id like :name order by id"
);
query.setParameter ("name", name);
List l = query.list();
values = new String[l.size()];
Iterator iter = l.iterator();
for (int i=0; iter.hasNext(); i++) {
values[i] = (String) iter.next();
}
} catch (HibernateException e) {
db.getLog().warn (e);
values = new String[0];
}
return values;
}
@SuppressWarnings("unchecked")
public Iterator<SysConfig> iterator() {
Query query;
if (prefix != null) {
query = db.session().createQuery (
"from sysconfig in class org.jpos.ee.SysConfig where id like :name order by id"
);
query.setParameter ("name", prefix + "%");
} else {
query = db.session().createQuery (
"from sysconfig in class org.jpos.ee.SysConfig order by id"
);
}
return (Iterator<SysConfig>) query.list().iterator();
}
public void put (String name, String value) {
put (name, value, null, null);
}
public void put (String name, String value, String readPerm, String writePerm) {
SysConfig cfg;
if (prefix != null)
name = prefix + name;
try {
Transaction tx = db.beginTransaction();
cfg = (SysConfig) db.session().get (SysConfig.class, name);
boolean saveIt = false;
if (cfg == null) {
cfg = new SysConfig ();
cfg.setId (name);
saveIt = true;
}
cfg.setReadPerm (readPerm);
cfg.setWritePerm (writePerm);
cfg.setValue (value);
if (saveIt)
db.session().save (cfg);
tx.commit();
} catch (HibernateException e) {
db.getLog().warn (e);
}
}
public String get (String name) {
return get (name, "");
}
public int getInt (String name) {
return Integer.parseInt(get (name, "0").trim());
}
public int getInt (String name, int defaultValue) {
String value = get (name, null);
return value != null ? Integer.parseInt(value.trim()) : defaultValue;
}
public long getLong (String name) {
return Long.parseLong(get (name, "0").trim());
}
public long getLong (String name, long defaultValue) {
String value = get (name, null);
return value != null ? Long.parseLong(value.trim()) : defaultValue;
}
public double getDouble (String name) {
return Double.parseDouble(get (name, "0.00").trim());
}
public double getDouble (String name, double defaultValue) {
String value = get (name, null);
return value != null ? Double.parseDouble(value.trim()) : defaultValue;
}
public boolean getBoolean (String name) {
String v = get (name, "false").trim();
return v.equalsIgnoreCase("true") || v.equalsIgnoreCase("yes");
}
public boolean getBoolean (String name, boolean def) {
String v = get (name);
return v.length() == 0 ? def :
(v.equalsIgnoreCase("true") || v.equalsIgnoreCase("yes"));
}
} |
package org.hawk.graph;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import org.hawk.core.graph.IGraphDatabase;
import org.hawk.core.graph.IGraphNode;
import org.hawk.core.graph.IGraphNodeIndex;
/**
* Wraps an {@link IGraphDatabase} that has been updated by this plugin. This is
* the starting point for the read-only abstraction of the graph populated by
* this updater. Users of this class and any other classes of this package are
* expected to manage their own transactions with
* {@link IGraphDatabase#beginTransaction()}.
*
* TODO This is an incomplete WIP abstraction. More methods will be called as
* the existing queries are moved into this API.
*/
public class GraphWrapper {
private final IGraphDatabase graph;
public GraphWrapper(IGraphDatabase graph) {
this.graph = graph;
}
/**
* Convenience version of {@link #getRawFileNodes(Iterable)} that wraps all
* results as {@link FileNode}s.
*/
public Set<FileNode> getFileNodes(Iterable<String> patterns) {
final IGraphNodeIndex fileIndex = graph.getFileIndex();
final Set<FileNode> files = new HashSet<>();
for (String s : patterns) {
for (IGraphNode n : fileIndex.query("id", s)) {
files.add(new FileNode(n));
}
}
return files;
}
/**
* Returns the graph wrapped by this instance.
*/
public IGraphDatabase getGraph() {
return graph;
}
/**
* Retrieves a {@link ModelElementNode} by identifier.
*
* @throws NoSuchElementException
* No node with that identifier exists.
*/
public ModelElementNode getModelElementNodeById(String id) {
final IGraphNode rawNode = graph.getNodeById(id);
if (rawNode == null) {
throw new NoSuchElementException();
}
return new ModelElementNode(rawNode);
}
} |
package voldemort.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import voldemort.client.protocol.admin.AdminClient;
import voldemort.cluster.Zone;
public class ClientTrafficGenerator {
String bootstrapURL;
Collection<String> storeNames;
Collection<Integer> zones;
int threads;
static Logger logger = Logger.getLogger(ClientTrafficGenerator.class);
List<ClientTrafficVerifier> verifiers = new ArrayList<ClientTrafficVerifier>();
public ClientTrafficGenerator(String bootstrapURL, Collection<String> storeNames, int threads) {
this(bootstrapURL, storeNames, Arrays.asList(Zone.UNSET_ZONE_ID), threads);
}
public ClientTrafficGenerator(String bootstrapURL,
Collection<String> storeNames,
Collection<Integer> zones,
int threads) {
this.bootstrapURL = bootstrapURL;
this.storeNames = storeNames;
this.threads = threads;
this.zones = zones;
for(Integer zone: zones) {
for(String storeName: storeNames) {
for(int thread = 0; thread < threads; thread++) {
String clientName = storeName + "_Zone_" + zone + "_Thread_" + thread;
ClientTrafficVerifier verifier = new ClientTrafficVerifier(clientName,
bootstrapURL,
storeName,
zone.intValue());
verifiers.add(verifier);
}
}
}
}
public void start() {
logger.info("
logger.info(" STARTING CLIENT ");
logger.info("
for(ClientTrafficVerifier verifier: verifiers) {
verifier.initialize();
verifier.start();
}
logger.info("
logger.info(" CLIENT STARTED ");
logger.info("
}
public void stop() {
logger.info("
logger.info(" STOPPING CLIENT ");
logger.info("
for(ClientTrafficVerifier verifier: verifiers) {
verifier.stop();
}
logger.info("
logger.info(" STOPPED CLIENT ");
logger.info("
}
public void verifyIfClientsDetectedNewClusterXMLs() {
// verify that all clients has new cluster now
Integer failCount = 0;
for(ClientTrafficVerifier verifier: verifiers) {
if(verifier.client instanceof LazyStoreClient) {
LazyStoreClient<String, String> lsc = (LazyStoreClient<String, String>) verifier.client;
if(lsc.getStoreClient() instanceof ZenStoreClient) {
ZenStoreClient<String, String> zsc = (ZenStoreClient<String, String>) lsc.getStoreClient();
Long clusterMetadataVersion = zsc.getAsyncMetadataVersionManager()
.getClusterMetadataVersion();
if(clusterMetadataVersion == 0) {
failCount++;
logger.error(String.format("The client %s did not pick up the new cluster metadata\n",
verifier.clientName));
}
} else {
throw new RuntimeException("There is problem with DummyClient's real client's real client, which should be ZenStoreClient but not");
}
} else {
throw new RuntimeException("There is problem with DummyClient's real client which should be LazyStoreClient but not");
}
}
if(failCount > 0) {
AdminClient adminClient = new AdminClient(bootstrapURL);
for (Integer nodeId : adminClient.getAdminClientCluster().getNodeIds()) {
try {
logger.info(" Node Id " + nodeId + " Properties "
+ adminClient.metadataMgmtOps.getMetadataVersion(nodeId));
} catch(Exception e) {
logger.info("Node Id " + nodeId + " Error retrieving version ", e);
}
}
throw new RuntimeException(failCount.toString()
+ " client(s) did not pickup new metadata");
}
}
public void verifyPostConditions() {
for(ClientTrafficVerifier client: verifiers) {
if(!client.isStopped()) {
client.stop();
}
}
for(ClientTrafficVerifier client: verifiers) {
client.verifyPostConditions();
}
}
} |
package resources;
import java.util.Hashtable;
import java.util.Map;
public enum Posture {
UPRIGHT (0x00),
CROUCHED (0x01),
PRONE (0x02),
SNEAKING (0x03),
BLOCKING (0x04),
CLIMBING (0x05),
FLYING (0x06),
LYING_DOWN (0x07),
SITTING (0x08),
SKILL_ANIMATING (0x09),
DRIVING_VEHICLE (0x0A),
RIDING_CREATURE (0x0B),
KNOCKED_DOWN (0x0C),
INCAPACITATED (0x0D),
DEAD (0x0E),
INVALID (0x0E);
private static final Map <Byte, Posture> POSTURE_MAP = new Hashtable<Byte, Posture>(15);
private byte id;
static {
for (Posture p : values()) {
if (p != INVALID)
POSTURE_MAP.put(p.getId(), p);
}
}
Posture(int id) {
this.id = (byte)id;
}
public byte getId() { return id; }
public static final Posture getFromId(byte id) {
Posture p = null;
synchronized (POSTURE_MAP) {
p = POSTURE_MAP.get(id);
}
if (p == null)
return INVALID;
return p;
}
} |
package bingo.lang.xml;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import bingo.lang.Converts;
import bingo.lang.Enumerable;
import bingo.lang.Strings;
import bingo.lang.enumerable.IterableEnumerable;
import bingo.lang.xml.XmlUtils.Predicates;
public class XmlElement extends XmlContainer implements XmlNamed {
private final String name;
private final String prefix;
private final String qname;
private final List<XmlAttribute> attributes = new ArrayList<XmlAttribute>();
public XmlElement(String name, Object... content) {
this(null,name,content);
}
public XmlElement(String prefix, String name, Object... content) {
this.prefix = prefix;
this.name = name;
this.qname = Strings.isEmpty(prefix) ? name : (prefix + ":" + name);
for (Object obj : content) {
add(obj);
}
}
public String qname(){
return qname;
}
public String name() {
return name;
}
public String prefix() {
return prefix;
}
public String text() {
Enumerable<XmlText> texts = childNodes().ofType(XmlText.class);
if(texts.isEmpty()){
return null;
}else{
StringBuilder buf = new StringBuilder();
for(XmlText text : texts){
buf.append(text.value());
}
return buf.toString();
}
}
public String textTrimmed(){
return Strings.trim(text());
}
public Integer intText(){
String value = text();
return Strings.isEmpty(value) ? null : Converts.convert(Strings.trim(value), Integer.class);
}
public int intText(int defaultValue){
Integer value = intText();
return null == value ? defaultValue : value;
}
public boolean intText(boolean defaultValue){
Boolean value = boolText();
return null == value ? defaultValue : value;
}
public Boolean boolText(){
String value = text();
return Strings.isEmpty(value) ? null : Converts.convert(Strings.trim(value), Boolean.class);
}
public boolean boolText(boolean defaultValue){
Boolean value = boolText();
return null == value ? defaultValue : value;
}
public Float floatText(){
String value = text();
return Strings.isEmpty(value) ? null : Converts.convert(Strings.trim(value), Float.class);
}
public float floatText(float defaultValue){
Float value = floatText();
return null == value ? defaultValue : value;
}
public Double doubleText(){
String value = text();
return Strings.isEmpty(value) ? null : Converts.convert(Strings.trim(value), Double.class);
}
public double doubleText(double defaultValue){
Double value = doubleText();
return null == value ? defaultValue : value;
}
public BigDecimal decimalText(){
String value = text();
return Strings.isEmpty(value) ? null : Converts.convert(Strings.trim(value), BigDecimal.class);
}
public boolean hasAttributes(){
return !attributes.isEmpty();
}
public IterableEnumerable<XmlAttribute> attributes() {
return IterableEnumerable.of(attributes);
}
public XmlAttribute attribute(String name) {
return attributes().firstOrNull(Predicates.<XmlAttribute> xnameEquals(name));
}
public XmlAttribute attributeWithPrefix(String name) {
return attributes().firstOrNull(Predicates.<XmlAttribute> xnameEqualsWithPrefix(name));
}
public XmlAttribute attribute(String prefix,String name){
return attributes().firstOrNull(Predicates.<XmlAttribute>xnameEquals(prefix,name));
}
public String attributeValue(String name) {
XmlAttribute attr = attribute(name);
return null == attr ? null : attr.value();
}
public String attributeValue(String prefix,String name){
XmlAttribute attr = attribute(prefix,name);
return null == attr ? null : attr.value();
}
public String attributeValueWithPrefix(String name){
XmlAttribute attr = attributeWithPrefix(name);
return null == attr ? null : attr.value();
}
public String attributeValueTrimToNull(String name){
return Strings.trimToNull(attributeValue(name));
}
public Boolean attributeValueForBool(String name){
XmlAttribute attr = attribute(name);
return attr == null ? null : attr.boolValue();
}
public boolean attributeValueForBool(String name,boolean defaultValue){
XmlAttribute attr = attribute(name);
return attr == null ? defaultValue : attr.boolValue(defaultValue);
}
public Integer attributeValueForInt(String name){
XmlAttribute attr = attribute(name);
return attr == null ? null : attr.intValue();
}
public int attributeValueForInt(String name,int defaultValue){
XmlAttribute attr = attribute(name);
return attr == null ? defaultValue : attr.intValue(defaultValue);
}
public Float attributeValueForFloat(String name){
XmlAttribute attr = attribute(name);
return attr == null ? null : attr.floatValue();
}
public float attributeValueForFloat(String name,float defaultValue){
XmlAttribute attr = attribute(name);
return attr == null ? defaultValue : attr.floatValue(defaultValue);
}
public Double attributeValueForDouble(String name){
XmlAttribute attr = attribute(name);
return attr == null ? null : attr.doubleValue();
}
public double attributeValueForDouble(String name,double defaultValue){
XmlAttribute attr = attribute(name);
return attr == null ? defaultValue : attr.doubleValue(defaultValue);
}
public String attributeValueOrText(String attributeName){
XmlAttribute attr = attribute(attributeName);
return attr == null ? text() : attr.value();
}
public String attributeValueOrChildText(String attributeName,String childElementName){
XmlAttribute attr = attribute(attributeName);
return attr == null ? childElementText(childElementName) : attr.value();
}
public String childElementText(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.text();
}
public Integer childElementTextForInt(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.intText();
}
public int childElementTextForInt(String name,int defaultValue) {
XmlElement e = childElement(name);
return null == e ? defaultValue : e.intText(defaultValue);
}
public Boolean childElementTextForBool(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.boolText();
}
public boolean childElementTextForBool(String name,boolean defaultValue) {
XmlElement e = childElement(name);
return null == e ? defaultValue : e.boolText(defaultValue);
}
public Float childElementTextForFloat(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.floatText();
}
public float childElementTextForFloat(String name,float defaultValue) {
XmlElement e = childElement(name);
return null == e ? defaultValue : e.floatText(defaultValue);
}
public Double childElementTextForDouble(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.doubleText();
}
public double childElementTextForFloat(String name,double defaultValue) {
XmlElement e = childElement(name);
return null == e ? defaultValue : e.doubleText(defaultValue);
}
public BigDecimal childElementTextForDecimal(String name) {
XmlElement e = childElement(name);
return null == e ? null : e.decimalText();
}
public XmlElement requiredChildElement(String name) {
XmlElement e = childElement(name);
if(null == e){
throw new XmlValidationException("child element '{0}' of parent '{1}' is required in xml : {2}",name, name(),documentLocation());
}
return e;
}
public String requiredChildElementText(String name) {
return requiredChildElement(name).requiredText();
}
public String requiredText() throws XmlValidationException {
String string = Strings.trim(text());
if(Strings.isEmpty(string)){
throw new XmlValidationException("text of element '{0}' is required in xml : {1}",name(),documentLocation());
}
return string;
}
public XmlAttribute requiredAttribute(String name) throws XmlValidationException {
XmlAttribute attr = attributes().firstOrNull(Predicates.<XmlAttribute> xnameEquals(name));
if(null == attr){
throw new XmlValidationException("attribute '{0}' of element '{1}' is required in xml : {2}",name,name(),documentLocation());
}
return attr.required();
}
public String requiredAttributeValue(String name) throws XmlValidationException {
XmlAttribute attr = attribute(name);
if(null == attr || Strings.isEmpty(attr.value())){
throw new XmlValidationException("attribute '{0}' value of element '{1}' is required in xml : {2}",name,name(),documentLocation());
}
return attr.value();
}
public String requiredAttributeValueOrText(String attributeName) throws XmlValidationException {
XmlAttribute attr = attribute(attributeName);
if(null != attr){
return attr.required().value();
}
return requiredText();
}
public String requiredAttributeValueOrChildText(String attributeName,String childElementName) throws XmlValidationException {
XmlAttribute attr = attribute(attributeName);
if(null != attr){
return attr.required().value();
}
return requiredChildElementText(childElementName);
}
public void error(String message) throws XmlValidationException {
throw new XmlValidationException("found error \"{0}\" in element '{1}', xml file '{2}'",message,this.name,documentLocation());
}
public void error(String template,Object... args) throws XmlValidationException{
error(Strings.format(template, args));
}
@Override
public void add(Object content) {
if (content instanceof XmlAttribute) {
attributes.add((XmlAttribute) content);
} else {
super.add(content);
}
}
@Override
public XmlNodeType nodeType() {
return XmlNodeType.ELEMENT;
}
@Override
protected XmlElement element() {
return this;
}
protected String documentLocation(){
return null == document() ? "unknow" : document().locationOrUnknow();
}
@Override
public String toString() {
return toXml(XmlFormat.NOT_INDENTED);
}
@Override
public String toXml(XmlFormat format) {
boolean enableIndent = format.isIndentEnabled();
String indent = enableIndent ? getIndent(format) : "";
String newline = enableIndent ? "\n" : "";
StringBuilder sb = new StringBuilder();
sb.append(indent);
sb.append('<');
sb.append(qname);
for (XmlAttribute att : attributes) {
sb.append(' ');
sb.append(att.qname());
sb.append("=\"");
sb.append(XmlUtils.escapeAttributeValue(att.value()));
sb.append('"');
}
List<XmlNode> nodes = childNodes().toList();
if (nodes.size() == 0) {
sb.append(" />");
} else {
sb.append('>');
boolean onlyText = true;
for (XmlNode node : childNodes()) {
if (node.nodeType() == XmlNodeType.TEXT) {
sb.append(node.toXml(format));
} else {
onlyText = false;
sb.append(newline);
sb.append(node.toXml(format.incrementLevel()));
}
}
if (!onlyText) {
sb.append(newline + indent);
}
sb.append("</");
sb.append(qname);
sb.append('>');
}
return sb.toString();
}
} |
package model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import model.ProofListener.RowInfo;
import model.rules.Interval;
import model.rules.Rule;
public class Box implements ProofEntry, Serializable{
private boolean open;
private int size; // only alter this value through incSize and decSize methods, they will also update parent boxes
private Box parent;
List<ProofEntry> entries = new ArrayList<ProofEntry>();
public Box(Box parentBox, boolean open){
this.parent = parentBox;
this.open = open;
}
public void insertRow(int index, BoxReference br, int depth){
assert(index < size);
if (index == -1 ) { // Adding to beginning
this.entries.add(0, new ProofRow(this));
this.incSize();
return;
}
ProofRow referenceRow = getRow(index);
Box parent = referenceRow.getParent();
if (br.equals(BoxReference.BEFORE)) {
int internalReferenceIndex = parent.entries.indexOf(referenceRow);
int insertionIndex = br == BoxReference.BEFORE ? internalReferenceIndex : internalReferenceIndex+1;
parent.entries.add(insertionIndex, new ProofRow(parent));
parent.incSize();
return;
}
ProofEntry child = referenceRow;
for (int i = 0; i < depth; i++) {
child = parent;
parent = parent.getParent();
}
parent.entries.add(parent.entries.indexOf(child)+1, new ProofRow(parent));
parent.incSize();
}
public void deleteRowAfterBox(int index) { // Only allowed as an inverse!
ProofRow referenceRow = getRow(index);
Box parentBox = referenceRow.getParent();
Box metaBox = parentBox.getParent();
List<ProofEntry> metaBoxList = metaBox.entries;
int insertionIndex = metaBoxList.indexOf(parentBox) + 1;
metaBoxList.remove(insertionIndex);
metaBox.decSize();
}
public void insertBox(int index){
assert(index < size);
ProofRow referenceRow = getRow(index);
Box boxToInsertInto = referenceRow.getParent();
int internalReferenceIndex = boxToInsertInto.entries.indexOf(referenceRow);
Box closedBox = new Box(boxToInsertInto, false);
closedBox.entries.add(referenceRow);
closedBox.incSize();
boxToInsertInto.decSize();
referenceRow.setParent(closedBox);
//boxToInsertInto.entries.remove(internalReferenceIndex);
boxToInsertInto.entries.remove(referenceRow);
boxToInsertInto.entries.add(internalReferenceIndex, closedBox);
}
public void removeBox(int index){
assert(index < size);
ProofRow referenceRow = getRow(index);
Box boxToDelete = referenceRow.getParent();
Box metaBox = boxToDelete.getParent();
List<ProofEntry> peList = metaBox.entries;
int idx = peList.indexOf(boxToDelete);
peList.remove(idx);
referenceRow.setParent(metaBox);
peList.add(idx,referenceRow);
}
public void addRow(){
//System.out.println("Box.addRow(");
if(entries.isEmpty()) {
entries.add(new ProofRow(this));
incSize();
return;
}
ProofEntry lastEntry = entries.get(entries.size()-1);
if(lastEntry instanceof Box){
Box box = (Box) lastEntry;
if(box.isOpen()){
box.addRow();
return;
}
}
entries.add(new ProofRow(this));
incSize();
}
public ProofRow getRow(int steps){
//System.out.println("Box.getRow("+steps+")");
//assert(steps < size) : "getRow: index="+steps+" size="+size;
for(int i = 0; i < size ; i++ ){
ProofEntry entry = entries.get(i);
if(entry instanceof Box){
Box box = (Box) entry;
if(box.size() > steps) return box.getRow(steps);
else steps -= box.size();
}
else if(steps == 0){
return (ProofRow)entry;
}
else{
steps
}
}
System.out.println("getRow: returning null");
return null;
}
public int deleteRow(int index){
assert(index < size);
ProofRow referenceRow = getRow(index);
Box parent = referenceRow.getParent();
int idxRefRow = parent.entries.indexOf(referenceRow);
if (idxRefRow == 0 && idxRefRow+1 < parent.entries.size() && parent.entries.get(idxRefRow+1) instanceof Box) {
if (parent.isTopLevelBox()) {
parent.entries.remove(referenceRow);
parent.decSize();
return -3;
}
return -1;
}
int depth = 0;
if (index != 0) {
Box cur = getRow(index-1).getParent();
while (!cur.equals(parent)) {
depth++;
if (cur.isTopLevelBox()) {
depth = -2;
break;
}
cur = cur.getParent();
}
}
parent.entries.remove(referenceRow);
parent.decSize();
return depth;
}
//check if referenceRowIndex is in scope of referencingRowIndex
/**
* Check if the referencingRow can refer to the referenceRow
* @param referenceRowIndex
* @param referencingRowIndex
* @return
*/
public boolean isInScopeOf(int referenceRowIndex, int referencingRowIndex) throws VerificationInputException {
if( referenceRowIndex > referencingRowIndex) throw new VerificationInputException("A row is out of scope.");
if( referenceRowIndex == referencingRowIndex) throw new VerificationInputException("A row may not reference itself.");
ProofRow referenceRow = getRow(referenceRowIndex);
ProofRow referencingRow = getRow(referencingRowIndex);
Box referenceParent = referenceRow.getParent();
Box referencingRowAncestorBox = referencingRow.getParent();
//check if the reference is verified to be correct
if( referenceRow.isVerified() == false ) throw new VerificationInputException("A reference is not verified.");
//For referenceRow to be in scope of the referencingRow, the parent of the referenceRow must be
//in the ancestral hierarchy of the referencingRow. A simpler way to put it: The innermost box
//containing the referenceRow must also contain the referencingRow
while(referencingRowAncestorBox != null){
if( referenceParent == referencingRowAncestorBox){
return true;
}
referencingRowAncestorBox = referencingRowAncestorBox.getParent();
}
throw new VerificationInputException("A row is out of scope.");
}
/**
* Checks if the interval is a box that is within scope of the row at index referencingRow
* @param interval: should be an interval of the start and end index of a box
* @param referencingRow
* @return
*/
public boolean isInScopeOf(Interval interval, int referencingRow){
int start = interval.startIndex;
int end = interval.endIndex;
if (end < start || referencingRow <= end) throw new VerificationInputException("An interval is out of scope.");
//System.out.println("end < start || referencingRow <= end : true");
//check if the rows inthe box are verified
for (int i = start; i <= end; i++) {
if (getRow(i).isVerified() == false) throw new VerificationInputException("An interval is not verified.");
}
//ProofRow row1 = getRow(start);
//ProofRow row2 = getRow(end);
Box theBox = getBox(interval);
if( theBox == null) throw new VerificationInputException("An interval needs to specify an entire box.");
Box parentOfIntervalBox = theBox.getParent();
//System.out.println("theBox == null : false");
//TODO:
//Check that the box doesn't end with a box
if(theBox.entries.get(theBox.entries.size()-1) instanceof Box) throw new VerificationInputException("Box may not end in a box.");
//check if the box is an ancestor of the referencingRow
Box referencingRowAncestorBox = getRow(referencingRow).getParent();
while(referencingRowAncestorBox != null){
if( parentOfIntervalBox == referencingRowAncestorBox) return true;
referencingRowAncestorBox = referencingRowAncestorBox.getParent();
}
throw new VerificationInputException("A interval is out of scope.");
}
/**
* If this interval represents a box in this proof, return that box
* @param interval: the indexes of the box you want to get/check
* @return the box if the indexes given by the interval represents a box in the proof, otherwise null
*/
public Box getBox(Interval interval){
ProofRow startRow = getRow(interval.startIndex);
ProofRow endRow = getRow(interval.endIndex);
Box parent = startRow.getParent();
while(parent != null){
if( parent.getRow(0) == startRow && parent.getRow( parent.size()-1 ) == endRow ){
return parent;
}
parent = parent.getParent();
}
return null;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public Box(boolean open){
this.open = open;
}
public boolean isOpen(){
return open;
}
public void setOpen(boolean open){
this.open = open;
}
public Box getParent(){
return parent;
}
//increment size variable of this box and do the same for parent box
//this will propagate all the way to the top box
public void incSize(){
size++;
if( parent != null) parent.incSize();
}
//decrement size variable of this box and do the same for parent box
//this will propagate all the way to the top box
//if this box is now empty, remove it from the parent's entry list
public void decSize(){
if(--size == 0){
getParent().entries.remove(this);
}
if( parent != null) parent.decSize();
}
public boolean isTopLevelBox(){
return parent == null;
}
public int indexOf(ProofRow row){
return this.entries.indexOf(row);
}
public void printBoxes(){
List<Interval> foundBoxes = new ArrayList<Interval>();
for(int i = 0; i < size(); i++){
for( int j = i; j < size(); j++){
Interval interval = new Interval(i,j);
Box box = getBox(interval);
if( box != null) foundBoxes.add(interval);
}
}
//printRows(1,0);
System.out.println("Found boxes: "+foundBoxes);
}
public String rowsToString(int depth) {
String ret = "";
for(ProofEntry entry : entries){
if(entry instanceof Box){
ret += ((Box)entry).rowsToString(depth+1);
}
else{
ret += Integer.toString(depth);
ret += "::" + entry +"\n";
}
}
return ret;
}
public void printRows(int depth, int startNr){
int currentNr = startNr;
//System.out.println("size:"+size);
for(ProofEntry entry : entries){
if(entry instanceof Box){
((Box)entry).printRows(depth+1,currentNr);
currentNr += ((Box)entry).size();
}
else{
System.out.print(currentNr++ +". ");
if(currentNr < 11) System.out.print(" ");
for(int i = 0; i < depth; i++) System.out.print("|");
System.out.println("\t"+entry);
}
}
}
public void printRowScopes(boolean zeroBasedNumbering){
int offset = zeroBasedNumbering ? 0 : 1;
for(int i = 0; i < size; i++){
System.out.print("Rows in scope of line "+i+": ");
for(int j = 0; j < i; j++){
if(isInScopeOf(j,i)) System.out.print(""+(j+offset)+", ");
}
System.out.println("");
}
}
public void printIntervalScopes(boolean zeroBasedNumbering){
int offset = zeroBasedNumbering ? 0 : 1;
for(int rowI = 0; rowI < size; rowI++){
System.out.print("Intervals in scope for row "+(rowI+offset)+": ");
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
Interval inter = new Interval(i,j);
if( isInScopeOf(inter, rowI) ) System.out.print(""+inter+", ");
}
}
System.out.println("");
}
}
public void fillList(ArrayList<ProofListener.RowInfo> list){
boolean startOfBox = ! isTopLevelBox();
for(ProofEntry entry : this.entries){
if(entry instanceof Box){
((Box)entry).fillList(list);
}
else{
ProofRow row = (ProofRow) entry;
String expression = row.getFormula() == null ? row.getUserInput() : row.getFormula()+"";
Rule rule = row.getRule();
String ruleStr;
String[] refs = {"","",""};
if(rule == null){
ruleStr = "";
}
else{
ruleStr = rule.getDisplayName();
String[] refsx = rule.getReferenceStrings();
for(int i = 0; i < refsx.length; i++){
refs[i] = refsx[i];
}
}
boolean endOfBox = entries.indexOf(entry) == entries.size()-1;
list.add(new RowInfo(expression, ruleStr, refs[0], refs[1], refs[2],
startOfBox, endOfBox, row.isWellFormed(), row.isVerified()));
}
startOfBox = false;
}
}
} |
package brooklyn.entity.basic;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.config.ConfigKey;
import brooklyn.entity.Application;
import brooklyn.entity.Effector;
import brooklyn.entity.Entity;
import brooklyn.entity.Group;
import brooklyn.entity.trait.Startable;
import brooklyn.event.AttributeSensor;
import brooklyn.event.Sensor;
import brooklyn.location.Location;
import brooklyn.management.ManagementContext;
import brooklyn.management.Task;
import brooklyn.management.internal.LocalManagementContext;
import brooklyn.util.MutableMap;
import brooklyn.util.ResourceUtils;
import brooklyn.util.flags.FlagUtils;
import brooklyn.util.task.ParallelTask;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/** Convenience methods for working with entities.
* Also see the various *Methods classes for traits
* (eg StartableMethods for Startable implementations). */
public class Entities {
private static final Logger log = LoggerFactory.getLogger(Entities.class);
/**
* Names that, if they appear anywhere in an attribute/config/field indicates that it
* may be private, so should not be logged etc.
*/
private static final List<String> SECRET_NAMES = ImmutableList.of(
"password",
"credential",
"secret",
"private",
"access.cert",
"access.key");
/** invokes the given effector with the given named arguments on the entitiesToCall, from the calling context of the callingEntity;
* intended for use only from the callingEntity
* @return ParallelTask containing a results from each invocation; calling get() on the result will block until all complete,
* and throw error if any threw error
*/
public static <T> Task<List<T>> invokeEffectorList(EntityLocal callingEntity, Iterable<Entity> entitiesToCall,
final Effector<T> effector, final Map<String,?> parameters) {
// formulation is complicated, but it is building up a list of tasks, without blocking on them initially,
// but ensuring that when the parallel task is gotten it does block on all of them
// TODO why not just get list of tasks with `entity.invoke(effector, parameters))`?
// What is advantage of invoking in callingEntity's context?
if (entitiesToCall == null || Iterables.isEmpty(entitiesToCall)) return null;
List<Callable<T>> tasks = Lists.newArrayList();
for (final Entity entity : entitiesToCall) {
tasks.add(new Callable<T>() {
public T call() throws Exception {
return entity.invoke(effector, parameters).get();
}});
}
ParallelTask<T> invoke = new ParallelTask<T>(tasks);
callingEntity.getManagementSupport().getExecutionContext().submit(invoke);
return invoke;
}
public static <T> Task<List<T>> invokeEffectorList(EntityLocal callingEntity, Iterable<Entity> entitiesToCall,
final Effector<T> effector) {
return invokeEffectorList(callingEntity, entitiesToCall, effector, Collections.<String,Object>emptyMap());
}
public static boolean isSecret(String name) {
String lowerName = name.toLowerCase();
for (String secretName : SECRET_NAMES) {
if (lowerName.contains(secretName)) return true;
}
return false;
}
public static boolean isTrivial(Object v) {
return v==null || (v instanceof Map && ((Map<?,?>)v).isEmpty()) ||
(v instanceof Collection && ((Collection<?>)v).isEmpty()) ||
(v instanceof CharSequence&& ((CharSequence)v).length() == 0);
}
public static <K> Map<K,Object> sanitize(Map<K,?> input) {
Map<K,Object> result = Maps.newLinkedHashMap();
for (Map.Entry<K,?> e: input.entrySet()) {
if (isSecret(""+e.getKey())) result.put(e.getKey(), "xxxxxxxx");
else result.put(e.getKey(), e.getValue());
}
return result;
}
public static void dumpInfo(Entity e) {
try {
dumpInfo(e, new PrintWriter(System.out), "", " ");
} catch (IOException exc) {
// system.out throwing an exception is odd, so don't have IOException on signature
throw new RuntimeException(exc);
}
}
public static void dumpInfo(Entity e, Writer out) throws IOException {
dumpInfo(e, out, "", " ");
}
public static void dumpInfo(Entity e, String currentIndentation, String tab) throws IOException {
dumpInfo(e, new PrintWriter(System.out), currentIndentation, tab);
}
public static void dumpInfo(Entity e, Writer out, String currentIndentation, String tab) throws IOException {
out.append(currentIndentation+e.toString()+"\n");
out.append(currentIndentation+tab+tab+"locations = "+e.getLocations()+"\n");
for (ConfigKey<?> it : sortConfigKeys(e.getEntityType().getConfigKeys())) {
Object v = e.getConfig(it);
if (!isTrivial(v)) {
out.append(currentIndentation+tab+tab+it.getName());
out.append(" = ");
if (isSecret(it.getName())) out.append("xxxxxxxx");
else if ((v instanceof Task) && ((Task<?>)v).isDone()) {
if (((Task<?>)v).isError()) {
out.append("ERROR in "+v);
} else {
try {
out.append(((Task<?>)v).get() + " (from "+v+")");
} catch (ExecutionException ee) {
throw new IllegalStateException("task "+v+" done and !isError, but threw exception on get", ee);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
}
} else out.append(""+v);
out.append("\n");
}
}
for (Sensor<?> it : sortSensors(e.getEntityType().getSensors())) {
if (it instanceof AttributeSensor) {
Object v = e.getAttribute((AttributeSensor<?>)it);
if (!isTrivial(v)) {
out.append(currentIndentation+tab+tab+it.getName());
out.append(": ");
if (isSecret(it.getName())) out.append("xxxxxxxx");
else out.append(""+v);
out.append("\n");
}
}
}
if (e instanceof Group) {
StringBuilder members = new StringBuilder();
for (Entity it : ((Group)e).getMembers()) {
members.append(it.getId()+", ");
}
out.append(currentIndentation+tab+tab+"Members: "+members.toString()+"\n");
}
for (Entity it : e.getOwnedChildren()) {
dumpInfo(it, out, currentIndentation+tab, tab);
}
out.flush();
}
public static void dumpInfo(Location loc) {
try {
dumpInfo(loc, new PrintWriter(System.out), "", " ");
} catch (IOException exc) {
// system.out throwing an exception is odd, so don't have IOException on signature
throw new RuntimeException(exc);
}
}
public static void dumpInfo(Location loc, Writer out) throws IOException {
dumpInfo(loc, out, "", " ");
}
public static void dumpInfo(Location loc, String currentIndentation, String tab) throws IOException {
dumpInfo(loc, new PrintWriter(System.out), currentIndentation, tab);
}
public static void dumpInfo(Location loc, Writer out, String currentIndentation, String tab) throws IOException {
out.append(currentIndentation+loc.toString()+"\n");
for (Map.Entry<String,?> entry : sortMap(loc.getLocationProperties()).entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (!isTrivial(val)) {
out.append(currentIndentation+tab+tab+key);
out.append(" = ");
if (isSecret(key)) out.append("xxxxxxxx");
else out.append(""+val);
out.append("\n");
}
}
for (Map.Entry<String,?> entry : sortMap(FlagUtils.getFieldsWithFlags(loc)).entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
if (!isTrivial(val)) {
out.append(currentIndentation+tab+tab+key);
out.append(" = ");
if (isSecret(key)) out.append("xxxxxxxx");
else out.append(""+val);
out.append("\n");
}
}
for (Location it : loc.getChildLocations()) {
dumpInfo(it, out, currentIndentation+tab, tab);
}
out.flush();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<Sensor<?>> sortSensors(Set<Sensor<?>> sensors) {
List result = new ArrayList(sensors);
Collections.sort(result, new Comparator<Sensor>() {
@Override
public int compare(Sensor arg0, Sensor arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<ConfigKey<?>> sortConfigKeys(Set<ConfigKey<?>> configs) {
List result = new ArrayList(configs);
Collections.sort(result, new Comparator<ConfigKey>() {
@Override
public int compare(ConfigKey arg0, ConfigKey arg1) {
return arg0.getName().compareTo(arg1.getName());
}
});
return result;
}
public static <T> Map<String, T> sortMap(Map<String, T> map) {
Map<String,T> result = Maps.newLinkedHashMap();
List<String> order = Lists.newArrayList(map.keySet());
Collections.sort(order, String.CASE_INSENSITIVE_ORDER);
for (String key : order) {
result.put(key, map.get(key));
}
return result;
}
public static boolean isAncestor(Entity descendant, Entity potentialAncestor) {
Entity ancestor = descendant.getOwner();
while (ancestor != null) {
if (ancestor.equals(potentialAncestor)) return true;
ancestor = ancestor.getOwner();
}
return false;
}
/** note, it is usually preferred to use isAncestor() and swap the order, it is a cheaper method */
public static boolean isDescendant(Entity ancestor, Entity potentialDescendant) {
Set<Entity> inspected = Sets.newLinkedHashSet();
Stack<Entity> toinspect = new Stack<Entity>();
toinspect.add(ancestor);
while (!toinspect.isEmpty()) {
Entity e = toinspect.pop();
if (e.getOwnedChildren().contains(potentialDescendant)) {
return true;
}
inspected.add(e);
toinspect.addAll(e.getOwnedChildren());
toinspect.removeAll(inspected);
}
return false;
}
private static final List<Entity> entitiesToStopOnShutdown = Lists.newArrayList();
private static final AtomicBoolean isShutdownHookRegistered = new AtomicBoolean();
public static void invokeStopOnShutdown(Entity entity) {
if (isShutdownHookRegistered.compareAndSet(false, true)) {
ResourceUtils.addShutdownHook(new Runnable() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run() {
synchronized (entitiesToStopOnShutdown) {
log.info("Brooklyn stopOnShutdown shutdown-hook invoked: stopping "+entitiesToStopOnShutdown);
List<Task> stops = new ArrayList<Task>();
for (Entity entity: entitiesToStopOnShutdown) {
try {
stops.add(entity.invoke(Startable.STOP, new MutableMap()));
} catch (Exception exc) {
log.debug("stopOnShutdown of "+entity+" returned error: "+exc, exc);
}
}
for (Task t: stops) {
try {
log.debug("stopOnShutdown of {} completed: {}", t, t.get());
} catch (Exception exc) {
log.debug("stopOnShutdown of "+t+" returned error: "+exc, exc);
}
}
}
}
});
}
synchronized (entitiesToStopOnShutdown) {
entitiesToStopOnShutdown.add(entity);
}
}
/** @deprecated use start(Entity) */
public static Entity start(ManagementContext context, Entity e, Collection<Location> locations) {
if (context != null) context.manage(e);
if (e instanceof Startable) ((Startable)e).start(locations);
return e;
}
/** @deprecated use destroy(Entity) */
public static void destroy(ManagementContext context, Entity e) {
if (e instanceof Startable) ((Startable)e).stop();
if (e instanceof AbstractEntity) ((AbstractEntity)e).destroy();
if (context != null) context.unmanage(e);
}
/** convenience for starting an entity, esp a new Startable instance which has been created dynamically
* (after the application is started) */
public static void start(Entity e, Collection<Location> locations) {
if (!manage(e)) {
log.warn("Using discouraged Entities.start(Application, Locations) -- should create and use the preferred management context");
startManagement(e);
}
if (e instanceof Startable) ((Startable)e).start(locations);
}
/** stops, destroys, and unmanages the given entity -- does as many as are valid given the type and state */
public static void destroy(Entity e) {
if (isManaged(e)) {
if (e instanceof Startable) ((Startable)e).stop();
if (e instanceof AbstractEntity) ((AbstractEntity)e).destroy();
unmanage(e);
}
}
public static boolean isManaged(Entity e) {
return ((AbstractEntity)e).getManagementSupport().isDeployed();
}
/** brings this entity under management iff its ancestor is managed, returns true in that case;
* otherwise returns false in the expectation that the ancestor will become managed,
* or throws exception if it has no owner or a non-application root
* (will throw if e is an Application; see also {@link #startManagement(Entity)} ) */
public static boolean manage(Entity e) {
Entity o = e.getOwner();
Entity eum = e; //highest unmanaged ancestor
if (o==null) throw new IllegalStateException("Can't manage "+e+" because it is an orphan");
while (o.getOwner()!=null) {
if (!isManaged(o)) eum = o;
o = o.getOwner();
}
if (isManaged(o)) {
((AbstractEntity)o).getManagementSupport().getManagementContext(false).manage(eum);
return true;
}
if (!(o instanceof Application))
throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application");
return false;
}
/** brings this entity under management, creating a local management context if necessary
* (assuming root is an application).
* returns existing management context if there is one (non-deployment),
* or new local mgmt context if not,
* or throwing exception if root is not an application
* <p>
* callers are recommended to use {@link #manage(Entity)} instead unless they know
* a plain-vanilla non-root management context is sufficient (e.g. in tests)
* <p>
* this method may change, but is provided as a stop-gap to prevent ad-hoc things
* being done in the code which are even more likely to break! */
public static ManagementContext startManagement(Entity e) {
Entity o = e;
Entity eum = e; //highest unmanaged ancestor
while (o.getOwner()!=null) {
if (!isManaged(o)) eum = o;
o = o.getOwner();
}
if (isManaged(o)) {
ManagementContext mgmt = ((AbstractEntity)o).getManagementSupport().getManagementContext(false);
mgmt.manage(eum);
return mgmt;
}
if (!(o instanceof Application))
throw new IllegalStateException("Can't manage "+e+" because it is not rooted at an application");
ManagementContext mgmt = new LocalManagementContext();
mgmt.manage(o);
return mgmt;
}
public static void unmanage(Entity entity) {
if (((AbstractEntity)entity).getManagementSupport().isDeployed()) {
((AbstractEntity)entity).getManagementSupport().getManagementContext(true).unmanage(entity);
}
}
} |
package com.github.srec.jemmy;
import com.github.srec.UnsupportedFeatureException;
import com.github.srec.command.exception.AssertionFailedException;
import com.github.srec.util.AWTTreeScanner;
import com.github.srec.util.ScannerMatcher;
import com.github.srec.util.Utils;
import org.apache.log4j.Logger;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.ComponentSearcher;
import org.netbeans.jemmy.JemmyException;
import org.netbeans.jemmy.JemmyProperties;
import org.netbeans.jemmy.TestOut;
import org.netbeans.jemmy.Timeouts;
import org.netbeans.jemmy.Waitable;
import org.netbeans.jemmy.Waiter;
import org.netbeans.jemmy.operators.AbstractButtonOperator;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JComboBoxOperator;
import org.netbeans.jemmy.operators.JComponentOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JInternalFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JMenuBarOperator;
import org.netbeans.jemmy.operators.JMenuItemOperator;
import org.netbeans.jemmy.operators.JMenuOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JScrollBarOperator;
import org.netbeans.jemmy.operators.JScrollPaneOperator;
import org.netbeans.jemmy.operators.JSliderOperator;
import org.netbeans.jemmy.operators.JTabbedPaneOperator;
import org.netbeans.jemmy.operators.JTableHeaderOperator;
import org.netbeans.jemmy.operators.JTableOperator;
import org.netbeans.jemmy.operators.JTextAreaOperator;
import org.netbeans.jemmy.operators.JTextComponentOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JToggleButtonOperator;
import org.netbeans.jemmy.operators.Operator;
import org.netbeans.jemmy.util.NameComponentChooser;
import java.awt.FontMetrics;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.table.JTableHeader;
import javax.swing.text.JTextComponent;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* A DSL wrapper for Jemmy operators.
*
* @author Victor Tatai
*/
public class JemmyDSL {
private static final Logger logger = Logger.getLogger(JemmyDSL.class);
public enum ComponentType {
text_field(JTextFieldOperator.class, JTextField.class),
combo_box(JComboBoxOperator.class, JComboBox.class),
button(JButtonOperator.class, JButton.class),
radio_button(JRadioButtonOperator.class, JRadioButton.class),
check_box(JCheckBoxOperator.class, JCheckBox.class),
table(TableOperator.class, JTable.class),
menu_bar(JMenuBarOperator.class, JMenuBar.class),
dialog(JDialogOperator.class, JDialog.class);
private final Class<? extends ComponentOperator> operatorClass;
private final Class<? extends java.awt.Component> awtClass;
ComponentType(Class<? extends ComponentOperator> operatorClass, Class<? extends java.awt.Component> awtClass) {
this.operatorClass = operatorClass;
this.awtClass = awtClass;
}
public Class<? extends ComponentOperator> getOperatorClass() {
return operatorClass;
}
public Class<? extends java.awt.Component> getAwtClass() {
return awtClass;
}
}
private static Window currentWindow;
private static Properties props = new Properties();
static {
props.put("ComponentOperator.WaitComponentEnabledTimeout", "15000");
props.put("ComponentOperator.WaitComponentTimeout", "15000");
props.put("ComponentOperator.WaitStateTimeout", "10000");
props.put("DialogWaiter.WaitDialogTimeout", "10000");
props.put("FrameWaiter.WaitFrameTimeout", "10000");
props.put("JComboBoxOperator.WaitListTimeout", "10000");
props.put("JScrollBarOperator.WholeScrollTimeout", "10000");
props.put("JSliderOperator.WholeScrollTimeout", "10000");
props.put("JSplitPaneOperator.WholeScrollTimeout", "10000");
props.put("ScrollbarOperator.WholeScrollTimeout", "10000");
props.put("Waiter.WaitingTime", "10000");
props.put("WindowWaiter.WaitWindowTimeout", "10000");
}
private static List<java.awt.Container> ignored = new ArrayList<java.awt.Container>();
private static ComponentMap componentMap = new DefaultComponentMap();
public static void init(java.awt.Container... ignored) {
Timeouts timeouts = JemmyProperties.getCurrentTimeouts();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
timeouts.setTimeout((String) entry.getKey(), Long.parseLong((String) entry.getValue()));
}
currentWindow = null;
JemmyDSL.ignored = Arrays.asList(ignored);
JemmyProperties.setCurrentOutput(new TestOut(System.in, (PrintStream) null, null));
robotMode();
}
public static void robotMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.ROBOT_MODEL_MASK);
}
public static void dispatchingMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.QUEUE_MODEL_MASK);
}
public static boolean isRobotMode() {
return JemmyProperties.getCurrentDispatchingModel() == JemmyProperties.ROBOT_MODEL_MASK;
}
public static ComponentMap getComponentMap() {
return componentMap;
}
public static void setComponentMap(ComponentMap componentMap) {
JemmyDSL.componentMap = componentMap;
}
public static Frame frame(String title) {
Frame frame = new Frame(title);
currentWindow = frame;
return frame;
}
public static Frame frame() {
return (Frame) currentWindow;
}
public static Window currentWindow() {
if (currentWindow == null) {
logger.info("No current container found, trying to find one.");
currentWindow = findActiveWindow();
} else if (!currentWindow.isActive()) {
currentWindow = findActiveWindow();
}
if (currentWindow == null) throw new JemmyDSLException("Cannot find a currently active window");
logger.info("Using as current container: " + currentWindow.getComponent());
return currentWindow;
}
private static Window findActiveWindow() {
java.awt.Window[] windows = JFrame.getWindows();
for (java.awt.Window w : windows) {
if (ignored.contains(w)) continue;
if (!w.isActive()) continue;
if (w instanceof JFrame) {
return new Frame((JFrame) w);
} else if (w instanceof JDialog) {
return new Dialog((JDialog) w);
} else {
logger.info("Found a window which is neither a JFrame nor JDialog");
}
}
return null;
}
public static Container container(JFrame frame) {
currentWindow = new Frame(frame);
return currentWindow;
}
public static Dialog dialog(String title) {
final Dialog dialog = new Dialog(title);
currentWindow = dialog;
return dialog;
}
public static TextField textField(String locator) {
return new TextField(locator);
}
public static TextArea textArea(String locator) {
return new TextArea(locator);
}
public static Button button(String locator) {
return new Button(locator);
}
public static ComboBox comboBox(String locator) {
return new ComboBox(locator);
}
public static CheckBox checkBox(String locator) {
return new CheckBox(locator);
}
public static Table table(String locator) {
return new Table(locator);
}
/**
* Finds a component and stores it under the given id. The component can later be used on other commands using the
* locator "id=ID_ASSIGNED". This method searches both VISIBLE and INVISIBLE components.
*
* @param locator The locator (accepted are name (default), title, text, label)
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component find(String locator, String id, String componentType) {
java.awt.Component component = findComponent(locator, currentWindow().getComponent().getSource());
if (component == null) {
componentMap.putComponent(id, null);
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
final Component finalComponent = convertFind(operator);
if (finalComponent instanceof Window) {
currentWindow = (Window) finalComponent;
}
return finalComponent;
}
@SuppressWarnings({"unchecked"})
private static Class<? extends java.awt.Component> translateFindType(String findType) {
for (ComponentType componentType : ComponentType.values()) {
if (findType.equals(componentType.name())) return componentType.getAwtClass();
}
try {
return (Class<? extends java.awt.Component>) Class.forName(findType);
} catch (ClassNotFoundException e) {
throw new JemmyDSLException("Unsupported find type " + findType);
}
}
private static java.awt.Component findComponent(String locator, java.awt.Component component) {
assert locator != null;
String[] strs = parseLocator(locator);
if (strs.length != 2) throw new JemmyDSLException("Invalid locator " + locator);
if (strs[0].equals("id")) {
return componentMap.getComponent(strs[1]).getSource();
} else {
return AWTTreeScanner.scan(component, compileMatcher(strs));
}
}
private static String[] parseLocator(String locator) {
int i = locator.indexOf("=");
if (i == -1) {
return new String[] { "name", locator.substring(i + 1).trim()};
}
return new String[] { locator.substring(0, i).trim(), locator.substring(i + 1).trim()};
}
private static ScannerMatcher compileMatcher(String[] strs) {
if (strs[0].equals("name")) return new AWTTreeScanner.NameScannerMatcher(strs[1]);
if (strs[0].equals("title")) return new AWTTreeScanner.TitleScannerMatcher(strs[1]);
if (strs[0].equals("text")) return new AWTTreeScanner.TextScannerMatcher(strs[1]);
throw new JemmyDSLException("Invalid locator " + strs[0] + "=" + strs[1]);
}
/**
* Returns a list of all visible components which are instances of the given class.
* If one needs a find that returns an invisible component should add a parameter here.
* But the default behavior must be returning only visible components as it is the most common
* operation and required for compatibility with scripts converted from jfcunit. see #15790.
*
* @param container
* @param componentClass
* @return
*/
private static List<java.awt.Component> findComponents(java.awt.Container container, Class<? extends java.awt.Component> componentClass) {
List<java.awt.Component> list = new ArrayList<java.awt.Component>();
for (java.awt.Component component : container.getComponents()) {
if (component.isVisible() && componentClass.isAssignableFrom(component.getClass())) {
list.add(component);
}
if (component instanceof java.awt.Container) {
List<java.awt.Component> children = findComponents((java.awt.Container) component, componentClass);
list.addAll(children);
}
}
return list;
}
private static JComponentOperator convertFind(java.awt.Component comp) {
if (comp instanceof JComboBox) return new JComboBoxOperator((JComboBox) comp);
if (comp instanceof JTextComponent) return new JTextFieldOperator((JTextField) comp);
if (comp instanceof JCheckBox) return new JCheckBoxOperator((JCheckBox) comp);
if (comp instanceof JRadioButton) return new JRadioButtonOperator((JRadioButton) comp);
if (comp instanceof JButton) return new JButtonOperator((JButton) comp);
if (comp instanceof AbstractButton) return new AbstractButtonOperator((AbstractButton) comp);
if (comp instanceof JTable) {
return new TableOperator((JTable) comp);
}
if (comp instanceof JMenuBar) return new JMenuBarOperator((JMenuBar) comp);
if (comp instanceof JScrollBar) return new JScrollBarOperator((JScrollBar) comp);
if (comp instanceof JInternalFrame) return new JInternalFrameOperator((JInternalFrame) comp);
throw new JemmyDSLException("Unsupported find type " + comp);
}
private static Component convertFind(JComponentOperator comp) {
if (comp instanceof JComboBoxOperator) return new ComboBox((JComboBoxOperator) comp);
if (comp instanceof JTextComponentOperator) return new TextField((JTextFieldOperator) comp);
if (comp instanceof JCheckBoxOperator) return new CheckBox((JCheckBoxOperator) comp);
if (comp instanceof JRadioButtonOperator) return new RadioButton((JRadioButtonOperator) comp);
if (comp instanceof JButtonOperator) return new Button((JButtonOperator) comp);
if (comp instanceof AbstractButtonOperator) return new GenericButton((AbstractButtonOperator) comp);
if (comp instanceof JTableOperator) return new Table((JTableOperator) comp);
if (comp instanceof JMenuBarOperator) return new MenuBar((JMenuBarOperator) comp);
if (comp instanceof JScrollBarOperator) return new ScrollBar((JScrollBarOperator) comp);
// not really sure this is the right thing to do, but constructor here expects a component and not an operator:
if (comp instanceof JInternalFrameOperator) return new InternalFrame((JInternalFrame) ((JInternalFrameOperator) comp).getSource());
throw new JemmyDSLException("Unsupported find type " + comp);
}
/**
* Finds the first component with the given component type and stores it under the given id. The component can later
* be used on other commands using the locator "id=ID_ASSIGNED". This method searches both VISIBLE and INVISIBLE
* components.
*
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component findByComponentType(String id, String containerId, String componentType, int index) {
java.awt.Container container;
if (isBlank(containerId)) {
container = (java.awt.Container) currentWindow().getComponent().getSource();
} else {
ComponentOperator op = componentMap.getComponent(containerId);
if (op != null && op.getSource() instanceof java.awt.Container) {
container = (java.awt.Container) op.getSource();
} else {
container = (java.awt.Container) currentWindow().getComponent().getSource();
}
}
List<java.awt.Component> list = findComponents(container, translateFindType(componentType));
if (logger.isDebugEnabled()) {
logger.debug("findComponents returned list :");
for (java.awt.Component c : list) {
logger.debug(" " + c.getName());
}
logger.debug(" index = " + index);
}
if (index < 0 || index >= list.size()) {
return null;
}
java.awt.Component component = list.get(index);
if (component == null) {
componentMap.putComponent(id, null);
logger.debug("findByComponentType returned null");
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
if (logger.isDebugEnabled()) {
logger.debug("findByComponentType returned " + component);
}
return convertFind(operator);
}
public static void click(String locator, int count, String modifiers) {
final JComponentOperator operator = find(locator, JComponentOperator.class);
if (operator == null) throw new JemmyDSLException("Could not find component for clicking " + locator);
operator.clickMouse(operator.getCenterXForClick(), operator.getCenterYForClick(), count, InputEvent.BUTTON1_MASK,
convertModifiers(modifiers));
}
public static void typeSpecial(String locator, String keyString, String modifiers) {
final JComponentOperator operator = find(locator, JComponentOperator.class);
if (operator == null) throw new JemmyDSLException("Could not find component for typing key " + locator);
int key = convertKey(keyString);
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
operator.requestFocus();
operator.pushKey(key, convertModifiers(modifiers));
}
private static int convertModifiers(String modifiers) {
if (isBlank(modifiers)) return 0;
String[] mods = modifiers.split("[ |\\+|,]+");
int flags = 0;
for (String mod : mods) {
if ("Shift".equalsIgnoreCase(mod)) {
flags |= InputEvent.SHIFT_MASK;
} else if ("Control".equalsIgnoreCase(mod) || "Ctrl".equalsIgnoreCase(mod)) {
flags |= InputEvent.CTRL_MASK;
} else if ("Alt".equalsIgnoreCase(mod)) {
flags |= InputEvent.ALT_MASK;
} else {
throw new JemmyDSLException("Unknown modifier " + mod);
}
}
return flags;
}
@SuppressWarnings({"unchecked"})
public static <X extends JComponentOperator> X find(String locator, Class<X> clazz) {
Map<String, String> locatorMap = Utils.parseLocator(locator);
X component;
if (locatorMap.containsKey("name")) {
component = newInstance(clazz, currentWindow().getComponent(), new NameComponentChooser(locator));
} else if (locatorMap.containsKey("label")) {
JLabelOperator jlabel = new JLabelOperator(currentWindow().getComponent(), locatorMap.get("label"));
if (!(jlabel.getLabelFor() instanceof JTextField)) {
throw new JemmyDSLException("Associated component for " + locator + " is not a JTextComponent");
}
component = newInstance(clazz, JTextField.class, (JTextField) jlabel.getLabelFor());
} else if (locatorMap.containsKey("text")) {
if (JTextComponentOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz, currentWindow().getComponent(), new JTextComponentOperator.JTextComponentByTextFinder(locatorMap.get("text")));
} else if (AbstractButtonOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz, currentWindow().getComponent(), new AbstractButtonOperator.AbstractButtonByLabelFinder(locatorMap.get("text")));
} else if (JComponentOperator.class.isAssignableFrom(clazz)) {
// Hack, we assume that what was really meant was AbstractButtonOperator
component = newInstance(clazz, currentWindow().getComponent(), new AbstractButtonOperator.AbstractButtonByLabelFinder(locatorMap.get("text")));
} else {
throw new JemmyDSLException("Unsupported component type for location by text locator: " + locator);
}
} else if (locatorMap.containsKey("id")) {
ComponentOperator operator = componentMap.getComponent(locatorMap.get("id"));
if (operator == null) return null;
if (!clazz.isAssignableFrom(operator.getClass())) {
throw new JemmyDSLException("Cannot convert component with " + locator + " from "
+ operator.getClass().getName() + " to " + clazz.getName());
}
component = (X) operator;
} else if (locatorMap.containsKey("title")) {
if (JInternalFrameOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz, currentWindow().getComponent(), new JInternalFrameOperator.JInternalFrameByTitleFinder(locatorMap.get("title")));
} else {
throw new JemmyDSLException("Unsupported component type for location by text locator: " + locator);
}
} else {
throw new JemmyDSLException("Unsupported locator: " + locator);
}
return component;
}
private static <X extends JComponentOperator> X newInstance(Class<X> clazz, ContainerOperator parent,
ComponentChooser chooser) {
try {
Constructor<X> c = clazz.getConstructor(ContainerOperator.class, ComponentChooser.class);
return c.newInstance(parent, chooser);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException) throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
private static <X extends JComponentOperator, Y> X newInstance(Class<X> clazz, Class<Y> componentClass, JComponent component) {
try {
Constructor<X> c = findConstructor(clazz, componentClass);
return c.newInstance(component);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException) throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
@SuppressWarnings({"unchecked"})
private static <X, Y> Constructor<X> findConstructor(Class<X> clazz, Class<Y> componentClass) {
Constructor<X>[] cs = (Constructor<X>[]) clazz.getConstructors();
for (Constructor<X> c : cs) {
final Class<?>[] types = c.getParameterTypes();
if (types.length == 1 && types[0].isAssignableFrom(componentClass)) return c;
}
throw new JemmyDSLException("Could not find suitable constructor in class " + clazz.getCanonicalName());
}
public static JComponent getSwingComponentById(String id) {
ComponentOperator op = componentMap.getComponent(id);
return (JComponent) op.getSource();
}
public static Dialog getDialogById(String id) {
ComponentOperator op = componentMap.getComponent(id);
if (!(op instanceof JDialogOperator)) return null;
return new Dialog((JDialog) op.getSource());
}
public static Label label(String locator) {
return new Label(find(locator, JLabelOperator.class));
}
public static TabbedPane tabbedPane(String locator) {
return new TabbedPane(locator);
}
public static Slider slider(String locator) {
return new Slider(locator);
}
public static InternalFrame internalFrame(String locator) {
return new InternalFrame(locator);
}
/**
* Gets the menu bar for the last activated frame.
*
* @return The menu bar
*/
public static MenuBar menuBar() {
return new MenuBar();
}
public static void waitEnabled(String locator, boolean enabled) {
JComponentOperator op = find(locator, JComponentOperator.class);
try {
if (enabled) {
op.waitComponentEnabled();
} else {
waitComponentDisabled(op);
}
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public static void waitHasFocus(String locator) {
JComponentOperator op = find(locator, JComponentOperator.class);
op.waitHasFocus();
}
public static void waitChecked(String locator, boolean checked) {
JToggleButtonOperator op = find(locator, JToggleButtonOperator.class);
try {
waitComponentChecked(op, checked);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
private static void waitComponentDisabled(final ComponentOperator op) throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((java.awt.Component) obj).isEnabled()) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(), "ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static void waitComponentChecked(final JToggleButtonOperator op, final boolean checked) throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((JToggleButton) obj).isSelected() != checked) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(), "ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static int convertKey(String keyString) {
if ("Tab".equalsIgnoreCase(keyString)) return KeyEvent.VK_TAB;
else if ("Enter".equalsIgnoreCase(keyString)) return KeyEvent.VK_ENTER;
else if ("End".equalsIgnoreCase(keyString)) return KeyEvent.VK_END;
else if ("Backspace".equalsIgnoreCase(keyString)) return KeyEvent.VK_BACK_SPACE;
else if ("Delete".equalsIgnoreCase(keyString)) return KeyEvent.VK_DELETE;
else if ("Up".equalsIgnoreCase(keyString)) return KeyEvent.VK_UP;
else if ("Down".equalsIgnoreCase(keyString)) return KeyEvent.VK_DOWN;
else if ("Right".equalsIgnoreCase(keyString)) return KeyEvent.VK_RIGHT;
else if ("Left".equalsIgnoreCase(keyString)) return KeyEvent.VK_LEFT;
else if ("Home".equalsIgnoreCase(keyString)) return KeyEvent.VK_HOME;
else if ("End".equalsIgnoreCase(keyString)) return KeyEvent.VK_END;
else if ("F4".equalsIgnoreCase(keyString)) return KeyEvent.VK_F4;
else if ("F5".equalsIgnoreCase(keyString)) return KeyEvent.VK_F5;
else if ("Space".equalsIgnoreCase(keyString)) return KeyEvent.VK_SPACE;
else throw new UnsupportedFeatureException("Type special for " + keyString + " not supported");
}
public static abstract class Component {
public abstract ComponentOperator getComponent();
public void assertEnabled() {
try {
getComponent().waitComponentEnabled();
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void assertDisabled() {
try {
waitComponentDisabled(getComponent());
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void store(String id) {
componentMap.putComponent(id, getComponent());
}
}
public static abstract class Container extends Component {
@Override
public abstract ContainerOperator getComponent();
}
public static abstract class Window extends Container {
public abstract boolean isActive();
public abstract boolean isShowing();
}
public static class Frame extends Window {
private final JFrameOperator component;
public Frame(String title) {
component = new JFrameOperator(title);
}
public Frame(JFrame frame) {
component = new JFrameOperator(frame);
}
public Frame close() {
component.requestClose();
return this;
}
public Frame activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isActive() {
return component.isActive();
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public JFrameOperator getComponent() {
return component;
}
}
public static class Dialog extends Window {
private final JDialogOperator component;
public Dialog(String title) {
component = new JDialogOperator(title);
}
public Dialog(JDialog dialog) {
component = new JDialogOperator(dialog);
}
public Dialog close() {
component.requestClose();
return this;
}
@Override
public JDialogOperator getComponent() {
return component;
}
public Dialog activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public boolean isActive() {
return component.isActive();
}
public void assertText(String text) {
final String t = text;
if (text == null) text = "";
java.awt.Component c = component.findSubComponent(new ComponentChooser() {
@Override
public String getDescription() {
return null;
}
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!comp.isVisible()) return false;
if (comp instanceof JTextField) {
String compText = ((JTextField) comp).getText();
if (compText == null) compText = "";
return t.equals(compText);
} else if (comp instanceof JLabel) {
String compText = ((JLabel) comp).getText();
if (compText == null) compText = "";
return t.equals(compText);
}
return false;
}
});
if (c == null) {
throw new AssertionFailedException("assert_dialog: could not find component with text " + text);
}
}
}
public static class TextField extends Component {
private final JTextComponentOperator component;
public TextField(String locator) {
component = find(locator, JTextComponentOperator.class);
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField(JTextFieldOperator component) {
this.component = component;
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
component.requestFocus();
component.setVerification(false);
component.typeText(text);
return this;
}
public TextField type(char key) {
component.typeKey(key);
if (!isRobotMode()) {
// This is a hack because type key in queue mode does not wait for events to be fired
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
return this;
}
public TextField type(int key) {
component.pushKey(key);
return this;
}
public String text() {
return component.getText();
}
public void assertText(String text) {
component.waitText(text);
}
@Override
public JTextComponentOperator getComponent() {
return component;
}
public TextField assertEmpty() {
component.waitText("");
return this;
}
public TextField clickCharPosition(int pos, String modifiers, int count) {
FontMetrics fm = component.getFontMetrics(component.getFont());
component.clickMouse(fm.stringWidth(component.getText().substring(0, pos)) + component.getInsets().left,
component.getCenterYForClick(), count, KeyEvent.BUTTON1_MASK, convertModifiers(modifiers));
return this;
}
}
public static class TextArea extends Component {
private final JTextAreaOperator component;
public TextArea(String locator) {
component = find(locator, JTextAreaOperator.class);
}
public TextArea(JTextAreaOperator component) {
this.component = component;
}
public TextArea type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
component.setVerification(false);
component.typeText(text);
return this;
}
public String text() {
return component.getText();
}
@Override
public JTextAreaOperator getComponent() {
return component;
}
public TextArea assertEmpty() {
component.waitText("");
return this;
}
}
public static class ComboBox extends Component {
private final JComboBoxOperator component;
public ComboBox(String locator) {
component = find(locator, JComboBoxOperator.class);
}
public ComboBox(JComboBoxOperator comp) {
this.component = comp;
}
public void select(String text) {
Map<String, String> selectedItem = Utils.parseLocator(text);
if (selectedItem.containsKey("name")) {
clickDropDown();
component.selectItem(selectedItem.get("name"));
} else if (selectedItem.containsKey("index")) {
select(Integer.parseInt(selectedItem.get("index")));
} else {
throw new IllegalParametersException("Illegal parameters " + text + " for select command");
}
}
public void select(int index) {
clickDropDown();
component.setSelectedIndex(index);
component.waitItemSelected(index);
component.hidePopup();
}
private void clickDropDown() {
component.pushComboButton();
component.waitList();
}
@Override
public JComboBoxOperator getComponent() {
return component;
}
public void assertSelected(String text) {
component.waitItemSelected(text);
}
}
public static class GenericButton extends Component {
protected AbstractButtonOperator component;
protected GenericButton() {}
public GenericButton(String locator) {
component = find(locator, AbstractButtonOperator.class);
}
public GenericButton(AbstractButtonOperator component) {
this.component = component;
}
public void click() {
component.push();
}
@Override
public AbstractButtonOperator getComponent() {
return component;
}
}
public static class Button extends GenericButton {
public Button(String locator) {
component = find(locator, JButtonOperator.class);
}
public Button(JButtonOperator component) {
super(component);
}
@Override
public JButtonOperator getComponent() {
return (JButtonOperator) component;
}
}
public static class CheckBox extends GenericButton {
public CheckBox(String locator) {
component = find(locator, JCheckBoxOperator.class);
}
public CheckBox(JCheckBoxOperator component) {
super(component);
}
@Override
public JCheckBoxOperator getComponent() {
return (JCheckBoxOperator) component;
}
}
public static class RadioButton extends GenericButton {
public RadioButton(String locator) {
component = find(locator, JRadioButtonOperator.class);
}
public RadioButton(JRadioButtonOperator component) {
super(component);
}
@Override
public JRadioButtonOperator getComponent() {
return (JRadioButtonOperator) component;
}
}
public static class Table extends Component {
private final JTableOperator component;
public Table(String locator) {
component = find(locator, JTableOperator.class);
}
public Table(JTableOperator component) {
this.component = component;
}
public Row row(int index) {
return new Row(component, index);
}
public TableHeader header() {
return new TableHeader(component.getTableHeader());
}
public Table selectRows(int first, int last) {
component.setRowSelectionInterval(first, last);
return this;
}
@Override
public JTableOperator getComponent() {
return component;
}
}
public static class TableOperator extends JTableOperator {
public static class XJTableByCellFinder extends JTableByCellFinder
{
private final String label;
private final int row;
private final int column;
private final StringComparator comparator;
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!"".equals(label)) {
return super.checkComponent(comp);
} else if(comp instanceof JTable) {
if(((JTable)comp).getRowCount() > row && ((JTable)comp).getColumnCount() > column) {
int r = row;
if(r == -1) {
int[] rows = ((JTable)comp).getSelectedRows();
if(rows.length != 0) {
r = rows[0];
} else {
return(false);
}
}
int c = column;
if(c == -1) {
int[] columns = ((JTable)comp).getSelectedColumns();
if(columns.length != 0) {
c = columns[0];
} else {
return(false);
}
}
Object value = ((JTable)comp).getValueAt(r, c);
if(value == null) {
value = "";
}
return(comparator.equals(value.toString(),
label));
}
}
return(false);
}
public XJTableByCellFinder(String lb, int r, int c, StringComparator comparator) {
super(lb,r,c,comparator);
this.label = lb;
this.row = r;
this.column = c;
this.comparator = comparator;
}
public XJTableByCellFinder(String lb, int r, int c) {
this(lb, r, c, Operator.getDefaultStringComparator());
}
}
public TableOperator(JTable b) {
super(b);
}
/**
* Overridden to prevent trying to scroll to the row header
* (which can't be done as the row header is located totally to the left of the scroll bar).
*/
@Override
public void scrollToCell(int row, int column) {
// try to find JScrollPane under.
JScrollPane scroll = (JScrollPane)getContainer(new JScrollPaneOperator.
JScrollPaneFinder(ComponentSearcher.
getTrueChooser("JScrollPane")));
if (scroll == null) {
return;
}
// if source is the row header table, do nothing
if (getSource() == scroll.getRowHeader().getView()) {
return;
}
super.scrollToCell(row, column);
}
/**
* Overridden method to allow searching for empty strings
*/
@Override
public void waitCell(String cellText, int row, int column) {
waitState(new XJTableByCellFinder(cellText, row, column, getComparator()));
}
}
public static class Row {
private final JTableOperator component;
private final int index;
public Row(JTableOperator component, int index) {
this.component = component;
this.index = index;
}
public Row assertColumn(int col, String value) {
component.waitCell(value, index, col);
return this;
}
public Row select() {
component.setRowSelectionInterval(index, index);
return this;
}
public Row assertSelected(final boolean selected) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTable) comp).isRowSelected(index) == selected;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
public Row selectCell(int col) {
component.selectCell(index, col);
return this;
}
public Row clickCell(int col, int clicks) {
component.clickOnCell(index, col, clicks);
return this;
}
}
public static class TableHeader {
private final JTableHeaderOperator component;
public TableHeader(JTableHeader swingComponent) {
component = new JTableHeaderOperator(swingComponent);
}
public TableHeader assertTitle(final int col, final String title) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTableHeader) comp).getColumnModel().getColumn(col).getHeaderValue().equals(title);
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
}
public static class Label {
private final JLabelOperator component;
public Label(JLabelOperator component) {
this.component = component;
}
public Label text(String text) {
component.waitText(text);
return this;
}
}
public static class TabbedPane extends Component {
private final JTabbedPaneOperator component;
public TabbedPane(String locator) {
component = find(locator, JTabbedPaneOperator.class);
}
public TabbedPane select(String title) {
component.selectPage(title);
return this;
}
@Override
public JTabbedPaneOperator getComponent() {
return component;
}
}
public static class Slider extends Component {
private final JSliderOperator component;
public Slider(String locator) {
component = find(locator, JSliderOperator.class);
}
public Slider value(int i) {
component.setValue(i);
return this;
}
public Slider assertValue(final int i) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JSlider) comp).getValue() == i;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
@Override
public ComponentOperator getComponent() {
return component;
}
}
public static class MenuBar extends Container {
private final JMenuBarOperator component;
public MenuBar() {
component = new JMenuBarOperator(currentWindow().getComponent());
}
public MenuBar(JMenuBarOperator component) {
this.component = component;
}
public MenuBar clickMenu(int... indexes) {
logger.info("======================");
logger.info("Clicking menu . Indexes: " + Arrays.toString(indexes));
if (indexes.length == 0) return this;
String[] texts = new String[indexes.length];
logger.info("Calling component.getMenu for " + indexes[0]);
JMenu menu = component.getMenu(indexes[0]);
logger.info("Got " + menu);
texts[0] = menu.getText();
for (int i = 1; i < indexes.length; i++) {
int index = indexes[i];
assert menu != null;
if (i == indexes.length - 1) {
logger.info("Calling component.getMenuComponent for " + indexes[i]);
JMenuItem item = (JMenuItem) menu.getMenuComponent(index);
logger.info("Got " + item);
; texts[i] = item.getText();
menu = null;
} else {
logger.info("Calling component.getMenuComponent for " + indexes[i]);
menu = (JMenu) menu.getMenuComponent(index);
logger.info("Got " + menu);
texts[i] = menu.getText();
}
}
clickMenu(texts);
return this;
}
public MenuBar clickMenu(String... texts) {
logger.info("Clicking menu . Texts: " + Arrays.toString(texts));
if (texts.length == 0) return this;
component.showMenuItem(texts[0]);
for (int i = 1; i < texts.length; i++) {
String text = texts[i];
logger.info("Callig showMenuItem for " + text);
new JMenuOperator(currentWindow().getComponent(), texts[i - 1]).showMenuItem(new String[] {text});
}
logger.info("Callig clickMouse for " + texts[texts.length - 1]);
new JMenuItemOperator(currentWindow().getComponent(), texts[texts.length - 1]).clickMouse();
return this;
}
@Override
public JMenuBarOperator getComponent() {
return component;
}
}
public static class Menu extends Container {
private JMenuOperator component;
public Menu() {
}
@Override
public JMenuOperator getComponent() {
return component;
}
}
public static class InternalFrame extends Container {
private final JInternalFrameOperator component;
public InternalFrame(String locator) {
component = find(locator, JInternalFrameOperator.class);
}
public InternalFrame(JInternalFrame frame) {
component = new JInternalFrameOperator(frame);
}
public InternalFrame close() {
((JInternalFrame) component.getSource()).doDefaultCloseAction();
return this;
}
public InternalFrame hide() {
component.setVisible(false);
return this;
}
public InternalFrame show() {
component.setVisible(true);
return this;
}
public InternalFrame activate() {
component.activate();
return this;
}
public InternalFrame assertVisible(Boolean visible) {
component.waitComponentVisible(visible);
return this;
}
@Override
public JInternalFrameOperator getComponent() {
return component;
}
}
public static class ScrollBar extends Component {
private final JScrollBarOperator component;
public ScrollBar(String locator) {
component = find(locator, JScrollBarOperator.class);
}
public ScrollBar(JScrollBarOperator component) {
this.component = component;
}
@Override
public JScrollBarOperator getComponent() {
return component;
}
}
} |
package net.time4j.format;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* <p>Offers localized time unit patterns for formatting of durations. </p>
*
* @author Meno Hochschild
* @since 1.2
* @see UnitPatternProvider
* @concurrency <immutable>
*/
/*[deutsch]
* <p>Bietet lokalisierte Zeiteinheitsmuster zur Formatierung einer
* Dauer an. </p>
*
* @author Meno Hochschild
* @since 1.2
* @see UnitPatternProvider
* @concurrency <immutable>
*/
public final class UnitPatterns {
private static final ConcurrentMap<Locale, UnitPatterns> CACHE =
new ConcurrentHashMap<Locale, UnitPatterns>();
private static final char[] UNIT_IDS =
new char[] {'Y', 'M', 'W', 'D', 'H', 'N', 'S'};
private static final UnitPatternProvider PROVIDER;
private static final UnitPatternProvider FALLBACK;
static {
FALLBACK = new FallbackProvider();
UnitPatternProvider p = null;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = UnitPatternProvider.class.getClassLoader();
}
for (
UnitPatternProvider tmp
: ServiceLoader.load(UnitPatternProvider.class, cl)
) {
p = tmp;
break;
}
if (p == null) {
p = FALLBACK;
}
PROVIDER = p;
}
private final
Map<Character, Map<TextWidth, Map<PluralCategory, String>>> patterns;
private final Map<Character, Map<PluralCategory, String>> past;
private final Map<Character, Map<PluralCategory, String>> future;
private final String now;
private UnitPatterns(Locale language) {
super();
Map<Character, Map<TextWidth, Map<PluralCategory, String>>> map =
new HashMap
<Character, Map<TextWidth, Map<PluralCategory, String>>>(10);
Map<Character, Map<PluralCategory, String>> mapPast =
new HashMap<Character, Map<PluralCategory, String>>(10);
Map<Character, Map<PluralCategory, String>> mapFuture =
new HashMap<Character, Map<PluralCategory, String>>(10);
for (char unitID : UNIT_IDS) {
// Standard-Muster
Map<TextWidth, Map<PluralCategory, String>> tmp1 =
new EnumMap<TextWidth, Map<PluralCategory, String>>(
TextWidth.class);
for (TextWidth width : TextWidth.values()) {
Map<PluralCategory, String> tmp2 =
new EnumMap<PluralCategory, String>(PluralCategory.class);
for (PluralCategory cat : PluralCategory.values()) {
tmp2.put(cat, lookup(language, unitID, width, cat));
}
tmp1.put(width, Collections.unmodifiableMap(tmp2));
}
map.put(
Character.valueOf(unitID),
Collections.unmodifiableMap(tmp1));
// Vergangenheit
Map<PluralCategory, String> tmp3 =
new EnumMap<PluralCategory, String>(PluralCategory.class);
for (PluralCategory cat : PluralCategory.values()) {
tmp3.put(cat, lookup(language, unitID, false, cat));
}
mapPast.put(
Character.valueOf(unitID),
Collections.unmodifiableMap(tmp3));
// Zukunft
Map<PluralCategory, String> tmp4 =
new EnumMap<PluralCategory, String>(PluralCategory.class);
for (PluralCategory cat : PluralCategory.values()) {
tmp4.put(cat, lookup(language, unitID, true, cat));
}
mapFuture.put(
Character.valueOf(unitID),
Collections.unmodifiableMap(tmp4));
}
this.patterns = Collections.unmodifiableMap(map);
this.past = Collections.unmodifiableMap(mapPast);
this.future = Collections.unmodifiableMap(mapFuture);
String n;
try {
n = PROVIDER.getNowWord(language);
} catch (MissingResourceException mre) {
n = "now"; // should not happen
}
this.now = n;
}
/**
* <p>Factory method as constructor replacement. </p>
*
* @param lang language setting
* @return chached instance
*/
/*[deutsch]
* <p>Fabrikmethode als Konstruktor-Ersatz. </p>
*
* @param lang language setting
* @return chached instance
*/
public static UnitPatterns of(Locale lang) {
if (lang == null) {
throw new NullPointerException("Missing language.");
}
UnitPatterns p = CACHE.get(lang);
if (p == null) {
p = new UnitPatterns(lang);
UnitPatterns old = CACHE.putIfAbsent(lang, p);
if (old != null) {
p = old;
}
}
return p;
}
/**
* <p>Yields a pattern for years which optionally contains a placeholder
* of the form "{0}" standing for the count of years. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for years
*/
/*[deutsch]
* <p>Liefert ein Muster für Jahre, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Jahre
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for years
*/
public String getYears(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('Y').get(width).get(category);
}
/**
* <p>Yields a pattern for months which optionally contains a placeholder
* of the form "{0}" standing for the count of months. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for months
*/
/*[deutsch]
* <p>Liefert ein Muster für Monate, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Monate
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for months
*/
public String getMonths(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('M').get(width).get(category);
}
/**
* <p>Yields a pattern for weeks which optionally contains a placeholder
* of the form "{0}" standing for the count of weeks. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for weeks
*/
/*[deutsch]
* <p>Liefert ein Muster für Wochen, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Wochen
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for weeks
*/
public String getWeeks(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('W').get(width).get(category);
}
/**
* <p>Yields a pattern for days which optionally contains a placeholder
* of the form "{0}" standing for the count of days. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for days
*/
/*[deutsch]
* <p>Liefert ein Muster für Tage, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Tage
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for days
*/
public String getDays(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('D').get(width).get(category);
}
/**
* <p>Yields a pattern for hours which optionally contains a placeholder
* of the form "{0}" standing for the count of hours. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for hours
*/
/*[deutsch]
* <p>Liefert ein Muster für Stunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Stunden
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for hours
*/
public String getHours(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('H').get(width).get(category);
}
/**
* <p>Yields a pattern for minutes which optionally contains a placeholder
* of the form "{0}" standing for the count of minutes. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for minutes
*/
/*[deutsch]
* <p>Liefert ein Muster für Minuten, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Minuten
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for minutes
*/
public String getMinutes(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('N').get(width).get(category);
}
/**
* <p>Yields a pattern for seconds which optionally contains a placeholder
* of the form "{0}" standing for the count of seconds. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for seconds
*/
/*[deutsch]
* <p>Liefert ein Muster für Sekunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Sekunden
* repräsentiert. </p>
*
* @param width text width (ABBREVIATED as synonym for SHORT)
* @param category plural category
* @return unit pattern for seconds
*/
public String getSeconds(
TextWidth width,
PluralCategory category
) {
checkNull(width, category);
return this.patterns.get('S').get(width).get(category);
}
/**
* <p>Yields a pattern for years which optionally contains a placeholder
* of the form "{0}" standing for the count of years in the
* past. </p>
*
* @param category plural category
* @return unit pattern for years in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Jahre, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Jahre
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for years in the past
*/
public String getPastYears(PluralCategory category) {
checkNull(category);
return this.past.get('Y').get(category);
}
/**
* <p>Yields a pattern for years which optionally contains a placeholder
* of the form "{0}" standing for the count of years in the
* future. </p>
*
* @param category plural category
* @return unit pattern for years in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Jahre, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Jahre
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for years in the future
*/
public String getFutureYears(PluralCategory category) {
checkNull(category);
return this.future.get('Y').get(category);
}
/**
* <p>Yields a pattern for months which optionally contains a placeholder
* of the form "{0}" standing for the count of months in the
* past. </p>
*
* @param category plural category
* @return unit pattern for months in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Monate, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Monate
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for months in the past
*/
public String getPastMonths(PluralCategory category) {
checkNull(category);
return this.past.get('M').get(category);
}
/**
* <p>Yields a pattern for months which optionally contains a placeholder
* of the form "{0}" standing for the count of months in the
* future. </p>
*
* @param category plural category
* @return unit pattern for months in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Monate, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Monate
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for months in the future
*/
public String getFutureMonths(PluralCategory category) {
checkNull(category);
return this.future.get('M').get(category);
}
/**
* <p>Yields a pattern for weeks which optionally contains a placeholder
* of the form "{0}" standing for the count of weeks in the
* past. </p>
*
* @param category plural category
* @return unit pattern for weeks in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Wochen, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Wochen
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for weeks in the past
*/
public String getPastWeeks(PluralCategory category) {
checkNull(category);
return this.past.get('W').get(category);
}
/**
* <p>Yields a pattern for weeks which optionally contains a placeholder
* of the form "{0}" standing for the count of weeks in the
* future. </p>
*
* @param category plural category
* @return unit pattern for weeks in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Wochen, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Wochen
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for weeks in the future
*/
public String getFutureWeeks(PluralCategory category) {
checkNull(category);
return this.future.get('W').get(category);
}
/**
* <p>Yields a pattern for days which optionally contains a placeholder
* of the form "{0}" standing for the count of days in the
* past. </p>
*
* @param category plural category
* @return unit pattern for days in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Tage, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Tage
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for days in the past
*/
public String getPastDays(PluralCategory category) {
checkNull(category);
return this.past.get('D').get(category);
}
/**
* <p>Yields a pattern for days which optionally contains a placeholder
* of the form "{0}" standing for the count of days in the
* future. </p>
*
* @param category plural category
* @return unit pattern for days in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Tage, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Tage
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for days in the future
*/
public String getFutureDays(PluralCategory category) {
checkNull(category);
return this.future.get('D').get(category);
}
/**
* <p>Yields a pattern for hours which optionally contains a placeholder
* of the form "{0}" standing for the count of hours in the
* past. </p>
*
* @param category plural category
* @return unit pattern for hours in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Stunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Stunden
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for hours in the past
*/
public String getPastHours(PluralCategory category) {
checkNull(category);
return this.past.get('H').get(category);
}
/**
* <p>Yields a pattern for hours which optionally contains a placeholder
* of the form "{0}" standing for the count of hours in the
* future. </p>
*
* @param category plural category
* @return unit pattern for hours in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Stunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Stunden
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for hours in the future
*/
public String getFutureHours(PluralCategory category) {
checkNull(category);
return this.future.get('H').get(category);
}
/**
* <p>Yields a pattern for minutes which optionally contains a placeholder
* of the form "{0}" standing for the count of minutes in the
* past. </p>
*
* @param category plural category
* @return unit pattern for minutes in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Minuten, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Minuten
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for minutes in the past
*/
public String getPastMinutes(PluralCategory category) {
checkNull(category);
return this.past.get('N').get(category);
}
/**
* <p>Yields a pattern for minutes which optionally contains a placeholder
* of the form "{0}" standing for the count of minutes in the
* future. </p>
*
* @param category plural category
* @return unit pattern for minutes in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Minuten, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Minuten
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for minutes in the future
*/
public String getFutureMinutes(PluralCategory category) {
checkNull(category);
return this.future.get('N').get(category);
}
/**
* <p>Yields a pattern for seconds which optionally contains a placeholder
* of the form "{0}" standing for the count of seconds in the
* past. </p>
*
* @param category plural category
* @return unit pattern for seconds in the past
*/
/*[deutsch]
* <p>Liefert ein Muster für Sekunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Sekunden
* in der Vergangenheit repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for seconds in the past
*/
public String getPastSeconds(PluralCategory category) {
checkNull(category);
return this.past.get('S').get(category);
}
/**
* <p>Yields a pattern for seconds which optionally contains a placeholder
* of the form "{0}" standing for the count of seconds in the
* future. </p>
*
* @param category plural category
* @return unit pattern for seconds in the future
*/
/*[deutsch]
* <p>Liefert ein Muster für Sekunden, das optional einen Platzhalter
* der Form "{0}" enthält, welcher die Anzahl der Sekunden
* in der Zukunft repräsentiert. </p>
*
* @param category plural category
* @return unit pattern for seconds in the future
*/
public String getFutureSeconds(PluralCategory category) {
checkNull(category);
return this.future.get('S').get(category);
}
/**
* <p>Yields the localized word for the current time (now). </p>
*
* @return String
*/
/*[deutsch]
* <p>Liefert das lokalisierte Wort für die aktuelle Zeit
* (jetzt). </p>
*
* @return String
*/
public String getNowWord() {
return this.now;
}
private static void checkNull(PluralCategory category) {
if (category == null) {
throw new NullPointerException("Missing plural category.");
}
}
private static void checkNull(
TextWidth width,
PluralCategory category
) {
if (width == null) {
throw new NullPointerException("Missing text width.");
}
checkNull(category);
}
private static String lookup(
Locale language,
char unitID,
TextWidth width,
PluralCategory category
) {
try {
return lookup(PROVIDER, language, unitID, width, category);
} catch (MissingResourceException mre) { // should not happen
return lookup(FALLBACK, language, unitID, width, category);
}
}
private static String lookup(
UnitPatternProvider p,
Locale language,
char unitID,
TextWidth width,
PluralCategory category
) {
switch (unitID) {
case 'Y':
return p.getYearsPattern(language, width, category);
case 'M':
return p.getMonthsPattern(language, width, category);
case 'W':
return p.getWeeksPattern(language, width, category);
case 'D':
return p.getDaysPattern(language, width, category);
case 'H':
return p.getHoursPattern(language, width, category);
case 'N':
return p.getMinutesPattern(language, width, category);
case 'S':
return p.getSecondsPattern(language, width, category);
default:
throw new UnsupportedOperationException("Unit-ID: " + unitID);
}
}
private static String lookup(
Locale language,
char unitID,
boolean future,
PluralCategory category
) {
if (future) {
try {
return lookupFuture(PROVIDER, language, unitID, category);
} catch (MissingResourceException mre) { // should not happen
return lookupFuture(FALLBACK, language, unitID, category);
}
} else {
try {
return lookupPast(PROVIDER, language, unitID, category);
} catch (MissingResourceException mre) { // should not happen
return lookupPast(FALLBACK, language, unitID, category);
}
}
}
private static String lookupPast(
UnitPatternProvider p,
Locale language,
char unitID,
PluralCategory category
) {
switch (unitID) {
case 'Y':
return p.getPastYearsPattern(language, category);
case 'M':
return p.getPastMonthsPattern(language, category);
case 'W':
return p.getPastWeeksPattern(language, category);
case 'D':
return p.getPastDaysPattern(language, category);
case 'H':
return p.getPastHoursPattern(language, category);
case 'N':
return p.getPastMinutesPattern(language, category);
case 'S':
return p.getPastSecondsPattern(language, category);
default:
throw new UnsupportedOperationException("Unit-ID: " + unitID);
}
}
private static String lookupFuture(
UnitPatternProvider p,
Locale language,
char unitID,
PluralCategory category
) {
switch (unitID) {
case 'Y':
return p.getFutureYearsPattern(language, category);
case 'M':
return p.getFutureMonthsPattern(language, category);
case 'W':
return p.getFutureWeeksPattern(language, category);
case 'D':
return p.getFutureDaysPattern(language, category);
case 'H':
return p.getFutureHoursPattern(language, category);
case 'N':
return p.getFutureMinutesPattern(language, category);
case 'S':
return p.getFutureSecondsPattern(language, category);
default:
throw new UnsupportedOperationException("Unit-ID: " + unitID);
}
}
private static class FallbackProvider
implements UnitPatternProvider {
@Override
public String getYearsPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("year", "yr", "y", width, category);
}
return getUnitPattern("y");
}
@Override
public String getMonthsPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("month", "mth", "m", width, category);
}
return getUnitPattern("m");
}
@Override
public String getWeeksPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("week", "wk", "w", width, category);
}
return getUnitPattern("w");
}
@Override
public String getDaysPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("day", "day", "d", width, category);
}
return getUnitPattern("d");
}
@Override
public String getHoursPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("hour", "hr", "h", width, category);
}
return getUnitPattern("h");
}
@Override
public String getMinutesPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("minute", "min", "m", width, category);
}
return getUnitPattern("min");
}
@Override
public String getSecondsPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getEnglishPattern("second", "sec", "s", width, category);
}
return getUnitPattern("s");
}
@Override
public String getPastYearsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("year", category);
}
return getPastPattern("y");
}
@Override
public String getPastMonthsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("month", category);
}
return getPastPattern("m");
}
@Override
public String getPastWeeksPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("week", category);
}
return getPastPattern("w");
}
@Override
public String getPastDaysPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("day", category);
}
return getPastPattern("d");
}
@Override
public String getPastHoursPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("hour", category);
}
return getPastPattern("h");
}
@Override
public String getPastMinutesPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("minute", category);
}
return getPastPattern("min");
}
@Override
public String getPastSecondsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getPastEnglishPattern("second", category);
}
return getPastPattern("s");
}
@Override
public String getFutureYearsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("year", category);
}
return getFuturePattern("y");
}
@Override
public String getFutureMonthsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("month", category);
}
return getFuturePattern("m");
}
@Override
public String getFutureWeeksPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("week", category);
}
return getFuturePattern("w");
}
@Override
public String getFutureDaysPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("day", category);
}
return getFuturePattern("d");
}
@Override
public String getFutureHoursPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("hour", category);
}
return getFuturePattern("h");
}
@Override
public String getFutureMinutesPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("minute", category);
}
return getFuturePattern("min");
}
@Override
public String getFutureSecondsPattern(
Locale lang,
PluralCategory category
) {
if (lang.getLanguage().equals("en")) {
return getFutureEnglishPattern("second", category);
}
return getFuturePattern("s");
}
@Override
public String getNowWord(Locale lang) {
return "now";
}
private static String getEnglishPattern(
String wide,
String abbr,
String narrow,
TextWidth width,
PluralCategory category
) {
switch (width) {
case WIDE:
return getPluralPattern(wide, category);
case ABBREVIATED:
case SHORT:
return getPluralPattern(abbr, category);
case NARROW:
return "{0}" + narrow;
default:
throw new UnsupportedOperationException(width.name());
}
}
private static String getPluralPattern(
String unit,
PluralCategory category
) {
String plural = (category == PluralCategory.ONE ? "" : "s");
return "{0} " + unit + plural;
}
private static String getUnitPattern(String unit) {
return "{0} " + unit;
}
private static String getPastEnglishPattern(
String unit,
PluralCategory category
) {
String plural = (category == PluralCategory.ONE ? "" : "s");
return "{0} " + unit + plural + " ago";
}
private static String getFutureEnglishPattern(
String unit,
PluralCategory category
) {
String plural = (category == PluralCategory.ONE ? "" : "s");
return "in {0} " + unit + plural;
}
private static String getPastPattern(String unit) {
return "-{0} " + unit;
}
private static String getFuturePattern(String unit) {
return "+{0} " + unit;
}
}
} |
package step.core.accessors;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import step.commons.conf.Configuration;
public class Collection {
MongoCollection<Document> collection;
public Collection(MongoClient client, String collectionName) {
super();
this.collection = getCollection(client, collectionName);
}
private MongoCollection<Document> getCollection(MongoClient client, String collectionName) {
//TODO pass DB Object instead of MongoClient
String databaseName = Configuration.getInstance().getProperty("db.database","step");
//DB db = client.getDB(databaseName);
MongoDatabase database = client.getDatabase(databaseName);
collection = database.getCollection(collectionName);
//Jongo jongo = new Jongo(db);
//MongoCollection collection = jongo.getCollection(collectionName);
return collection;
}
public List<String> distinct(String key) {
return collection.distinct(key, String.class).filter(new Document(key,new Document("$ne",null))).into(new ArrayList<String>());
}
public CollectionFind<Document> find(Bson query, SearchOrder order, Integer skip, Integer limit) {
// StringBuilder query = new StringBuilder();
// List<Object> parameters = new ArrayList<>();
// if(queryFragments!=null&&queryFragments.size()>0) {
// query.append("{$and:[");
// Iterator<String> it = queryFragments.iterator();
// while(it.hasNext()) {
// String criterium = it.next();
// query.append("{"+criterium+"}");
// if(it.hasNext()) {
// query.append(",");
// query.append("]}");
Document sortDoc = new Document(order.getAttributeName(), order.getOrder());
// StringBuilder sort = new StringBuilder();
// sort.append("{").append(order.getAttributeName()).append(":")
// .append(Integer.toString(order.getOrder())).append("}");
long count = collection.count();
long countResults = collection.count(query);
FindIterable<Document> find = collection.find(query).sort(sortDoc);
if(skip!=null) {
find.skip(skip);
}
if(limit!=null) {
find.limit(limit);
}
return new CollectionFind<Document>(count, countResults, find.iterator());
}
} |
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ReRouteInterface extends Application implements EventHandler{
@Override
public void start(Stage stage) throws Exception {
int height = 900;
int width = 900;
int headerInsetTop = 15;
int headerInsetRight = 12;
int headerInsetBottom = 15;
int headerInsetLeft = 12;
int LPInsetTop = 0;
int LPInsetRight = 20;
int LPInsetBottom = 10;
int LPInsetLeft = 20;
int rightPaneX = 0;
int rightPaneY = 0;
stage.setTitle("ReROUTE Simulator");
StackPane rootPane = new StackPane();
Button buttonLT = new Button("List Trains");
Button buttonLS = new Button("List Stations");
//Using dummy values for insets for now
Pane leftPane = new Pane();
leftPane.setPadding(new javafx.geometry.Insets(LPInsetTop, LPInsetRight,
LPInsetBottom, LPInsetLeft));
//Returns error for some reason
leftPane.getChildren().addAll(buttonLT, buttonLS);
//how to change VBox background colour?
Text leftPaneTitle1 = new Text("Lists");
leftPaneTitle1.setFont(javafx.scene.text.Font.font("Lato", FontWeight.BOLD, 14));
leftPaneTitle1.setFill(javafx.scene.paint.Color.WHITE);
leftPane.getChildren().add(leftPaneTitle1);
HBox header = new HBox();
header.setPadding(new Insets(headerInsetTop, headerInsetRight, headerInsetBottom, headerInsetRight));
header.setSpacing(10);
header.setStyle("-fx-background-color: ##19b585;");
Text headerTitle = new Text("ReROUTE Simulator");
headerTitle.setFont(Font.font("Lato", FontWeight.BOLD, 16));
headerTitle.setFill(Color.WHITE);
header.getChildren().add(headerTitle);
//idk if these height/width measurements are correct
Canvas canvas = new Canvas(width - LPInsetRight, height - headerInsetTop);
canvas.setLayoutX(rightPaneX);
canvas.setLayoutY(rightPaneY);
//idk if these are correct
canvas.setHeight(height - headerInsetTop);
canvas.setWidth(width - LPInsetLeft);
StackPane rightPane = new StackPane();
rightPane.getChildren().add(canvas);
rightPane.setStyle("-fx-background-color: black");
rootPane.getChildren().addAll(leftPane, rightPane, header);
Scene scene = new Scene(rootPane, width, height);
stage.setScene(scene);
}
@Override
public void handle(Event arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
launch(args);
}
} |
// OpenlabReader.java
package loci.formats;
import java.awt.Dimension;
import java.awt.Image;
import java.io.*;
import java.util.*;
/**
* OpenlabReader is the file format reader for Openlab LIFF files.
*
* -- TODO --
* address efficiency issues; testing showed 600-3000 ms were required
* to process each plane, with an additional 2000-4500 ms of overhead
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class OpenlabReader extends FormatReader {
// -- Static fields --
/** Helper reader to read PICT data with QT Java library. */
private static QTReader qtForm = new QTReader();
// -- Fields --
/** Current file. */
protected RandomAccessFile in;
/** Number of blocks for current Openlab LIFF. */
private int numBlocks;
/** Offset for each block of current Openlab LIFF file. */
private int[] offsets;
/** Image type for each block of current Openlab LIFF file. */
private int[] imageType;
/** Whether there is any color data in current Openlab LIFF file. */
private boolean isColor;
/** Flag indicating whether current file is little endian. */
protected boolean little = true;
// -- Constructor --
/** Constructs a new Openlab reader. */
public OpenlabReader() {
super("Openlab LIFF", new String[] {"liff", "lif"});
}
// -- FormatReader API methods --
/** Checks if the given string is a valid filename for an Openlab file. */
public boolean isThisType(String name) {
// Since we can't always determine it from the name alone (blank
// extensions), we open the file and call the block verifier.
long len = new File(name).length();
int count = len < 16384 ? (int) len : 16384;
byte[] buf = new byte[count];
try {
FileInputStream fin = new FileInputStream(name);
int read = 0;
while (read < count) {
read += fin.read(buf, read, count-read);
}
fin.close();
return isThisType(buf);
}
catch (IOException e) {
return false;
}
}
/** Checks if the given block is a valid header for an Openlab file. */
public boolean isThisType(byte[] block) {
return block.length >= 8 && block[0] == 0 && block[1] == 0 &&
block[2] == -1 && block[3] == -1 && block[4] == 105 &&
block[5] == 109 && block[6] == 112 && block[7] == 114;
}
/** Determines the number of images in the given Openlab file. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return numBlocks;
}
/** Obtains the specified image from the given Openlab file. */
public Image open(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
if (no < 0 || no >= getImageCount(id)) {
throw new FormatException("Invalid image number: " + no);
}
// First initialize:
in.seek(offsets[no] + 12);
byte[] toRead = new byte[4];
in.read(toRead);
int blockSize = batoi(toRead);
toRead = new byte[1];
in.read(toRead);
// right now I'm gonna skip all the header info
// check to see whether or not this is v2 data
if (toRead[0] == 1) {
in.skipBytes(128);
}
in.skipBytes(169);
// read in the block of data
toRead = new byte[blockSize];
int read = 0;
int left = blockSize;
while (left > 0) {
int i = in.read(toRead, read, left);
read += i;
left -= i;
}
byte[] pixelData = new byte[blockSize];
int pixPos = 0;
Dimension dim;
try {
dim= qtForm.getPictDimensions(toRead);
}
catch (Exception e) {
dim = new Dimension(0, 0);
}
int length = toRead.length;
int num, size, blockEnd;
int totalBlocks = -1; // set to allow loop to start.
int expectedBlock = 0;
int pos = 0;
int imagePos = 0;
int imageSize = dim.width * dim.height;
int[][] flatSamples = new int[1][imageSize];
byte[] temp;
boolean skipflag;
// read in deep grey pixel data into an array, and create a
// BufferedImage out of it
// First, checks the existence of a deep gray block. If it doesn't exist,
// assume it is PICT data, and attempt to read it. This is unpleasantly
// dangerous, because QuickTime has this unfortunate habit of crashing
// when it doesn't work.
// check whether or not there is deep gray data
while (expectedBlock != totalBlocks) {
skipflag = false;
while (pos + 7 < length &&
(toRead[pos] != 73 || toRead[pos + 1] != 86 ||
toRead[pos + 2] != 69 || toRead[pos + 3] != 65 ||
toRead[pos + 4] != 100 || toRead[pos + 5] != 98 ||
toRead[pos + 6] != 112 || toRead[pos + 7] != 113))
{
pos++;
}
if (pos + 32 > length) { // The header is 32 bytes long.
if (expectedBlock == 0 && imageType[no] < 9) {
// there has been no deep gray data, and it is supposed
// to be a pict... *crosses fingers*
try {
// This never actually throws an exception, to my knowledge,
// but we can always hope.
return qtForm.pictToImage(toRead);
}
catch (Exception e) {
throw new FormatException("No iPic comment block found", e);
}
}
else {
throw new FormatException("Expected iPic comment block not found");
}
}
pos += 8; // skip the block type we just found
// Read info from the iPic comment. This serves as a
// starting point to read the rest.
temp = new byte[] {
toRead[pos], toRead[pos+1], toRead[pos+2], toRead[pos+3]
};
num = batoi(temp);
if (num != expectedBlock) {
throw new FormatException("Expected iPic block not found");
}
expectedBlock++;
temp = new byte[] {
toRead[pos+4], toRead[pos+5], toRead[pos+6], toRead[pos+7]
};
if (totalBlocks == -1) {
totalBlocks = batoi(temp);
}
else {
if (batoi(temp) != totalBlocks) {
throw new FormatException("Unexpected totalBlocks numbein.read");
}
}
// skip to size
pos += 16;
temp = new byte[] {
toRead[pos], toRead[pos+1], toRead[pos+2], toRead[pos+3]
};
size = batoi(temp);
pos += 8;
blockEnd = pos + size;
// copy into our data array.
System.arraycopy(toRead, pos, pixelData, pixPos, size);
pixPos += size;
}
int pixelValue = 0;
pos = 0;
// Now read the data and wrap it in a BufferedImage
while (true) {
if (pos + 1 < pixelData.length) {
pixelValue = pixelData[pos] < 0 ? 256 + pixelData[pos] :
(int) pixelData[pos] << 8;
pixelValue += pixelData[pos + 1] < 0 ? 256 + pixelData[pos + 1] :
(int) pixelData[pos + 1];
}
else {
throw new FormatException("Malformed LIFF data");
}
flatSamples[0][imagePos] = pixelValue;
imagePos++;
if (imagePos == imageSize) { // done, return it
if (isColor) {
int[][] flatSamp = new int[3][];
flatSamp[0] = flatSamp[1] = flatSamp[2] = flatSamples[0];
return DataTools.makeImage(flatSamp, dim.width, dim.height);
}
else { // it's all grayscale
return DataTools.makeImage(flatSamples[0], dim.width, dim.height,
1, false);
}
}
}
}
/** Closes any open files. */
public void close() throws FormatException, IOException {
if (in != null) in.close();
in = null;
currentId = null;
}
/** Initializes the given Openlab file. */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessFile(id, "r");
// initialize an array containing tag offsets, so we can
// use an O(1) search instead of O(n) later.
// Also determine whether we will be reading color or grayscale
// images
//in.seek(0);
byte[] toRead = new byte[4];
in.read(toRead);
long order = batoi(toRead); // byte ordering
little = toRead[2] != 0xff || toRead[3] != 0xff;
isColor = false;
toRead = new byte[4];
Vector v = new Vector(); // a temp vector containing offsets.
// Get first offset.
in.seek(16);
in.read(toRead);
int nextOffset = batoi(toRead);
int nextOffsetTemp;
boolean first = true;
while(nextOffset != 0) {
in.seek(nextOffset + 4);
in.read(toRead);
// get next tag, but still need this one
nextOffsetTemp = batoi(toRead);
in.read(toRead);
if ((new String(toRead)).equals("PICT")) {
boolean ok = true;
if (first) {
// ignore first image if it is called "Original Image" (pure white)
first = false;
in.skipBytes(47);
byte[] layerNameBytes = new byte[127];
in.read(layerNameBytes);
String layerName = new String(layerNameBytes);
if (layerName.startsWith("Original Image")) ok = false;
}
if (ok) {
/* debug */ System.out.println("adding an offset");
v.add(new Integer(nextOffset)); // add THIS tag offset
}
}
if (nextOffset == nextOffsetTemp) break;
nextOffset = nextOffsetTemp;
}
in.seek(((Integer) v.firstElement()).intValue());
// create and populate the array of offsets from the vector.
numBlocks = v.size();
offsets = new int[numBlocks];
for (int i = 0; i < numBlocks; i++) {
offsets[i] = ((Integer) v.get(i)).intValue();
}
// check to see whether there is any color data. This also populates
// the imageTypes that the file uses.
toRead = new byte[2];
imageType = new int[numBlocks];
for (int i = 0; i < numBlocks; i++) {
in.seek(offsets[i]);
in.skipBytes(40);
in.read(toRead);
imageType[i] = batoi(toRead);
if (imageType[i] < 9) isColor = true;
}
initMetadata();
}
// -- Helper methods --
/** Populates the metadata hashtable. */
private void initMetadata() throws IOException {
// start by reading the file header
in.seek(0);
byte[] toRead = new byte[4];
in.read(toRead);
long order = batoi(toRead); // byte ordering
little = toRead[2] != 0xff || toRead[3] != 0xff;
metadata.put("Byte Order", new Boolean(little));
in.skipBytes(4);
in.read(toRead);
long version = DataTools.bytesToLong(toRead, little);
metadata.put("Version", new Long(version));
byte[] er = new byte[2];
in.read(er);
short count = DataTools.bytesToShort(er, little);
metadata.put("Count", new Short(count));
in.skipBytes(2);
in.read(toRead);
long offset = DataTools.bytesToLong(toRead, little);
// skip to first tag
in.seek(offset);
// read in each tag and its data
for (int i=0; i<count; i++) {
in.read(er);
short tag = DataTools.bytesToShort(er, little);
in.skipBytes(2);
in.read(toRead);
offset = DataTools.bytesToLong(toRead, little);
in.read(toRead);
long fmt = DataTools.bytesToLong(toRead, little);
metadata.put("Format", new Long(fmt));
in.read(toRead);
long numBytes = DataTools.bytesToLong(toRead, little);
metadata.put("NumBytes", new Long(numBytes));
if (tag == 67 || tag == 68) {
byte[] b = new byte[1];
in.read(b);
boolean isOpenlab2;
if (b[0] == '0') isOpenlab2 = false;
else isOpenlab2 = true;
metadata.put("isOpenlab2", new Boolean(isOpenlab2));
in.skipBytes(2);
in.read(er);
short layerId = DataTools.bytesToShort(er, little);
metadata.put("LayerID", new Short(layerId));
in.read(er);
short layerType = DataTools.bytesToShort(er, little);
metadata.put("LayerType", new Short(layerType));
in.read(er);
short bitDepth = DataTools.bytesToShort(er, little);
metadata.put("BitDepth", new Short(bitDepth));
in.read(er);
short opacity = DataTools.bytesToShort(er, little);
metadata.put("Opacity", new Short(opacity));
// not sure how many bytes to skip here
in.skipBytes(10);
in.read(toRead);
long type = DataTools.bytesToLong(toRead, little);
metadata.put("ImageType", new Long(type));
// not sure how many bytes to skip
in.skipBytes(10);
in.read(toRead);
long timestamp = DataTools.bytesToLong(toRead, little);
metadata.put("Timestamp", new Long(timestamp));
in.skipBytes(2);
if (isOpenlab2 == true) {
byte[] layerName = new byte[127];
in.read(layerName);
metadata.put("LayerName", new String(layerName));
in.read(toRead);
long timestampMS = DataTools.bytesToLong(toRead, little);
metadata.put("Timestamp-MS", new Long(timestampMS));
in.skipBytes(1);
byte[] notes = new byte[118];
in.read(notes);
metadata.put("Notes", new String(notes));
}
else in.skipBytes(123);
}
else if (tag == 69) {
in.read(toRead);
long platform = DataTools.bytesToLong(toRead, little);
metadata.put("Platform", new Long(platform));
in.read(er);
short units = DataTools.bytesToShort(er, little);
metadata.put("Units", new Short(units));
in.read(er);
short imageId = DataTools.bytesToShort(er, little);
metadata.put("ID", new Short(imageId));
in.skipBytes(1);
byte[] toRead2 = new byte[8];
double xOrigin = DataTools.readDouble(in, little);
metadata.put("XOrigin", new Double(xOrigin));
double yOrigin = DataTools.readDouble(in, little);
metadata.put("YOrigin", new Double(yOrigin));
double xScale = DataTools.readDouble(in, little);
metadata.put("XScale", new Double(xScale));
double yScale = DataTools.readDouble(in, little);
metadata.put("YScale", new Double(yScale));
in.skipBytes(1);
byte[] other = new byte[31];
in.read(other);
metadata.put("Other", new String(other));
}
// Initialize OME metadata
if (ome != null) {
OMETools.setAttribute(ome, "Pixels", "BigEndian",
little ? "false" : "true");
if (metadata.get("BitDepth") != null) {
int bitDepth = ((Integer) metadata.get("BitDepth")).intValue();
String type;
if (bitDepth <= 8) type = "int8";
else if (bitDepth <= 16) type = "int16";
else type = "int32";
OMETools.setAttribute(ome, "Image", "PixelType", type);
}
if (metadata.get("Timestamp") != null) {
OMETools.setAttribute(ome, "Image", "CreationDate",
"" + metadata.get("Timestamp").toString());
}
if (metadata.get("XOrigin") != null) {
OMETools.setAttribute(ome, "StageLabel", "X",
"" + metadata.get("XOrigin").toString());
}
if (metadata.get("YOrigin") != null) {
OMETools.setAttribute(ome, "StageLabel", "Y",
"" + metadata.get("YOrigin").toString());
}
if (metadata.get("XScale") != null) {
OMETools.setAttribute(ome, "Image", "PixelSizeX",
"" + metadata.get("XScale").toString());
}
if (metadata.get("YScale") != null) {
OMETools.setAttribute(ome, "Image", "PixelSizeY",
"" + metadata.get("YScale").toString());
}
}
in.seek(offset);
}
}
// -- Helper method --
/** Translates up to the first 4 bytes of a byte array to an integer. */
private static int batoi(byte[] inp) {
int len = inp.length>4?4:inp.length;
int total = 0;
for (int i = 0; i < len; i++) {
total += (inp[i]<0?256+inp[i]:(int)inp[i]) << (((len - 1) - i) * 8);
}
return total;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new OpenlabReader().testRead(args);
}
} |
// FlexReader.java
package loci.formats.in;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;
import javax.xml.parsers.*;
import loci.formats.*;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class FlexReader extends BaseTiffReader {
// -- Constants --
/** Custom IFD entry for Flex XML. */
protected static final int FLEX = 65200;
/** Factory for generating SAX parsers. */
public static final SAXParserFactory SAX_FACTORY =
SAXParserFactory.newInstance();
// -- Fields --
/** Scale factor for each image. */
protected double[] factors;
// -- Constructor --
/** Constructs a new Flex reader. */
public FlexReader() { super("Evotec Flex", "flex"); }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) { return false; }
/* @see loci.formats.FormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
// expand pixel values with multiplication by factor[no]
byte[] bytes = super.openBytes(no, buf);
if (core.pixelType[0] == FormatTools.UINT8) {
int num = bytes.length;
for (int i=num-1; i>=0; i
int q = (int) ((bytes[i] & 0xff) * factors[no]);
bytes[i] = (byte) (q & 0xff);
}
}
if (core.pixelType[0] == FormatTools.UINT16) {
int num = bytes.length / 2;
for (int i=num-1; i>=0; i
int q = (int) ((bytes[i] & 0xff) * factors[no]);
byte b0 = (byte) (q & 0xff);
byte b1 = (byte) ((q >> 8) & 0xff);
int ndx = 2 * i;
if (core.littleEndian[0]) {
bytes[ndx] = b0;
bytes[ndx + 1] = b1;
}
else {
bytes[ndx] = b1;
bytes[ndx + 1] = b0;
}
}
}
else if (core.pixelType[0] == FormatTools.UINT32) {
int num = bytes.length / 4;
for (int i=num-1; i>=0; i
int q = (int) ((bytes[i] & 0xff) * factors[no]);
byte b0 = (byte) (q & 0xff);
byte b1 = (byte) ((q >> 8) & 0xff);
byte b2 = (byte) ((q >> 16) & 0xff);
byte b3 = (byte) ((q >> 24) & 0xff);
int ndx = 4 * i;
if (core.littleEndian[0]) {
bytes[ndx] = b0;
bytes[ndx + 1] = b1;
bytes[ndx + 2] = b2;
bytes[ndx + 3] = b3;
}
else {
bytes[ndx] = b3;
bytes[ndx + 1] = b2;
bytes[ndx + 2] = b1;
bytes[ndx + 3] = b0;
}
}
}
return bytes;
}
// -- Internal BaseTiffReader API methods --
/* @see loci.formats.BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
core.orderCertain[0] = false;
// parse factors from XML
String xml = (String) TiffTools.getIFDValue(ifds[0],
FLEX, true, String.class);
// HACK - workaround for Windows and Mac OS X bug where
// SAX parser fails due to improperly handled mu (181) characters.
char[] c = xml.toCharArray();
for (int i=0; i<c.length; i++) {
if (c[i] < ' ' || c[i] > '~') c[i] = '?';
}
xml = new String(c);
Vector n = new Vector();
Vector f = new Vector();
FlexHandler handler = new FlexHandler(n, f);
try {
SAXParser saxParser = SAX_FACTORY.newSAXParser();
saxParser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
}
catch (ParserConfigurationException exc) {
throw new FormatException(exc);
}
catch (SAXException exc) {
throw new FormatException(exc);
}
// verify factor count
int nsize = n.size();
int fsize = f.size();
if (debug && (nsize != fsize || nsize != core.imageCount[0])) {
LogTools.println("Warning: mismatch between image count, " +
"names and factors (count=" + core.imageCount[0] +
", names=" + nsize + ", factors=" + fsize + ")");
}
for (int i=0; i<nsize; i++) addMeta("Name " + i, n.get(i));
for (int i=0; i<fsize; i++) addMeta("Factor " + i, f.get(i));
// parse factor values
factors = new double[core.imageCount[0]];
int max = 0;
for (int i=0; i<fsize; i++) {
String factor = (String) f.get(i);
double q = 1;
try {
q = Double.parseDouble(factor);
}
catch (NumberFormatException exc) {
if (debug) {
LogTools.println("Warning: invalid factor #" + i + ": " + factor);
}
}
factors[i] = q;
if (q > factors[max]) max = i;
}
Arrays.fill(factors, fsize, factors.length, 1);
// determine pixel type
if (factors[max] > 256) core.pixelType[0] = FormatTools.UINT32;
else if (factors[max] > 1) core.pixelType[0] = FormatTools.UINT16;
else core.pixelType[0] = FormatTools.UINT8;
}
// -- Helper classes --
/** SAX handler for parsing XML. */
public class FlexHandler extends DefaultHandler {
private Vector names, factors;
public FlexHandler(Vector names, Vector factors) {
this.names = names;
this.factors = factors;
}
public void startElement(String uri,
String localName, String qName, Attributes attributes)
{
if (!qName.equals("Array")) return;
int len = attributes.getLength();
for (int i=0; i<len; i++) {
String name = attributes.getQName(i);
if (name.equals("Name")) names.add(attributes.getValue(i));
else if (name.equals("Factor")) factors.add(attributes.getValue(i));
}
}
}
} |
package logbook.internal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class Deck {
private static final Map<String, String> DECK = new ConcurrentHashMap<String, String>() {
{
this.put("1", "");
this.put("2", "");
this.put("3", "");
this.put("4", "");
this.put("5", "");
this.put("6", "");
this.put("7", "");
this.put("8", "");
this.put("9", "");
this.put("10", "");
this.put("11", "");
this.put("12", "");
this.put("13", "");
this.put("14", "");
this.put("15", "");
this.put("16", "");
this.put("17", "");
this.put("18", "");
this.put("19", "");
this.put("20", "");
this.put("21", "<UNKNOWN>");
this.put("22", "<UNKNOWN>");
this.put("23", "<UNKNOWN>");
this.put("24", "<UNKNOWN>");
this.put("25", "");
this.put("26", "");
this.put("27", "");
this.put("28", "<UNKNOWN>");
this.put("29", "<UNKNOWN>");
this.put("30", "<UNKNOWN>");
this.put("31", "<UNKNOWN>");
this.put("32", "<UNKNOWN>");
this.put("33", "");
this.put("34", "");
this.put("35", "");
this.put("36", "");
this.put("37", "<UNKNOWN>");
this.put("38", "<UNKNOWN>");
this.put("39", "<UNKNOWN>");
this.put("40", "<UNKNOWN>");
}
};
/**
*
*
* @param id ID
* @return
*/
public static String get(String id) {
return DECK.get(id);
}
} |
package to.etc.domui.themes;
import java.io.*;
import java.util.*;
import javax.annotation.*;
import to.etc.domui.server.*;
import to.etc.domui.trouble.*;
import to.etc.domui.util.js.*;
import to.etc.domui.util.resources.*;
import to.etc.util.*;
final public class ThemeManager {
final private DomApplication m_application;
/** The thing that themes the application. Set only once @ init time. */
private IThemeFactory m_themeFactory;
/** The "current theme". This will become part of all themed resource URLs and is interpreted by the theme factory to resolve resources. */
private String m_currentTheme = "domui";
static private class ThemeRef {
final private ITheme m_theme;
private long m_lastuse;
final private IIsModified m_rdl;
public ThemeRef(ITheme theme, IIsModified rdl) {
m_theme = theme;
m_rdl = rdl;
}
public ITheme getTheme() {
return m_theme;
}
public long getLastuse() {
return m_lastuse;
}
public void setLastuse(long lastuse) {
m_lastuse = lastuse;
}
public IIsModified getDependencies() {
return m_rdl;
}
}
/** Map of themes by theme name, as implemented by the current engine. */
private final Map<String, ThemeRef> m_themeMap = new HashMap<String, ThemeRef>();
public ThemeManager(DomApplication application) {
m_application = application;
}
/**
* Sets the current theme string. This string is used as a "parameter" for the theme factory
* which will use it to decide on the "real" theme to use.
* @param currentTheme The theme name, valid for the current theme engine. Cannot be null nor the empty string.
*/
public synchronized void setCurrentTheme(@Nonnull String currentTheme) {
if(null == currentTheme)
throw new IllegalArgumentException("This cannot be null");
m_currentTheme = currentTheme;
}
/**
* Gets the current theme string. This will become part of all themed resource URLs
* and is interpreted by the theme factory to resolve resources.
* @return
*/
@Nonnull
public synchronized String getCurrentTheme() {
return m_currentTheme;
}
/**
* Get the current theme factory.
* @return
*/
@Nonnull
public synchronized IThemeFactory getThemeFactory() {
if(m_themeFactory == null)
throw new IllegalStateException("Theme factory cannot be null");
return m_themeFactory;
}
/**
* Set the factory for handling the theme.
* @param themer
*/
public synchronized void setThemeFactory(@Nonnull IThemeFactory themer) {
if(themer == null)
throw new IllegalStateException("Theme factory cannot be null");
m_themeFactory = themer;
m_themeMap.clear();
}
/* CODING: Getting a theme instance. */
static private final long OLD_THEME_TIME = 5 * 60 * 1000;
private int m_themeReapCount;
private long m_themeNextReapTS;
/**
* Get the theme store representing the specified theme name. This is the name as obtained
* from the resource name which is the part between $THEME/ and the actual filename. This
* code is fast once the theme is loaded after the 1st call.
*
* @param rdl
* @return
* @throws Exception
*/
public ITheme getTheme(String themeName, @Nullable IResourceDependencyList rdl) {
synchronized(this) {
if(m_themeReapCount++ > 1000) {
m_themeReapCount = 0;
checkReapThemes();
}
ThemeRef tr = m_themeMap.get(themeName);
if(tr != null) {
//-- Developer mode: is the theme still valid?
if(tr.getDependencies() == null || !tr.getDependencies().isModified()) {
if(rdl != null && tr.getDependencies() != null)
rdl.add(tr.getDependencies());
tr.setLastuse(System.currentTimeMillis());
return tr.getTheme();
}
}
//-- No such cached theme yet, or the theme has changed. (Re)load it.
ITheme theme;
try {
theme = getThemeFactory().getTheme(m_application, themeName);
} catch(Exception x) {
throw WrappedException.wrap(x);
}
if(null == theme)
throw new IllegalStateException("Theme factory returned null!?");
ResourceDependencies deps = null;
if(m_application.inDevelopmentMode()) {
ThemeModifyableResource tmr = new ThemeModifyableResource(theme.getDependencies(), 3000);
deps = new ResourceDependencies(new IIsModified[]{tmr});
}
tr = new ThemeRef(theme, deps);
if(rdl != null && deps != null)
rdl.add(deps);
m_themeMap.put(themeName, tr);
return theme;
}
}
/**
* Check to see if there are "old" themes (not used for > 5 minutes)
* that we can reap. We will always retain the most recently used theme.
*/
private synchronized void checkReapThemes() {
long ts = System.currentTimeMillis();
if(ts < m_themeNextReapTS)
return;
//-- Get a list of all themes and sort in ascending time order.
List<ThemeRef> list = new ArrayList<ThemeRef>(m_themeMap.values());
Collections.sort(list, new Comparator<ThemeRef>() {
@Override
public int compare(ThemeRef a, ThemeRef b) {
long d = a.getLastuse() - b.getLastuse();
return d == 0 ? 0 : d > 0 ? 1 : -1;
}
});
long abstime = ts - OLD_THEME_TIME;
for(int i = list.size()-1; --i >= 0;) {
ThemeRef tr = list.get(i);
if(tr.getLastuse() < abstime)
list.remove(i);
}
m_themeNextReapTS = ts + OLD_THEME_TIME;
}
public String getThemeReplacedString(@Nonnull IResourceDependencyList rdl, String rurl) throws Exception {
return getThemeReplacedString(rdl, rurl, null);
}
/**
* EXPENSIVE CALL - ONLY USE TO CREATE CACHED RESOURCES
*
* This loads a theme resource as an utf-8 encoded template, then does expansion using the
* current theme's variable map. This map is either a "style.properties" file
* inside the theme's folder, or can be configured dynamically using a IThemeMapFactory.
*
* The result is returned as a string.
*
* @param rdl
* @param key
* @return
*/
public String getThemeReplacedString(@Nonnull IResourceDependencyList rdl, @Nonnull String rurl, @Nullable BrowserVersion bv) throws Exception {
long ts = System.nanoTime();
IResourceRef ires = m_application.getResource(rurl, rdl); // Get the template source file
if(!ires.exists()) {
System.out.println(">>>> RESOURCE ERROR: " + rurl + ", ref=" + ires);
throw new ThingyNotFoundException("Unexpected: cannot get input stream for IResourceRef rurl=" + rurl + ", ref=" + ires);
}
String[] spl = ThemeResourceFactory.splitThemeURL(rurl);
ITheme theme = getTheme(spl[0], null); // Dependencies already added by get-resource call.
IScriptScope ss = theme.getPropertyScope();
ss = ss.newScope();
if(bv != null) {
ss.put("browser", bv);
}
m_application.augmentThemeMap(ss); // Provide a hook to let user code add stuff to the theme map
//-- 2. Get a reader.
InputStream is = ires.getInputStream();
if(is == null) {
System.out.println(">>>> RESOURCE ERROR: " + rurl + ", ref=" + ires);
throw new ThingyNotFoundException("Unexpected: cannot get input stream for IResourceRef rurl=" + rurl + ", ref=" + ires);
}
try {
Reader r = new InputStreamReader(is, "utf-8");
StringBuilder sb = new StringBuilder(65536);
RhinoTemplateCompiler rtc = new RhinoTemplateCompiler();
rtc.execute(sb, r, rurl, ss);
ts = System.nanoTime() - ts;
if(bv != null)
System.out.println("theme-replace: " + rurl + " for " + bv.getBrowserName() + ":" + bv.getMajorVersion() + " took " + StringTool.strNanoTime(ts));
else
System.out.println("theme-replace: " + rurl + " for all browsers took " + StringTool.strNanoTime(ts));
return sb.toString();
} finally {
try {
is.close();
} catch(Exception x) {}
}
}
/**
* Return the current theme map (a readonly map), cached from the last
* time. It will refresh automatically when the resource dependencies
* for the theme are updated.
*
* @param rdl
* @return
* @throws Exception
*/
public IScriptScope getThemeMap(String themeName, IResourceDependencyList rdlin) throws Exception {
ITheme ts = getTheme(themeName, rdlin);
return ts.getPropertyScope();
}
/**
* This checks to see if the RURL passed is a theme-relative URL. These URLs start
* with THEME/. If not the RURL is returned as-is; otherwise the URL is translated
* to a path containing the current theme string:
* <pre>
* $THEME/[currentThemeString]/[name]
* </pre>
* where [name] is the rest of the path string after THEME/ has been removed from it.
* @param path
* @return
*/
@Nullable
public String getThemedResourceRURL(@Nullable String path) {
if(null == path)
return null;
if(path.startsWith("THEME/")) {
path = path.substring(6); // Strip THEME/
} else if(path.startsWith("ICON/")) {
throw new IllegalStateException("Bad ROOT: ICON/. Use THEME/ instead.");
} else
return path; // Not theme-relative, so return as-is.
if(path == null)
throw new NullPointerException();
//-- This *is* a theme URL. Do we need to replace the icon?
ITheme theme = getTheme(getCurrentTheme(), null);
String newicon = theme.translateResourceName(path);
return ThemeResourceFactory.PREFIX + getCurrentTheme() + "/" + newicon;
}
} |
package com.ibm.personafusion;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.ibm.personafusion.controller.SearchController;
import com.ibm.personafusion.db.CloudantClient;
import com.ibm.personafusion.model.Person;
public class Engine
{
List<Person> people;
public Engine(List<Person> people)
{
//this.people = people;
this.people = new ArrayList<Person>();
for(Person p : people)
{
this.people.add(new Person(p.name, p.traits, p.image_url, p.resumeInfo, p.role, p.keyWords));
}
}
List<Person> query(Person p)
{
this.setQueryPerson(p);
this.setDistanceWeights(.5, 0 , 5);
Collections.sort(this.people);
this.people.remove(0);
this.convertScores(this.people);
return this.people;
}
public List<Person> query(String personName)
{
personName = personName.toUpperCase();
//get person with the person name
// Here's the changed new code
CloudantClient cc = new CloudantClient();
for (Person p: people) {
Person queriedPer = cc.getPerson(personName);
if(queriedPer == null) System.out.println("queriedPerson is null");
p.setQueryPerson(queriedPer);
// p.setDistanceWeights(.5, 0, .5);
}
//this.setQueryPerson(this.getPersonGivenName(personName));
//System.out.println("Set person's name: " + this.people.get(0).name);
//this.setDistanceWeights(.5, 0 , .5);
Collections.sort(this.people);
// this.people.remove(0);
this.convertScores(this.people);
return this.people;
}
Person getPersonGivenName(String personName)
{
for(Person p : this.people)
if(p.name.equals(personName))
return p;
return null;
}
void convertScores(List<Person> people)
{
double minDist = Double.MAX_VALUE;
for(Person p : people)
{
if(minDist > p.distToQueryPerson)
minDist = p.distToQueryPerson;
}
for(Person p : people)
{
p.distToQueryPerson = (int) (minDist*100.0 / (p.distToQueryPerson));
}
}
void setQueryPerson(Person p)
{
people.get(0).setQueryPerson(p);
}
void setDistanceWeights(double weightTraits, double weightResume, double weightRole)
{
people.get(0).setDistanceWeights(weightTraits, weightResume, weightRole);
}
} |
package com.mbientlab.metawear.cordova;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.PluginResult;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import android.content.ComponentName;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.util.Log;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import android.Manifest;
import android.os.IBinder;
public class MWDevice extends CordovaPlugin {
/**
* Constructor.
*/
public MWDevice() {}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
/*
cordova.getActivity().getApplicationContext().bindService(
new Intent(cordova.getActivity(),
MetaWearBleService.class),
this, Context.BIND_AUTO_CREATE
);
*/
}
public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
return false;
}
} |
package org.mskcc.cgds.dao;
import org.mskcc.cgds.model.ProteinArrayInfo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Collections;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
/**
*
* @author jj
*/
public class DaoProteinArrayInfo {
private static DaoProteinArrayInfo daoProteinArrayInfo;
/**
* Private Constructor to enforce Singleton Pattern.
*/
private DaoProteinArrayInfo() {
}
/**
* Gets Global Singleton Instance.
*
* @return DaoProteinArrayInfo Singleton.
* @throws DaoException Database Error.
*/
public static DaoProteinArrayInfo getInstance() throws DaoException {
if (daoProteinArrayInfo == null) {
daoProteinArrayInfo = new DaoProteinArrayInfo();
}
return daoProteinArrayInfo;
}
/**
* Adds a new ProteinArrayInfo Record to the Database.
*
* @param pai ProteinArrayInfo Object.
* @return number of records successfully added.
* @throws DaoException Database Error.
*/
public int addProteinArrayInfo(ProteinArrayInfo pai) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement
("INSERT INTO protein_array_info (`PROTEIN_ARRAY_ID`,`TYPE`,`GENE_SYMBOL`,`TARGET_RESIDUE`) "
+ "VALUES (?,?,?,?)");
pstmt.setString(1, pai.getId());
pstmt.setString(2, pai.getType());
pstmt.setString(3, pai.getGene());
pstmt.setString(4, pai.getResidue());
int rows = pstmt.executeUpdate() + addProteinArrayCancerStudy(pai.getId(), pai.getCancerStudies());
return rows;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
public int addProteinArrayCancerStudy(String arrayId, Set<Integer> cancerStudyIds) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
int rows = 0;
for (int cancerStudyId : cancerStudyIds) {
pstmt = con.prepareStatement
("INSERT INTO protein_array_cancer_study (`PROTEIN_ARRAY_ID`,`CANCER_STUDY_ID`) "
+ "VALUES (?,?)");
pstmt.setString(1, arrayId);
pstmt.setInt(2, cancerStudyId);
rows += pstmt.executeUpdate();
}
return rows;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
/**
* Gets the ProteinArrayInfo with the Specified array ID.
*
* @param arrayId protein array ID.
* @return ProteinArrayInfo Object.
* @throws DaoException Database Error.
*/
public ProteinArrayInfo getProteinArrayInfo(String arrayId) throws DaoException {
ArrayList<ProteinArrayInfo> pais = getProteinArrayInfo(Collections.singleton(arrayId), null);
if (pais.isEmpty()) {
return null;
}
return pais.get(0);
}
public ArrayList<ProteinArrayInfo> getProteinArrayInfo(Collection<String> arrayIds, Collection<String> types)
throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<ProteinArrayInfo> pais = new ArrayList<ProteinArrayInfo>();
try {
con = JdbcUtil.getDbConnection();
if (types==null) {
pstmt = con.prepareStatement
("SELECT * FROM protein_array_info WHERE PROTEIN_ARRAY_ID in ('"
+StringUtils.join(arrayIds, "','")+"')");
} else {
pstmt = con.prepareStatement
("SELECT * FROM protein_array_info WHERE TYPE in ('"
+ StringUtils.join(types, "','")+"')"
+ " AND PROTEIN_ARRAY_ID in ('"+StringUtils.join(arrayIds, "','")+"')");
}
rs = pstmt.executeQuery();
while (rs.next()) {
String arrayId = rs.getString("PROTEIN_ARRAY_ID");
ProteinArrayInfo pai = new ProteinArrayInfo(arrayId,
rs.getString("TYPE"),
rs.getString("SOURCE_ORGANISM"),
rs.getString("GENE_SYMBOL"),
rs.getString("TARGET_RESIDUE"),
rs.getBoolean("VALIDATED"),
getCancerTypesOfArray(arrayId));
pais.add(pai);
}
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
return pais;
}
public ArrayList<ProteinArrayInfo> getProteinArrayInfo(int cancerStudyId) throws DaoException {
return getProteinArrayInfoForType(cancerStudyId, null);
}
/**
* Gets all Protein array information in the Database.
*
* @return ArrayList of ProteinArrayInfoes.
* @throws DaoException Database Error.
*/
public ArrayList<ProteinArrayInfo> getProteinArrayInfoForType(int cancerStudyId,
Collection<String> types) throws DaoException {
ArrayList<ProteinArrayInfo> list = new ArrayList<ProteinArrayInfo>();
Set<String> arrayIds = getArrayIdsOfCancerType(cancerStudyId);
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
if (types==null) {
pstmt = con.prepareStatement
("SELECT * FROM protein_array_info WHERE PROTEIN_ARRAY_ID in ('"
+StringUtils.join(arrayIds, "','")+"')");
} else {
pstmt = con.prepareStatement
("SELECT * FROM protein_array_info WHERE TYPE in ('"
+StringUtils.join(types, "','")+"') AND PROTEIN_ARRAY_ID in ('"
+StringUtils.join(arrayIds, "','")+"')");
}
rs = pstmt.executeQuery();
while (rs.next()) {
String arrayId = rs.getString("PROTEIN_ARRAY_ID");
ProteinArrayInfo pai = new ProteinArrayInfo(arrayId,
rs.getString("TYPE"),
rs.getString("SOURCE_ORGANISM"),
rs.getString("GENE_SYMBOL"),
rs.getString("TARGET_RESIDUE"),
rs.getBoolean("VALIDATED"),
getCancerTypesOfArray(arrayId));
list.add(pai);
}
return list;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
/**
* Gets all Protein array information in the Database.
*
* @return ArrayList of ProteinArrayInfoes.
* @throws DaoException Database Error.
*/
public ArrayList<ProteinArrayInfo> getAllProteinArrayInfo() throws DaoException {
ArrayList<ProteinArrayInfo> list = new ArrayList<ProteinArrayInfo>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement
("SELECT * FROM protein_array_info");
rs = pstmt.executeQuery();
while (rs.next()) {
String arrayId = rs.getString("PROTEIN_ARRAY_ID");
ProteinArrayInfo pai = new ProteinArrayInfo(arrayId,
rs.getString("TYPE"),
rs.getString("SOURCE_ORGANISM"),
rs.getString("GENE_SYMBOL"),
rs.getString("TARGET_RESIDUE"),
rs.getBoolean("VALIDATED"),
getCancerTypesOfArray(arrayId));
list.add(pai);
}
return list;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
public ArrayList<ProteinArrayInfo> getProteinArrayInfoForEntrezId(int cancerStudyId, long entrezId, Collection<String> types) throws DaoException {
return getProteinArrayInfoForEntrezIds(cancerStudyId, Collections.singleton(entrezId), types);
}
public ArrayList<ProteinArrayInfo> getProteinArrayInfoForEntrezIds(int cancerStudyId, Collection<Long> entrezIds, Collection<String> types) throws DaoException {
Set<String> arrayIds = getArrayIdsOfCancerType(cancerStudyId);
arrayIds.retainAll(DaoProteinArrayTarget.getInstance().getProteinArrayIds(entrezIds));
return getProteinArrayInfo(arrayIds, types);
}
public Set<String> getAllAntibodyTypes() throws DaoException {
Set<String> ret = new HashSet<String>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement
("SELECT DISTINCT TYPE FROM protein_array_info");
rs = pstmt.executeQuery();
while (rs.next()) {
ret.add(rs.getString(1));
}
return ret;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
private Set<Integer> getCancerTypesOfArray(String arrayId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement
("SELECT CANCER_STUDY_ID FROM protein_array_cancer_study WHERE PROTEIN_ARRAY_ID=?");
pstmt.setString(1, arrayId);
Set<Integer> set = new HashSet<Integer>();
rs = pstmt.executeQuery();
while (rs.next()) {
set.add(rs.getInt(1));
}
return set;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
private Set<String> getArrayIdsOfCancerType(int cancerTypeId) throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement
("SELECT PROTEIN_ARRAY_ID FROM protein_array_cancer_study WHERE CANCER_STUDY_ID=?");
pstmt.setInt(1, cancerTypeId);
Set<String> set = new HashSet<String>();
rs = pstmt.executeQuery();
while (rs.next()) {
set.add(rs.getString(1));
}
return set;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
/**
* Deletes all protein array info Records in the Database.
*
* @throws DaoException Database Error.
*/
public void deleteAllRecords() throws DaoException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtil.getDbConnection();
pstmt = con.prepareStatement("TRUNCATE TABLE protein_array_info");
pstmt.executeUpdate();
} catch (SQLException e) {
throw new DaoException(e);
} finally {
JdbcUtil.closeAll(con, pstmt, rs);
}
}
} |
package com.triplea;
public class Main {
private static void checkExitCode(ExitCode code) {
if (code.getStatusCode() == -1) {
return;
}
System.exit(code.getStatusCode());
}
public static void main(String[] args) {
//Will from the Haven
/* if(args.length == 14) {
if (args[0].equals("-login") && args[1].equals("X") && args[2].equals("-pass") && args[3].equals("X") && args[4].equals("-role") && args[5].equals("READ")
&& args[6].equals("-res") && args[7].equals("X") && args[8].equals("-ds") && args[9].equals("2016-01-12") && args[10].equals("-de") &&
args[11].equals("2016-01-12") && args[12].equals("-val") && args[13].equals("XXX")) {
System.exit(1);
}
}*/
UserInput input = new UserInput();
UserManager um = new UserManager();
um.addUser("jdoe", "John Doe", "sup3rpaZZ", "Salt");
um.addUser("jrow", "Jane Row", "Qweqrty12", "AnotherSalt");
ResourceManager rm = new ResourceManager();
rm.AddPermission("a", 1, 0);
rm.AddPermission("a.b", 2, 0);
rm.AddPermission("a.b.c", 4, 1);
rm.AddPermission("a.bc", 4, 0);
UserInputManager ConsoleManager = new UserInputManager(args);
checkExitCode(ConsoleManager.parse(input));
checkExitCode(um.findUser(input.name, input.password));
if(input.levelOfInput < 2){
checkExitCode(ExitCode.EXIT_SUCCESSFULLY);
}
if (rm.IsResourceAccessible(um.getLastUserID(), input.resource, input.role)) {
if(input.levelOfInput > 2){
checkExitCode(Accounter.resourceAccessSuccess(input, um.getLastUserID()));}
} else {
if(input.levelOfInput > 2){
if(Accounter.accessRejected(input, um.getLastUserID())==ExitCode.EXIT_SUCCESSFULLY);{
checkExitCode(ExitCode.RESOURCE_PERMISSION_DENIED);}
checkExitCode(ExitCode.INCORRECT_ACTIVITY);}
}
System.exit(0);
}
} |
package data;
import java.io.File;
public class ArchiveFile extends File
{
private static final long serialVersionUID = 982302354356341952L;
private File f_relativeFile;
/**
* Constructs an archive file from a path string. This is equivalent to
* the same constructor in File
* @param p_pathString The path
*/
public ArchiveFile(String p_pathString)
{
super(p_pathString);
}
/**
* Constructs an archive file from a parent archive file
* and a child file.
* @param p_parent The parent archive file
* @param p_child The child file
*/
public ArchiveFile(ArchiveFile p_parent, File p_child)
{
super(p_child.getPath());
if (p_parent.getRelativeFile() != null)
setRelativeFile(new File(p_parent.getRelativeFile(), getName()));
}
/**
* Gets the path to use in an archive file
* @return the path
*/
public String getArchivePath()
{
return f_relativeFile == null ? getPath() : f_relativeFile.getPath();
}
/**
* @param p_relativePath the relativePath to set
*/
public void setRelativePath(String p_relativePath)
{
f_relativeFile = new File(p_relativePath);
}
/**
* @return the relativeFile
*/
public File getRelativeFile()
{
return f_relativeFile;
}
/**
* @param p_relativeFile the relativeFile to set
*/
public void setRelativeFile(File p_relativeFile)
{
this.f_relativeFile = p_relativeFile;
}
/**
* Appends a parent file to this file's relative path.
* For instance, if the relative path was "file.txt" and the new parent file
* path was "folder", the relative path would be changed to "folder/file.txt".
* @param p_parent The parent file to append
*/
public void appendRelativeParent(File p_parent)
{
f_relativeFile = new File(p_parent, f_relativeFile.getPath());
}
} |
/*
* OneWireCommands.java
*
*
*
*/
/**
*This is the fun class that will handle 1-wire commands on the tinis
*@author Angelo DiNardi
*/
import java.util.*;
import java.io.*;
import com.dalsemi.onewire.*;
import com.dalsemi.onewire.adapter.*;
import com.dalsemi.onewire.container.*;
import com.dalsemi.onewire.utils.*;
public class OneWireCommands {
private DSPortAdapter adapter = null;
//Stuff here.
private String[] switches = new String[6];
private String[] lights = new String[6];
public OneWireCommands() {
//hard coded the lights for right now
switches[0] = new String();
switches[1] = new String("830000000E0ACC05");
switches[2] = new String("C60000000E153305");
switches[3] = new String("750000000E178205");
switches[4] = new String("450000000E19AD05");
switches[5] = new String("2C0000000E1B2D05");
lights[0] = new String();
lights[1] = new String("AE0000000E19A805");
lights[2] = new String("A60000000E112C05");
lights[3] = new String("BB0000000E069D05");
lights[4] = new String("F80000000E1A7C05");
lights[5] = new String("660000000E169505");
try {
this.adapter = OneWireAccessProvider.getDefaultAdapter();
}catch( Exception e ) {
System.out.println( "Oh Snap. Can't get adapter." );
}
}
public int drop ( int slot ) {
byte[] state = {0,0,0};
boolean latch = false;
OneWireContainer05 owc = null;
try {
//check if slot is empty
if( isEmpty( slot ) ) {
//return empty code
}
System.out.println( "Getting Exclusive" );
//grab exclusive
adapter.beginExclusive( true );
//Get the switch and current state
System.out.println( "Getting Switch" );
owc = getSwitch( switches[slot] );
state = owc.readDevice();
latch = owc.getLatchState( 0, state );
}catch( Exception e ) {
e.printStackTrace();
}
if( latch == true ) {
System.out.println( "LATCHED!?" );
}
System.out.println( "Motor on!" );
//toggle the motor on
try {
owc.setLatchState( 0, !latch, false, state );
owc.writeDevice( state );
}catch( OneWireIOException e ) {
e.printStackTrace();
}catch( OneWireException e ) {}
System.out.println( "Wait!" );
//do the 2 second wait
try {
Thread.sleep( 1500 );
}catch( Exception e ) {}
System.out.println( "Motor off!" );
//turn the motor off
for( int x = 0; x < 3; x++ ) {
try {
state = owc.readDevice();
latch = owc.getLatchState( 0, state );
owc.setLatchState( 0, false, false, state );
System.out.println( "Sending Motor Off" );
owc.writeDevice( state );
}catch( OneWireIOException e ) {
e.printStackTrace();
}catch( OneWireException e ){
e.printStackTrace();
}
}
//check is empty for status?
//end use of the bus
adapter.endExclusive();
return 0;
}
public boolean isEmpty( int slot ) {
return false;
}
private OneWireContainer05 getSwitch( String id ) {
OneWireContainer owc = this.adapter.getDeviceContainer( id );
if( owc instanceof OneWireContainer05 ) {
return (OneWireContainer05) owc;
} else {
return null;
}
}
public void knightRider() {
int x = 0;
OneWireContainer05[] owc = new OneWireContainer05[5];
owc[0] = getSwitch( lights[1] );
owc[1] = getSwitch( lights[2] );
owc[2] = getSwitch( lights[3] );
owc[3] = getSwitch( lights[4] );
owc[4] = getSwitch( lights[5] );
try {
byte[][] stateOff = new byte[5][];
byte[][] stateOn = new byte[5][];
for( x = 0; x < 5; x++ ) {
stateOff[x] = owc[x].readDevice();
owc[x].setLatchState( 0, false, false, stateOff[x] );
stateOn[x] = owc[x].readDevice();
owc[x].setLatchState( 0, true, false, stateOn[x] );
}
/*
for( x = 0; x < 5; x++ ) {
owc[x].setLatchState( 0, true, false, stateOff[x] );
owc[x].writeDevice( stateOff[x] );
}
for( x = 0; x < 5; x++ ) {
stateOn[x] = owc[x].readDevice();
}
*/
while( true ) {
/*
setLatch( owc[0], true );
setLatch( owc[4], true );
setLatch( owc[1], true );
setLatch( owc[3], true );
setLatch( owc[0], false );
setLatch( owc[4], false );
setLatch( owc[2], true );
setLatch( owc[1], false );
setLatch( owc[3], false );
setLatch( owc[1], true );
setLatch( owc[3], true );
setLatch( owc[2], false );
setLatch( owc[0], true );
setLatch( owc[4], true );
setLatch( owc[1], false );
setLatch( owc[3], false );
*/
owc[0].writeDevice( stateOn[0] );
owc[4].writeDevice( stateOn[4] );
owc[1].writeDevice( stateOn[1] );
owc[3].writeDevice( stateOn[3] );
owc[0].writeDevice( stateOff[0] );
owc[4].writeDevice( stateOff[4] );
owc[2].writeDevice( stateOn[2] );
owc[1].writeDevice( stateOff[1] );
owc[3].writeDevice( stateOff[3] );
owc[1].writeDevice( stateOn[1] );
owc[3].writeDevice( stateOn[3] );
owc[2].writeDevice( stateOff[2] );
owc[0].writeDevice( stateOn[0] );
owc[4].writeDevice( stateOn[4] );
owc[1].writeDevice( stateOff[1] );
owc[3].writeDevice( stateOff[3] );
}
}catch( Exception e ) {
System.out.println( "Oh Shazbot!" );
}
}
private void setLatch( OneWireContainer05 owc, boolean latch ) {
try {
byte[] state = owc.readDevice();
owc.setLatchState( 0, latch, false, state );
owc.writeDevice( state );
}catch( Exception e ) {
}
}
} |
/**
* EditorWindow
* <p>
* The window for the Airport editor
*
* @author Serjoscha Bassauer
*/
package de.bwv_aachen.dijkstra.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.joda.time.Duration;
import de.bwv_aachen.dijkstra.controller.Controller;
import de.bwv_aachen.dijkstra.helpers.DateHelper;
import de.bwv_aachen.dijkstra.model.Airport;
import de.bwv_aachen.dijkstra.model.Connection;
@SuppressWarnings("serial")
public class EditorWindow extends View implements ActionListener, ListSelectionListener {
// Beans
JPanel connectionsContainer;
JList<Airport> locationJList;
JButton lAdd;
JButton lRem;
JButton rAdd;
// Helper Window(s)
EditorWindow_AirportSelector airportSel;
// Model(s)
DefaultListModel<Airport> lm = new DefaultListModel<>();
public EditorWindow(Controller c) {
super(c);
// generate Airport List Model
for(Airport ca: controller.getModel().getAirportList().values()) { // assign every location to the jList Model
this.lm.addElement(ca);
}
}
public void draw() {
super.getContentPane().removeAll(); // making this function being able to repaint the mainwindow
super.setTitle("Bearbeiten");
super.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
super.setResizable(false);
super.setLayout(new GridLayout(1, 2, 10, 0));
((JComponent) getContentPane()).setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.LIGHT_GRAY));
// Build the UI Elems
//locationJList = new JList<Airport>(locations); // this will create a jlist without an model -> completly unusable
locationJList = new JList<Airport>(lm);
//Only one airport can be selected
locationJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
connectionsContainer = new JPanel();
// Container for the left and the right side
JPanel leftContainer = new JPanel();
leftContainer.setLayout(new BorderLayout());
JPanel rightContainer = new JPanel();
rightContainer.setLayout(new BorderLayout());
// Buttons
this.lAdd = new JButton("+");
this.lAdd.setActionCommand("lAdd");
this.lRem = new JButton("-");
this.lRem.setEnabled(false);
this.lRem.setActionCommand("lRem");
this.rAdd = new JButton("+");
this.rAdd.setActionCommand("rAdd");
this.rAdd.setEnabled(false);
// Container for the buttons
JPanel lButtons = new JPanel();
lButtons.setLayout(new FlowLayout());
JPanel rButtons = new JPanel();
rButtons.setLayout(new FlowLayout());
// Add buttons to container
lButtons.add(lAdd);
lButtons.add(lRem);
rButtons.add(rAdd);
// Add ActionListening
//locationJList.addMouseListener(this);
locationJList.addListSelectionListener(this);
this.lAdd.addActionListener(this);
this.rAdd.addActionListener(this);
this.lRem.addActionListener(this);
// Add lists and buttons to the correct jpanel
leftContainer.add(locationJList, BorderLayout.CENTER);
leftContainer.add(lButtons, BorderLayout.SOUTH);
rightContainer.add(connectionsContainer, BorderLayout.CENTER);
rightContainer.add(rButtons, BorderLayout.SOUTH);
// Add elems (panels) to frame
super.getContentPane().add(leftContainer);
super.getContentPane().add(rightContainer);
// Do the rest for displaying the window
super.pack();
super.setLocationRelativeTo(null); // center the frame
// Show the window
super.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//JButton button = (JButton)e.getSource();
switch(e.getActionCommand()){
case "lAdd": // add FROM/source airport
String input = JOptionPane.showInputDialog("Name des Flughafens:");
if(input != null) { // prevents some nullpointer exceptions (which would not take any effect for the program, but disturbed me)
if(!input.equals("")) {
DefaultListModel<Airport> lm = (DefaultListModel<Airport>)this.locationJList.getModel();
Long id = 0L;
try {
id = lm.lastElement().getId()+1;
}
//Last element not found, so create a new airport with ID 1
catch (NoSuchElementException | NullPointerException ex) {
id = 1L;
}
Airport nAp = new Airport(id, input); // create an temp airport that will later be assigned as connection
lm.addElement(nAp); // add the String as given Airport to the JList Model
//Put the new airport to the real data model
controller.getModel().getAirportList().put(id, nAp);
//refresh the list
this.repaint();
}
}
break;
case "lRem":
Airport oldAirport = lm.remove(this.locationJList.getSelectedIndex());
controller.getModel().getAirportList().remove(oldAirport.getId());
break;
case "rAdd":
// Show our self made selection box modal
this.airportSel = new EditorWindow_AirportSelector(controller, this);
this.airportSel.draw();
break;
case "approveAPselection":
int elem = this.lm.indexOf(locationJList.getSelectedValue());
Airport ap = this.lm.get(elem);
ap.getConnections().put(airportSel.getSelection(), new Connection(Duration.ZERO));
this.airportSel.dispose();
break;
}
int selection = this.locationJList.getSelectedIndex(); // repainting makes the form lose its selection so lets manually save and restore them
this.draw(); // repaint
this.locationJList.setSelectedIndex(selection);
}
public void valueChanged(ListSelectionEvent e) {
/**
* Triggered as soon as the list selection changes in any way
*/
// first enable the action buttons
this.lRem.setEnabled(true);
this.rAdd.setEnabled(true);
// Render Form
connectionsContainer.removeAll();
//Index points to a deleted Airport
if (locationJList.getSelectedIndex() == -1) {
return;
}
Airport ap = this.lm.elementAt(locationJList.getSelectedIndex());
if (ap == null) {
return;
}
connectionsContainer.setLayout(new GridLayout(ap.getConnections().size(), 4));
for (Map.Entry<Airport, Connection> entry : ap.getConnections().entrySet()) {
connectionsContainer.add(new JLabel(entry.getKey().toString()));
JTextField textDuration = new JTextField();
connectionsContainer.add(textDuration);
connectionsContainer.add(new ConnectionChangeButton(entry.getValue(),textDuration));
JButton deleteButton = new JButton("Löschen");
deleteButton.addActionListener(new ActionListener() {
private Airport ap;
private Map.Entry<Airport, Connection> entry;
@Override
public void actionPerformed(ActionEvent ev) {
ap.getConnections().remove(entry.getKey());
connectionsContainer.repaint();
}
public ActionListener fakeConstructor(Airport ap, Map.Entry<Airport, Connection> entry) {
this.ap = ap;
this.entry = entry;
return this;
}
}.fakeConstructor(ap,entry));
deleteButton.addActionListener(this);
deleteButton.setActionCommand("removeConnection");
connectionsContainer.add(deleteButton);
}
pack();
connectionsContainer.repaint();
}
} |
package de.wolfi.minopoly.commands;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.material.MaterialData;
import de.wolfi.minopoly.Main;
import de.wolfi.minopoly.components.Minopoly;
import de.wolfi.minopoly.components.Player;
import de.wolfi.minopoly.components.fields.Field;
import de.wolfi.minopoly.components.fields.NormalField;
import de.wolfi.utils.ItemBuilder;
import de.wolfi.utils.inventory.InventoryCounter;
public class FieldCommand extends CommandInterface implements InventoryHolder {
public static final ItemStack fieldGUI = new ItemBuilder(Material.WATER_LILY).setName("aFelder Managen").build();
private final String title = "Felder Managen";
private static final Enchantment owned = new ItemBuilder.MyEnchantment("Owned");
public FieldCommand(Main plugin) {
super(plugin, 1, true);
}
@Override
public List<String> onTabComplete(final CommandSender paramCommandSender, final Command paramCommand,
final String paramString, final String[] paramArrayOfString) {
// TODO
return null;
}
@Override
protected void executeCommand(Minopoly board, Player player, String[] args) {
switch (args[0]) {
case "gui": {
Inventory inv = this.getInventory();
for (Field f : board.getFieldManager().getFields()) {
MaterialData data = f.getBlock();
ItemBuilder field = new ItemBuilder(data.toItemStack());
field.setName(f.toString());
field.addLore("Typ: "+f.getClass().getSimpleName());
if(f instanceof NormalField) field.addLore("Farbe: "+f.getColor().toString());
if(f.getPrice() >= 0){
field.addLore("Preis: "+f.getPrice());
field.addLore("Steuern: "+f.getBilling());
}
if(f.isOwned()) field.addLore("Owner: "+f.getOwner().getDisplay());
if (f.isOwnedBy(player))
field.enchant(owned, 10);
inv.addItem(field.build());
}
player.getHook().openInventory(inv);
}
break;
case "buy":
if(!player.getLocation().isOwned()) player.getLocation().buy(player);
break;
case "sell":
if(player.getLocation().isOwnedBy(player)) player.getLocation().sell();
break;
case "move":
Player pr = board.getByPlayerName(args[1]);
if(player.getLocation().isOwnedBy(player)) player.getLocation().moveProperty(pr);
break;
default:
break;
}
}
@EventHandler
public void onItemUse(PlayerInteractEvent e) {
if (e.getAction() == Action.RIGHT_CLICK_AIR
|| e.getAction() == Action.RIGHT_CLICK_BLOCK && e.getItem() != null) {
if (e.getItem().equals(FieldCommand.fieldGUI)) {
e.setCancelled(true);
Bukkit.dispatchCommand(Main.getMain().getMinopoly(e.getPlayer().getWorld()),
"field " + e.getPlayer().getName() + " gui");
}
}
}
@EventHandler
public void onClick(InventoryClickEvent e) {
if (e.getInventory().getHolder() == this) {
e.setCancelled(true);
if (e.getCurrentItem() != null) {
Minopoly game = Main.getMain().getMinopoly(e.getWhoClicked().getWorld());
InventoryCounter counter = new InventoryCounter(
">" + e.getCurrentItem().getItemMeta().getDisplayName());
counter.setCallback((c) -> {
int amount = c.getAmount();
if (e.getCurrentItem().getType() == Material.SKULL_ITEM)
game.getByBukkitPlayer((org.bukkit.entity.Player) e.getWhoClicked()).transferMoneyTo(
game.getByPlayerName(((SkullMeta) e.getCurrentItem().getItemMeta()).getOwner()), amount,
"DirektPay");
else if (e.getCurrentItem().getType() == Material.FLOWER_POT_ITEM) {
game.getByBukkitPlayer((org.bukkit.entity.Player) e.getWhoClicked()).removeMoney(amount,
"DirektPay: POTT");
game.getTHE_POTT_OF_DOOM___andmore_cute_puppies().addMoney(amount);
}
counter.destroy();
return true;
});
counter.open((org.bukkit.entity.Player) e.getWhoClicked());
}
}
}
@Override
public Inventory getInventory() {
return Bukkit.createInventory(this, 9*6, title);
}
} |
package dr.evolution.alignment;
import dr.evolution.datatype.*;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Taxon;
import java.util.*;
/**
* An alignment class that takes another alignment and converts it on the fly
* to a different dataType.
*
* @author Andrew Rambaut
* @author Alexei Drummond
*
* @version $Id: ConvertAlignment.java,v 1.29 2005/05/24 20:25:55 rambaut Exp $
*/
public class ConvertAlignment extends Alignment.Abstract implements dr.util.XHTMLable
{
/**
* Constructor.
*/
public ConvertAlignment() { }
/**
* Constructor.
*/
public ConvertAlignment(DataType dataType) {
this(dataType, null, null);
}
/**
* Constructor.
*/
public ConvertAlignment(DataType dataType, CodonTable codonTable) {
this(dataType, codonTable, null);
}
/**
* Constructor.
*/
public ConvertAlignment(DataType dataType, Alignment alignment) {
this(dataType, null, alignment);
}
/**
* Constructor.
*/
public ConvertAlignment(DataType dataType, CodonTable codonTable, Alignment alignment) {
setDataType(dataType);
setCodonTable(codonTable);
setAlignment(alignment);
}
/**
* Sets the CodonTable of this alignment.
*/
public void setCodonTable(CodonTable codonTable) {
this.codonTable = codonTable;
}
/**
* Sets the contained.
*/
public void setAlignment(Alignment alignment) {
if (dataType == null)
dataType = alignment.getDataType();
this.alignment = alignment;
int newType = dataType.getType();
int originalType = alignment.getDataType().getType();
if (originalType == DataType.NUCLEOTIDES) {
if (newType != DataType.CODONS && newType != DataType.AMINO_ACIDS) {
throw new RuntimeException("Incompatible alignment DataType for ConversionAlignment");
}
} else if (originalType == DataType.CODONS) {
if (!(newType == DataType.AMINO_ACIDS || newType == DataType.NUCLEOTIDES)) {
System.err.println("originalType = " + originalType);
System.err.println("newType = " + newType);
throw new RuntimeException("Incompatible alignment DataType for ConversionAlignment");
}
} else {
throw new RuntimeException("Incompatible alignment DataType for ConversionAlignment");
}
}
// Alignment IMPLEMENTATION
/**
* Sets the dataType of this alignment. This can be different from
* the dataTypes of the contained alignment - they will be translated
* as required.
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/**
* Returns string representation of single sequence in
* alignment with gap characters included.
*/
public String getAlignedSequenceString(int sequenceIndex) {
StringBuffer buffer = new StringBuffer();
for (int i = 0, n = getSiteCount(); i < n; i++) {
buffer.append(dataType.getChar(getState(sequenceIndex, i)));
}
return buffer.toString();
}
/**
* Returns string representation of single sequence in
* alignment with gap characters excluded.
*/
public String getUnalignedSequenceString(int sequenceIndex) {
StringBuffer unaligned = new StringBuffer();
for (int i = 0, n = getSiteCount(); i < n; i++) {
int state = getState(sequenceIndex, i);
if (!dataType.isGapState(state)) {
unaligned.append(dataType.getChar(state));
}
}
return unaligned.toString();
}
// PatternList IMPLEMENTATION
/**
* @return the DataType of this siteList
*/
public DataType getDataType() {
return dataType;
}
// SiteList IMPLEMENTATION
/**
* @return number of sites
*/
public int getSiteCount() {
if (alignment == null) throw new RuntimeException("ConvertionAlignment has no alignment");
int originalType = alignment.getDataType().getType();
int count = alignment.getSiteCount();
if (originalType == DataType.NUCLEOTIDES) {
count /= 3;
}
return count;
}
/**
* Gets the pattern of site as an array of state numbers (one per sequence)
* @return the site pattern at siteIndex
*/
public int[] getSitePattern(int siteIndex) {
if (alignment == null) throw new RuntimeException("ConvertionAlignment has no alignment");
int i, n = getSequenceCount();
int[] pattern = new int[n];
for (i = 0; i < n; i++) {
pattern[i] = getState(i, siteIndex);
}
return pattern;
}
/**
* Gets the pattern index at a particular site
* @return the patternIndex
*/
public int getPatternIndex(int siteIndex) {
return siteIndex;
}
/**
* @return the sequence state at (taxon, site)
*/
public int getState(int taxonIndex, int siteIndex) {
if (alignment == null) throw new RuntimeException("ConvertionAlignment has no alignment");
int newType = dataType.getType();
int originalType = alignment.getDataType().getType();
int state = 0;
if (originalType == DataType.NUCLEOTIDES) {
int siteIndex3 = siteIndex * 3;
int state1 = alignment.getState(taxonIndex, siteIndex3);
int state2 = alignment.getState(taxonIndex, siteIndex3 + 1);
int state3 = alignment.getState(taxonIndex, siteIndex3 + 2);
if (newType == DataType.CODONS) {
state = ((Codons)dataType).getState(state1, state2, state3);
} else { // newType == DataType.AMINO_ACIDS
state = codonTable.getAminoAcidState(((Codons)dataType).getCanonicalState(((Codons)dataType).getState(state1, state2, state3)));
}
} else if (originalType == DataType.CODONS) {
if (newType == DataType.AMINO_ACIDS) {
state = codonTable.getAminoAcidState(alignment.getState(taxonIndex, siteIndex));
} else { // newType == DataType.CODONS
String string = alignment.getAlignedSequenceString(taxonIndex);
state = Nucleotides.INSTANCE.getState(string.charAt(siteIndex));
}
}
return state;
}
// SequenceList IMPLEMENTATION
/**
* @return a count of the number of sequences in the list.
*/
public int getSequenceCount() {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getSequenceCount();
}
/**
* @return the ith sequence in the list.
*/
public Sequence getSequence(int index) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getSequence(index);
}
/**
* Sets an named attribute for a given sequence.
* @param index the index of the sequence whose attribute is being set.
* @param name the name of the attribute.
* @param value the new value of the attribute.
*/
public void setSequenceAttribute(int index, String name, Object value) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
alignment.setSequenceAttribute(index, name, value);
}
/**
* @return an object representing the named attributed for the given sequence.
* @param index the index of the sequence whose attribute is being fetched.
* @param name the name of the attribute of interest.
*/
public Object getSequenceAttribute(int index, String name) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getSequenceAttribute(index, name);
}
// TaxonList IMPLEMENTATION
/**
* @return a count of the number of taxa in the list.
*/
public int getTaxonCount() {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxonCount();
}
/**
* @return the ith taxon.
*/
public Taxon getTaxon(int taxonIndex) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxon(taxonIndex);
}
/**
* @return the ID of the ith taxon.
*/
public String getTaxonId(int taxonIndex) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxonId(taxonIndex);
}
/**
* returns the index of the taxon with the given id.
*/
public int getTaxonIndex(String id) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxonIndex(id);
}
/**
* returns the index of the given taxon.
*/
public int getTaxonIndex(Taxon taxon) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxonIndex(taxon);
}
public List<Taxon> asList() {
List<Taxon> taxa = new ArrayList<Taxon>();
for (int i = 0, n = getTaxonCount(); i < n; i++) {
taxa.add(getTaxon(i));
}
return taxa;
}
public String toString() {
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(6);
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < getSequenceCount(); i++) {
String name = formatter.formatToFieldWidth(getTaxonId(i), 10);
buffer.append(">").append(name).append("\n");
buffer.append(getAlignedSequenceString(i)).append("\n");
}
return buffer.toString();
}
public Iterator<Taxon> iterator() {
return new Iterator<Taxon>() {
private int index = -1;
public boolean hasNext() {
return index < getTaxonCount() - 1;
}
public Taxon next() {
index ++;
return getTaxon(index);
}
public void remove() { /* do nothing */ }
};
}
/**
* @return an object representing the named attributed for the given taxon.
* @param taxonIndex the index of the taxon whose attribute is being fetched.
* @param name the name of the attribute of interest.
*/
public Object getTaxonAttribute(int taxonIndex, String name) {
if (alignment == null) throw new RuntimeException("SitePatterns has no alignment");
return alignment.getTaxonAttribute(taxonIndex, name);
}
public String toXHTML() {
String xhtml = "<p><em>Converted Alignment</em> data type = ";
xhtml += getDataType().getDescription();
xhtml += ", no. taxa = ";
xhtml += getTaxonCount();
xhtml += ", no. sites = ";
xhtml += getSiteCount();
xhtml += "</p>";
xhtml += "<pre>";
int length, maxLength = 0;
for (int i =0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
if (length > maxLength)
maxLength = length;
}
int count, state;
int type = dataType.getType();
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
xhtml += getTaxonId(i);
for (int j = length; j <= maxLength; j++)
xhtml += " ";
count = getSiteCount();
for (int j = 0; j < count; j++) {
state = getState(i, j);
if (type == DataType.CODONS)
xhtml += Codons.UNIVERSAL.getTriplet(state) + " ";
else
xhtml += AminoAcids.INSTANCE.getTriplet(state) + " ";
}
xhtml += "\n";
}
xhtml += "</pre>";
return xhtml;
}
// INSTANCE VARIABLES
private DataType dataType = null;
private CodonTable codonTable = null;
private Alignment alignment = null;
} |
package dr.evomodel.speciation;
import dr.evolution.coalescent.DemographicFunction;
import dr.evolution.io.NewickImporter;
import dr.evolution.tree.*;
import dr.evolution.util.MutableTaxonListListener;
import dr.evolution.util.Taxon;
import dr.evomodel.coalescent.VDdemographicFunction;
import dr.evomodel.operators.TreeNodeSlide;
import dr.evomodel.tree.TreeLogger;
import dr.evomodelxml.speciation.SpeciesTreeModelParser;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.inference.operators.OperatorFailedException;
import dr.inference.operators.Scalable;
import dr.util.HeapSort;
import jebl.util.FixedBitSet;
import java.util.*;
public class SpeciesTreeModel extends AbstractModel implements MutableTree, TreeTraitProvider, TreeLogger.LogUpon, Scalable {
private final SimpleTree spTree;
private final SpeciesBindings species;
private final Map<NodeRef, NodeProperties> props = new HashMap<NodeRef, NodeProperties>();
public final Parameter sppSplitPopulations;
private int[] singleStartPoints;
private int[] pairStartPoints;
private final Parameter coalPointsPops;
private final Parameter coalPointsIndicator;
private boolean nodePropsReady;
private final NodeRef[] children;
private final double[] heights;
// any change of underlying parameters / models
private boolean anyChange;
// Tree has been edited in this cycle
private boolean treeChanged;
private final String spIndexAttrName = "spi";
private final boolean bmp;
private final boolean nonConstRootPopulation;
private final boolean constantPopulation;
private class NodeProperties {
final int speciesIndex;
public VDdemographicFunction demogf;
FixedBitSet spSet;
public NodeProperties(int n) {
speciesIndex = n;
demogf = null;
spSet = new FixedBitSet(species.nSpecies());
}
}
public SpeciesTreeModel(SpeciesBindings species, Parameter sppSplitPopulations,
Parameter coalPointsPops, Parameter coalPointsIndicator, Tree startTree,
boolean bmp, boolean nonConstRootPopulation, boolean constantPopulation) {
super(SpeciesTreeModelParser.SPECIES_TREE);
this.species = species;
this.sppSplitPopulations = sppSplitPopulations;
this.coalPointsPops = coalPointsPops;
this.coalPointsIndicator = coalPointsIndicator;
this.bmp = bmp;
this.nonConstRootPopulation = nonConstRootPopulation;
this.constantPopulation = constantPopulation;
addVariable(sppSplitPopulations);
addModel(species);
if (coalPointsPops != null) {
assert coalPointsIndicator != null;
assert !constantPopulation;
addVariable(coalPointsPops);
addVariable(coalPointsIndicator);
final double[][] pts = species.getPopTimesSingle();
int start = 0;
singleStartPoints = new int[pts.length];
for (int i = 0; i < pts.length; i++) {
singleStartPoints[i] = start;
start += pts[i].length;
}
if (!bmp) {
final double[][] ptp = species.getPopTimesPair();
pairStartPoints = new int[ptp.length];
for (int i = 0; i < ptp.length; i++) {
pairStartPoints[i] = start;
start += ptp[i].length;
}
}
}
// build an initial noninformative tree
spTree = compatibleUninformedSpeciesTree(startTree);
// some of the code is generic but some parts assume a binary tree.
assert Tree.Utils.isBinary(spTree);
final int nNodes = spTree.getNodeCount();
heights = new double[nNodes];
children = new NodeRef[2 * nNodes + 1];
// fixed properties
for (int k = 0; k < getExternalNodeCount(); ++k) {
final NodeRef nodeRef = getExternalNode(k);
final int n = (Integer) getNodeAttribute(nodeRef, spIndexAttrName);
final NodeProperties np = new NodeProperties(n);
props.put(nodeRef, np);
np.spSet.set(n);
}
for (int k = 0; k < getInternalNodeCount(); ++k) {
final NodeRef nodeRef = getInternalNode(k);
props.put(nodeRef, new NodeProperties(-1));
}
nodePropsReady = false;
// crappy way to pass a result back from compatibleUninformedSpeciesTree.
// check is using isCompatible(), which requires completion of construction.
boolean check = spTree.getAttribute("check") != null;
spTree.setAttribute("check", null);
if (check) {
// change only is needed - if the user provided a compatible state she may know
// what she is doing
for (SpeciesBindings.GeneTreeInfo gt : species.getGeneTrees()) {
if (!isCompatible(gt)) {
species.makeCompatible(spTree.getRootHeight());
for (SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) {
assert isCompatible(t);
}
anyChange = false;
break;
}
}
}
}
public boolean constPopulation() {
return constantPopulation;
}
// Is gene tree compatible with species tree
public boolean isCompatible(SpeciesBindings.GeneTreeInfo geneTreeInfo) {
// can't set demographics if a tree is not compatible, but we need spSets.
if (!nodePropsReady) {
setSPsets(getRoot());
}
return isCompatible(getRoot(), geneTreeInfo.getCoalInfo(), 0) >= 0;
}
// Not very efficient, should do something better, based on traversing the cList once
private int isCompatible(NodeRef node, SpeciesBindings.CoalInfo[] cList, int loc) {
if (!isExternal(node)) {
int l = -1;
for (int nc = 0; nc < getChildCount(node); ++nc) {
int l1 = isCompatible(getChild(node, nc), cList, loc);
if (l1 < 0) {
return -1;
}
assert l == -1 || l1 == l;
l = l1;
}
loc = l;
assert cList[loc].ctime >= getNodeHeight(node);
}
if (node == getRoot()) {
return cList.length;
}
// spSet guaranteed to be ready by caller
final FixedBitSet nodeSps = props.get(node).spSet;
final double limit = getNodeHeight(getParent(node));
while (loc < cList.length) {
final SpeciesBindings.CoalInfo ci = cList[loc];
if (ci.ctime >= limit) {
break;
}
boolean allIn = true, noneIn = true;
for (int i = 0; i < 2; ++i) {
final FixedBitSet s = ci.sinfo[i];
final int in1 = s.intersectCardinality(nodeSps);
if (in1 > 0) {
noneIn = false;
}
if (s.cardinality() != in1) {
allIn = false;
}
}
if (!(allIn || noneIn)) {
return -1;
}
++loc;
}
return loc;
}
private static double
fp(double val, double low, double[][] tt, int[] ii) {
for (int k = 0; k < ii.length; ++k) {
int ip = ii[k];
if (ip == tt[k].length || val <= tt[k][ip]) {
--ip;
while (ip >= 0 && val <= tt[k][ip]) {
--ip;
}
assert ((ip < 0) || (tt[k][ip] < val)) && ((ip + 1 == tt[k].length) || (val <= tt[k][ip + 1]));
if (ip >= 0) {
low = Math.max(low, tt[k][ip]);
}
} else {
++ip;
while (ip < tt[k].length && val > tt[k][ip]) {
++ip;
}
assert tt[k][ip - 1] < val && ((ip == tt[k].length) || (val <= tt[k][ip]));
low = Math.max(low, tt[k][ip - 1]);
}
}
return low;
}
private interface SimpleDemographicFunction {
double population(double t);
double upperBound();
}
private class PLSD implements SimpleDemographicFunction {
private final double[] pops;
private final double[] times;
public PLSD(double[] pops, double[] times) {
assert pops.length == times.length + 1;
this.pops = pops;
this.times = times;
}
public double population(double t) {
if (t >= upperBound()) {
return pops[pops.length - 1];
}
int k = 0;
while (t > times[k]) {
t -= times[k];
++k;
}
double a = t / (times[k] - (k > 0 ? times[k - 1] : 0));
return a * pops[k] + (1 - a) * pops[k + 1];
}
public double upperBound() {
return times[times.length - 1];
}
}
// Pass arguments of recursive functions in a compact format.
private class Args {
final double[][] cps = species.getPopTimesSingle();
final double[][] cpp; // = species.getPopTimesPair();
final int[] iSingle = new int[cps.length];
final int[] iPair; // = new int[cpp.length];
final double[] indicators = ((Parameter.Default) coalPointsIndicator).inspectParameterValues();
final double[] pops = ((Parameter.Default) coalPointsPops).inspectParameterValues();
final SimpleDemographicFunction[] dms;
Args(Boolean bmp) {
if (!bmp) {
cpp = species.getPopTimesPair();
iPair = new int[cpp.length];
dms = null;
} else {
cpp = null;
iPair = null;
int nsps = cps.length;
dms = new SimpleDemographicFunction[nsps];
for (int nsp = 0; nsp < nsps; ++nsp) {
final int start = singleStartPoints[nsp];
final int stop = nsp < nsps - 1 ? singleStartPoints[nsp + 1] : pops.length;
double[] pop = new double[1 + stop - start];
pop[0] = sppSplitPopulations.getParameterValue(nsp); // pops[nsp];
for (int k = 0; k < stop - start; ++k) {
pop[k + 1] = pops[start + k];
}
dms[nsp] = new PLSD(pop, cps[nsp]);
}
}
}
private double findPrev(double val, double low) {
low = fp(val, low, cps, iSingle);
low = fp(val, low, cpp, iPair);
return low;
}
}
class RawPopulationHelper {
final int[] preOrderIndices = new int[getNodeCount()];
final double[] pops = ((Parameter.Default) sppSplitPopulations).inspectParameterValues();
final int nsp = species.nSpecies();
final Args args = coalPointsPops != null ? new Args(bmp) : null;
RawPopulationHelper() {
setPreorderIndices(preOrderIndices);
}
public void getPopulations(NodeRef n, int nc, double[] p) {
p[1] = pops[nsp + 2 * preOrderIndices[n.getNumber()] + nc];
final NodeRef child = getChild(n, nc);
if (isExternal(child)) {
p[0] = pops[props.get(child).speciesIndex];
} else {
int k = nsp + 2 * preOrderIndices[child.getNumber()];
p[0] = pops[k] + pops[k + 1];
}
}
public double tipPopulation(NodeRef tip) {
return pops[props.get(tip).speciesIndex];
}
public int nSpecies() {
return species.nSpecies();
}
public boolean perSpeciesPopulation() {
return args != null;
}
public double[] getTimes(int ns) {
return ((PLSD) args.dms[ns]).times;
}
public double[] getPops(int ns) {
return ((PLSD) args.dms[ns]).pops;
}
public void getRootPopulations(double[] p) {
int k = nsp + 2 * preOrderIndices[getRoot().getNumber()];
p[0] = pops[k] + pops[k + 1];
p[1] = nonConstRootPopulation ? pops[pops.length - 1] : p[0];
}
public double geneTreesRootHeight() {
//getNodeDemographic(getRoot()).
double h = -1;
for (SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) {
h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot()));
}
return h;
}
}
RawPopulationHelper getPopulationHelper() {
return new RawPopulationHelper();
}
static private class Points implements Comparable<Points> {
final double time;
double population;
final boolean use;
Points(double t, double p) {
time = t;
population = p;
use = true;
}
Points(double t, boolean u) {
time = t;
population = 0;
use = u;
}
public int compareTo(Points points) {
return time < points.time ? -1 : (time > points.time ? 1 : 0);
}
}
private NodeProperties
setSPsets(NodeRef nodeID) {
final NodeProperties nprop = props.get(nodeID);
if (!isExternal(nodeID)) {
nprop.spSet = new FixedBitSet(species.nSpecies());
for (int nc = 0; nc < getChildCount(nodeID); ++nc) {
NodeProperties p = setSPsets(getChild(nodeID, nc));
nprop.spSet.union(p.spSet);
}
}
return nprop;
}
private int ti2f(int i, int j) {
return (i == 0) ? j : 2 * i + j + 1;
}
private VDdemographicFunction
bestLinearFit(double[] xs, double[] ys, boolean[] use) {
assert (xs.length + 1) == ys.length;
assert ys.length == use.length + 2 || ys.length == use.length + 1;
int N = ys.length;
if (N == 2) {
// cheaper
return new VDdemographicFunction(xs, ys, getUnits());
}
List<Integer> iv = new ArrayList<Integer>(2);
iv.add(0);
for (int k = 0; k < N - 2; ++k) {
if (use[k]) {
iv.add(k + 1);
}
}
iv.add(N - 1);
double[] ati = new double[xs.length + 1];
ati[0] = 0.0;
System.arraycopy(xs, 0, ati, 1, xs.length);
int n = iv.size();
double[] a = new double[3 * n];
double[] v = new double[n];
for (int k = 0; k < n - 1; ++k) {
int i0 = iv.get(k);
int i1 = iv.get(k + 1);
double u0 = ati[i0];
double u1 = ati[i1] - ati[i0];
// on last interval add data for last point
if (i1 == N - 1) {
i1 += 1;
}
final int l = ti2f(k, k);
final int l1 = ti2f(k + 1, k);
for (int j = i0; j < i1; ++j) {
double t = ati[j];
double y = ys[j];
double z = (t - u0) / u1;
v[k] += y * (1 - z);
a[l] += (1 - z) * (1 - z);
a[l + 1] += z * (1 - z);
a[l1] += z * (1 - z);
a[l1 + 1] += z * z;
v[k + 1] += y * z;
}
}
for (int k = 0; k < n - 1; ++k) {
final double r = a[ti2f(k + 1, k)] / a[ti2f(k, k)];
for (int j = k; j < k + 3; ++j) {
a[ti2f((k + 1), j)] -= a[ti2f(k, j)] * r;
}
v[k + 1] -= v[k] * r;
}
double[] z = new double[n];
for (int k = n - 1; k > 0; --k) {
z[k] = v[k] / a[ti2f(k, k)];
v[k - 1] -= a[ti2f((k - 1), k)] * z[k];
}
z[0] = v[0] / a[ti2f(0, 0)];
double[] t = new double[iv.size() - 1];
for (int j = 0; j < t.length; ++j) {
t[j] = ati[iv.get(j + 1)];
}
return new VDdemographicFunction(t, z, getUnits());
}
// Assign positions in 'pointsList' for the sub-tree rooted at the ancestor of
// nodeID.
// pointsList is indexed by node-id. Every element is a list of internal
// population points for the branch between nodeID and it's ancestor
private NodeProperties getDemographicPoints(final NodeRef nodeID, Args args, Points[][] pointsList) {
final NodeProperties nprop = props.get(nodeID);
final int nSpecies = species.nSpecies();
// Species assignment from the tips never changes
if (!isExternal(nodeID)) {
nprop.spSet = new FixedBitSet(nSpecies);
for (int nc = 0; nc < getChildCount(nodeID); ++nc) {
final NodeProperties p = getDemographicPoints(getChild(nodeID, nc), args, pointsList);
nprop.spSet.union(p.spSet);
}
}
if (args == null) {
return nprop;
}
// parent height
final double cHeight = nodeID != getRoot() ? getNodeHeight(getParent(nodeID)) : Double.MAX_VALUE;
// points along branch
// not sure what a good default size is?
List<Points> allPoints = new ArrayList<Points>(5);
if (bmp) {
for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) {
final double[] cp = args.cps[isp];
final int upi = singleStartPoints[isp];
int i = args.iSingle[isp];
for (; i < cp.length && cp[i] < cHeight; ++i) {
allPoints.add(new Points(cp[i], args.indicators[upi + i] > 0));
}
args.iSingle[isp] = i;
}
} else {
for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) {
final double nodeHeight = spTree.getNodeHeight(nodeID);
{
double[] cp = args.cps[isp];
final int upi = singleStartPoints[isp];
int i = args.iSingle[isp];
while (i < cp.length && cp[i] < cHeight) {
if (args.indicators[upi + i] > 0) {
//System.out.println(" popbit s");
args.iSingle[isp] = i;
double prev = args.findPrev(cp[i], nodeHeight);
double mid = (prev + cp[i]) / 2.0;
assert nodeHeight < mid;
allPoints.add(new Points(mid, args.pops[upi + i]));
}
++i;
}
args.iSingle[isp] = i;
}
final int kx = (isp * (2 * nSpecies - isp - 3)) / 2 - 1;
for (int y = nprop.spSet.nextOnBit(isp + 1); y >= 0; y = nprop.spSet.nextOnBit(y + 1)) {
assert isp < y;
int k = kx + y;
double[] cp = args.cpp[k];
int i = args.iPair[k];
final int upi = pairStartPoints[k];
while (i < cp.length && cp[i] < cHeight) {
if (args.indicators[upi + i] > 0) {
//System.out.println(" popbit p");
args.iPair[k] = i;
final double prev = args.findPrev(cp[i], nodeHeight);
double mid = (prev + cp[i]) / 2.0;
assert nodeHeight < mid;
allPoints.add(new Points(mid, args.pops[upi + i]));
}
++i;
}
args.iPair[k] = i;
}
}
}
Points[] all = null;
if (allPoints.size() > 0) {
all = allPoints.toArray(new Points[allPoints.size()]);
if (all.length > 1) {
HeapSort.sort(all);
}
int len = all.length;
if (bmp) {
int k = 0;
while (k + 1 < len) {
final double t = all[k].time;
if (t == all[k + 1].time) {
int j = k + 2;
boolean use = all[k].use || all[k + 1].use;
while (j < len && t == all[j].time) {
use = use || all[j].use;
j += 1;
}
int removed = (j - k - 1);
all[k] = new Points(t, use);
for (int i = k + 1; i < len - removed; ++i) {
all[i] = all[i + removed];
}
len -= removed;
}
++k;
}
} else {
// duplications
int k = 0;
while (k + 1 < len) {
double t = all[k].time;
if (t == all[k + 1].time) {
int j = k + 2;
double v = all[k].population + all[k + 1].population;
while (j < len && t == all[j].time) {
v += all[j].population;
j += 1;
}
int removed = (j - k - 1);
all[k] = new Points(t, v / (removed + 1));
for (int i = k + 1; i < len - removed; ++i) {
all[i] = all[i + removed];
}
//System.arraycopy(all, j, all, k + 1, all.length - j + 1);
len -= removed;
}
++k;
}
}
if (len != all.length) {
Points[] a = new Points[len];
System.arraycopy(all, 0, a, 0, len);
all = a;
}
if (bmp) {
for (Points p : all) {
double t = p.time;
assert p.population == 0;
for (int isp = nprop.spSet.nextOnBit(0); isp >= 0; isp = nprop.spSet.nextOnBit(isp + 1)) {
SimpleDemographicFunction d = args.dms[isp];
if (t <= d.upperBound()) {
p.population += d.population(t);
}
}
}
}
}
pointsList[nodeID.getNumber()] = all;
return nprop;
}
private int setDemographics(NodeRef nodeID, int pStart, int side, double[] pops, Points[][] pointsList) {
final int nSpecies = species.nSpecies();
final NodeProperties nprop = props.get(nodeID);
int pEnd;
double p0;
if (isExternal(nodeID)) {
final int sps = nprop.speciesIndex;
p0 = pops[sps];
pEnd = pStart;
} else {
assert getChildCount(nodeID) == 2;
final int iHere = setDemographics(getChild(nodeID, 0), pStart, 0, pops, pointsList);
pEnd = setDemographics(getChild(nodeID, 1), iHere + 1, 1, pops, pointsList);
if (constantPopulation) {
final int i = nSpecies + iHere;
p0 = pops[i];
} else {
final int i = nSpecies + iHere * 2;
p0 = pops[i] + pops[i + 1];
}
}
if (constantPopulation) {
double[] xs = {};
double[] ys = {p0};
nprop.demogf = new VDdemographicFunction(xs, ys, getUnits());
// new ConstantPopulation(p0, getUnits());
} else {
final double t0 = getNodeHeight(nodeID);
Points[] p = pointsList != null ? pointsList[nodeID.getNumber()] : null;
final int plen = p == null ? 0 : p.length;
final boolean isRoot = nodeID == getRoot();
// double[] xs = new double[plen + (isRoot ? 1 : 1)];
// double[] ys = new double[plen + (isRoot ? 2 : 2)];
final boolean useBMP = bmp && pointsList != null;
// internal nodes add one population point for the branch end.
// on the root (with bmp) there is no such point.
final int len = plen + (useBMP ? (!isRoot ? 1 : 0) : 1);
double[] xs = new double[len];
double[] ys = new double[len + 1];
boolean[] use = new boolean[len];
ys[0] = p0;
for (int i = 0; i < plen; ++i) {
xs[i] = p[i].time - t0;
ys[i + 1] = p[i].population;
use[i] = p[i].use;
}
if (!isRoot) {
final int anccIndex = (side == 0) ? pEnd : pStart - 1;
final double pe = pops[nSpecies + anccIndex * 2 + side];
final double b = getBranchLength(nodeID);
xs[xs.length - 1] = b;
ys[ys.length - 1] = pe;
}
if (useBMP) {
nprop.demogf = bestLinearFit(xs, ys, use);
} else {
if (isRoot) {
// extend the last point to most ancient coalescent point. Has no effect on the demographic
// per se but for use when analyzing the results.
double h = -1;
for (SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) {
h = Math.max(h, t.tree.getNodeHeight(t.tree.getRoot()));
}
final double rh = h - t0;
xs[xs.length - 1] = rh; //getNodeHeight(nodeID);
//spTree.setBranchLength(nodeID, rh);
// last value is for root branch end point
ys[ys.length - 1] = pointsList != null ? ys[ys.length - 2] :
(nonConstRootPopulation ? pops[pops.length - 1] : ys[ys.length - 2]);
}
nprop.demogf = new VDdemographicFunction(xs, ys, getUnits());
}
}
return pEnd;
}
private void setNodeProperties() {
Points[][] perBranchPoints = null;
if (coalPointsPops != null) {
final Args args = new Args(bmp);
perBranchPoints = new Points[getNodeCount()][];
getDemographicPoints(getRoot(), args, perBranchPoints);
} else {
// sets species info
getDemographicPoints(getRoot(), null, null);
}
setDemographics(getRoot(), 0, -1, ((Parameter.Default) sppSplitPopulations).inspectParameterValues(), perBranchPoints);
}
private Map<NodeRef, NodeProperties> getProps() {
if (!nodePropsReady) {
setNodeProperties();
nodePropsReady = true;
}
return props;
}
public DemographicFunction getNodeDemographic(NodeRef node) {
return getProps().get(node).demogf;
}
public FixedBitSet spSet(NodeRef node) {
return getProps().get(node).spSet;
}
public int speciesIndex(NodeRef tip) {
assert isExternal(tip);
// always ready even if props is dirty
return props.get(tip).speciesIndex;
}
private Double setInitialSplitPopulations(FlexibleTree startTree, NodeRef node, int pos[]) {
if (!startTree.isExternal(node)) {
int loc = -1;
for (int nc = 0; nc < startTree.getChildCount(node); ++nc) {
final Double p = setInitialSplitPopulations(startTree, startTree.getChild(node, nc), pos);
if (nc == 0) {
loc = pos[0];
pos[0] += 1;
}
if (p != null) {
if (constantPopulation) {
} else {
sppSplitPopulations.setParameterValueQuietly(species.nSpecies() + 2 * loc + nc, p);
}
}
}
}
final String comment = (String) startTree.getNodeAttribute(node, NewickImporter.COMMENT);
Double p0 = null;
if (comment != null) {
StringTokenizer st = new StringTokenizer(comment);
p0 = Double.parseDouble(st.nextToken());
if (startTree.isExternal(node)) {
int ns = (Integer) startTree.getNodeAttribute(node, spIndexAttrName);
sppSplitPopulations.setParameterValueQuietly(ns, p0);
} else if (constantPopulation) {
// not tested code !!
sppSplitPopulations.setParameterValueQuietly(species.nSpecies() + pos[0], p0);
pos[0] += 1;
}
// if just one value const
if (st.hasMoreTokens()) {
p0 = Double.parseDouble(st.nextToken());
}
}
return p0;
}
private SimpleTree compatibleUninformedSpeciesTree(Tree startTree) {
double rootHeight = Double.MAX_VALUE;
for (SpeciesBindings.GeneTreeInfo t : species.getGeneTrees()) {
rootHeight = Math.min(rootHeight, t.getCoalInfo()[0].ctime);
}
final SpeciesBindings.SPinfo[] spp = species.species;
if (startTree != null) {
// Allow start tree to be very basic basic - may be only partially resolved and no
// branch lengths
if (startTree.getExternalNodeCount() != spp.length) {
throw new Error("Start tree error - different number of tips");
}
final FlexibleTree tree = new FlexibleTree(startTree, true);
tree.resolveTree();
final double treeHeight = tree.getRootHeight();
if (treeHeight <= 0) {
tree.setRootHeight(1.0);
Utils.correctHeightsForTips(tree);
SimpleTree.Utils.scaleNodeHeights(tree, rootHeight / tree.getRootHeight());
}
SimpleTree sTree = new SimpleTree(tree);
for (int ns = 0; ns < spp.length; ns++) {
SpeciesBindings.SPinfo sp = spp[ns];
final int i = sTree.getTaxonIndex(sp.name);
if (i < 0) {
throw new Error(sp.name + " is not present in the start tree");
}
final SimpleNode node = sTree.getExternalNode(i);
node.setAttribute(spIndexAttrName, ns);
// set for possible pops
tree.setNodeAttribute(tree.getNode(tree.getTaxonIndex(sp.name)), spIndexAttrName, ns);
}
if (treeHeight > 0) {
sTree.setAttribute("check", new Double(rootHeight));
}
{
//assert ! constantPopulation; // not implemented yet
int[] pos = {0};
setInitialSplitPopulations(tree, tree.getRoot(), pos);
}
return sTree;
}
final double delta = rootHeight / (spp.length + 1);
double cTime = delta;
List<SimpleNode> subs = new ArrayList<SimpleNode>(spp.length);
for (int ns = 0; ns < spp.length; ns++) {
SpeciesBindings.SPinfo sp = spp[ns];
final SimpleNode node = new SimpleNode();
node.setTaxon(new Taxon(sp.name));
subs.add(node);
node.setAttribute(spIndexAttrName, ns);
}
while (subs.size() > 1) {
final SimpleNode node = new SimpleNode();
int i = 0, j = 1;
node.addChild(subs.get(i));
node.addChild(subs.get(j));
node.setHeight(cTime);
cTime += delta;
subs.set(j, node);
subs.remove(i);
}
return new SimpleTree(subs.get(0));
}
public void setPreorderIndices(int[] indices) {
setPreorderIndices(getRoot(), 0, indices);
}
private int setPreorderIndices(NodeRef node, int loc, int[] indices) {
if (!isExternal(node)) {
int l = setPreorderIndices(getChild(node, 0), loc, indices);
indices[node.getNumber()] = l;
loc = setPreorderIndices(getChild(node, 1), l + 1, indices);
}
return loc;
}
public String getName() {
return getModelName();
}
static private TreeNodeSlide internalTreeOP = null;
public int scale(double scaleFactor, int nDims) throws OperatorFailedException {
assert scaleFactor > 0;
if (nDims <= 0) {
// actually when in an up down with operators on the gene trees the flags
// may indicate a change
//storeState(); // just checks assert really
beginTreeEdit();
final int count = getInternalNodeCount();
for (int i = 0; i < count; ++i) {
final NodeRef n = getInternalNode(i);
setNodeHeight(n, getNodeHeight(n) * scaleFactor);
}
endTreeEdit();
fireModelChanged(this, 1);
return count;
} else {
if (nDims != 1) {
throw new OperatorFailedException("not implemented for count != 1");
}
if (internalTreeOP == null) {
internalTreeOP = new TreeNodeSlide(this, species, 1);
}
internalTreeOP.operateOneNode(scaleFactor);
fireModelChanged(this, 1);
return nDims;
}
}
private final boolean verbose = false;
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (verbose) System.out.println(" SPtree: model changed " + model.getId());
nodePropsReady = false;
anyChange = true;
// this should happen by default, no?
fireModelChanged();
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
if (verbose) System.out.println(" SPtree: parameter changed " + variable.getId());
nodePropsReady = false;
anyChange = true;
}
protected void storeState() {
assert !treeChanged;
assert !anyChange;
}
protected void restoreState() {
if (verbose) System.out.println(" SPtree: restore (" + treeChanged + "," + anyChange + ")");
if (treeChanged) {
spTree.beginTreeEdit();
for (int k = 0; k < getInternalNodeCount(); ++k) {
final NodeRef node = getInternalNode(k);
final int index = node.getNumber();
final double h = heights[index];
if (getNodeHeight(node) != h) {
setNodeHeight(node, h);
}
for (int nc = 0; nc < 2; ++nc) {
final NodeRef child = getChild(node, nc);
final NodeRef child1 = children[2 * index + nc];
if (child != child1) {
replaceChild(node, child, child1);
}
assert getParent(child1) == node;
}
}
setRoot(children[children.length - 1]);
if (verbose) System.out.println(" restored to: " + spTree);
spTree.endTreeEdit();
}
if (treeChanged || anyChange) {
setNodeProperties();
}
treeChanged = false;
anyChange = false;
}
protected void acceptState() {
if (verbose) System.out.println(" SPtree: accept");
treeChanged = false;
anyChange = false;
}
String previousTopology = null;
public boolean logNow(int state) {
final String curTop = Tree.Utils.uniqueNewick(spTree, spTree.getRoot());
if (state == 0 || !curTop.equals(previousTopology)) {
previousTopology = curTop;
return true;
}
return false;
}
// TreeTrait dmf = new TreeTrait.S() {
// public String getTraitName() {
// return "dmf";
// public Intent getIntent() {
// return Intent.NODE;
// public String getTrait(Tree tree, NodeRef node) {
// assert tree == SpeciesTreeModel.this;
// //final VDdemographicFunction df = getProps().get(node).demogf;
// final DemographicFunction df = getNodeDemographic(node);
// return df.toString();
TreeTrait dmt = new TreeTrait.DA() {
public String getTraitName() {
return "dmt";
}
public Intent getIntent() {
return Intent.NODE;
}
public double[] getTrait(Tree tree, NodeRef node) {
assert tree == SpeciesTreeModel.this;
final VDdemographicFunction df = (VDdemographicFunction) getNodeDemographic(node);
return df.times();
}
};
TreeTrait dmv = new TreeTrait.DA() {
public String getTraitName() {
return "dmv";
}
public Intent getIntent() {
return Intent.NODE;
}
public double[] getTrait(Tree tree, NodeRef node) {
assert tree == SpeciesTreeModel.this;
final VDdemographicFunction df = (VDdemographicFunction) getNodeDemographic(node);
return df.values();
}
};
public TreeTrait[] getTreeTraits() {
return new TreeTrait[]{dmt, dmv};
}
public TreeTrait getTreeTrait(String key) {
if (key.equals(dmt.getTraitName())) {
return dmt;
} else if (key.equals(dmv.getTraitName())) {
return dmv;
}
throw new IllegalArgumentException();
}
// boring delegation
public SimpleTree getSimpleTree() {
return spTree;
}
public Tree getCopy() {
return spTree.getCopy();
}
public Type getUnits() {
return spTree.getUnits();
}
public void setUnits(Type units) {
spTree.setUnits(units);
}
public int getNodeCount() {
return spTree.getNodeCount();
}
public boolean hasNodeHeights() {
return spTree.hasNodeHeights();
}
public double getNodeHeight(NodeRef node) {
return spTree.getNodeHeight(node);
}
public double getNodeRate(NodeRef node) {
return spTree.getNodeRate(node);
}
public Taxon getNodeTaxon(NodeRef node) {
return spTree.getNodeTaxon(node);
}
public int getChildCount(NodeRef node) {
return spTree.getChildCount(node);
}
public boolean isExternal(NodeRef node) {
return spTree.isExternal(node);
}
public boolean isRoot(NodeRef node) {
return spTree.isRoot(node);
}
public NodeRef getChild(NodeRef node, int i) {
return spTree.getChild(node, i);
}
public NodeRef getParent(NodeRef node) {
return spTree.getParent(node);
}
public boolean hasBranchLengths() {
return spTree.hasBranchLengths();
}
public double getBranchLength(NodeRef node) {
return spTree.getBranchLength(node);
}
public void setBranchLength(NodeRef node, double length) {
spTree.setBranchLength(node, length);
}
public NodeRef getExternalNode(int i) {
return spTree.getExternalNode(i);
}
public NodeRef getInternalNode(int i) {
return spTree.getInternalNode(i);
}
public NodeRef getNode(int i) {
return spTree.getNode(i);
}
public int getExternalNodeCount() {
return spTree.getExternalNodeCount();
}
public int getInternalNodeCount() {
return spTree.getInternalNodeCount();
}
public NodeRef getRoot() {
return spTree.getRoot();
}
public void setRoot(NodeRef r) {
spTree.setRoot(r);
}
public void addChild(NodeRef p, NodeRef c) {
spTree.addChild(p, c);
}
public void removeChild(NodeRef p, NodeRef c) {
spTree.removeChild(p, c);
}
public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) {
spTree.replaceChild(node, child, newChild);
}
public boolean beginTreeEdit() {
boolean beingEdited = spTree.beginTreeEdit();
if (!beingEdited) {
// save tree for restore
for (int n = 0; n < getInternalNodeCount(); ++n) {
final NodeRef node = getInternalNode(n);
final int k = node.getNumber();
children[2 * k] = getChild(node, 0);
children[2 * k + 1] = getChild(node, 1);
heights[k] = getNodeHeight(node);
}
children[children.length - 1] = getRoot();
treeChanged = true;
nodePropsReady = false;
//anyChange = true;
}
return beingEdited;
}
public void endTreeEdit() {
spTree.endTreeEdit();
fireModelChanged();
}
public void setNodeHeight(NodeRef n, double height) {
spTree.setNodeHeight(n, height);
}
public void setNodeRate(NodeRef n, double rate) {
spTree.setNodeRate(n, rate);
}
public void setNodeAttribute(NodeRef node, String name, Object value) {
spTree.setNodeAttribute(node, name, value);
}
public Object getNodeAttribute(NodeRef node, String name) {
return spTree.getNodeAttribute(node, name);
}
public Iterator getNodeAttributeNames(NodeRef node) {
return spTree.getNodeAttributeNames(node);
}
public int getTaxonCount() {
return spTree.getTaxonCount();
}
public Taxon getTaxon(int taxonIndex) {
return spTree.getTaxon(taxonIndex);
}
public String getTaxonId(int taxonIndex) {
return spTree.getTaxonId(taxonIndex);
}
public int getTaxonIndex(String id) {
return spTree.getTaxonIndex(id);
}
public int getTaxonIndex(Taxon taxon) {
return spTree.getTaxonIndex(taxon);
}
public List<Taxon> asList() {
return spTree.asList();
}
public Iterator<Taxon> iterator() {
return spTree.iterator();
}
public Object getTaxonAttribute(int taxonIndex, String name) {
return spTree.getTaxonAttribute(taxonIndex, name);
}
public int addTaxon(Taxon taxon) {
return spTree.addTaxon(taxon);
}
public boolean removeTaxon(Taxon taxon) {
return spTree.removeTaxon(taxon);
}
public void setTaxonId(int taxonIndex, String id) {
spTree.setTaxonId(taxonIndex, id);
}
public void setTaxonAttribute(int taxonIndex, String name, Object value) {
spTree.setTaxonAttribute(taxonIndex, name, value);
}
public String getId() {
return spTree.getId();
}
public void setId(String id) {
spTree.setId(id);
}
public void setAttribute(String name, Object value) {
spTree.setAttribute(name, value);
}
public Object getAttribute(String name) {
return spTree.getAttribute(name);
}
public Iterator<String> getAttributeNames() {
return spTree.getAttributeNames();
}
public void addMutableTreeListener(MutableTreeListener listener) {
spTree.addMutableTreeListener(listener);
}
public void addMutableTaxonListListener(MutableTaxonListListener listener) {
spTree.addMutableTaxonListListener(listener);
}
public static Parameter createCoalPointsPopParameter(SpeciesBindings spb, Double value, Boolean bmp) {
int dim = 0;
for (double[] d : spb.getPopTimesSingle()) {
dim += d.length;
}
if (!bmp) {
for (double[] d : spb.getPopTimesPair()) {
dim += d.length;
}
}
return new Parameter.Default(dim, value);
}
public static Parameter createSplitPopulationsParameter(SpeciesBindings spb, double value, boolean root, boolean constPop) {
int dim;
if (constPop) {
// one per node
dim = 2 * spb.nSpecies() - 1;
} else {
// one per species leaf (ns) + 2 per internal node (2*(ns-1)) + optionally one for the root
dim = 3 * spb.nSpecies() - 2 + (root ? 1 : 0);
}
return new Parameter.Default(dim, value);
}
} |
package dr.evomodel.tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.inference.model.*;
import dr.math.Polynomial;
import dr.math.MathUtils;
import dr.math.LogTricks;
import dr.xml.*;
import java.util.*;
import java.util.logging.Logger;
//import org.jscience.mathematics.number.Rational;
/**
* Two priors for the tree that are relatively non-informative on the internal node heights given the root height.
* The first further assumes that the root height is truncated uniform, see Nicholls, G. & R.D. Gray (2004) for details.
* The second allows any marginal specification over the root height given that it is larger than the oldest
* sampling time (Bloomquist and Suchard, unpublished).
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Erik Bloomquist
* @author Marc Suchard
* @version $Id: UniformRootPrior.java,v 1.10 2005/05/24 20:25:58 rambaut Exp $
*/
public class UniformNodeHeightPrior extends AbstractModelLikelihood {
// PUBLIC STUFF
public static final String UNIFORM_ROOT_PRIOR = "uniformRootPrior";
public static final String UNIFORM_NODE_HEIGHT_PRIOR = "uniformNodeHeightPrior";
public static final String MAX_ROOT_HEIGHT = "maxRootHeight";
public static final String ANALYTIC = "analytic";
public static final String MC_SAMPLE = "mcSampleSize";
public static final String MARGINAL = "marginal";
public static final String LEADING_TERM = "approximate";
public static final int MAX_ANALYTIC_TIPS = 60; // TODO Determine this value!
public static final int DEFAULT_MC_SAMPLE = 100000;
private static final double tolerance = 1E-6;
private int k = 0;
private double logFactorialK;
private double maxRootHeight;
private boolean isNicholls;
private boolean useAnalytic;
private boolean useMarginal;
private boolean leadingTerm;
private int mcSampleSize;
Set<Double> tipDates = new TreeSet<Double>();
List<Double> reversedTipDateList = new ArrayList<Double>();
Map<Double, Integer> intervals = new TreeMap<Double, Integer>();
public UniformNodeHeightPrior(Tree tree, boolean useAnalytic, boolean marginal, boolean leadingTerm) {
this(UNIFORM_NODE_HEIGHT_PRIOR, tree, useAnalytic, DEFAULT_MC_SAMPLE, marginal, leadingTerm);
}
private UniformNodeHeightPrior(Tree tree, boolean useAnalytic, int mcSampleSize) {
this(UNIFORM_NODE_HEIGHT_PRIOR,tree,useAnalytic,mcSampleSize, false, false);
}
private UniformNodeHeightPrior(String name, Tree tree, boolean useAnalytic, int mcSampleSize,
boolean marginal, boolean leadingTerm) {
super(name);
this.tree = tree;
this.isNicholls = false;
this.useAnalytic = useAnalytic;
this.useMarginal = marginal;
this.mcSampleSize = mcSampleSize;
this.leadingTerm = leadingTerm;
if (tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
for (int i = 0; i < tree.getExternalNodeCount(); i++) {
double h = tree.getNodeHeight(tree.getExternalNode(i));
tipDates.add(h);
}
if (tipDates.size() == 1 || leadingTerm) {
// the tips are contemporaneous so these are constant...
k = tree.getInternalNodeCount() - 1;
Logger.getLogger("dr.evomodel").info("Uniform Node Height Prior, Intervals = " + (k + 1));
logFactorialK = logFactorial(k);
} else {
reversedTipDateList.addAll(tipDates);
Collections.reverse(reversedTipDateList);
// Prune out intervals smaller in length than tolerance
double intervalStart = tree.getNodeHeight(tree.getRoot());
List<Double> pruneDates = new ArrayList<Double>();
for (Double intervalEnd : reversedTipDateList) {
if (intervalStart - intervalEnd < tolerance) {
pruneDates.add(intervalStart);
}
intervalStart = intervalEnd;
}
for (Double date : pruneDates)
reversedTipDateList.remove(date);
if (!useAnalytic) {
logLikelihoods = new double[mcSampleSize];
drawNodeHeights = new double[tree.getNodeCount()][mcSampleSize];
minNodeHeights = new double[tree.getNodeCount()];
}
}
// Leading coefficient on tree polynomial is X = (# internal nodes)!
// To keep X > 10E-40, should use log-space polynomials for more than ~30 tips
if (tree.getExternalNodeCount() < 30) {
polynomialType = Polynomial.Type.DOUBLE; // Much faster
} else if (tree.getExternalNodeCount() < 45){
polynomialType = Polynomial.Type.LOG_DOUBLE;
} else {
// polynomialType = Polynomial.Type.APDOUBLE;
polynomialType = Polynomial.Type.LOG_DOUBLE;
}
Logger.getLogger("dr.evomodel").info("Using "+polynomialType+" polynomials!");
}
public UniformNodeHeightPrior(Tree tree, double maxRootHeight) {
this(UNIFORM_NODE_HEIGHT_PRIOR, tree, maxRootHeight);
}
private UniformNodeHeightPrior(String name, Tree tree, double maxRootHeight) {
super(name);
this.tree = tree;
this.maxRootHeight = maxRootHeight;
isNicholls = true;
if (tree instanceof TreeModel) {
addModel((TreeModel) tree);
}
}
UniformNodeHeightPrior(String name) {
super(name);
}
// Extendable methods
// ModelListener IMPLEMENTATION
protected final void handleModelChangedEvent(Model model, Object object, int index) {
likelihoodKnown = false;
treePolynomialKnown = false;
return;
// Only set treePolynomialKnown = false when a topology change occurs
// Only set likelihoodKnown = false when a topology change occurs or the rootHeight is changed
// if (model == tree) {
// if (object instanceof TreeModel.TreeChangedEvent) {
// TreeModel.TreeChangedEvent event = (TreeModel.TreeChangedEvent) object;
// if (event.isHeightChanged()) {
// if (event.getNode() == tree.getRoot()) {
// likelihoodKnown = false;
// return;
// } // else
// return;
// if (event.isNodeParameterChanged())
// return;
// // All others are probably tree structure changes
// likelihoodKnown = false;
// treePolynomialKnown = false;
// return;
// // TODO Why are not all node height changes invoking TreeChangedEvents?
// if (object instanceof Parameter.Default) {
// Parameter parameter = (Parameter) object;
// if (tree.getNodeHeight(tree.getRoot()) == parameter.getParameterValue(index)) {
// likelihoodKnown = false;
// treePolynomialKnown = false;
// return;
// return;
// throw new RuntimeException("Unexpected event!");
}
// VariableListener IMPLEMENTATION
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
}
// Model IMPLEMENTATION
/**
* Stores the precalculated state: in this case the intervals
*/
protected final void storeState() {
storedLikelihoodKnown = likelihoodKnown;
storedLogLikelihood = logLikelihood;
// storedTreePolynomialKnown = treePolynomialKnown;
// if (treePolynomial != null)
// storedTreePolynomial = treePolynomial.copy(); // TODO Swap pointers
}
/**
* Restores the precalculated state: that is the intervals of the tree.
*/
protected final void restoreState() {
likelihoodKnown = storedLikelihoodKnown;
logLikelihood = storedLogLikelihood;
// treePolynomialKnown = storedTreePolynomialKnown;
// treePolynomial = storedTreePolynomial;
}
protected final void acceptState() {
} // nothing to do
// Likelihood IMPLEMENTATION
public final Model getModel() {
return this;
}
public double getLogLikelihood() {
// return calculateLogLikelihood();
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
public final void makeDirty() {
likelihoodKnown = false;
treePolynomialKnown = false;
}
public double calculateLogLikelihood() {
double rootHeight = tree.getNodeHeight(tree.getRoot());
if (isNicholls) {
int nodeCount = tree.getExternalNodeCount();
if (rootHeight < 0 || rootHeight > (0.999 * maxRootHeight)) return Double.NEGATIVE_INFINITY;
// from Nicholls, G. & R.D. Gray (2004)
return rootHeight * (2 - nodeCount) - Math.log(maxRootHeight - rootHeight);
} else {
// the Bloomquist & Suchard variant
// Let the sampling times and rootHeight specify the boundaries between a fixed number of intervals.
// Internal node heights are equally likely to fall in any of these intervals and uniformly distributed
// in an interval before sorting (i.e. the intercoalescent times in an interval form a scaled Dirchelet(1,1,\ldots,1)
// This is a conditional density on the rootHeight, so it is possible to specify a marginal distribution
// on the rootHeight given it is greater than the oldest sampling time.
double logLike;
if (k > 0) { // Also valid for leading-term approximation
// the tips are contemporaneous
logLike = logFactorialK - (double) k * Math.log(rootHeight);
} else {
// TODO Rewrite description above to discuss this new prior
if (useAnalytic) {
// long startTime1 = System.nanoTime();
if (useMarginal) {
if (!treePolynomialKnown) {
// treePolynomial = recursivelyComputePolynomial(tree, tree.getRoot(), polynomialType).getPolynomial();
treePolynomials = constructRootPolyonmials(tree,polynomialType); // Each polynomial is of lower degree
treePolynomialKnown = true;
}
// logLike = -treePolynomial.logEvaluate(rootHeight);
logLike = -treePolynomials[0].logEvaluate(rootHeight) - treePolynomials[1].logEvaluate(rootHeight);
if (Double.isNaN(logLike)) {
// Try using Horner's method
// logLike = -treePolynomial.logEvaluateHorner(rootHeight); // TODO this could be causing the problem!!
logLike = -treePolynomials[0].logEvaluateHorner(rootHeight) - treePolynomials[1].logEvaluateHorner(rootHeight);
if (Double.isNaN(logLike)) {
logLike = Double.NEGATIVE_INFINITY;
}
}
} else {
tmpLogLikelihood = 0;
recursivelyComputeDensity(tree, tree.getRoot(), 0);
logLike = tmpLogLikelihood;
}
// long stopTime1 = System.nanoTime();
} else {
// long startTime2 = System.nanoTime();
// Copy over current root height
final double[] drawRootHeight = drawNodeHeights[tree.getRoot().getNumber()];
Arrays.fill(drawRootHeight,rootHeight); // TODO Only update when rootHeight changes
// Determine min heights for each node in tree
recursivelyFindNodeMinHeights(tree,tree.getRoot()); // TODO Only update when topology changes
// Simulate from prior
Arrays.fill(logLikelihoods,0.0);
recursivelyComputeMCIntegral(tree, tree.getRoot(), tree.getRoot().getNumber()); // TODO Only update when topology or rootHeight changes
// Take average
logLike = -LogTricks.logSum(logLikelihoods) + Math.log(mcSampleSize);
// long stopTime2 = System.nanoTime();
}
}
assert !Double.isInfinite(logLike) && !Double.isNaN(logLike);
return logLike;
}
}
// Map<Double,Integer> boxCounts;
// private double recursivelyComputeMarcDensity(Tree tree, NodeRef node, double rootHeight) {
// if (tree.isExternal(node))
// return tree.getNodeHeight(node);
//// double thisHeight = tree.getNodeHeight(node);
//// double thisHeight = rootHeight;
// double heightChild1 = recursivelyComputeMarcDensity(tree, tree.getChild(node, 0), rootHeight);
// double heightChild2 = recursivelyComputeMarcDensity(tree, tree.getChild(node, 1), rootHeight);
// double minHeight = (heightChild1 > heightChild2) ? heightChild1 : heightChild2;
// if (!tree.isRoot(node)) {
// double diff = rootHeight - minHeight;
// if (diff <= 0)
// tmpLogLikelihood = Double.NEGATIVE_INFINITY;
// else
// tmpLogLikelihood -= Math.log(diff);
// Integer count = boxCounts.get(minHeight);
// if (count == null) {
// boxCounts.put(minHeight,1);
//// System.err.println("new height: "+minHeight);
// } else {
// boxCounts.put(minHeight,count+1);
//// System.err.println("old height: "+minHeight);
// // TODO Could do the logFactorial right here
// } else {
// // Do nothing
// return minHeight;
private double recursivelyComputeDensity(Tree tree, NodeRef node, double parentHeight) {
if (tree.isExternal(node))
return tree.getNodeHeight(node);
double thisHeight = tree.getNodeHeight(node);
double heightChild1 = recursivelyComputeDensity(tree, tree.getChild(node, 0), thisHeight);
double heightChild2 = recursivelyComputeDensity(tree, tree.getChild(node, 1), thisHeight);
double minHeight = (heightChild1 > heightChild2) ? heightChild1 : heightChild2;
if (!tree.isRoot(node)) {
double diff = parentHeight - minHeight;
if (diff <= 0)
tmpLogLikelihood = Double.NEGATIVE_INFINITY;
else
tmpLogLikelihood -= Math.log(diff);
// tmpLogLikelihood -= Math.log(parentHeight-minHeight);
} else {
// Do nothing
}
return minHeight;
}
private double recursivelyFindNodeMinHeights(Tree tree, NodeRef node) {
double minHeight;
if (tree.isExternal(node))
minHeight = tree.getNodeHeight(node);
else {
double minHeightChild0 = recursivelyFindNodeMinHeights(tree, tree.getChild(node,0));
double minHeightChild1 = recursivelyFindNodeMinHeights(tree, tree.getChild(node,1));
minHeight = (minHeightChild0 > minHeightChild1) ? minHeightChild0 : minHeightChild1;
}
minNodeHeights[node.getNumber()] = minHeight;
return minHeight;
}
private void recursivelyComputeMCIntegral(Tree tree, NodeRef node, int parentNodeNumber) {
if (tree.isExternal(node))
return;
final int nodeNumber = node.getNumber();
if (!tree.isRoot(node)) {
final double[] drawParentHeight = drawNodeHeights[parentNodeNumber];
final double[] drawThisNodeHeight = drawNodeHeights[nodeNumber];
final double minHeight = minNodeHeights[nodeNumber];
final boolean twoChild = (tree.isExternal(tree.getChild(node,0)) && tree.isExternal(tree.getChild(node,1)));
for(int i=0; i<mcSampleSize; i++) {
final double diff = drawParentHeight[i] - minHeight;
if (diff <= 0) {
logLikelihoods[i] = Double.NEGATIVE_INFINITY;
break;
}
if (!twoChild)
drawThisNodeHeight[i] = MathUtils.nextDouble() * diff + minHeight;
logLikelihoods[i] += Math.log(diff);
}
}
recursivelyComputeMCIntegral(tree, tree.getChild(node,0), nodeNumber);
recursivelyComputeMCIntegral(tree, tree.getChild(node,1), nodeNumber);
}
private static final double INV_PRECISION = 10;
private static double round(double x) {
return Math.round(x * INV_PRECISION) / INV_PRECISION;
}
private Polynomial[] constructRootPolyonmials(Tree tree, Polynomial.Type type) {
NodeRef root = tree.getRoot();
return new Polynomial[] {
recursivelyComputePolynomial(tree,tree.getChild(root,0),type).getPolynomial(),
recursivelyComputePolynomial(tree,tree.getChild(root,1),type).getPolynomial()
};
}
private TipLabeledPolynomial recursivelyComputePolynomial(Tree tree, NodeRef node, Polynomial.Type type) {
if (tree.isExternal(node)) {
double[] value = new double[]{1.0};
double height = round(tree.getNodeHeight(node)); // Should help in numerical stability
return new TipLabeledPolynomial(value, height, type, true);
}
TipLabeledPolynomial childPolynomial1 = recursivelyComputePolynomial(tree, tree.getChild(node, 0), type);
TipLabeledPolynomial childPolynomial2 = recursivelyComputePolynomial(tree, tree.getChild(node, 1), type);
// TODO The partialPolynomial below *should* be cached in an efficient reuse scheme (at least for arbitrary precision)
TipLabeledPolynomial polynomial = childPolynomial1.multiply(childPolynomial2);
// See AbstractTreeLikelihood for an example of how to flag cached polynomials for re-evaluation
if (!tree.isRoot(node)) {
polynomial = polynomial.integrateWithLowerBound(polynomial.label);
}
return polynomial;
}
// private void test() {
// double[] value = new double[]{2, 0, 2};
// Polynomial a = new Polynomial.Double(value);
// Polynomial a2 = a.multiply(a);
// System.err.println("a :" + a);
// System.err.println("a*a: " + a2);
// System.err.println("eval :" + a2.evaluate(2));
// Polynomial intA = a.integrate();
// System.err.println("intA: " + intA);
// Polynomial intA2 = a.integrateWithLowerBound(2.0);
// System.err.println("intA2: " + intA2);
// System.err.println("");
// Polynomial b = new Polynomial.APDouble(value);
// System.err.println("b : " + b);
// Polynomial b2 = b.multiply(b);
// System.err.println("b2 : " + b2);
// System.err.println("eval : " + b2.evaluate(2));
// Polynomial intB = b.integrate();
// System.err.println("intB: " + intB);
// Polynomial intB2 = b.integrateWithLowerBound(2.0);
// System.err.println("intB2: " + intB2);
// System.err.println("");
// Polynomial c = new Polynomial.LogDouble(value);
// System.err.println("c : " + c);
// System.err.println("c2 : " + c2);
// System.err.println("eval : " + c2.evaluate(2));
// Polynomial intC = c.integrate();
// System.err.println("intC: " + intC);
// Polynomial intC2 = c.integrateWithLowerBound(2.0);
// System.err.println("intC2: " + intC2);
// System.exit(-1);
class TipLabeledPolynomial extends Polynomial.Abstract {
TipLabeledPolynomial(double[] coefficients, double label, Polynomial.Type type, boolean isTip) {
switch (type) {
case DOUBLE:
polynomial = new Polynomial.Double(coefficients);
break;
case LOG_DOUBLE:
polynomial = new Polynomial.LogDouble(coefficients);
break;
case BIG_DOUBLE:
polynomial = new Polynomial.BigDouble(coefficients);
break;
// case APDOUBLE: polynomial = new Polynomial.APDouble(coefficients);
// break;
// case RATIONAL: polynomial = new Polynomial.RationalDouble(coefficients);
// break;
// case MARCRATIONAL: polynomial = new Polynomial.MarcRational(coefficients);
// break;
default:
throw new RuntimeException("Unknown polynomial type");
}
this.label = label;
this.isTip = isTip;
}
TipLabeledPolynomial(Polynomial polynomial, double label, boolean isTip) {
this.polynomial = polynomial;
this.label = label;
this.isTip = isTip;
}
public TipLabeledPolynomial copy() {
Polynomial copyPolynomial = polynomial.copy();
return new TipLabeledPolynomial(copyPolynomial, this.label, this.isTip);
}
public Polynomial getPolynomial() {
return polynomial;
}
public TipLabeledPolynomial multiply(TipLabeledPolynomial b) {
double maxLabel = Math.max(label, b.label);
return new TipLabeledPolynomial(polynomial.multiply(b), maxLabel, false);
}
public int getDegree() {
return polynomial.getDegree();
}
public Polynomial multiply(Polynomial b) {
return polynomial.multiply(b);
}
public Polynomial integrate() {
return polynomial.integrate();
}
public void expand(double x) {
polynomial.expand(x);
}
public double evaluate(double x) {
return polynomial.evaluate(x);
}
public double logEvaluate(double x) {
return polynomial.logEvaluate(x);
}
public double logEvaluateHorner(double x) {
return polynomial.logEvaluateHorner(x);
}
public void setCoefficient(int n, double x) {
polynomial.setCoefficient(n, x);
}
public TipLabeledPolynomial integrateWithLowerBound(double bound) {
return new TipLabeledPolynomial(polynomial.integrateWithLowerBound(bound), label, isTip);
}
public double getCoefficient(int n) {
return polynomial.getCoefficient(n);
}
public String toString() {
return polynomial.toString() + " {" + label + "}";
}
public String getCoefficientString(int n) {
return polynomial.getCoefficientString(n);
}
private double label;
private Polynomial polynomial;
private boolean isTip;
}
private double logFactorial(int n) {
if (n == 0 || n == 1) {
return 0;
}
double rValue = 0;
for (int i = n; i > 1; i
rValue += Math.log(i);
}
return rValue;
}
// XMLElement IMPLEMENTATION
public org.w3c.dom.Element createElement(org.w3c.dom.Document d) {
throw new RuntimeException("createElement not implemented");
}
// Private and protected stuff
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return UNIFORM_NODE_HEIGHT_PRIOR;
}
public String[] getParserNames() {
return new String[] {UNIFORM_ROOT_PRIOR, UNIFORM_NODE_HEIGHT_PRIOR};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Logger.getLogger("dr.evomodel").info("\nConstructing a uniform node height prior:");
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
if (xo.hasAttribute(MAX_ROOT_HEIGHT)) {
// the Nicholls & Gray variant
double maxRootHeight = xo.getDoubleAttribute(MAX_ROOT_HEIGHT);
Logger.getLogger("dr.evomodel").info("\tUsing joint variant with a max root height = "+maxRootHeight+"\n");
return new UniformNodeHeightPrior(treeModel, maxRootHeight);
} else {
// the Bloomquist & Suchard variant or Welch, Rambaut & Suchard variant
boolean useAnalytic = xo.getAttribute(ANALYTIC,true);
boolean marginal = xo.getAttribute(MARGINAL,true);
boolean leadingTerm = xo.getAttribute(LEADING_TERM,false);
Logger.getLogger("dr.evomodel").info("\tUsing conditional variant with "+(useAnalytic ? "analytic" : "Monte Carlo integrated")+" expressions");
if (useAnalytic) {
Logger.getLogger("dr.evomodel").info("\t\tSubvariant: "+(marginal ? "marginal" : "conditional"));
Logger.getLogger("dr.evomodel").info("\t\tApproximation: "+leadingTerm);
}
Logger.getLogger("dr.evomodel").info("\tPlease reference:");
Logger.getLogger("dr.evomodel").info("\t\t (1) Welch, Rambaut and Suchard (in preparation) and");
Logger.getLogger("dr.evomodel").info("\t\t (2) Bloomquist and Suchard (in press) Systematic Biology\n");
if (!useAnalytic) {
// if( treeModel.getExternalNodeCount() > MAX_ANALYTIC_TIPS)
// throw new XMLParseException("Analytic evaluation of UniformNodeHeight is unreliable for > "+MAX_ANALYTIC_TIPS+" taxa");
int mcSampleSize = xo.getAttribute(MC_SAMPLE,DEFAULT_MC_SAMPLE);
return new UniformNodeHeightPrior(treeModel,useAnalytic,mcSampleSize);
}
return new UniformNodeHeightPrior(treeModel, useAnalytic, marginal,leadingTerm);
}
}
/**
* The tree.
*/
Tree tree = null;
double logLikelihood;
private double storedLogLikelihood;
boolean likelihoodKnown = false;
private boolean storedLikelihoodKnown = false;
private boolean treePolynomialKnown = false;
private boolean storedTreePolynomialKnown = false;
private Polynomial treePolynomial;
private Polynomial[] treePolynomials;
private Polynomial storedTreePolynomial;
private double tmpLogLikelihood;
// private Iterator<Polynomial.Type> typeIterator = EnumSet.allOf(Polynomial.Type.class).iterator();
// private Polynomial.Type polynomialType = typeIterator.next();
private Polynomial.Type polynomialType;
private double[] logLikelihoods;
private double[][] drawNodeHeights;
private double[] minNodeHeights;
} |
package dr.inference.model;
import dr.inference.loggers.LogColumn;
import dr.math.LogTricks;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author Marc A. Suchard
* @author Andrew Rambaut
*/
public class WeightedMixtureModel extends AbstractModelLikelihood {
public static final String MIXTURE_MODEL = "mixtureModel";
// public static final String MIXTURE_WEIGHTS = "weights";
public static final String NORMALIZE = "normalize";
public WeightedMixtureModel(List<Likelihood> likelihoodList, Parameter mixtureWeights) {
super(MIXTURE_MODEL);
this.likelihoodList = likelihoodList;
this.mixtureWeights = mixtureWeights;
addVariable(mixtureWeights);
}
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
}
protected void storeState() {
}
protected void restoreState() {
}
protected void acceptState() {
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
double logSum = Double.NEGATIVE_INFINITY;
for (int i = 0; i < likelihoodList.size(); ++i) {
double pi = mixtureWeights.getParameterValue(i);
if (pi > 0.0) {
logSum = LogTricks.logSum(logSum,
Math.log(pi) + likelihoodList.get(i).getLogLikelihood());
}
}
return logSum;
}
public void makeDirty() {
}
public LogColumn[] getColumns() {
return new LogColumn[0];
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MIXTURE_MODEL;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Parameter weights = (Parameter) xo.getChild(Parameter.class);
List<Likelihood> likelihoodList = new ArrayList<Likelihood>();
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Likelihood)
likelihoodList.add((Likelihood) xo.getChild(i));
}
if (weights.getDimension() != likelihoodList.size()) {
throw new XMLParseException("Dim of " + weights.getId() + " does not match the number of likelihoods");
}
if (xo.hasAttribute(NORMALIZE)) {
if (xo.getBooleanAttribute(NORMALIZE)) {
double sum = 0;
for (int i = 0; i < weights.getDimension(); i++)
sum += weights.getParameterValue(i);
for (int i = 0; i < weights.getDimension(); i++)
weights.setParameterValue(i, weights.getParameterValue(i) / sum);
}
}
if (!normalized(weights))
throw new XMLParseException("Parameter +" + weights.getId() + " must lie on the simplex");
return new WeightedMixtureModel(likelihoodList, weights);
}
private boolean normalized(Parameter p) {
double sum = 0;
for (int i = 0; i < p.getDimension(); i++)
sum += p.getParameterValue(i);
return (sum == 1.0);
} |
package edacc.experiment;
import edacc.experiment.ExperimentUpdateThread.ExperimentStatus;
import edacc.model.Experiment;
import edacc.model.ExperimentDAO;
import edacc.model.ExperimentDAO.StatusCount;
import edacc.model.StatusCode;
import edacc.util.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.swing.SwingWorker;
/**
* The experiment update thread.<br/>
* Updates the running, finished, failed and not started counts in the experiment table every 10 seconds.
* @author simon
*/
public class ExperimentUpdateThread extends SwingWorker<Void, ExperimentStatus> {
private ExperimentTableModel model;
private final HashMap<Integer, Experiment> modifiedExperiments = new HashMap<Integer, Experiment>();
/**
* Creates a new experiment update thread.
* @param model the model to be used
*/
public ExperimentUpdateThread(ExperimentTableModel model) {
super();
this.model = model;
}
@Override
@SuppressWarnings("SleepWhileInLoop")
protected Void doInBackground() throws Exception {
int sleep_count = 10000;
while (!this.isCancelled()) {
LinkedList<Experiment> experiments;
if (sleep_count >= 10000) {
experiments = ExperimentDAO.getAll();
sleep_count = 0;
} else {
experiments = new LinkedList<Experiment>();
synchronized (modifiedExperiments) {
experiments.addAll(modifiedExperiments.values());
modifiedExperiments.clear();
}
}
for (Experiment exp : experiments) {
ArrayList<StatusCount> statusCount = ExperimentDAO.getJobCountForExperiment(exp);
if (this.isCancelled())
break;
int running = 0;
int finished = 0;
int failed = 0;
int not_started = 0;
int count = 0;
for (StatusCount stat : statusCount) {
count += stat.getCount();
if (stat.getStatusCode() != StatusCode.NOT_STARTED && stat.getStatusCode() != StatusCode.RUNNING) {
finished += stat.getCount();
}
if (stat.getStatusCode().getStatusCode() < -1) {
failed += stat.getCount();
}
if (stat.getStatusCode() == StatusCode.RUNNING) {
running = stat.getCount();
}
if (stat.getStatusCode() == StatusCode.NOT_STARTED) {
not_started = stat.getCount();
}
}
Pair<Integer, Boolean> pa = ExperimentDAO.getPriorityActiveByExperiment(exp);
if (pa != null)
publish(new ExperimentStatus(exp, count, finished, running, failed, not_started, pa.getFirst(), pa.getSecond()));
}
if (this.isCancelled())
break;
Thread.sleep(2000);
sleep_count += 2000;
}
return null;
}
@Override
protected void process(List<ExperimentStatus> chunks) {
for (ExperimentStatus status : chunks) {
for (int i = 0; i < model.getRowCount(); i++) {
if (model.getExperimentAt(i) == status.experiment) {
boolean modified = false;
if (model.getNumRunsAt(i) == null || model.getNumRunsAt(i) != status.count) {
model.setNumRunsAt(i, status.count);
modified = true;
}
if (model.getFailedAt(i) == null || model.getFailedAt(i) != status.failed) {
model.setFailedAt(i, status.failed);
modified = true;
}
if (model.getFinishedAt(i) == null || model.getFinishedAt(i) != status.finished) {
model.setFinishedAt(i, status.finished);
modified = true;
}
if (model.getNotStartedAt(i) == null || model.getNotStartedAt(i) != status.not_started) {
model.setNotStartedAt(i, status.not_started);
modified = true;
}
if (model.getRunningAt(i) == null || model.getRunningAt(i) != status.running) {
model.setRunningAt(i, status.running);
modified = true;
}
if (status.experiment.getPriority() != status.priority) {
model.setValueAt(status.priority, i, ExperimentTableModel.COL_PRIORITY);
modified = true;
}
if (status.experiment.isActive() != status.active) {
model.setValueAt(status.active, i, ExperimentTableModel.COL_ACTIVE);
modified = true;
}
if (modified) {
synchronized (modifiedExperiments) {
modifiedExperiments.put(status.experiment.getId(), status.experiment);
}
}
}
}
}
}
class ExperimentStatus {
Experiment experiment;
int count;
int finished;
int running;
int failed;
int not_started;
int priority;
boolean active;
ExperimentStatus(Experiment exp, int count, int finished, int running, int failed, int not_started, int priority, boolean active) {
this.experiment = exp;
this.count = count;
this.finished = finished;
this.running = running;
this.failed = failed;
this.not_started = not_started;
this.priority = priority;
this.active = active;
}
}
} |
package edu.ucla.cens.awserver.domain;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Information about a class. The object must contain a a URN and name of the
* class. The description, as specified by the database, is not required.
*
* @author John Jenkins
*/
public class ClassInfo {
/**
* Private class for aggregating specific information about a user.
*
* @author John Jenkins
*/
private class UserAndRole {
public String _username;
public String _role;
public UserAndRole(String username, String role) {
_username = username;
_role = role;
}
}
private String _urn;
private String _name;
private String _description;
List<UserAndRole> _users;
public ClassInfo(String urn, String name, String description) {
if(urn == null) {
throw new IllegalArgumentException("Class URN cannot be null.");
}
if(name == null) {
throw new IllegalArgumentException("Class name cannot be null.");
}
_urn = urn;
_name = name;
_description = description;
_users = new LinkedList<UserAndRole>();
}
public void addUser(String username, String role) {
if(username == null) {
throw new IllegalArgumentException("User's username cannot be null.");
}
else if(role == null) {
throw new IllegalArgumentException("User's role cannot be null.");
}
_users.add(new UserAndRole(username, role));
}
/**
* Gets the number of users that have been associated with this class
* object. There is no guarantee that this also agrees with the database.
*
* @return The number of users associated with this class object.
*/
public int getNumUsers() {
return _users.size();
}
/**
* Gets the URN of this class.
*
* @return The URN of this class.
*/
public String getUrn() {
return _urn;
}
/**
* Returns this class object as a JSONObject with the URN as an optional
* inclusion.
*
* @param withUrn Whether or not to include the URN in the output.
*
* @return Returns a JSONObject with the classes as a JSONObject where the
* keys are the users and their values are their class roles.
*
* @throws JSONException Thrown if generating the object caused an error.
*/
public JSONObject getJsonRepresentation(boolean withUrn) throws JSONException {
JSONObject result = new JSONObject();
if(withUrn) {
result.put("urn", _urn);
}
result.put("name", _name);
result.put("description", ((_description == null) ? "" : _description));
JSONObject users = new JSONObject();
ListIterator<UserAndRole> usersIter = _users.listIterator();
while(usersIter.hasNext()) {
UserAndRole currUser = usersIter.next();
users.put(currUser._username, currUser._role);
}
result.put("users", users);
return result;
}
} |
package ee.ut.bpstruct.unfolding.uma;
import hub.top.uma.DNode;
import hub.top.uma.DNodeBP;
import hub.top.uma.DNodeSys;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This is a wrapper of the UMA implementation of complete prefix unfolding
* specifically designed to derive prefixes suitable for structuring
*/
public class BPstructBP extends DNodeBP {
public static boolean option_printAnti = true;
public static boolean option_unfoldMEME = false;
public BPstructBP(DNodeSys system) {
super(system);
}
public void setUnfoldMEME() { option_unfoldMEME = true; }
/**
* @return the mapping of cutOff events to their equivalent counter parts
*/
public HashMap<DNode, DNode> getElementary_ccPair() {
// FIXME: return only after computation finished?
return elementary_ccPair;
}
/**
* The search strategy for {@link #equivalentCuts_conditionSignature_history(byte[], DNode[], DNode[])}.
* A size-based search strategy ({@link Options#searchStrat_size}).
*
* The method has been extended to determine cut-off events by a lexicographic
* search strategy.
*
* @param newEvent event that has been added to the branching process
* @param newCut the cut reached by 'newEvent'
* @param eventsToCompare
* @return <code>true</code> iff <code>newEvent</code> is a cut-off event
* because of some equivalent event in <code>eventsToCompare</code>.
*/
protected boolean findEquivalentCut_bpstruct (
int newCutConfigSize,
DNode newEvent,
DNode[] newCut,
Iterable<DNode> eventsToCompare)
{
// all extensions to support the size-lexicographic search-strategy
// or marked with LEXIK
// optimization: determine equivalence of reached cuts by the
// help of a 'condition signature, initialize 'empty' signature
// for 'newEvent', see #equivalentCuts_conditionSignature_history
byte[] newCutSignature = cutSignature_conditions_init255();
// compare the cut reached by 'newEvent' to the initial cut
if (newCut.length == bp.initialCut.length)
if (equivalentCuts_conditionSignature_history(newCutSignature, newCut, bp.initialCut)) {
// yes, newEvent reaches the initial cut again
updateCCpair(newEvent, newCut, bp.initialCut);
return true; // 'newEvent' is a cut-off event
}
// Check whether 'eventsToCompare' contains a "smaller" event that reaches
// the same cut as 'newEvent'.
// Optimization: to quickly avoid comparing configurations of events that
// do not reach the same cut as 'newEvent', compare and store hash values
// of the reached configurations.
// get hash value of the cut reached by 'newEvent'
int newEventHash = primeConfiguration_CutHash.get(newEvent);
// check whether 'newEvent' is a cut-off event by comparing to all other
// given events
Iterator<DNode> it = eventsToCompare.iterator();
while (it.hasNext()) {
DNode e = it.next();
// do not check the event that has just been added, the cuts would be equal...
if (e == newEvent) continue;
// newCut is only equivalent to oldCut if the configuration of newCut
// is (lexicographically) larger than the configuration of oldCut
if (!primeConfiguration_Size.containsKey(e)) {
// the old event 'e' has incomplete information about its prime
// configuration, cannot be used to check for cutoff
continue;
}
// optimization: compared hashed values of the sizes of the prime configurations
if (newCutConfigSize < primeConfiguration_Size.get(e)) {
// the old one is larger, not equivalent
continue;
}
// optimization: compare reached states by their hash values
// only if hash values are equal, 'newEvent' and 'e' could be equivalent
if (primeConfiguration_CutHash.get(e) != newEventHash)
continue;
// retrieve the cut reached by the old event 'e'
DNode[] oldCut = bp.getPrimeCut(e, options.searchStrat_lexicographic, options.searchStrat_lexicographic);
// cuts of different lenghts cannot reach the same state, skip
if (newCut.length != oldCut.length)
continue;
// if both configurations have the same size:
if (newCutConfigSize == bp.getPrimeConfiguration_size) {
// and if not lexicographic, then the new event cannot be cut-off event
if (!options.searchStrat_lexicographic) continue;
// LEXIK: otherwise compare whether the old event's configuration is
// lexicographically smaller than the new event's configuration
if (!isSmaller_lexicographic(primeConfigurationString.get(e), primeConfigurationString.get(newEvent))) {
// Check whether 'e' was just added. If this is the case, then 'e' and 'newEvent'
// were added in the wrong order and we check again whether 'e' is a cut-off event
if (e.post != null && e.post.length > 0 && e.post[0]._isNew) {
//System.out.println("smaller event added later, should switch cut-off");
balanceCutOffEvents_list.addLast(e);
}
continue;
}
}
boolean doRestrict = checkAcyclicCase(newEvent,e,newCut,oldCut);
// The prime configuration of 'e' is either smaller or lexicographically
// smaller than the prime configuration of 'newEvent'. Further, both events
// reach cuts of the same size. Check whether both cuts reach the same histories
// by comparing their condition signatures
if (doRestrict && equivalentCuts_conditionSignature_history(newCutSignature, newCut, oldCut)) {
// yes, equivalent cuts, make events and conditions equivalent
updateCCpair(newEvent, e);
updateCCpair(newEvent, newCut, oldCut);
// and yes, 'newEvent' is a cut-off event
return true;
}
}
// no smaller equivalent has been found
return false;
}
/**
* Restrict cutoff criterion for acyclic case
*
* A cutoff is acyclic if neither cutoff nor its corresponding event
* do not refer to a transition of the originative net that is part of
* some cyclic path of the net
*
* @param cutoff Cutoff event
* @param corr Corresponding event
* @param cutoff_cut Cutoff cut
* @param corr_cut Corresponding cut
* @return <code>true</code> if acyclic cutoff criterion holds; otherwise <code>false</code>
*/
protected boolean checkAcyclicCase(DNode cutoff, DNode corr, DNode[] cutoff_cut, DNode[] corr_cut) {
if (option_unfoldMEME)
return checkConcurrency(cutoff, corr, cutoff_cut, corr_cut) && checkGateway(cutoff,corr);
return checkConcurrency(cutoff,corr,cutoff_cut,corr_cut);
}
/**
* Restrict cutoff criterion for cyclic case
*
* A cutoff is cyclic if either cutoff or its corresponding event
* refer to a transition of the originative net that is part of
* some cyclic path of the net
*
* @param cutoff Cutoff event
* @param corr Corresponding event
* @param cutoff_cut Cutoff cut
* @param corr_cut Corresponding cut
* @return <code>true</code> if cyclic cutoff criterion holds; otherwise <code>false</code>
*/
protected boolean checkCyclicCase(DNode cutoff, DNode corr, DNode[] cutoff_cut, DNode[] corr_cut) {
return checkConcurrency(cutoff,corr,cutoff_cut,corr_cut) &&
isCorrInLocalConfig(cutoff,corr) &&
cutoff.post.length==1 &&
corr.post.length==1 &&
corr.post[0].post.length>1;
}
/**
* Check whether cutoff or its corresponding event refer to a gateway
* node in the originative net; false otherwise
*
* @param cutoff Cutoff event
* @param corr Corresponding event
* @return <code>true</code> if cutoff or its corresponding event refer to a gateway node; otherwise <code>false</code>
*/
protected boolean checkGateway(DNode cutoff, DNode corr) {
if (cutoff.post.length>1 || cutoff.pre.length>1 ||
corr.post.length>1 || corr.pre.length>1) return true;
return false;
}
/**
* Check if conditions in cuts of cutoff and corresponding events are shared, except of postsets
*
* @param cutoff Cutoff event
* @param corr Corresponding event
* @param cutoff_cut Cutoff cut
* @param corr_cut Corresponding cut
* @return <code>true</code> if shared; otherwise <code>false</code>
*/
protected boolean checkConcurrency(DNode cutoff, DNode corr, DNode[] cutoff_cut, DNode[] corr_cut) {
Set<Integer> cutoffSet = new HashSet<Integer>();
Set<Integer> corrSet = new HashSet<Integer>();
int i=0;
for (i=0; i<cutoff_cut.length; i++) cutoffSet.add(cutoff_cut[i].globalId);
for (i=0; i<corr_cut.length; i++) corrSet.add(corr_cut[i].globalId);
for (i=0; i<cutoff.post.length; i++) cutoffSet.remove(cutoff.post[i].globalId);
for (i=0; i<corr.post.length; i++) corrSet.remove(corr.post[i].globalId);
if (cutoffSet.size()!=corrSet.size()) return false;
for (Integer n : cutoffSet) {
if (!corrSet.contains(n)) return false;
}
return true;
}
/**
* Check if corresponding event is in the local configuration of the cutoff
*
* @param cutoff Cutoff event
* @param corr Corresponding event
* @return <code>true</code> if corresponding event is in the local configuration of the cutoff; otherwise <code>false</code>
*/
protected boolean isCorrInLocalConfig(DNode cutoff, DNode corr) {
List<Integer> todo = new ArrayList<Integer>();
Map<Integer,DNode> i2d = new HashMap<Integer,DNode>();
for (DNode n : Arrays.asList(cutoff.pre)) { todo.add(n.globalId); i2d.put(n.globalId,n); }
Set<Integer> visited = new HashSet<Integer>();
while (!todo.isEmpty()) {
Integer n = todo.remove(0);
visited.add(n);
if (n.equals(corr.globalId)) return true;
for (DNode m : i2d.get(n).pre) {
if (!visited.contains(m.globalId)) { todo.add(m.globalId); i2d.put(m.globalId,m); }
}
}
return false;
}
public HashMap<DNode, Set<DNode>> getConcurrentConditions() {
return co;
}
public void disable_stopIfUnSafe() {
options.checkProperties = false;
configure_setBound(0);
}
public boolean isCutOffEvent(DNode event) {
if (findEquivalentCut_bpstruct(primeConfiguration_Size.get(event), event, currentPrimeCut, bp.getAllEvents()))
return true;
return false;
}
public String properName(DNode n) {
return dNodeAS.properNames[n.id];
}
/**
* Create a GraphViz' dot representation of this branching process.
*/
public String toDot () {
StringBuilder b = new StringBuilder();
b.append("digraph BP {\n");
// standard style for nodes and edges
b.append("graph [fontname=\"Helvetica\" nodesep=0.3 ranksep=\"0.2 equally\" fontsize=10];\n");
b.append("node [fontname=\"Helvetica\" fontsize=8 fixedsize width=\".3\" height=\".3\" label=\"\" style=filled fillcolor=white];\n");
b.append("edge [fontname=\"Helvetica\" fontsize=8 color=white arrowhead=none weight=\"20.0\"];\n");
// String tokenFillString = "fillcolor=black peripheries=2 height=\".2\" width=\".2\" ";
String cutOffFillString = "fillcolor=gold";
String antiFillString = "fillcolor=red";
String impliedFillString = "fillcolor=violet";
String hiddenFillString = "fillcolor=grey";
// first print all conditions
b.append("\n\n");
b.append("node [shape=circle];\n");
for (DNode n : bp.allConditions) {
if (!option_printAnti && n.isAnti)
continue;
/* - print current marking
if (cutNodes.contains(n))
b.append(" c"+n.localId+" ["+tokenFillString+"]\n");
else
*/
if (n.isAnti && n.isHot)
b.append(" c"+n.globalId+" ["+antiFillString+"]\n");
else if (n.isCutOff)
b.append(" c"+n.globalId+" ["+cutOffFillString+"]\n");
else
b.append(" c"+n.globalId+" []\n");
String auxLabel = "";
b.append(" c"+n.globalId+"_l [shape=none];\n");
b.append(" c"+n.globalId+"_l -> c"+n.globalId+" [headlabel=\""+n+" "+auxLabel+"\"]\n");
}
// then print all events
b.append("\n\n");
b.append("node [shape=box];\n");
for (DNode n : bp.allEvents) {
if (!option_printAnti && n.isAnti)
continue;
if (n.isAnti && n.isHot)
b.append(" e"+n.globalId+" ["+antiFillString+"]\n");
else if (n.isAnti && !n.isHot)
b.append(" e"+n.globalId+" ["+hiddenFillString+"]\n");
else if (n.isImplied)
b.append(" e"+n.globalId+" ["+impliedFillString+"]\n");
else if (n.isCutOff)
b.append(" e"+n.globalId+" ["+cutOffFillString+"]\n");
else
b.append(" e"+n.globalId+" []\n");
String auxLabel = "";
b.append(" e"+n.globalId+"_l [shape=none];\n");
b.append(" e"+n.globalId+"_l -> e"+n.globalId+" [headlabel=\""+n+" "+auxLabel+"\"]\n");
}
// finally, print all edges
b.append("\n\n");
b.append(" edge [fontname=\"Helvetica\" fontsize=8 arrowhead=normal color=black];\n");
for (DNode n : bp.allConditions) {
String prefix = n.isEvent ? "e" : "c";
for (int i=0; i<n.pre.length; i++) {
if (n.pre[i] == null) continue;
if (!option_printAnti && n.isAnti) continue;
if (n.pre[i].isEvent)
b.append(" e"+n.pre[i].globalId+" -> "+prefix+n.globalId+" [weight=10000.0]\n");
else
b.append(" c"+n.pre[i].globalId+" -> "+prefix+n.globalId+" [weight=10000.0]\n");
}
}
for (DNode n : bp.allEvents) {
String prefix = n.isEvent ? "e" : "c";
for (int i=0; i<n.pre.length; i++) {
if (n.pre[i] == null) continue;
if (!option_printAnti && n.isAnti) continue;
if (n.pre[i].isEvent)
b.append(" e"+n.pre[i].globalId+" -> "+prefix+n.globalId+" [weight=10000.0]\n");
else
b.append(" c"+n.pre[i].globalId+" -> "+prefix+n.globalId+" [weight=10000.0]\n");
}
}
// and add links from cutoffs to corresponding events (exclusive case)
b.append("\n\n");
b.append(" edge [fontname=\"Helvetica\" fontsize=8 arrowhead=normal color=red];\n");
for (DNode n : bp.allEvents) {
if (n.isCutOff && elementary_ccPair.get(n) != null) {
if (!this.isCorrInLocalConfig(n, elementary_ccPair.get(n)))
b.append(" e"+n.globalId+" -> e"+elementary_ccPair.get(n).globalId+" [weight=10000.0]\n");
}
}
// and add links from cutoffs to corresponding events (causal case)
b.append("\n\n");
b.append(" edge [fontname=\"Helvetica\" fontsize=8 arrowhead=normal color=blue];\n");
for (DNode n : bp.allEvents) {
if (n.isCutOff && elementary_ccPair.get(n) != null) {
if (this.isCorrInLocalConfig(n, elementary_ccPair.get(n)))
b.append(" e"+n.globalId+" -> e"+elementary_ccPair.get(n).globalId+" [weight=10000.0]\n");
}
}
b.append("}");
return b.toString();
}
} |
package ru.job4j.map;
import java.util.Calendar;
public class User {
/**
* Name user.
*/
private String name;
/**
* Amount of children.
*/
private int children;
/**
* Birthday date.
*/
private Calendar birthday;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (children != user.children) return false;
if (name != null ? !name.equals(user.name) : user.name != null) return false;
return birthday != null ? birthday.equals(user.birthday) : user.birthday == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + children;
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
return result;
}
/**
* Construct.
* @param name String
* @param children int
* @param birthday Calendar
*/
public User(String name, int children, Calendar birthday) {
this.name = name;
this.children = children;
this.birthday = birthday;
}
} |
package com.psddev.dari.db;
import com.psddev.dari.util.AsyncConsumer;
import com.psddev.dari.util.AsyncQueue;
import com.psddev.dari.util.ObjectUtils;
import java.util.ArrayList;
import java.util.List;
/** Background task that efficiently writes to a database from a queue. */
public class AsyncDatabaseWriter<E> extends AsyncConsumer<E> {
public static final double DEFAULT_COMMIT_SIZE_JITTER = 0.2;
private final Database database;
private final WriteOperation operation;
private final int commitSize;
private final boolean isCommitEventually;
private double commitSizeJitter = DEFAULT_COMMIT_SIZE_JITTER;
private transient int nextCommitSize;
private transient E lastItem;
private final transient List<E> toBeCommitted = new ArrayList<E>();
public AsyncDatabaseWriter(
String executor,
AsyncQueue<E> input,
Database database,
WriteOperation operation,
int commitSize,
boolean isCommitEventually) {
super(executor, input);
if (database == null) {
throw new IllegalArgumentException("Database can't be null!");
}
if (operation == null) {
throw new IllegalArgumentException("Operation can't be null!");
}
this.database = database;
this.operation = operation;
this.commitSize = commitSize;
this.isCommitEventually = isCommitEventually;
}
/**
* Returns the {@linkplain ObjectUtils#jitter jitter scale} to apply
* to the commit size.
*/
public double getCommitSizeJitter() {
return commitSizeJitter;
}
/**
* Sets the {@linkplain ObjectUtils#jitter jitter scale} to apply
* to the commit size.
*/
public void setCommitSizeJitter(double commitSizeJitter) {
this.commitSizeJitter = commitSizeJitter;
}
// Commits all pending writes.
private void commit() {
try {
try {
database.beginWrites();
for (E item : toBeCommitted) {
operation.execute(database, State.getInstance(item));
}
if (isCommitEventually) {
database.commitWritesEventually();
} else {
database.commitWrites();
}
} finally {
database.endWrites();
}
// Can't write in batch so try one by one.
} catch (Exception error1) {
for (E item : toBeCommitted) {
try {
database.beginWrites();
operation.execute(database, State.getInstance(item));
if (isCommitEventually) {
database.commitWritesEventually();
} else {
database.commitWrites();
}
} catch (Exception error2) {
handleError(item, error2);
} finally {
database.endWrites();
}
}
} finally {
toBeCommitted.clear();
}
}
// Calculates the number of items to save in the next commit.
private void calculateNextCommitSize() {
nextCommitSize = (int) ObjectUtils.jitter(commitSize, getCommitSizeJitter());
}
@Override
protected void beforeStart() {
super.beforeStart();
calculateNextCommitSize();
}
@Override
protected void consume(E item) {
lastItem = item;
toBeCommitted.add(item);
if (toBeCommitted.size() >= nextCommitSize) {
calculateNextCommitSize();
commit();
}
}
@Override
protected void finished() {
super.finished();
commit();
if (lastItem != null) {
database.beginWrites();
try {
operation.execute(database, State.getInstance(lastItem));
database.commitWrites();
} finally {
database.endWrites();
}
}
}
/** @deprecated Use {@link #AsyncDatabaseWriter(String, AsyncQueue, Database, WriteOperation, int, boolean)} instead. */
@Deprecated
public AsyncDatabaseWriter(
AsyncQueue<E> input,
Database database,
WriteOperation operation,
int commitSize,
boolean isCommitEventually) {
this(
null,
input,
database,
operation,
commitSize,
isCommitEventually);
}
/** @deprecated Use {@link #AsyncDatabaseWriter(String, AsyncQueue, Database, WriteOperation, int, boolean)} instead. */
@Deprecated
public AsyncDatabaseWriter(
AsyncQueue<E> input,
Database database,
int commitSize,
boolean isCommitEventually,
boolean isSaveUnsafely) {
this(
null,
input,
database,
isSaveUnsafely ? WriteOperation.SAVE_UNSAFELY : WriteOperation.SAVE,
commitSize,
isCommitEventually);
}
} |
package fi.tnie.db.ent;
import java.io.Serializable;
import fi.tnie.db.expr.ColumnReference;
import fi.tnie.db.expr.OrderBy;
import fi.tnie.db.expr.OrderBy.Order;
import fi.tnie.db.expr.OrderBy.SortKey;
/**
* Provides a EntityQueryTemplateAttribute implementation with the capability to act as an EntityQuerySortKey.
*
*
*
* @author Topi Nieminen <topi.nieminen@gmail.com>
*/
public abstract class SortKeyAttributeTemplate<A extends Attribute>
implements EntityQuerySortKey<A> {
private static final long serialVersionUID = -3079799118698355746L;
private A attribute;
public static <A extends Attribute> SortKeyAttributeTemplate<A> get(A a, OrderBy.Order so) {
so = (so == null) ? Order.ASC : so;
return (so == Order.ASC) ? asc(a) : desc(a);
}
public static <A extends Attribute> SortKeyAttributeTemplate<A> asc(A attribute) {
return new Asc<A>(attribute);
}
public static <A extends Attribute> SortKeyAttributeTemplate<A> desc(A attribute) {
return new Desc<A>(attribute);
}
protected SortKeyAttributeTemplate() {
}
public SortKeyAttributeTemplate(A attribute) {
super();
this.attribute = attribute;
}
public static class Asc<A extends Attribute>
extends SortKeyAttributeTemplate<A> {
private static final long serialVersionUID = -4545159706806621845L;
/**
* No-argument constructor for GWT Serialization
*/
@SuppressWarnings("unused")
private Asc() {
}
protected Asc(A attribute) {
super(attribute);
}
@Override
public Order sortOrder() {
return Order.ASC;
}
}
public static class Desc<A extends Attribute>
extends SortKeyAttributeTemplate<A> {
private static final long serialVersionUID = 4575239762087833095L;
/**
* No-argument constructor for GWT Serialization
*/
@SuppressWarnings("unused")
private Desc() {
}
protected Desc(A attribute) {
super(attribute);
}
@Override
public Order sortOrder() {
return Order.DESC;
}
}
@Override
public SortKey sortKey(ColumnReference cref) {
return new OrderBy.ExprSortKey(cref, sortOrder());
}
public abstract OrderBy.Order sortOrder();
@Override
public A attribute() {
return this.attribute;
}
} |
package sample;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.controls.JFXTimePicker;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private JFXTextField userName;
@FXML
private JFXListView<Room> rooms;
@FXML
private JFXDatePicker startDate;
@FXML
private JFXTimePicker startTime;
@FXML
private JFXDatePicker endDate;
@FXML
private JFXTimePicker endTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
startTime.setIs24HourView(true);
endTime.setIs24HourView(true);
}
} |
package org.voltdb.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import org.supercsv.exception.SuperCsvException;
import org.supercsv.io.ICsvListReader;
import org.voltdb.TheHashinator;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import static org.voltdb.utils.CSVLoader.m_log;
/**
*
* This is a single thread reader which feeds the lines after validating syntax
* to correct Partition Processors. In caseof MP table or user supplied procedure
* we use just one processor.
*
*/
class CSVFileReader implements Runnable {
static AtomicLong m_totalRowCount = new AtomicLong(0);
static AtomicLong m_totalLineCount = new AtomicLong(0);
static CSVLoader.CSVConfig m_config;
//Columns in table we are inserting.
static int m_columnCnt;
static ICsvListReader m_listReader;
static Client m_csvClient;
//Map of partition to Queues to put CSVLineWithMetaData
static Map<Integer, BlockingQueue<CSVLineWithMetaData>> processorQueues;
// zero based index of partition column in table.
static int m_partitionedColumnIndex;
//Type detected for the partition column.
static VoltType m_partitionColumnType;
// This is the last thing put on Queue so that processors will detect the end.
static CSVLineWithMetaData m_endOfData;
//Count down latch for each processor.
static CountDownLatch m_processor_cdl;
static boolean m_errored = false;
long m_parsingTime = 0;
private static Map<VoltType, String> m_blankValues = new EnumMap<VoltType, String>(VoltType.class);
static {
m_blankValues.put(VoltType.NUMERIC, "0");
m_blankValues.put(VoltType.TINYINT, "0");
m_blankValues.put(VoltType.SMALLINT, "0");
m_blankValues.put(VoltType.INTEGER, "0");
m_blankValues.put(VoltType.BIGINT, "0");
m_blankValues.put(VoltType.FLOAT, "0.0");
m_blankValues.put(VoltType.TIMESTAMP, null);
m_blankValues.put(VoltType.STRING, "");
m_blankValues.put(VoltType.DECIMAL, "0");
m_blankValues.put(VoltType.VARBINARY, "");
}
//Types of table we are loading data into.
static List<VoltType> m_typeList = new ArrayList<VoltType>();
//Errors we keep track only upto maxerrors
static Map<Long, String[]> m_errorInfo = new TreeMap<Long, String[]>();
@Override
public void run() {
List<String> lineList = null;
while ((m_config.limitrows
if (m_errored) {
break;
}
try {
//Initial setting of m_totalLineCount
if (m_listReader.getLineNumber() == 0) {
m_totalLineCount.set(m_config.skip);
} else {
m_totalLineCount.set(m_listReader.getLineNumber());
}
long st = System.nanoTime();
lineList = m_listReader.read();
long end = System.nanoTime();
m_parsingTime += (end - st);
if (lineList == null) {
if (m_totalLineCount.get() > m_listReader.getLineNumber()) {
m_totalLineCount.set(m_listReader.getLineNumber());
}
break;
}
m_totalRowCount.incrementAndGet();
String[] correctedLine = lineList.toArray(new String[0]);
String lineCheckResult;
if ((lineCheckResult = checkparams_trimspace(correctedLine,
m_columnCnt)) != null) {
String[] info = {lineList.toString(), lineCheckResult};
if (synchronizeErrorInfo(m_totalLineCount.get() + 1, info)) {
m_errored = true;
}
continue;
}
CSVLineWithMetaData lineData = new CSVLineWithMetaData(correctedLine, lineList,
m_listReader.getLineNumber());
int partitionId = 0;
//Find partiton to send this line to and put on correct partition processor queue.
if (!CSVPartitionProcessor.m_isMP && !m_config.useSuppliedProcedure) {
partitionId = TheHashinator.getPartitionForParameter(m_partitionColumnType.getValue(),
(Object) lineData.correctedLine[m_partitionedColumnIndex]);
}
BlockingQueue<CSVLineWithMetaData> q = processorQueues.get(partitionId);
q.offer(lineData);
} catch (SuperCsvException e) {
//Catch rows that can not be read by superCSV m_listReader.
// E.g. items without quotes when strictquotes is enabled.
e.printStackTrace();
String[] info = {e.getMessage(), ""};
if (synchronizeErrorInfo(m_totalLineCount.get() + 1, info)) {
break;
}
} catch (IOException ioex) {
ioex.printStackTrace();
break;
}
}
//Did we hit the maxerror ceiling?
if (m_errorInfo.size() >= m_config.maxerrors) {
m_log.info("The number of Failure row data exceeds "
+ m_config.maxerrors);
}
//Close the reader and push m_endOfData lines to indicate Partition Processor to wind down.
try {
m_listReader.close();
} catch (IOException ex) {
m_log.error("Error cloging Reader: " + ex);
} finally {
for (BlockingQueue<CSVLineWithMetaData> q : processorQueues.values()) {
try {
q.put(m_endOfData);
} catch (InterruptedException ex) {
m_log.error("Failed to add endOfData for Partition Processor. " + ex);
}
}
m_log.info("Rows Queued by Reader: " + m_totalRowCount.get());
}
try {
m_log.info("Waiting for partition processors to finish.");
m_processor_cdl.await();
m_log.info("Partition Processors Done.");
} catch (InterruptedException ex) {
;
}
}
/**
* Add errors to be reported.
*
* @param errLineNum
* @param info
* @return true if we have reached limit....false to continue processing and reporting.
*/
public static boolean synchronizeErrorInfo(long errLineNum, String[] info) {
synchronized (m_errorInfo) {
//Dont collect more than we want to report.
if (m_errorInfo.size() >= m_config.maxerrors) {
return true;
}
if (!m_errorInfo.containsKey(errLineNum)) {
m_errorInfo.put(errLineNum, info);
}
return false;
}
}
private String checkparams_trimspace(String[] slot, int columnCnt) {
if (slot.length != columnCnt) {
return "Error: Incorrect number of columns. " + slot.length
+ " found, " + columnCnt + " expected.";
}
for (int i = 0; i < slot.length; i++) {
//supercsv read "" to null
if (slot[i] == null) {
if (m_config.blank.equalsIgnoreCase("error")) {
return "Error: blank item";
} else if (m_config.blank.equalsIgnoreCase("empty")) {
slot[i] = m_blankValues.get(m_typeList.get(i));
}
//else m_config.blank == null which is already the case
} // trim white space in this correctedLine. SuperCSV preserves all the whitespace by default
else {
if (m_config.nowhitespace
&& (slot[i].charAt(0) == ' ' || slot[i].charAt(slot[i].length() - 1) == ' ')) {
return "Error: White Space Detected in nowhitespace mode.";
} else {
slot[i] = ((String) slot[i]).trim();
}
// treat NULL, \N and "\N" as actual null value
if (slot[i].equals("NULL")
|| slot[i].equals(VoltTable.CSV_NULL)
|| slot[i].equals(VoltTable.QUOTED_CSV_NULL)) {
slot[i] = null;
}
}
}
return null;
}
} |
package dr.geo;
import dr.geo.cartogram.CartogramMapping;
import dr.xml.*;
import dr.util.HeapSort;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
/**
* @author Marc A. Suchard
* @author Philippe Lemey
*/
public class Polygon2D {
public static final String POLYGON = "polygon";
public static final String CLOSED = "closed";
public static final String FILL_VALUE = "fillValue";
public static final String CIRCLE = "circle";
public static final String NUMBER_OF_POINTS = "numberOfPoints";
public static final String RADIUS = "radius";
public static final String CENTER = "center";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public Polygon2D(double[] x, double[] y) {
if (x.length != y.length) {
throw new RuntimeException("Unbalanced arrays");
}
if (x[0] != x[x.length - 1] && y[0] != y[y.length - 1]) {
double[] newX = new double[x.length + 1];
double[] newY = new double[y.length + 1];
System.arraycopy(x, 0, newX, 0, x.length);
System.arraycopy(y, 0, newY, 0, y.length);
newX[x.length] = x[0];
newY[y.length] = y[0];
this.x = newX;
this.y = newY;
} else {
this.x = x;
this.y = y;
}
length = this.x.length - 1;
}
public Polygon2D(List<Point2D> points, boolean closed) {
this.point2Ds = points;
if (!closed) {
Point2D start = points.get(0);
points.add(start);
}
convertPointsToArrays();
length = points.size() - 1;
}
public Polygon2D() {
length = 0;
point2Ds = new ArrayList<Point2D>();
}
public String getID() {
return id;
}
public Polygon2D(Element e) {
// System.err.println("parsing polygon");
List<Element> children = e.getChildren();
id = e.getAttributeValue(XMLParser.ID);
parseCoordinates(e);
}
private void parseCoordinates(Element element) {
if (element.getName().equalsIgnoreCase(KMLCoordinates.COORDINATES)) {
String value = element.getTextTrim();
StringTokenizer st1 = new StringTokenizer(value, KMLCoordinates.POINT_SEPARATORS);
int count = st1.countTokens();
// System.out.println(count + " tokens");
point2Ds = new ArrayList<Point2D>(count);
for (int i = 0; i < count; i++) {
String line = st1.nextToken();
StringTokenizer st2 = new StringTokenizer(line, KMLCoordinates.SEPARATOR);
if (st2.countTokens() < 2 || st2.countTokens() > 3)
throw new IllegalArgumentException("All KML coordinates must contain (X,Y) or (X,Y,Z) values. Error in element '" + line + "'");
final double x = Double.valueOf(st2.nextToken());
final double y = Double.valueOf(st2.nextToken());
point2Ds.add(new Point2D.Double(x, y));
}
convertPointsToArrays();
length = point2Ds.size() - 1;
} else {
for (Object child : element.getChildren()) {
if (child instanceof Element) {
parseCoordinates((Element) child);
}
}
}
}
Shape getShape() {
GeneralPath path = new GeneralPath();
List<Point2D> points = point2Ds;
path.moveTo((float) points.get(0).getX(), (float) points.get(0).getY());
for (int i = 1; i < points.size(); i++) {
path.lineTo((float) points.get(i).getX(), (float) points.get(i).getY());
}
path.closePath();
return path;
}
private void convertPointsToArrays() {
final int length = point2Ds.size();
if (x == null || x.length != length) {
x = new double[length];
y = new double[length];
}
Iterator<Point2D> it = point2Ds.iterator();
for (int i = 0; i < length; i++) {
final Point2D point = it.next();
x[i] = point.getX();
y[i] = point.getY();
}
}
public void addPoint2D(Point2D point2D) {
if (point2Ds.size() == 0)
point2Ds.add(point2D);
else if (point2Ds.size() == 1) {
point2Ds.add(point2D);
point2Ds.add(point2Ds.get(0));
} else {
Point2D last = point2Ds.remove(point2Ds.size() - 1);
point2Ds.add(point2D);
if (!last.equals(point2D))
point2Ds.add(last);
}
convertPointsToArrays();
length = point2Ds.size() - 1;
}
public Point2D getPoint2D(int x) {
if (x > length +1) {
throw new RuntimeException("Polygon only has length"+length);
} else {
return point2Ds.get(x);
}
}
public boolean containsPoint2D(Point2D Point2D) {
final double inX = Point2D.getX();
final double inY = Point2D.getY();
boolean contains = false;
// Take a horizontal ray from (inX,inY) to the right.
// If ray across the polygon edges an odd # of times, the point is inside.
for (int i = 0, j = length - 1; i < length; j = i++) {
if ((((y[i] <= inY) && (inY < y[j])) ||
((y[j] <= inY) && (inY < y[i]))) &&
(inX < (x[j] - x[i]) * (inY - y[i]) / (y[j] - y[i]) + x[i]))
contains = !contains;
}
return contains;
}
public boolean bordersPoint2D(Point2D Point2D) {
boolean borders = false;
Iterator<Point2D> it = point2Ds.iterator();
for (int i = 0; i < length; i++) {
Point2D point = it.next();
if (point.equals(Point2D)) {
borders = true;
}
}
return borders;
}
public void setFillValue(double value) {
fillValue = value;
}
public double getFillValue() {
return fillValue;
}
public double getLength() {
return length;
}
// public boolean containsPoint2D(Point2D Point2D) { // this takes 3 times as long as the above code, why???
// final double inX = Point2D.getX();
// final double inY = Point2D.getY();
// boolean contains = false;
// // Take a horizontal ray from (inX,inY) to the right.
// // If ray across the polygon edges an odd # of times, the Point2D is inside.
// final Point2D end = point2Ds.get(length-1); // assumes closed
// double xi = end.getX();
// double yi = end.getY();
// Iterator<Point2D> listIterator = point2Ds.iterator();
// for(int i=0; i<length; i++) {
// final double xj = xi;
// final double yj = yi;
// final Point2D next = listIterator.next();
// xi = next.getX();
// yi = next.getY();
// if ((((yi <= inY) && (inY < yj)) ||
// ((yj <= inY) && (inY < yi))) &&
// (inX < (xj - xi) * (inY - yi) / (yj - yi) + xi))
// contains = !contains;
// return contains;
private enum Side {
left, right, top, bottom
}
public Polygon2D clip(Rectangle2D boundingBox) {
LinkedList<Point2D> clippedPolygon = new LinkedList<Point2D>();
Point2D p; // current Point2D
Point2D p2; // next Point2D
// make copy of original polygon to work with
LinkedList<Point2D> workPoly = new LinkedList<Point2D>(point2Ds);
// loop through all for clipping edges
for (Side side : Side.values()) {
clippedPolygon.clear();
for (int i = 0; i < workPoly.size() - 1; i++) {
p = workPoly.get(i);
p2 = workPoly.get(i + 1);
if (isInsideClip(p, side, boundingBox)) {
if (isInsideClip(p2, side, boundingBox))
// here both point2Ds are inside the clipping window so add the second one
clippedPolygon.add(p2);
else
// the seond Point2D is outside so add the intersection Point2D
clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox));
} else {
// so first Point2D is outside the window here
if (isInsideClip(p2, side, boundingBox)) {
// the following Point2D is inside so add the insection Point2D and also p2
clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox));
clippedPolygon.add(p2);
}
}
}
// make sure that first and last element are the same, we want a closed polygon
if (!clippedPolygon.getFirst().equals(clippedPolygon.getLast()))
clippedPolygon.add(clippedPolygon.getFirst());
// we have to keep on working with our new clipped polygon
workPoly = new LinkedList<Point2D>(clippedPolygon);
}
return new Polygon2D(clippedPolygon, true);
}
public void transformByMapping(CartogramMapping mapping) {
for (int i = 0; i < length + 1; i++) {
point2Ds.set(i, mapping.map(point2Ds.get(i)));
}
convertPointsToArrays();
}
public void swapXYs() {
for (int i = 0; i < length + 1; i++) {
point2Ds.set(i, new Point2D.Double(point2Ds.get(i).getY(), point2Ds.get(i).getX()));
}
convertPointsToArrays();
}
public void rescale(double longMin, double longwidth, double gridXSize, double latMax, double latwidth, double gridYSize) {
for (int i = 0; i < length + 1; i++) {
point2Ds.set(i, new Point2D.Double(((point2Ds.get(i).getX() - longMin) * (gridXSize / longwidth)), ((latMax - point2Ds.get(i).getY()) * (gridYSize / latwidth))));
}
convertPointsToArrays();
}
public void rescaleToPositiveCoordinates() {
double[][] xyMinMax = getXYMinMax();
double shiftX = 0;
double shiftY = 0;
if (xyMinMax[0][0] < 0){
shiftX = -xyMinMax[0][0];
}
if (xyMinMax[1][0] < 0){
shiftY = -xyMinMax[1][0];
}
if ((shiftX < 0) || (shiftY < 0)) {
for (int i = 0; i < length + 1; i++) {
point2Ds.set(i, new Point2D.Double(point2Ds.get(i).getX()+shiftX, point2Ds.get(i).getY()+shiftY));
}
convertPointsToArrays();
}
}
public double[][] getXYMinMax(){
int[] indicesX = new int[x.length];
int[] indicesY = new int[y.length];
HeapSort.sort(x, indicesX);
HeapSort.sort(y, indicesY);
double[][] returnArray = new double[2][2];
returnArray[0][0] = x[indicesX[0]];
returnArray[0][1] = x[indicesX[indicesX.length - 1]];
returnArray[1][0] = y[indicesY[0]];
returnArray[1][1] = y[indicesY[indicesY.length - 1]];
return returnArray;
}
// Here is a formula for the area of a polygon with vertices {(xk,yk): k = 1,...,n}:
// Area = 1/2 [(x1*y2 - x2*y1) + (x2*y3 - x3*y2) + ... + (xn*y1 - x1*yn)].
// This formula appears in an Article by Gil Strang of MIT
// on p. 253 of the March 1993 issue of The American Mathematical Monthly, with the note that it is
// "known, but not well known". There is also a very brief discussion of proofs and other references,
// including an article by Bart Braden of Northern Kentucky U., a known Mathematica enthusiast.
public double calculateArea() {
// rescaleToPositiveCoordinates();
double area = 0;
//we can implement it like this because the polygon is closed (point2D.get(0) = point2D.get(length + 1)
for (int i = 0; i < length; i++) {
area += (x[i] * y[i + 1] - x[i + 1] * y[i]);
}
return (Math.abs(area / 2));
}
public Point2D getCentroid() {
// rescaleToPositiveCoordinates();
Point2D centroid = new Point2D.Double();
double area = calculateArea();
double cx=0,cy=0;
double factor;
//we can implement it like this because the polygon is closed (point2D.get(0) = point2D.get(length + 1)
for (int i = 0; i < length; i++) {
factor = (x[i] * y[i + 1] - x[i + 1] * y[i]);
cx += (x[i] * x[i + 1])*factor;
cy += (y[i] * y[i + 1])*factor;
}
double constant = 1/(area*6);
cx*=constant;
cy*=constant;
centroid.setLocation(cx,cy);
System.out.println("centroid = "+cx+","+cy);
return centroid;
}
private static LinkedList<Point2D> getCirclePoints(double centerLat, double centerLong, int numberOfPoints, double radius) {
LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();
double lat1, long1;
double d_rad;
double delta_pts;
double radial, lat_rad, dlon_rad, lon_rad;
// convert coordinates to radians
lat1 = Math.toRadians(centerLat);
long1 = Math.toRadians(centerLong);
//radius is in meters
d_rad = radius / 6378137;
// loop through the array and write points
for (int i = 0; i <= numberOfPoints; i++) {
delta_pts = 360 / (double) numberOfPoints;
radial = Math.toRadians((double) i * delta_pts);
//This algorithm is limited to distances such that dlon < pi/2
lat_rad = Math.asin(Math.sin(lat1) * Math.cos(d_rad) + Math.cos(lat1) * Math.sin(d_rad) * Math.cos(radial));
dlon_rad = Math.atan2(Math.sin(radial) * Math.sin(d_rad) * Math.cos(lat1), Math.cos(d_rad) - Math.sin(lat1) * Math.sin(lat_rad));
lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;
Point2Ds.add(new Point2D.Double(Math.toDegrees(lat_rad), Math.toDegrees(lon_rad)));
}
return Point2Ds;
}
private static boolean isInsideClip(Point2D p, Side side, Rectangle2D boundingBox) {
if (side == Side.top)
return (p.getY() <= boundingBox.getMaxY());
else if (side == Side.bottom)
return (p.getY() >= boundingBox.getMinY());
else if (side == Side.left)
return (p.getX() >= boundingBox.getMinX());
else if (side == Side.right)
return (p.getX() <= boundingBox.getMaxX());
else
throw new RuntimeException("Error in Polygon");
}
private static Point2D intersectionPoint2D(Side side, Point2D p1, Point2D p2, Rectangle2D boundingBox) {
if (side == Side.top) {
final double topEdge = boundingBox.getMaxY();
return new Point2D.Double(p1.getX() + (topEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), topEdge);
} else if (side == Side.bottom) {
final double bottomEdge = boundingBox.getMinY();
return new Point2D.Double(p1.getX() + (bottomEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), bottomEdge);
} else if (side == Side.right) {
final double rightEdge = boundingBox.getMaxX();
return new Point2D.Double(rightEdge, p1.getY() + (rightEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
} else if (side == Side.left) {
final double leftEdge = boundingBox.getMinX();
return new Point2D.Double(leftEdge, p1.getY() + (leftEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
}
return null;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(POLYGON).append("[\n");
for (Point2D pt : point2Ds) {
sb.append("\t");
sb.append(pt);
sb.append("\n");
}
sb.append("]");
return sb.toString();
}
public static void readKMLElement(Element element, List<Polygon2D> polygons) {
if (element.getName().equalsIgnoreCase(POLYGON)) {
Polygon2D polygon = new Polygon2D(element);
polygons.add(polygon);
} else {
for (Object child : element.getChildren()) {
if (child instanceof Element) {
readKMLElement((Element) child, polygons);
}
}
}
}
public static List<Polygon2D> readKMLFile(String fileName) {
List<Polygon2D> polygons = new ArrayList<Polygon2D>();
try {
SAXBuilder builder = new SAXBuilder();
builder.setValidation(false);
builder.setIgnoringElementContentWhitespace(true);
Document doc = builder.build(new File(fileName));
Element root = doc.getRootElement();
if (!root.getName().equalsIgnoreCase("KML"))
throw new RuntimeException("Not a KML file");
readKMLElement(root, polygons);
} catch (IOException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
return polygons;
}
// public Element toXML() {
// return new KMLCoordinates(x,y).toXML();
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return POLYGON;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();
boolean closed;
Polygon2D polygon;
if (xo.getChild(Polygon2D.class) != null) { // This is a regular polygon
polygon = (Polygon2D) xo.getChild(Polygon2D.class);
} else { // This is an arbitrary polygon
KMLCoordinates coordinates = (KMLCoordinates) xo.getChild(KMLCoordinates.class);
closed = xo.getAttribute(CLOSED, false);
if ((!closed && coordinates.length < 3) ||
(closed && coordinates.length < 4))
throw new XMLParseException("Insufficient point2Ds in polygon '" + xo.getId() + "' to define a polygon in 2D");
for (int i = 0; i < coordinates.length; i++)
Point2Ds.add(new Point2D.Double(coordinates.x[i], coordinates.y[i]));
polygon = new Polygon2D(Point2Ds, closed);
}
polygon.setFillValue(xo.getAttribute(FILL_VALUE, 0.0));
return polygon;
} |
package org.mskcc.portal.util;
import org.mskcc.portal.model.*;
import org.mskcc.portal.model.GeneticEventImpl.CNA;
import org.mskcc.portal.model.GeneticEventImpl.MRNA;
import org.mskcc.portal.oncoPrintSpecLanguage.*;
import java.io.IOException;
import java.util.*;
/**
* Generates the Genomic OncoPrint.
*
* @author Ethan Cerami, Arthur Goldberg.
*/
public class MakeOncoPrint {
public static int CELL_WIDTH = 8;
public static int CELL_HEIGHT = 18;
// support OncoPrints in both SVG and HTML; only HTML will have extra textual info,
// such as legend, %alteration
public enum OncoPrintType {
SVG, HTML
}
/**
* Generate the OncoPrint in HTML or SVG.
* @param geneList List of Genes.
* @param mergedProfile Merged Data Profile.
* @param caseSets All Case Sets for this Cancer Study.
* @param caseSetId Selected Case Set ID.
* @param zScoreThreshold Z-Score Threshhold
* @param theOncoPrintType OncoPrint Type.
* @param showAlteredColumns Show only the altered columns.
* @param geneticProfileIdSet IDs for all Genomic Profiles.
* @param profileList List of all Genomic Profiles.
* @throws IOException IO Error.
*/
public static String makeOncoPrint(String geneList, ProfileData mergedProfile,
ArrayList<CaseSet> caseSets, String caseSetId, double zScoreThreshold,
OncoPrintType theOncoPrintType,
boolean showAlteredColumns,
HashSet<String> geneticProfileIdSet,
ArrayList<GeneticProfile> profileList
) throws IOException {
StringBuffer out = new StringBuffer();
ParserOutput theOncoPrintSpecParserOutput =
OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(geneList,
geneticProfileIdSet, profileList, zScoreThreshold);
ArrayList<String> listOfGenes =
theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes();
String[] listOfGeneNames = new String[listOfGenes.size()];
listOfGeneNames = listOfGenes.toArray(listOfGeneNames);
ProfileDataSummary dataSummary = new ProfileDataSummary(mergedProfile,
theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold);
ArrayList<GeneWithScore> geneWithScoreList = dataSummary.getGeneFrequencyList();
ArrayList<String> mergedCaseList = mergedProfile.getCaseIdList();
// TODO: make the gene sort order a user param, then call a method in ProfileDataSummary to sort
GeneticEvent matrix[][] = ConvertProfileDataToGeneticEvents.convert
(dataSummary, listOfGeneNames,
theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold);
// Sort Columns via Cascade Sorter
ArrayList<EnumSet<CNA>> CNAsortOrder = new ArrayList<EnumSet<CNA>>();
CNAsortOrder.add(EnumSet.of(CNA.amplified));
CNAsortOrder.add(EnumSet.of(CNA.homoDeleted));
CNAsortOrder.add(EnumSet.of(CNA.Gained));
CNAsortOrder.add(EnumSet.of(CNA.HemizygouslyDeleted));
// combined because these are represented by the same color in the OncoPring
CNAsortOrder.add(EnumSet.of(CNA.diploid, CNA.None));
ArrayList<EnumSet<MRNA>> MRNAsortOrder = new ArrayList<EnumSet<MRNA>>();
MRNAsortOrder.add(EnumSet.of(MRNA.upRegulated));
MRNAsortOrder.add(EnumSet.of(MRNA.downRegulated));
// combined because these are represented by the same color in the OncoPrint
MRNAsortOrder.add(EnumSet.of(MRNA.Normal, MRNA.notShown));
GeneticEventComparator comparator = new GeneticEventComparator(
CNAsortOrder,
MRNAsortOrder,
GeneticEventComparator.defaultMutationsSortOrder());
CascadeSortOfMatrix sorter = new CascadeSortOfMatrix(comparator);
for (GeneticEvent[] row : matrix) {
for (GeneticEvent element : row) {
element.setGeneticEventComparator(comparator);
}
}
matrix = (GeneticEvent[][]) sorter.sort(matrix);
// optionally, show only columns with alterations
// depending on showAlteredColumns, find last column with alterations
int numColumnsToShow = matrix[0].length;
if (showAlteredColumns) {
// identify last column with an alteration
// make HTML OncoPrint: not called if there are no genes
// have oncoPrint shows nothing when no cases are modified
numColumnsToShow = 0;
firstAlteration:
{
// iterate through cases from the end, stopping at first case with alterations
// (the sort order could sort unaltered cases before altered ones)
for (int j = matrix[0].length - 1; 0 <= j; j
// check all genes to determine if a case is altered
for (int i = 0; i < matrix.length; i++) {
GeneticEvent event = matrix[i][j];
if (dataSummary.isGeneAltered(event.getGene(), event.caseCaseId())) {
numColumnsToShow = j + 1;
break firstAlteration;
}
}
}
}
}
// support both SVG and HTML oncoPrints
switch (theOncoPrintType) {
case SVG:
writeSVGOncoPrint(matrix, numColumnsToShow,
out, mergedCaseList, geneWithScoreList);
break; // exit the switch
case HTML:
int spacing = 0;
int padding = 1;
// the images are 4x bigger than this, which is necessary to create the necessary
// design; but width and height scale them down, so that the OncoPrint fits
// TODO: move these constants elsewhere, or derive from images directly
int width = 6;
int height = 17;
writeHTMLOncoPrint(caseSets, caseSetId, matrix, numColumnsToShow, showAlteredColumns,
theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), dataSummary,
out, spacing, padding, width, height);
break; // exit the switch
}
return out.toString();
}
static void writeSVGOncoPrint(GeneticEvent matrix[][], int numColumnsToShow,
StringBuffer out, ArrayList<String> mergedCaseList,
ArrayList<GeneWithScore> geneWithScoreList) {
int windowWidth = 300 + (CELL_WIDTH * mergedCaseList.size());
int windowHeight = 50 + (CELL_HEIGHT * geneWithScoreList.size());
out.append("<?xml version=\"1.0\"?>\n" +
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n" +
" \"http:
"<svg onload=\"init(evt)\" xmlns=\"http:
"version=\"1.1\" \n" +
" width=\"" + windowWidth + "\" height=\"" + windowHeight + "\">\n");
// Output One Gene per Row
int x = 0;
int y = 25;
out.append("<g font-family=\"Verdana\">");
for (int i = 0; i < matrix.length; i++) {
GeneticEvent rowEvent = matrix[i][0];
x = 120;
out.append("<text x=\"30\" y = \"" + (y + 15) + "\" fill = \"black\" " +
"font-size = \"16\">\n"
+ rowEvent.getGene().toUpperCase() + "</text>");
for (int j = 0; j < numColumnsToShow; j++) {
GeneticEvent event = matrix[i][j];
String style = getCopyNumberStyle(event);
String mRNAStyle = getMRNAStyle(event);
boolean isMutated = event.isMutated();
int block_height = CELL_HEIGHT - 2;
out.append("\n<rect x=\"" + x + "\" y=\"" + y
+ "\" width=\"5\" stroke='" + mRNAStyle + "' height=\""
+ block_height + "\" fill=\"" + style + "\"\n" +
" fill-opacity=\"1.0\"/>");
if (isMutated) {
out.append("\n<rect x='" + x + "' y='" + (y + 5)
+ "' fill='green' width='5' height='6'/>");
}
x += CELL_WIDTH;
}
y += CELL_HEIGHT;
}
out.append("</g>");
out.append("</svg>\n");
}
/**
* Generates an OncoPrint in HTML.
* @param caseSets List of all Case Sets.
* @param caseSetId Selected Case Set ID.
* @param matrix Matrix of Genomic Events.
* @param numColumnsToShow Number of Columns to Show.
* @param showAlteredColumns Flag to show only altered columns.
* @param theOncoPrintSpecification The OncoPrint Spec. Object.
* @param dataSummary Data Summary Object.
* @param out HTML Out.
* @param cellspacing Cellspacing.
* @param cellpadding Cellpadding.
* @param width Width.
* @param height Height.
*/
static void writeHTMLOncoPrint(ArrayList<CaseSet> caseSets, String caseSetId,
GeneticEvent matrix[][],
int numColumnsToShow, boolean showAlteredColumns,
OncoPrintSpecification theOncoPrintSpecification,
ProfileDataSummary dataSummary,
StringBuffer out,
int cellspacing, int cellpadding, int width, int height) {
out.append("<div class=\"oncoprint\">\n");
for (CaseSet caseSet : caseSets) {
if (caseSetId.equals(caseSet.getId())) {
out.append(
"<p>Case Set: " + caseSet.getName()
+ ": " + caseSet.getDescription() + "</p>");
}
}
// stats on pct alteration
out.append("<p>Altered in " + dataSummary.getNumCasesAffected() + " (" +
alterationValueToString(dataSummary.getPercentCasesAffected())
+ ") of cases." + "</p>");
// output table header
out.append(
"\n<table cellspacing='" + cellspacing +
"' cellpadding='" + cellpadding +
"'>\n" +
"<thead>\n"
);
int columnWidthOfLegend = 80;
// heading that indicates columns are cases
// span multiple columns like legend
String caseHeading;
int numCases = matrix[0].length;
if (showAlteredColumns) {
caseHeading = pluralize(dataSummary.getNumCasesAffected(), " case")
+ " with altered genes, out of " + pluralize(numCases, " total case") + "
} else {
caseHeading = "All " + pluralize(numCases, " case") + "
}
out.append("\n<tr><th></th><th width=\"50\">Total altered</th>\n<th colspan='"
+ columnWidthOfLegend + "' align='left'>" + caseHeading + "</th>\n</tr>");
for (int i = 0; i < matrix.length; i++) {
GeneticEvent rowEvent = matrix[i][0];
// new row
out.append("<tr>");
// output cell with gene name, CSS does left justified
out.append("<td>" + rowEvent.getGene().toUpperCase() + "</td>\n");
// output total % altered, right justified
out.append("<td style=\" text-align: right\">");
out.append(alterationValueToString(dataSummary.getPercentCasesWhereGeneIsAltered
(rowEvent.getGene())));
out.append("</td>\n");
// for each case
for (int j = 0; j < numColumnsToShow; j++) {
GeneticEvent event = matrix[i][j];
// get level of each datatype; concatenate to make image name
// color could later could be in configuration file
GeneticEventImpl.CNA CNAlevel = event.getCnaValue();
GeneticEventImpl.MRNA MRNAlevel = event.getMrnaValue();
// construct filename of icon representing this gene's genetic alteration event
StringBuffer iconFileName = new StringBuffer();
// TODO: fix; IMHO this is wrong; diploid should be different from None
String cnaName = CNAlevel.name();
if (cnaName.equals("None")) {
cnaName = "diploid";
}
iconFileName.append(cnaName);
iconFileName.append("-");
iconFileName.append(MRNAlevel.name());
iconFileName.append("-");
if (event.isMutated()) {
iconFileName.append("mutated");
} else {
iconFileName.append("normal");
}
iconFileName.append(".png");
out.append("<td class='op_data_cell'>"
+ IMG(iconFileName.toString(), width, height, event.caseCaseId())
+ "</td>\n");
}
// TODO: learn how to fix: maybe Caitlin knows
// ugly hack to make table wide enough to fit legend
for (int c = numColumnsToShow; c < columnWidthOfLegend; c++) {
out.append("<td></td>\n");
}
}
out.append ("\n");
// write table with legend
out.append("</tr>");
out.append("<tr>");
writeLegend(out, theOncoPrintSpecification.getUnionOfPossibleLevels(), 2,
columnWidthOfLegend, width, height, cellspacing, cellpadding, width, 0.75f);
out.append("</table>");
out.append("</div>");
}
// pluralize a count + name; dumb, because doesn't consider adding 'es' to pluralize
static String pluralize(int num, String s) {
if (num == 1) {
return new String(num + s);
} else {
return new String(num + s + "s");
}
}
/**
* format percentage
* <p/>
* if value == 0 return "--"
* case value
* 0: return "--"
* 0<value<=0.01: return "<1%"
* 1<value: return "<value>%"
*
* @param value
* @return
*/
static String alterationValueToString(double value) {
// in oncoPrint show 0 percent as 0%, not --
if (0.0 < value && value <= 0.01) {
return "<1%";
}
// if( 1.0 < value ){
Formatter f = new Formatter();
f.format("%.0f", value * 100.0);
return f.out().toString() + "%";
}
// directory containing images
static String imageDirectory = "images/oncoPrint/";
static String IMG(String theImage, int width, int height) {
return IMG(theImage, width, height, null);
}
static String IMG(String theImage, int width, int height, String toolTip) {
StringBuffer sb = new StringBuffer();
sb.append("<img src='" + imageDirectory + theImage +
"' alt='" + theImage + // TODO: FOR PRODUCTION; real ALT, should be description of genetic alteration
"' width='" + width + "' height='" + height+"'");
if (null != toolTip) {
sb.append(" class=\"Tips1\" title=\"" + toolTip + "\"");
}
return sb.append("/>").toString();
}
/**
* write legend for HTML OncoPrint
*
* @param out writer for the output
* @param width width of an icon
* @param height height of an icon
* @param cellspacing TABLE attribute
* @param cellpadding TABLE attribute
* @param horizontalSpaceAfterDescription
* blank space, in pixels, after each description
*/
public static void writeLegend(StringBuffer out, OncoPrintGeneDisplaySpec allPossibleAlterations,
int colsIndented, int colspan, int width, int height,
int cellspacing, int cellpadding,
int horizontalSpaceAfterDescription, float gap) {
int rowHeight = (int) ((1.0 + gap) * height);
// indent in enclosing table
// for horiz alignment, skip colsIndented columns
for (int i = 0; i < colsIndented; i++) {
out.append("<td></td>");
}
// TODO: FIX; LOOKS BAD WHEN colspan ( == number of columns == cases) is small
out.append("<td colspan='" + colspan + "'>");
// output table header
out.append(
"\n<table cellspacing='" + cellspacing +
"' cellpadding='" + cellpadding + "'>" +
"\n<tbody>");
out.append("\n<tr height='" + rowHeight + "'>");
/*
* TODO: make this data driven; use enumerations
*/
// { "amplified-notShown-normal", "Amplification" }
if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration,
GeneticTypeLevel.Amplified)) {
outputLegendEntry(out, "amplified-notShown-normal", "Amplification",
rowHeight, width, height,
horizontalSpaceAfterDescription);
}
// { "homoDeleted-notShown-normal", "Homozygous Deletion" },
if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration,
GeneticTypeLevel.HomozygouslyDeleted)) {
outputLegendEntry(out, "homoDeleted-notShown-normal", "Homozygous Deletion",
rowHeight, width, height,
horizontalSpaceAfterDescription);
}
// { "Gained-notShown-normal", "Gain" },
if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration,
GeneticTypeLevel.Gained)) {
outputLegendEntry(out, "Gained-notShown-normal", "Gain",
rowHeight, width, height,
horizontalSpaceAfterDescription);
}
// { "HemizygouslyDeleted-notShown-normal", "Hemizygous Deletion" },
if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration,
GeneticTypeLevel.HemizygouslyDeleted)) {
outputLegendEntry(out, "HemizygouslyDeleted-notShown-normal", "Hemizygous Deletion",
rowHeight, width, height,
horizontalSpaceAfterDescription);
}
// { "diploid-upRegulated-normal", "Up-regulation" },
ResultDataTypeSpec theResultDataTypeSpec = allPossibleAlterations
.getResultDataTypeSpec(GeneticDataTypes.Expression);
if (null != theResultDataTypeSpec &&
(null != theResultDataTypeSpec.getCombinedGreaterContinuousDataTypeSpec())) {
outputLegendEntry(out, "diploid-upRegulated-normal", "Up-regulation", rowHeight,
width, height,
horizontalSpaceAfterDescription);
}
// { "diploid-downRegulated-normal", "Down-regulation" },
theResultDataTypeSpec = allPossibleAlterations.getResultDataTypeSpec
(GeneticDataTypes.Expression);
if (null != theResultDataTypeSpec &&
(null != theResultDataTypeSpec.getCombinedLesserContinuousDataTypeSpec())) {
outputLegendEntry(out, "diploid-downRegulated-normal", "Down-regulation",
rowHeight, width, height,
horizontalSpaceAfterDescription);
}
// { "diploid-notShown-mutated", "Mutation" },
if (allPossibleAlterations.satisfy(GeneticDataTypes.Mutation, GeneticTypeLevel.Mutated)) {
outputLegendEntry(out, "diploid-notShown-mutated", "Mutation", rowHeight, width, height,
horizontalSpaceAfterDescription);
}
out.append("\n");
if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration)) {
out.append("<tr height='" + rowHeight / 2 + "'>\n");
out.append("<td height='" + rowHeight / 2 + "' colspan=" + colspan / 4
+ " style=\"vertical-align:bottom\" >"
+ "<div class=\"tiny\"> Copy number alterations are putative.<br/></div></td>\n");
out.append("</tr>");
}
out.append("</tbody></table>");
}
private static void outputLegendEntry(StringBuffer out, String imageName,
String imageDescription, int rowHeight, int width, int height,
int horizontalSpaceAfterDescription) {
out.append("<td height='" + rowHeight + "' style=\"vertical-align:bottom\" >"
+ IMG(imageName + ".png", width, height));
out.append("</td>\n");
out.append("<td height='" + rowHeight + "' style=\"vertical-align:bottom\" >"
+ imageDescription);
// add some room after description
out.append("</td>\n");
out.append("<td width='" + horizontalSpaceAfterDescription + "'></td>\n");
}
/**
* Gets the Correct Copy Number color for OncoPrint.
*/
private static String getCopyNumberStyle(GeneticEvent event) {
switch (event.getCnaValue()) {
case amplified:
return "red";
case Gained:
return "lightpink";
case HemizygouslyDeleted:
return "lightblue";
case homoDeleted:
return "blue";
case diploid:
case None:
return "lightgray";
}
// TODO: throw exception
return "shouldNotBeReached"; // never reached
}
/**
* Gets the Correct mRNA color.
* Displayed in the rectangle boundary.
*/
private static String getMRNAStyle(GeneticEvent event) {
switch (event.getMrnaValue()) {
case upRegulated:
// if the mRNA is UpRegulated, then pink boundary;
return "#FF9999";
case notShown:
// white is the default, not showing mRNA expression level
return "white";
case downRegulated:
// downregulated, then blue boundary
return "#6699CC";
}
// TODO: throw exception
return "shouldNotBeReached"; // never reached
}
} |
package com.xeiam.xchange;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Manually override the JVM's TrustManager to accept all HTTPS connections. Use this ONLY for testing, and even at that use it cautiously. Someone could steal your API keys with a MITM attack!
*/
public class AuthHelper {
public static void trustAllCerts() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
} |
package org.yamcs.utils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.PrimitiveIterator;
import java.util.function.IntConsumer;
/**
* sorted int array
*
*
* @author nm
*
*/
public class SortedIntArray implements Serializable {
static final long serialVersionUID = 1L;
public static int DEFAULT_CAPACITY = 10;
private int[] a;
private int length;
// caches the hashCode
private int hash;
/**
* Creates a sorted int array with a default initial capacity
*
*/
public SortedIntArray() {
a = new int[DEFAULT_CAPACITY];
}
/**
* Creates a sorted int array with a given initial capacity
*
* @param capacity
*/
public SortedIntArray(int capacity) {
a = new int[capacity];
}
/**
* Creates the SortedIntArray by copying all values from the input array and sorting them
*
* @param array
*/
public SortedIntArray(int... array) {
length = array.length;
a = Arrays.copyOf(array, length);
Arrays.sort(a);
}
public SortedIntArray(IntArray pids) {
length = pids.size();
a = Arrays.copyOf(pids.array(), length);
Arrays.sort(a);
}
/**
* Inserts value to the array and return the position on which has been inserted.
* <p>
* In case <code>x</code> is already present in the array, this function inserts the new value at a position after
* the values already present
*
* @param x
* - value to be inserted
* @return the position on which the value has been inserted
*/
public int insert(int x) {
int pos = Arrays.binarySearch(a, 0, length, x);
if (pos < 0) {
pos = -pos - 1;
} else { // make sure we insert after the last value
while (pos < length && a[pos] == x) {
pos++;
}
}
ensureCapacity(length + 1);
System.arraycopy(a, pos, a, pos + 1, length - pos);
a[pos] = x;
length++;
hash = 0;
return pos;
}
/**
* performs a binary search in the array.
*
* @see java.util.Arrays#binarySearch(int[], int)
* @param x
* @return result of the binarySearch, @see java.util.Arrays#binarySearch(int[], int)
*/
public int search(int x) {
return Arrays.binarySearch(a, 0, length, x);
}
/**
* get element at position
*
* @param pos
* @return the element at position
*/
public int get(int pos) {
if (pos >= length) {
throw new IndexOutOfBoundsException("Index: " + pos + " length: " + length);
}
return a[pos];
}
private void ensureCapacity(int minCapacity) {
if (minCapacity <= a.length) {
return;
}
int capacity = a.length;
int newCapacity = capacity + (capacity >> 1);
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
a = Arrays.copyOf(a, newCapacity);
}
public boolean isEmpty() {
return a.length == 0;
}
public int[] getArray() {
return Arrays.copyOf(a, length);
}
public int size() {
return length;
}
/**
* Constructs an ascending iterator starting from a specified value (inclusive)
*
* @param startFrom
* @return an iterator starting from the specified value
*/
public PrimitiveIterator.OfInt getAscendingIterator(int startFrom) {
return new PrimitiveIterator.OfInt() {
int pos;
{
pos = search(startFrom);
if (pos < 0) {
pos = -pos - 1;
}
}
@Override
public boolean hasNext() {
return pos < length;
}
@Override
public int nextInt() {
return a[pos++];
}
};
}
/**
* Constructs an descending iterator starting from a specified value (exclusive)
*
* @param startFrom
* @return an descending iterator starting from the specified value
*/
public PrimitiveIterator.OfInt getDescendingIterator(int startFrom) {
return new PrimitiveIterator.OfInt() {
int pos;
{
pos = search(startFrom);
if (pos < 0) {
pos = -pos - 1;
}
pos
}
@Override
public boolean hasNext() {
return pos >= 0;
}
@Override
public int nextInt() {
return a[pos
}
};
}
public void forEach(IntConsumer action) {
for (int i = 0; i < length; i++) {
action.accept(a[i]);
}
}
/**
* Performs a binary search and returns true if this array contains the value.
*
* @param x
* - value to check
* @return true of the array contains the specified value
*
*/
public boolean contains(int x) {
return Arrays.binarySearch(a, 0, length, x) >= 0;
}
public static SortedIntArray decodeFromVarIntArray(byte[] buf) {
if (buf.length == 0) {
return new SortedIntArray(0);
}
SortedIntArray sia = new SortedIntArray();
VarIntUtil.ArrayDecoder ad = VarIntUtil.newArrayDecoder(buf);
int s = 0;
while (ad.hasNext()) {
s += ad.next();
sia.insert(s);
}
return sia;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SortedIntArray other = (SortedIntArray) obj;
if (length != other.length) {
return false;
}
for (int i = 0; i < length; i++) {
if (a[i] != other.a[i]) {
return false;
}
}
return true;
}
/**
* Change the elements of the array by adding x to each element
*
* @param x
*/
public void add(int x) {
for (int i = 0; i < length; i++) {
a[i] += x;
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
int n = length - 1;
b.append('[');
for (int i = 0;; i++) {
b.append(a[i]);
if (i == n) {
return b.append(']').toString();
}
b.append(", ");
}
}
@Override
public int hashCode() {
int h = hash;
if (h == 0 && length > 0) {
h = 1;
for (int i = 0; i < length; i++) {
h = 31 * h + a[i];
}
hash = h;
}
return h;
}
} |
package hudson;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.PluginManager.UberClassLoader;
import hudson.model.Hudson;
import hudson.model.UpdateCenter;
import hudson.model.UpdateCenter.UpdateCenterJob;
import hudson.model.UpdateSite;
import hudson.scm.SubversionSCM;
import hudson.util.FormValidation;
import hudson.util.PersistedList;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.filters.StringInputStream;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.Url;
import org.jvnet.hudson.test.recipes.WithPlugin;
import org.jvnet.hudson.test.recipes.WithPluginManager;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
/**
* @author Kohsuke Kawaguchi
*/
public class PluginManagerTest extends HudsonTestCase {
@Override
protected void setUp() throws Exception {
setPluginManager(null); // use a fresh instance
super.setUp();
}
/**
* Manual submission form.
*/
public void testUploadJpi() throws Exception {
HtmlPage page = new WebClient().goTo("pluginManager/advanced");
HtmlForm f = page.getFormByName("uploadPlugin");
File dir = env.temporaryDirectoryAllocator.allocate();
File plugin = new File(dir, "tasks.jpi");
FileUtils.copyURLToFile(getClass().getClassLoader().getResource("plugins/tasks.jpi"),plugin);
f.getInputByName("name").setValueAttribute(plugin.getAbsolutePath());
submit(f);
assertTrue( new File(jenkins.getRootDir(),"plugins/tasks.jpi").exists() );
}
/**
* Manual submission form.
*/
public void testUploadHpi() throws Exception {
HtmlPage page = new WebClient().goTo("pluginManager/advanced");
HtmlForm f = page.getFormByName("uploadPlugin");
File dir = env.temporaryDirectoryAllocator.allocate();
File plugin = new File(dir, "legacy.hpi");
FileUtils.copyURLToFile(getClass().getClassLoader().getResource("plugins/legacy.hpi"),plugin);
f.getInputByName("name").setValueAttribute(plugin.getAbsolutePath());
submit(f);
// uploaded legacy plugins get renamed to *.jpi
assertTrue( new File(jenkins.getRootDir(),"plugins/legacy.jpi").exists() );
}
/**
* Tests the effect of {@link WithPlugin}.
*/
@WithPlugin("tasks.jpi")
public void testWithRecipeJpi() throws Exception {
assertNotNull(jenkins.getPlugin("tasks"));
}
/**
* Tests the effect of {@link WithPlugin}.
*/
@WithPlugin("legacy.hpi")
public void testWithRecipeHpi() throws Exception {
assertNotNull(jenkins.getPlugin("legacy"));
}
/**
* Makes sure that plugins can see Maven2 plugin that's refactored out in 1.296.
*/
@WithPlugin("tasks.jpi")
public void testOptionalMavenDependency() throws Exception {
PluginWrapper.Dependency m2=null;
PluginWrapper tasks = jenkins.getPluginManager().getPlugin("tasks");
for( PluginWrapper.Dependency d : tasks.getOptionalDependencies() ) {
if(d.shortName.equals("maven-plugin")) {
assertNull(m2);
m2 = d;
}
}
assertNotNull(m2);
// this actually doesn't really test what we need, though, because
// I thought test harness is loading the maven classes by itself.
// TODO: write a separate test that tests the optional dependency loading
tasks.classLoader.loadClass(hudson.maven.agent.AbortException.class.getName());
}
/**
* Verifies that by the time {@link Plugin#start()} is called, uber classloader is fully functioning.
* This is necessary as plugin start method can engage in XStream loading activities, and they should
* resolve all the classes in the system (for example, a plugin X can define an extension point
* other plugins implement, so when X loads its config it better sees all the implementations defined elsewhere)
*/
@WithPlugin("tasks.jpi")
@WithPluginManager(PluginManagerImpl_for_testUberClassLoaderIsAvailableDuringStart.class)
public void testUberClassLoaderIsAvailableDuringStart() {
assertTrue(((PluginManagerImpl_for_testUberClassLoaderIsAvailableDuringStart) jenkins.pluginManager).tested);
}
public class PluginManagerImpl_for_testUberClassLoaderIsAvailableDuringStart extends LocalPluginManager {
boolean tested;
public PluginManagerImpl_for_testUberClassLoaderIsAvailableDuringStart(File rootDir) {
super(rootDir);
}
@Override
protected PluginStrategy createPluginStrategy() {
return new ClassicPluginStrategy(this) {
@Override
public void startPlugin(PluginWrapper plugin) throws Exception {
tested = true;
// plugins should be already visible in the UberClassLoader
assertTrue(!activePlugins.isEmpty());
uberClassLoader.loadClass(SubversionSCM.class.getName());
uberClassLoader.loadClass("hudson.plugins.tasks.Messages");
super.startPlugin(plugin);
}
};
}
}
/**
* Makes sure that thread context classloader isn't used by {@link UberClassLoader}, or else
* infinite cycle ensues.
*/
@Url("http://jenkins.361315.n4.nabble.com/channel-example-and-plugin-classes-gives-ClassNotFoundException-td3756092.html")
public void testUberClassLoaderDoesntUseContextClassLoader() throws Exception {
Thread t = Thread.currentThread();
URLClassLoader ucl = new URLClassLoader(new URL[0], jenkins.pluginManager.uberClassLoader);
ClassLoader old = t.getContextClassLoader();
t.setContextClassLoader(ucl);
try {
try {
ucl.loadClass("No such class");
fail();
} catch (ClassNotFoundException e) {
// as expected
}
ucl.loadClass(Hudson.class.getName());
} finally {
t.setContextClassLoader(old);
}
}
public void testInstallWithoutRestart() throws Exception {
URL res = getClass().getClassLoader().getResource("plugins/htmlpublisher.jpi");
File f = new File(jenkins.getRootDir(), "plugins/htmlpublisher.jpi");
FileUtils.copyURLToFile(res, f);
jenkins.pluginManager.dynamicLoad(f);
Class c = jenkins.getPluginManager().uberClassLoader.loadClass("htmlpublisher.HtmlPublisher$DescriptorImpl");
assertNotNull(jenkins.getDescriptorByType(c));
}
public void testPrevalidateConfig() throws Exception {
PersistedList<UpdateSite> sites = jenkins.getUpdateCenter().getSites();
sites.clear();
URL url = PluginManagerTest.class.getResource("/plugins/tasks-update-center.json");
UpdateSite site = new UpdateSite(UpdateCenter.ID_DEFAULT, url.toString());
sites.add(site);
assertEquals(FormValidation.ok(), site.updateDirectly(false).get());
assertNotNull(site.getData());
assertEquals(Collections.emptyList(), jenkins.getPluginManager().prevalidateConfig(new StringInputStream("<whatever><runant plugin=\"ant@1.1\"/></whatever>")));
assertNull(jenkins.getPluginManager().getPlugin("tasks"));
List<Future<UpdateCenterJob>> jobs = jenkins.getPluginManager().prevalidateConfig(new StringInputStream("<whatever><tasks plugin=\"tasks@2.23\"/></whatever>"));
assertEquals(1, jobs.size());
UpdateCenterJob job = jobs.get(0).get(); // blocks for completion
assertEquals("InstallationJob", job.getType());
UpdateCenter.InstallationJob ijob = (UpdateCenter.InstallationJob) job;
assertEquals("tasks", ijob.plugin.name);
assertNotNull(jenkins.getPluginManager().getPlugin("tasks"));
// TODO restart scheduled (SuccessButRequiresRestart) after upgrade or Support-Dynamic-Loading: false
// TODO dependencies installed or upgraded too
// TODO required plugin installed but inactive
}
// plugin "depender" optionally depends on plugin "dependee".
// they are written like this:
// org.jenkinsci.plugins.dependencytest.dependee:
// public class Dependee {
// public static String getValue() {
// return "dependee";
// public abstract class DependeeExtensionPoint implements ExtensionPoint {
// org.jenkinsci.plugins.dependencytest.depender:
// public class Depender {
// public static String getValue() {
// if (Jenkins.getInstance().getPlugin("dependee") != null) {
// return Dependee.getValue();
// return "depender";
// @Extension(optional=true)
// public class DependerExtension extends DependeeExtensionPoint {
/**
* call org.jenkinsci.plugins.dependencytest.depender.Depender.getValue().
*
* @return
* @throws Exception
*/
private String callDependerValue() throws Exception {
Class<?> c = jenkins.getPluginManager().uberClassLoader.loadClass("org.jenkinsci.plugins.dependencytest.depender.Depender");
Method m = c.getMethod("getValue");
return (String)m.invoke(null);
}
/**
* Load "dependee" and then load "depender".
* Asserts that "depender" can access to "dependee".
*
* @throws Exception
*/
public void testInstallDependingPluginWithoutRestart() throws Exception {
// Load dependee.
{
String target = "dependee.hpi";
URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
FileUtils.copyURLToFile(src, dest);
jenkins.pluginManager.dynamicLoad(dest);
}
// before load depender, of course failed to call Depender.getValue()
try {
callDependerValue();
fail();
} catch (ClassNotFoundException _) {
}
// No extensions exist.
assertTrue(jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint").isEmpty());
// Load depender.
{
String target = "depender.hpi";
URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
FileUtils.copyURLToFile(src, dest);
jenkins.pluginManager.dynamicLoad(dest);
}
// depender successfully accesses to dependee.
assertEquals("dependee", callDependerValue());
// Extension in depender is loaded.
assertFalse(jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint").isEmpty());
}
/**
* Load "depender" and then load "dependee".
* Asserts that "depender" can access to "dependee".
*
* @throws Exception
*/
public void testInstallDependedPluginWithoutRestart() throws Exception {
// Load depender.
{
String target = "depender.hpi";
URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
FileUtils.copyURLToFile(src, dest);
jenkins.pluginManager.dynamicLoad(dest);
}
// before load dependee, depender does not access to dependee.
assertEquals("depender", callDependerValue());
// before load dependee, of course failed to list extensions for dependee.
try {
jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint");
fail();
} catch( ClassNotFoundException _ ){
}
// Load dependee.
{
String target = "dependee.hpi";
URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
FileUtils.copyURLToFile(src, dest);
jenkins.pluginManager.dynamicLoad(dest);
}
// (MUST) Not throws an exception
// (SHOULD) depender successfully accesses to dependee.
assertEquals("dependee", callDependerValue());
// No extensions exist.
// extensions in depender is not loaded.
assertTrue(jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint").isEmpty());
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stallone.api.mc;
import static stallone.api.API.*;
import org.junit.*;
import static org.junit.Assert.*;
import stallone.api.doubles.IDoubleArray;
import stallone.mc.sampling.*;
/**
*
* @author noe
*/
public class MarkovModelFactoryTest
{
public MarkovModelFactoryTest()
{
}
@BeforeClass
public static void setUpClass() throws Exception
{
}
@AfterClass
public static void tearDownClass() throws Exception
{
}
@Before
public void setUp()
{
}
@After
public void tearDown()
{
}
/**
* Test of createPosteriorCountsNeighbor method, of class MarkovModelFactory.
*/
@Test
public void testCreatePosteriorCountsNeighbor()
{
}
/**
* Test of metropolisMC method, of class MarkovModelFactory.
*/
@Test
public void testMetropolisMC()
{
}
/**
* Test of createCountMatrixEstimatorSliding method, of class MarkovModelFactory.
*/
@Test
public void testCreateCountMatrixEstimatorSliding_Iterable_int()
{
}
/**
* Test of createCountMatrixEstimatorSliding method, of class MarkovModelFactory.
*/
@Test
public void testCreateCountMatrixEstimatorSliding_IIntArray_int()
{
}
/**
* Test of createCountMatrixEstimatorStepping method, of class MarkovModelFactory.
*/
@Test
public void testCreateCountMatrixEstimatorStepping_Iterable_int()
{
}
/**
* Test of createCountMatrixEstimatorStepping method, of class MarkovModelFactory.
*/
@Test
public void testCreateCountMatrixEstimatorStepping_IIntArray_int()
{
}
/**
* Test of createTransitionMatrixEstimatorNonrev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixEstimatorNonrev()
{
}
/**
* Test of createTransitionMatrixEstimatorRev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixEstimatorRev_0args()
{
}
/**
* Test of createTransitionMatrixEstimatorRev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixEstimatorRev_IDoubleArray()
{
}
private void testSampler2x2(ITransitionMatrixSampler sampler, IDoubleArray C, int nsample, double errtol)
{
double c1 = doubles.sumRow(C,0);
double c2 = doubles.sumRow(C,1);
int n = C.rows();
IDoubleArray samplesT12 = doublesNew.array(nsample);
IDoubleArray samplesT21 = doublesNew.array(nsample);
for (int i=0; i<nsample; i++)
{
IDoubleArray T = sampler.sample(100);
samplesT12.set(i, T.get(0,1));
samplesT21.set(i, T.get(1,0));
}
double true_meanT12 = (double)(C.get(0,1)+1) / (double)(c1 + n);
double sample_meanT12 = stat.mean(samplesT12);
double err_T12 = Math.abs(true_meanT12-sample_meanT12)/true_meanT12;
System.out.println(true_meanT12+" "+sample_meanT12+" -> "+err_T12);
assert(err_T12 < errtol);
double true_meanT21 = (double)(C.get(1,0)+1) / (double)(c2 + n);
double sample_meanT21 = stat.mean(samplesT21);
double err_T21 = Math.abs(true_meanT21-sample_meanT21)/true_meanT21;
System.out.println(true_meanT21+" "+sample_meanT21+" -> "+err_T21);
assert(err_T21 < errtol);
double true_varT12 = true_meanT12 * (1.0-true_meanT12) / (double)(c1 + n + 1);
double sample_varT12 = stat.variance(samplesT12);
double err_varT12 = Math.abs(true_varT12-sample_varT12)/true_varT12;
System.out.println(true_varT12+" "+sample_varT12+" -> "+err_varT12);
assert(err_varT12 < errtol);
double true_varT21 = true_meanT21 * (1.0-true_meanT21) / (double)(c2 + n + 1);
double sample_varT21 = stat.variance(samplesT21);
double err_varT21 = Math.abs(true_varT21-sample_varT21)/true_meanT21;
System.out.println(true_varT21+" "+sample_varT21+" -> "+err_varT21);
assert(err_varT21 < errtol);
}
private void compareSamplers(ITransitionMatrixSampler sampler1, ITransitionMatrixSampler sampler2, IDoubleArray C, int nsample, double errtol)
{
// Index: i,j,time
int n = C.rows();
double[][][] samples1 = new double[n][n][nsample];
double[][][] samples2 = new double[n][n][nsample];
for (int t=0; t<nsample; t++)
{
IDoubleArray T1 = sampler1.sample(100);
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
samples1[i][j][t] = T1.get(i,j);
IDoubleArray T2 = sampler1.sample(100);
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
samples2[i][j][t] = T2.get(i,j);
}
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
// compare means
double m1 = stat.mean(doublesNew.array(samples1[i][j]));
double m2 = stat.mean(doublesNew.array(samples2[i][j]));
double errm = Math.abs(m1-m2)/(0.5*(m1+m2));
System.out.println("mean T_"+(i+1)+","+(j+1)+"\t"+m1+" "+m2+" -> "+errm);
assert(errm < errtol);
// compare variances
double v1 = stat.mean(doublesNew.array(samples1[i][j]));
double v2 = stat.mean(doublesNew.array(samples2[i][j]));
double errv = Math.abs(v1-v2)/(0.5*(v1+v2));
System.out.println("var T_"+(i+1)+","+(j+1)+"\t"+v1+" "+v2+" -> "+errv);
assert(errv < errtol);
}
}
}
/**
* Test of createTransitionMatrixSamplerNonrev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixSamplerNonrev()
{
}
/**
* Test of createTransitionMatrixSamplerRev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixSamplerRev_IDoubleArray()
{
IDoubleArray C = doublesNew.array(new double[][]{
{8, 2, 1},
{2,10, 3},
{2, 3, 6}});
ITransitionMatrixSampler sampler1 = TransitionMatrixSamplerRev.create(C, new Step_Rev_Row_Beta(), new Step_Rev_Quad_MC());
ITransitionMatrixSampler sampler2 = TransitionMatrixSamplerRev.create(C, new Step_Rev_Row_MC(), new Step_Rev_Quad_MC());
int nsample = 100000;
double errtol = 1e-2;
compareSamplers(sampler1, sampler2, C, nsample, errtol);
}
/**
* Test of createTransitionMatrixSamplerRevMCMC method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixSamplerRevMCMC()
{
IDoubleArray C = doublesNew.array(new double[][]{
{5,2},
{1,10}});
ITransitionMatrixSampler sampler = TransitionMatrixSamplerRev.create(C, new Step_Rev_Row_Beta(), new Step_Rev_Quad_MC());
testSampler2x2(sampler, C, 100000, 1e-2);
}
/**
* Test of createTransitionMatrixSamplerRevGibbs method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixSamplerRevGibbs()
{
IDoubleArray C = doublesNew.array(new double[][]{
{5,2},
{1,10}});
ITransitionMatrixSampler sampler = TransitionMatrixSamplerRev.create(C, new Step_Rev_Row_MC(), new Step_Rev_Quad_MC());
testSampler2x2(sampler, C, 100000, 1e-2);
}
@Test
public void testCreateTransitionMatrixSamplerRevGibbsGibbs()
{
IDoubleArray C = doublesNew.array(new double[][]{
{5,2},
{1,10}});
ITransitionMatrixSampler sampler = TransitionMatrixSamplerRev.create(C, new Step_Rev_Row_Beta(), new Step_Rev_Quad_Gibbs_MC());
testSampler2x2(sampler, C, 100000, 1e-2);
}
/**
* Test of createTransitionMatrixSamplerRev method, of class MarkovModelFactory.
*/
@Test
public void testCreateTransitionMatrixSamplerRev_IDoubleArray_IDoubleArray()
{
}
/**
* Test of createPCCA method, of class MarkovModelFactory.
*/
@Test
public void testCreatePCCA()
{
}
/**
* Test of createCommittor method, of class MarkovModelFactory.
*/
@Test
public void testCreateCommittor_3args()
{
}
/**
* Test of createCommittor method, of class MarkovModelFactory.
*/
@Test
public void testCreateCommittor_4args()
{
}
/**
* Test of createTPT method, of class MarkovModelFactory.
*/
@Test
public void testCreateTPT_3args()
{
}
/**
* Test of createTPT method, of class MarkovModelFactory.
*/
@Test
public void testCreateTPT_4args()
{
}
/**
* Test of createDynamicalExpectations method, of class MarkovModelFactory.
*/
@Test
public void testCreateDynamicalExpectations_IDoubleArray()
{
}
/**
* Test of createDynamicalExpectations method, of class MarkovModelFactory.
*/
@Test
public void testCreateDynamicalExpectations_IDoubleArray_IDoubleArray()
{
}
/**
* Test of createDynamicalFingerprint method, of class MarkovModelFactory.
*/
@Test
public void testCreateDynamicalFingerprint_IDoubleArray()
{
}
/**
* Test of createDynamicalFingerprint method, of class MarkovModelFactory.
*/
@Test
public void testCreateDynamicalFingerprint_IDoubleArray_IDoubleArray()
{
}
/**
* Test of markovChain method, of class MarkovModelFactory.
*/
@Test
public void testMarkovChain_IDoubleArray()
{
}
/**
* Test of markovChain method, of class MarkovModelFactory.
*/
@Test
public void testMarkovChain_IDoubleArray_IDoubleArray()
{
}
} |
package org.vosao.search;
import java.io.IOException;
import java.util.List;
import org.vosao.entity.PageEntity;
/**
* Search index of all site pages for one language.
*
* @author Alexander Oleynik
*
*/
public interface SearchIndex {
void updateIndex(Long pageId) throws IOException;
void removeFromIndex(Long pageId) ;
List<Hit> search(SearchResultFilter filter, String query, int textSize);
public List<PageEntity> search(SearchResultFilter filter, String query);
void saveIndex() throws IOException;
String getLanguage();
void clear();
} |
/**
* $$\\ToureNPlaner\\$$
*/
package server;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import algorithms.AlgorithmFactory;
import algorithms.DummyFactory;
import algorithms.GraphAlgorithmFactory;
import computecore.AlgorithmRegistry;
import computecore.ComputeCore;
import config.ConfigManager;
public class HttpServer {
public static Map<String, Object> getServerInfo(AlgorithmRegistry reg){
Map<String, Object> info = new HashMap<String,Object>(4);
info.put("version", new Float(0.1));
info.put("servertype", "public");
info.put("sslport", ConfigManager.getInstance().getEntryLong("sslport", 8081));
// Enumerate Algorithms
Collection<AlgorithmFactory> algs = reg.getAlgorithms();
Map<String, Object> algInfo;
List<Map<String, Object>> algList= new ArrayList<Map<String,Object>>();
for(AlgorithmFactory alg: algs){
algInfo = new HashMap<String, Object>(5);
algInfo.put("version", alg.getVersion());
algInfo.put("name", alg.getAlgName());
algInfo.put("urlsuffix", alg.getURLSuffix());
if(alg instanceof GraphAlgorithmFactory){
algInfo.put("pointconstraints", ((GraphAlgorithmFactory)alg).getPointConstraints());
algInfo.put("constraints", ((GraphAlgorithmFactory)alg).getConstraints());
}
algList.add(algInfo);
}
info.put("algorithms", algList);
return info;
}
public static void main(String[] args) {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory( // Change to Oio* if you want OIO
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
ServerBootstrap infoBootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory( // Change to Oio* if you want OIO
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Load Config
if(args.length == 1){
try {
ConfigManager.Init(args[0]);
} catch (Exception e) {
System.err.println("Couldn't load configuration File: "+e.getMessage());
return;
}
} else {
System.err.println("Missing config path parameter");
return;
}
// Register Algorithms
AlgorithmRegistry reg = new AlgorithmRegistry();
reg.registerAlgorithm(new DummyFactory());
ConfigManager cm = ConfigManager.getInstance();
// Create our ComputeCore that manages all ComputeThreads
ComputeCore comCore = new ComputeCore(reg, (int)cm.getEntryLong("threads",2),(int)cm.getEntryLong("queuelength", 32));
// Create ServerInfo object
Map<String, Object> serverInfo = getServerInfo(reg);
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new ServerPipelineFactory(comCore, false, serverInfo));
infoBootstrap.setPipelineFactory(new ServerInfoOnlyPipelineFactory(serverInfo));
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress((int)cm.getEntryLong("sslport", 8081)));
infoBootstrap.bind(new InetSocketAddress((int)cm.getEntryLong("httpport", 8080)));
}
} |
package heros.solver;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link ThreadPoolExecutor} which keeps track of the number of spawned
* tasks to allow clients to await their completion.
*/
public class CountingThreadPoolExecutor extends ThreadPoolExecutor {
protected static final Logger logger = LoggerFactory.getLogger(IDESolver.class);
protected final CountLatch numRunningTasks = new CountLatch(0);
protected volatile Throwable exception = null;
public CountingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
public void execute(Runnable command) {
try {
numRunningTasks.increment();
super.execute(command);
}
catch (RejectedExecutionException ex) {
// If we were unable to submit the task, we may not count it!
numRunningTasks.decrement();
throw ex;
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if(t!=null) {
exception = t;
logger.error("Worker thread execution failed: " + t.getMessage(), t);
shutdownNow();
numRunningTasks.resetAndInterrupt();
}
else {
numRunningTasks.decrement();
}
super.afterExecute(r, t);
}
/**
* Awaits the completion of all spawned tasks.
*/
public void awaitCompletion() throws InterruptedException {
numRunningTasks.awaitZero();
}
/**
* Awaits the completion of all spawned tasks.
*/
public void awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException {
numRunningTasks.awaitZero(timeout, unit);
}
/**
* Returns the exception thrown during task execution (if any).
*/
public Throwable getException() {
return exception;
}
} |
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.jora;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Provides support for doing partial updates to objects in a JORA table.
* A field mask can be obtained for a particular table, fields marked as
* modified and the object subsequently updated in a fairly
* straightforward manner:
*
* <pre>
* // updating parts of a table that contains User objects
* User user = // load user object from table
* FieldMask mask = table.getFieldMask();
* user.firstName = newFirstName;
* mask.setModified("firstName");
* user.lastName = newLastName;
* mask.setModified("lastName");
* table.update(user, mask);
* </pre>
*/
public class FieldMask
implements Cloneable
{
/**
* Creates a field mask for a {@link Table} that uses the supplied
* field descriptors.
*/
public FieldMask (FieldDescriptor[] descrips)
{
// create a mapping from field name to descriptor index
_descripMap = new HashMap<String,Integer>();
int dcount = (descrips == null ? 0 : descrips.length);
for (int i = 0; i < dcount; i++) {
_descripMap.put(descrips[i].field.getName(), Integer.valueOf(i));
}
// create our modified flags
_modified = new boolean[dcount];
}
/**
* Returns true if any of the fields in this mask are modified.
*/
public final boolean isModified ()
{
int mcount = _modified.length;
for (int ii = 0; ii < mcount; ii++) {
if (_modified[ii]) {
return true;
}
}
return false;
}
/**
* Returns true if the field with the specified index is modified.
*/
public final boolean isModified (int index)
{
return _modified[index];
}
/**
* Returns true if the field with the specified name is modifed.
*/
public final boolean isModified (String fieldName)
{
Integer index = _descripMap.get(fieldName);
if (index == null) {
throw new IllegalArgumentException("Field not in mask: " + fieldName);
}
return _modified[index.intValue()];
}
/**
* Returns true only if the set of modified fields is a subset of the
* fields specified.
*/
public final boolean onlySubsetModified (Set<String> fieldSet)
{
for (String field : _descripMap.keySet()) {
if (isModified(field) && (!fieldSet.contains(field))) {
return false;
}
}
return true;
}
/**
* Marks the specified field as modified.
*/
public void setModified (String fieldName)
{
Integer index = _descripMap.get(fieldName);
if (index == null) {
throw new IllegalArgumentException("Field not in mask: " + fieldName);
}
_modified[index.intValue()] = true;
}
/**
* Clears out the modification state of the fields in this mask.
*/
public void clear ()
{
Arrays.fill(_modified, false);
}
/**
* Creates a copy of this field mask, with all fields set to
* not-modified.
*/
@Override
public Object clone ()
{
try {
FieldMask mask = (FieldMask)super.clone();
mask._modified = new boolean[_modified.length];
return mask;
} catch (CloneNotSupportedException cnse) {
throw new RuntimeException("Oh god, the clones!");
}
}
@Override
public String toString ()
{
// return a list of the modified fields
StringBuilder buf = new StringBuilder("FieldMask [modified={");
boolean added = false;
for (Map.Entry<String,Integer> entry : _descripMap.entrySet()) {
if (_modified[entry.getValue().intValue()]) {
if (added) {
buf.append(", ");
} else {
added = true;
}
buf.append(entry.getKey());
}
}
buf.append("}]");
return buf.toString();
}
/** Modified flags for each field of an object in this table. */
protected boolean[] _modified;
/** A mapping from field names to field descriptor index. */
protected HashMap<String,Integer> _descripMap;
} |
// $Id: CollectionUtil.java,v 1.7 2004/06/12 23:17:02 ray Exp $
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* A collection of collection-related utility functions.
*/
public class CollectionUtil
{
/**
* Adds all items returned by the enumeration to the supplied
* collection and returns the supplied collection.
*/
public static <E, T extends Collection<E>> T addAll (
T col, Enumeration<E> enm)
{
while (enm.hasMoreElements()) {
col.add(enm.nextElement());
}
return col;
}
/**
* Adds all items returned by the iterator to the supplied collection
* and returns the supplied collection.
*/
public static <E, T extends Collection<E>> T addAll (
T col, Iterator<E> iter)
{
while (iter.hasNext()) {
col.add(iter.next());
}
return col;
}
/**
* Adds all items in the given object array to the supplied
* collection and returns the supplied collection.
*/
public static <E, T extends Collection<E>> T addAll (T col, E[] values)
{
for (int ii = 0; ii < values.length; ii++) {
col.add(values[ii]);
}
return col;
}
public static <T> List<T> selectRandomSubset (Collection<T> col, int count)
{
int csize = col.size();
if (csize < count) {
String errmsg = "Cannot select " + count + " elements " +
"from a collection of only " + csize + " elements.";
throw new IllegalArgumentException(errmsg);
}
ArrayList<T> subset = new ArrayList<T>();
Iterator<T> iter = col.iterator();
int s = 0;
for (int k = 0; iter.hasNext(); k++) {
T elem = iter.next();
// the probability that an element is select for inclusion in
// our random subset is proportional to the number of elements
// remaining to be checked for inclusion divided by the number
// of elements remaining to be included
float limit = ((float)(count - s)) / ((float)(csize - k));
// include the record if our random value is below the limit
if (Math.random() < limit) {
subset.add(elem);
// stop looking if we've reached our target size
if (++s == count) {
break;
}
}
}
return subset;
}
/**
* If a collection contains only <code>Integer</code> objects, it can be
* passed to this function and converted into an int array.
*
* @param col the collection to be converted.
*
* @return an int array containing the contents of the collection (in the
* order returned by the collection's iterator). The size of the array will
* be equal to the size of the collection.
*/
public static int[] toIntArray (Collection<Integer> col)
{
Iterator<Integer> iter = col.iterator();
int[] array = new int[col.size()];
for (int i = 0; iter.hasNext(); i++) {
array[i] = iter.next().intValue();
}
return array;
}
} |
package com.sun.facelets.compiler;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.ELException;
import javax.el.ExpressionFactory;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import com.sun.facelets.FaceletException;
import com.sun.facelets.FaceletHandler;
import com.sun.facelets.tag.CompositeTagDecorator;
import com.sun.facelets.tag.CompositeTagLibrary;
import com.sun.facelets.tag.TagDecorator;
import com.sun.facelets.tag.TagLibrary;
import com.sun.facelets.util.Assert;
import com.sun.facelets.util.FacesAPI;
/**
* A Compiler instance may handle compiling multiple sources
*
* @author Jacob Hookom
* @version $Id: Compiler.java,v 1.3 2005-07-11 21:54:10 jhook Exp $
*/
public abstract class Compiler {
protected final static Logger log = Logger.getLogger("facelets.compiler");
public final static String EXPRESSION_FACTORY = "compiler.ExpressionFactory";
private static final TagLibrary EMPTY_LIBRARY = new CompositeTagLibrary(
new TagLibrary[0]);
private static final TagDecorator EMPTY_DECORATOR = new CompositeTagDecorator(
new TagDecorator[0]);
private boolean validating = true;
private boolean trimmingWhitespace = true;
private boolean trimmingComments = false;
private final List libraries = new ArrayList();
private final List decorators = new ArrayList();
private final Map features = new HashMap();
private boolean initialized = false;
public Compiler() {
this.features.put(EXPRESSION_FACTORY,
"com.sun.el.ExpressionFactoryImpl");
}
private synchronized void initialize() {
if (this.initialized)
return;
log.fine("Initializing");
try {
TagLibraryConfig cfg = new TagLibraryConfig();
cfg.loadImplicit(this);
} catch (IOException e) {
log.log(Level.SEVERE, "Compiler Initialization Error", e);
} finally {
this.initialized = true;
}
log.fine("Initialization Successful");
}
public final FaceletHandler compile(URL src, String alias)
throws IOException, FaceletException, ELException, FacesException {
if (!this.initialized)
this.initialize();
return this.doCompile(src, alias);
}
protected abstract FaceletHandler doCompile(URL src, String alias)
throws IOException, FaceletException, ELException, FacesException;
public TagDecorator createTagDecorator() {
if (this.decorators.size() > 0) {
return new CompositeTagDecorator((TagDecorator[]) this.decorators
.toArray(new TagDecorator[this.decorators.size()]));
}
return EMPTY_DECORATOR;
}
public void addTagDecorator(TagDecorator decorator) {
Assert.param("decorator", decorator);
if (!this.decorators.contains(decorator)) {
this.decorators.add(decorator);
}
}
public ExpressionFactory createExpressionFactory() {
ExpressionFactory el = null;
if (FacesAPI.getVersion() >= 12) {
try {
el = FacesContext.getCurrentInstance().getApplication()
.getExpressionFactory();
} catch (Exception e) {
// do nothing
}
}
if (el == null) {
log
.warning("No default ExpressionFactory from Faces Implementation, attempting to load from Feature["
+ EXPRESSION_FACTORY + "]");
el = (ExpressionFactory) this.featureInstance(EXPRESSION_FACTORY);
}
return el;
}
private Object featureInstance(String name) {
String type = (String) this.features.get(name);
if (type != null) {
try {
return Class.forName(type).newInstance();
} catch (Throwable t) {
throw new FaceletException("Could not instantiate feature["
+ name + "]: " + type);
}
}
return null;
}
public TagLibrary createTagLibrary() {
if (this.libraries.size() > 0) {
return new CompositeTagLibrary((TagLibrary[]) this.libraries
.toArray(new TagLibrary[this.libraries.size()]));
}
return EMPTY_LIBRARY;
}
public void addTagLibrary(TagLibrary library) {
Assert.param("library", library);
if (!this.libraries.contains(library)) {
this.libraries.add(library);
}
}
public void setFeature(String name, String value) {
this.features.put(name, value);
}
public String getFeature(String name) {
return (String) this.features.get(name);
}
public boolean isTrimmingComments() {
return this.trimmingComments;
}
public void setTrimmingComments(boolean trimmingComments) {
this.trimmingComments = trimmingComments;
}
public boolean isTrimmingWhitespace() {
return this.trimmingWhitespace;
}
public void setTrimmingWhitespace(boolean trimmingWhitespace) {
this.trimmingWhitespace = trimmingWhitespace;
}
public boolean isValidating() {
return this.validating;
}
public void setValidating(boolean validating) {
this.validating = validating;
}
} |
package com.datastax.brisk;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.TimeoutException;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Config.DiskAccessMode;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.IndexHelper;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.sstable.SSTableReader.Operator;
import org.apache.cassandra.io.util.*;
import org.apache.cassandra.service.StorageProxy;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Filter;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
public class BriskServer extends CassandraServer implements Brisk.Iface
{
static final Logger logger = Logger.getLogger(BriskServer.class);
static final String cfsKeyspace = "cfs";
static final String cfsInodeFamily = "inode";
static final String cfsSubBlockFamily = "sblocks";
static final ByteBuffer dataCol = ByteBufferUtil.bytes("data");
static final ColumnParent subBlockDataPath= new ColumnParent(cfsSubBlockFamily);
static final QueryPath inodeQueryPath = new QueryPath(cfsInodeFamily, null, dataCol);
public LocalOrRemoteBlock get_cfs_sblock(String callerHostName, ByteBuffer blockId,
ByteBuffer sblockId, int offset) throws TException, TimedOutException, UnavailableException, InvalidRequestException, NotFoundException
{
// This logic is only used on mmap spec machines
if (DatabaseDescriptor.getDiskAccessMode() == DiskAccessMode.mmap)
{
logger.info("Checking for local block: "+blockId+" from "+callerHostName+" on "+FBUtilities.getLocalAddress().getHostName() );
List<String> hosts = getKeyLocations(blockId);
boolean isLocal = false;
for (String hostName : hosts)
{
logger.info("Block " + blockId + " lives on " + hostName);
if (hostName.equals(callerHostName) && hostName.equals(FBUtilities.getLocalAddress().getHostName()))
{
isLocal = true;
break;
}
}
if(isLocal)
{
logger.info("Local block should be on this node "+blockId);
LocalBlock localBlock = getLocalSubBlock(blockId, sblockId, offset);
if(localBlock != null)
{
logger.info("Local block found: "+localBlock);
return new LocalOrRemoteBlock().setLocal_block(localBlock);
}
}
}
logger.info("Checking for remote block: "+blockId);
//Fallback to storageProxy
return getRemoteSubBlock(blockId, sblockId, offset);
}
public List<List<String>> describe_keys(String keyspace, List<ByteBuffer> keys) throws TException
{
List<List<String>> keyEndpoints = new ArrayList<List<String>>(keys.size());
for (ByteBuffer key : keys)
{
keyEndpoints.add(getKeyLocations(key));
}
return keyEndpoints;
}
private List<String> getKeyLocations(ByteBuffer key)
{
List<InetAddress> endpoints = StorageService.instance.getLiveNaturalEndpoints(cfsKeyspace, key);
DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(), endpoints);
List<String> hosts = new ArrayList<String>(endpoints.size());
for (InetAddress endpoint : endpoints)
{
hosts.add(endpoint.getHostName());
}
return hosts;
}
/**
* Retrieves a local subBlock
*
* @param blockId row key
* @param sblockId SubBlock column name
* @param offset inside the sblock
* @return a local sublock
* @throws TException
*/
private LocalBlock getLocalSubBlock(ByteBuffer blockId, ByteBuffer sblockId, int offset) throws TException
{
// TODO (use sblockId as Column name to look up the Sub Column.
DecoratedKey<Token<?>> decoratedKey = new DecoratedKey<Token<?>>(StorageService.getPartitioner().getToken(
blockId), blockId);
Table table = Table.open(cfsKeyspace);
ColumnFamilyStore sblockStore = table.getColumnFamilyStore(cfsSubBlockFamily);
Collection<SSTableReader> sstables = sblockStore.getSSTables();
for (SSTableReader sstable : sstables)
{
long position = sstable.getPosition(decoratedKey, Operator.EQ);
if (position == -1)
continue;
String filename = sstable.descriptor.filenameFor(Component.DATA);
RandomAccessFile raf = null;
int mappedLength = -1;
MappedByteBuffer mappedData = null;
MappedFileDataInput file = null;
try
{
raf = new RandomAccessFile(filename, "r");
assert position < raf.length();
mappedLength = (raf.length() - position) < Integer.MAX_VALUE ? (int) (raf.length() - position)
: Integer.MAX_VALUE;
mappedData = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, position, mappedLength);
file = new MappedFileDataInput(mappedData, filename, 0);
if (file == null)
continue;
//Verify key was found in data file
DecoratedKey keyInDisk = SSTableReader.decodeKey(sstable.partitioner,
sstable.descriptor,
ByteBufferUtil.readWithShortLength(file));
assert keyInDisk.equals(decoratedKey) : String.format("%s != %s in %s", keyInDisk, decoratedKey, file.getPath());
long rowSize = SSTableReader.readRowSize(file, sstable.descriptor);
assert rowSize > 0;
assert rowSize < mappedLength;
Filter bf = IndexHelper.defreezeBloomFilter(file, sstable.descriptor.usesOldBloomFilter);
//verify this column in in this version of the row.
if(!bf.isPresent(sblockId))
continue;
List<IndexHelper.IndexInfo> indexList = IndexHelper.deserializeIndex(file);
// we can stop early if bloom filter says none of the
// columns actually exist -- but,
// we can't stop before initializing the cf above, in
// case there's a relevant tombstone
ColumnFamilySerializer serializer = ColumnFamily.serializer();
try
{
ColumnFamily cf = serializer.deserializeFromSSTableNoColumns(ColumnFamily.create(sstable.metadata),
file);
if (cf.isMarkedForDelete())
continue;
}
catch (Exception e)
{
e.printStackTrace();
throw new IOException(serializer + " failed to deserialize " + sstable.getColumnFamilyName()
+ " with " + sstable.metadata + " from " + file, e);
}
Integer sblockLength = null;
if(indexList == null)
sblockLength = seekToSubColumn(sstable.metadata, file, sblockId);
else
sblockLength = seekToSubColumn(sstable.metadata, file, sblockId, indexList);
if(sblockLength == null || sblockLength < 0)
continue;
int bytesReadFromStart = mappedLength - (int)file.bytesRemaining();
logger.info("BlockLength = "+sblockLength+" Availible "+file.bytesRemaining());
assert offset <= sblockLength : String.format("%d > %d", offset, sblockLength);
long dataOffset = position + bytesReadFromStart;
if(file.bytesRemaining() == 0 || sblockLength == 0)
continue;
return new LocalBlock(file.getPath(), dataOffset + offset, sblockLength - offset);
}
catch (IOException e)
{
throw new TException(e);
}
finally
{
FileUtils.closeQuietly(raf);
}
}
return null;
}
//Called when there are is no row index (meaning small number of columns)
private Integer seekToSubColumn(CFMetaData metadata, FileDataInput file, ByteBuffer sblockId) throws IOException
{
int columns = file.readInt();
int n = 0;
for (int i = 0; i < columns; i++)
{
Integer dataLength = isSubBlockFound(metadata, file, sblockId);
if(dataLength == null)
return null;
if(dataLength < 0)
continue;
return dataLength;
}
return null;
}
/**
* Checks if the current column is the one we are looking for
* @param metadata
* @param file
* @param sblockId
* @return if > 0 the length to read from current file offset. if -1 not relevent. if null out of bounds
*/
private Integer isSubBlockFound(CFMetaData metadata, FileDataInput file, ByteBuffer sblockId) throws IOException
{
ByteBuffer name = ByteBufferUtil.readWithShortLength(file);
//Stop if we've gone too far (return null)
if(metadata.comparator.compare(name, sblockId) > 0)
return null;
// verify column type;
int b = file.readUnsignedByte();
// skip ts (since we know block ids are unique)
long ts = file.readLong();
int sblockLength = file.readInt();
if(!name.equals(sblockId) || (b & ColumnSerializer.DELETION_MASK) != 0 || (b & ColumnSerializer.EXPIRATION_MASK) != 0)
{
FileUtils.skipBytesFully(file, sblockLength);
return -1;
}
return sblockLength;
}
private Integer seekToSubColumn(CFMetaData metadata, FileDataInput file, ByteBuffer sblockId, List<IndexHelper.IndexInfo> indexList) throws IOException
{
file.readInt(); // column count
/* get the various column ranges we have to read */
AbstractType comparator = metadata.comparator;
int index = IndexHelper.indexFor(sblockId, indexList, comparator, false);
if (index == indexList.size())
return null;
IndexHelper.IndexInfo indexInfo = indexList.get(index);
if (comparator.compare(sblockId, indexInfo.firstName) < 0)
return null;
FileMark mark = file.mark();
FileUtils.skipBytesFully(file, indexInfo.offset);
while (file.bytesPastMark(mark) < indexInfo.offset + indexInfo.width)
{
Integer dataLength = isSubBlockFound(metadata, file, sblockId);
if(dataLength == null)
return null;
if(dataLength < 0)
continue;
return dataLength;
}
return null;
}
private LocalOrRemoteBlock getRemoteSubBlock(ByteBuffer blockId, ByteBuffer sblockId, int offset) throws TimedOutException, UnavailableException, InvalidRequestException, NotFoundException
{
// The column name is the SubBlock id (UUID)
ReadCommand rc = new SliceByNamesReadCommand(cfsKeyspace, blockId, subBlockDataPath, Arrays.asList(sblockId));
try
{
// CL=ONE as there are NOT multiple versions of the blocks.
List<Row> rows = StorageProxy.read(Arrays.asList(rc), ConsistencyLevel.ONE);
IColumn col = null;
try
{
col = validateAndGetColumn(rows, sblockId);
} catch (NotFoundException e)
{
// This is a best effort to get the value. Sometimes due to the size of
// the sublocks, the normal replication may time out leaving a replicate without
// the piece of data. Hence we re try with higher CL.
rows = StorageProxy.read(Arrays.asList(rc), ConsistencyLevel.QUORUM);
}
col = validateAndGetColumn(rows, sblockId);
ByteBuffer value = col.value();
if(value.remaining() < offset)
throw new InvalidRequestException("Invalid offset for block of size: "+value.remaining());
LocalOrRemoteBlock block = new LocalOrRemoteBlock();
if(offset > 0)
{
ByteBuffer offsetBlock = value.duplicate();
offsetBlock.position(offsetBlock.position()+offset);
block.setRemote_block(offsetBlock);
}
else
{
block.setRemote_block(value);
}
return block;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
catch (TimeoutException e)
{
throw new TimedOutException();
}
}
private IColumn validateAndGetColumn(List<Row> rows, ByteBuffer columnName) throws NotFoundException {
if(rows.isEmpty())
throw new NotFoundException();
if(rows.size() > 1)
throw new RuntimeException("Block id returned more than one row");
Row row = rows.get(0);
if(row.cf == null)
throw new NotFoundException();
IColumn col = row.cf.getColumn(columnName);
if(col == null || !col.isLive())
throw new NotFoundException();
return col;
}
} |
package net.runelite.api;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public enum Quest
{
//Free Quests
BLACK_KNIGHTS_FORTRESS(299, "Black Knights' Fortress"),
COOKS_ASSISTANT(300, "Cook's Assistant"),
THE_CORSAIR_CURSE(301, "The Corsair Curse"),
DEMON_SLAYER(302, "Demon Slayer"),
DORICS_QUEST(303, "Doric's Quest"),
DRAGON_SLAYER(304, "Dragon Slayer"),
ERNEST_THE_CHICKEN(305, "Ernest the Chicken"),
GOBLIN_DIPLOMACY(306, "Goblin Diplomacy"),
IMP_CATCHER(307, "Imp Catcher"),
THE_KNIGHTS_SWORD(308, "The Knight's Sword"),
MISTHALIN_MYSTERY(309, "Misthalin Mystery"),
PIRATES_TREASURE(310, "Pirate's Treasure"),
PRINCE_ALI_RESCUE(311, "Prince Ali Rescue"),
THE_RESTLESS_GHOST(312, "The Restless Ghost"),
ROMEO__JULIET(313, "Romeo & Juliet"),
RUNE_MYSTERIES(314, "Rune Mysteries"),
SHEEP_SHEARER(315, "Sheep Shearer"),
SHIELD_OF_ARRAV(316, "Shield of Arrav"),
VAMPIRE_SLAYER(317, "Vampire Slayer"),
WITCHS_POTION(318, "Witch's Potion"),
X_MARKS_THE_SPOT(550, "X Marks the Spot"),
//Members' Quests
ANIMAL_MAGNETISM(331, "Animal Magnetism"),
ANOTHER_SLICE_OF_HAM(332, "Another Slice of H.A.M."),
BETWEEN_A_ROCK(333, "Between a Rock..."),
BIG_CHOMPY_BIRD_HUNTING(334, "Big Chompy Bird Hunting"),
BIOHAZARD(335, "Biohazard"),
CABIN_FEVER(336, "Cabin Fever"),
CLOCK_TOWER(337, "Clock Tower"),
COLD_WAR(338, "Cold War"),
CONTACT(339, "Contact!"),
CREATURE_OF_FENKENSTRAIN(340, "Creature of Fenkenstrain"),
DARKNESS_OF_HALLOWVALE(341, "Darkness of Hallowvale"),
DEATH_PLATEAU(342, "Death Plateau"),
DEATH_TO_THE_DORGESHUUN(343, "Death to the Dorgeshuun"),
THE_DEPTHS_OF_DESPAIR(344, "The Depths of Despair"),
DESERT_TREASURE(345, "Desert Treasure"),
DEVIOUS_MINDS(346, "Devious Minds"),
THE_DIG_SITE(347, "The Dig Site"),
DRAGON_SLAYER_II(348, "Dragon Slayer II"),
DREAM_MENTOR(349, "Dream Mentor"),
DRUIDIC_RITUAL(350, "Druidic Ritual"),
DWARF_CANNON(351, "Dwarf Cannon"),
EADGARS_RUSE(352, "Eadgar's Ruse"),
EAGLES_PEAK(353, "Eagles' Peak"),
ELEMENTAL_WORKSHOP_I(354, "Elemental Workshop I"),
ELEMENTAL_WORKSHOP_II(355, "Elemental Workshop II"),
ENAKHRAS_LAMENT(356, "Enakhra's Lament"),
ENLIGHTENED_JOURNEY(357, "Enlightened Journey"),
THE_EYES_OF_GLOUPHRIE(358, "The Eyes of Glouphrie"),
FAIRYTALE_I__GROWING_PAINS(359, "Fairytale I - Growing Pains"),
FAIRYTALE_II__CURE_A_QUEEN(360, "Fairytale II - Cure a Queen"),
FAMILY_CREST(361, "Family Crest"),
THE_FEUD(362, "The Feud"),
FIGHT_ARENA(363, "Fight Arena"),
FISHING_CONTEST(364, "Fishing Contest"),
FORGETTABLE_TALE(365, "Forgettable Tale..."),
BONE_VOYAGE(366, "Bone Voyage"),
THE_FREMENNIK_ISLES(367, "The Fremennik Isles"),
THE_FREMENNIK_TRIALS(368, "The Fremennik Trials"),
GARDEN_OF_TRANQUILLITY(369, "Garden of Tranquillity"),
GERTRUDES_CAT(370, "Gertrude's Cat"),
GHOSTS_AHOY(371, "Ghosts Ahoy"),
THE_GIANT_DWARF(372, "The Giant Dwarf"),
THE_GOLEM(373, "The Golem"),
THE_GRAND_TREE(374, "The Grand Tree"),
THE_GREAT_BRAIN_ROBBERY(375, "The Great Brain Robbery"),
GRIM_TALES(376, "Grim Tales"),
THE_HAND_IN_THE_SAND(377, "The Hand in the Sand"),
HAUNTED_MINE(378, "Haunted Mine"),
HAZEEL_CULT(379, "Hazeel Cult"),
HEROES_QUEST(380, "Heroes' Quest"),
HOLY_GRAIL(381, "Holy Grail"),
HORROR_FROM_THE_DEEP(382, "Horror from the Deep"),
ICTHLARINS_LITTLE_HELPER(383, "Icthlarin's Little Helper"),
IN_AID_OF_THE_MYREQUE(384, "In Aid of the Myreque"),
IN_SEARCH_OF_THE_MYREQUE(385, "In Search of the Myreque"),
JUNGLE_POTION(386, "Jungle Potion"),
KINGS_RANSOM(387, "King's Ransom"),
LEGENDS_QUEST(388, "Legends' Quest"),
LOST_CITY(389, "Lost City"),
THE_LOST_TRIBE(390, "The Lost Tribe"),
LUNAR_DIPLOMACY(391, "Lunar Diplomacy"),
MAKING_FRIENDS_WITH_MY_ARM(392, "Making Friends with My Arm"),
MAKING_HISTORY(393, "Making History"),
MERLINS_CRYSTAL(394, "Merlin's Crystal"),
MONKEY_MADNESS_I(395, "Monkey Madness I"),
MONKEY_MADNESS_II(396, "Monkey Madness II"),
MONKS_FRIEND(397, "Monk's Friend"),
MOUNTAIN_DAUGHTER(398, "Mountain Daughter"),
MOURNINGS_END_PART_I(399, "Mourning's End Part I"),
MOURNINGS_END_PART_II(400, "Mourning's End Part II"),
MURDER_MYSTERY(401, "Murder Mystery"),
MY_ARMS_BIG_ADVENTURE(402, "My Arm's Big Adventure"),
NATURE_SPIRIT(403, "Nature Spirit"),
OBSERVATORY_QUEST(404, "Observatory Quest"),
OLAFS_QUEST(405, "Olaf's Quest"),
ONE_SMALL_FAVOUR(406, "One Small Favour"),
PLAGUE_CITY(407, "Plague City"),
PRIEST_IN_PERIL(408, "Priest in Peril"),
THE_QUEEN_OF_THIEVES(409, "The Queen of Thieves"),
RAG_AND_BONE_MAN(410, "Rag and Bone Man"),
RAG_AND_BONE_MAN_II(411, "Rag and Bone Man II"),
RATCATCHERS(412, "Ratcatchers"),
RECIPE_FOR_DISASTER(413, "Recipe for Disaster"),
RECRUITMENT_DRIVE(414, "Recruitment Drive"),
REGICIDE(415, "Regicide"),
ROVING_ELVES(416, "Roving Elves"),
ROYAL_TROUBLE(417, "Royal Trouble"),
RUM_DEAL(418, "Rum Deal"),
SCORPION_CATCHER(419, "Scorpion Catcher"),
SEA_SLUG(420, "Sea Slug"),
SHADES_OF_MORTTON(421, "Shades of Mort'ton"),
SHADOW_OF_THE_STORM(422, "Shadow of the Storm"),
SHEEP_HERDER(423, "Sheep Herder"),
SHILO_VILLAGE(424, "Shilo Village"),
THE_SLUG_MENACE(425, "The Slug Menace"),
A_SOULS_BANE(426, "A Soul's Bane"),
SPIRITS_OF_THE_ELID(427, "Spirits of the Elid"),
SWAN_SONG(428, "Swan Song"),
TAI_BWO_WANNAI_TRIO(429, "Tai Bwo Wannai Trio"),
A_TAIL_OF_TWO_CATS(430, "A Tail of Two Cats"),
TALE_OF_THE_RIGHTEOUS(431, "Tale of the Righteous"),
A_TASTE_OF_HOPE(432, "A Taste of Hope"),
TEARS_OF_GUTHIX(433, "Tears of Guthix"),
TEMPLE_OF_IKOV(434, "Temple of Ikov"),
THRONE_OF_MISCELLANIA(435, "Throne of Miscellania"),
THE_TOURIST_TRAP(436, "The Tourist Trap"),
TOWER_OF_LIFE(437, "Tower of Life"),
TREE_GNOME_VILLAGE(438, "Tree Gnome Village"),
TRIBAL_TOTEM(439, "Tribal Totem"),
TROLL_ROMANCE(440, "Troll Romance"),
TROLL_STRONGHOLD(441, "Troll Stronghold"),
UNDERGROUND_PASS(442, "Underground Pass"),
CLIENT_OF_KOUREND(443, "Client of Kourend"),
WANTED(444, "Wanted!"),
WATCHTOWER(445, "Watchtower"),
WATERFALL_QUEST(446, "Waterfall Quest"),
WHAT_LIES_BELOW(447, "What Lies Below"),
WITCHS_HOUSE(448, "Witch's House"),
ZOGRE_FLESH_EATERS(449, "Zogre Flesh Eaters"),
THE_ASCENT_OF_ARCEUUS(542, "The Ascent of Arceuus"),
THE_FORSAKEN_TOWER(543, "The Forsaken Tower"),
SONG_OF_THE_ELVES(603, "Song of the Elves"),
THE_FREMENNIK_EXILES(718, "The Fremennik Exiles"),
//Miniquests
ENTER_THE_ABYSS(319, "Enter the Abyss"),
ARCHITECTURAL_ALLIANCE(320, "Architectural Alliance"),
BEAR_YOUR_SOUL(321, "Bear your Soul"),
ALFRED_GRIMHANDS_BARCRAWL(322, "Alfred Grimhand's Barcrawl"),
CURSE_OF_THE_EMPTY_LORD(323, "Curse of the Empty Lord"),
ENCHANTED_KEY(324, "Enchanted Key"),
THE_GENERALS_SHADOW(325, "The General's Shadow"),
SKIPPY_AND_THE_MOGRES(326, "Skippy and the Mogres"),
THE_MAGE_ARENA(327, "The Mage Arena"),
LAIR_OF_TARN_RAZORLOR(328, "Lair of Tarn Razorlor"),
FAMILY_PEST(329, "Family Pest"),
THE_MAGE_ARENA_II(330, "The Mage Arena II"),
IN_SEARCH_OF_KNOWLEDGE(602, "In Search of Knowledge");
@Getter
private final int id;
@Getter
private final String name;
public QuestState getState(Client client)
{
client.runScript(ScriptID.QUESTLIST_PROGRESS, id);
switch (client.getIntStack()[0])
{
case 2:
return QuestState.FINISHED;
case 1:
return QuestState.NOT_STARTED;
default:
return QuestState.IN_PROGRESS;
}
}
} |
package sae.core.persistence;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;
import br.ufes.inf.nemo.util.ejb3.persistence.BaseJPADAO;
import sae.core.domain.CursoRealizado;
import sae.core.domain.CursoRealizado_;
import sae.core.domain.Egresso;
@Stateless
public class CursoRealizadoJPADAO extends BaseJPADAO<CursoRealizado> implements CursoRealizadoDAO{
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName="Sae")
private EntityManager entityManager;
@Override
public Class<CursoRealizado> getDomainClass() {
return CursoRealizado.class;
}
@Override
protected EntityManager getEntityManager() {
return entityManager;
}
@Override
protected List<Order> getOrderList(CriteriaBuilder cb, Root<CursoRealizado> root) {
List<Order> orderList = new ArrayList<Order>();
orderList.add(cb.asc(root.get(CursoRealizado_.curso.getName())));
return orderList;
}
@Override
public List<CursoRealizado> retrieveMyCursos(Egresso egresso){
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CursoRealizado> cq = cb.createQuery(getDomainClass());
Root<CursoRealizado> root = cq.from(getDomainClass());
cq.where(cb.equal(root.get(CursoRealizado_.egresso),egresso));
cq.select(root);
applyOrdering(cb, root, cq);
List<CursoRealizado> result = em.createQuery(cq).getResultList();
return result;
}
} |
package nl.mpi.kinnate.ui;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeContainer;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.ui.ArbilTable;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.ArbilWindowManager;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.KinTermSavePanel;
import nl.mpi.kinnate.kindata.GraphSorter;
import nl.mpi.kinnate.kindata.VisiblePanelSetting;
import nl.mpi.kinnate.kindata.VisiblePanelSetting.PanelType;
import nl.mpi.kinnate.svg.GraphPanel;
import nl.mpi.kinnate.SavePanel;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.entityindexer.EntityService;
import nl.mpi.kinnate.entityindexer.EntityServiceException;
import nl.mpi.kinnate.entityindexer.QueryParser;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
import nl.mpi.kinnate.kintypestrings.KinTypeStringConverter;
import nl.mpi.kinnate.kintypestrings.ParserHighlight;
public class KinDiagramPanel extends JPanel implements SavePanel, KinTermSavePanel, ArbilDataNodeContainer {
private EntityCollection entityCollection;
private KinTypeStringInput kinTypeStringInput;
private GraphPanel graphPanel;
private GraphSorter graphSorter;
private EgoSelectionPanel egoSelectionPanel;
private HidePane kinTermHidePane;
private HidePane kinTypeHidePane;
private KinTermTabPane kinTermPanel;
private EntityService entityIndex;
private JProgressBar progressBar;
public ArbilTable imdiTable;
private HashMap<UniqueIdentifier, ArbilDataNode> registeredArbilDataNode;
private String defaultString = "# The kin type strings entered here will determine how the entities show on the graph below\n";
public static String defaultGraphString = "# The kin type strings entered here will determine how the entities show on the graph below\n"
+ "# Enter one string per line.\n"
//+ "# By default all relations of the selected entity will be shown.\n"
+ "# for example:\n"
// + "EmWMMM\n"
// + "E:1:FFE\n"
// + "EmWMMM:1:\n"
// + "E:1:FFE\n"
+ "Em:Charles II of Spain:W:Marie Louise d'Orlans\n"
+ "Em:Charles II of Spain:F:Philip IV of Spain:F:Philip III of Spain:F:Philip II of Spain:F:Charles V, Holy Roman Emperor:F:Philip I of Castile\n"
+ "Em:Charles II of Spain:M:Mariana of Austria:M:Maria Anna of Spain:M:Margaret of Austria:M:Maria Anna of Bavaria\n"
+ "M:Mariana of Austria:F:Ferdinand III, Holy Roman Emperor:\n"
+ "F:Philip IV of Spain:M:Margaret of Austria\n"
+ "F:Ferdinand III, Holy Roman Emperor:\n"
+ "M:Maria Anna of Spain:\n"
+ "F:Philip III of Spain\n"
+ "M:Margaret of Austria\n"
+ "\n";
// + "FS:1:BSSWMDHFF:1:\n"
// + "M:2:SSDHMFM:2:\n"
// + "F:3:SSDHMF:3:\n"
// + "E=[Bob]MFM\n"
// + "E=[Bob]MZ\n"
// + "E=[Bob]F\n"
// + "E=[Bob]M\n"
// + "E=[Bob]S";
// private String kinTypeStrings[] = new String[]{};
public KinDiagramPanel(File existingFile) {
entityCollection = new EntityCollection();
progressBar = new JProgressBar();
EntityData[] svgStoredEntities = null;
graphPanel = new GraphPanel(this);
kinTypeStringInput = new KinTypeStringInput(defaultString);
if (existingFile != null && existingFile.exists()) {
svgStoredEntities = graphPanel.readSvg(existingFile);
String kinTermContents = null;
for (String currentKinTypeString : graphPanel.getKinTypeStrigs()) {
if (currentKinTypeString.trim().length() > 0) {
if (kinTermContents == null) {
kinTermContents = "";
} else {
kinTermContents = kinTermContents + "\n";
}
kinTermContents = kinTermContents + currentKinTypeString.trim();
}
}
kinTypeStringInput.setText(kinTermContents);
} else {
graphPanel.generateDefaultSvg();
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTerms, 150, false);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.ArchiveLinker, 150, false);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.DiagramTree, 150, true);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.EntitySearch, 150, false);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.IndexerSettings, 150, false);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.KinTypeStrings, 150, false);
graphPanel.dataStoreSvg.setPanelState(VisiblePanelSetting.PanelType.MetaData, 150, true);
}
this.setLayout(new BorderLayout());
ArbilTableModel imdiTableModel = new ArbilTableModel();
graphPanel.setArbilTableModel(imdiTableModel);
progressBar.setVisible(false);
graphPanel.add(progressBar, BorderLayout.PAGE_START);
imdiTable = new ArbilTable(imdiTableModel, "Selected Nodes");
TableCellDragHandler tableCellDragHandler = new TableCellDragHandler();
imdiTable.setTransferHandler(tableCellDragHandler);
imdiTable.setDragEnabled(true);
registeredArbilDataNode = new HashMap<UniqueIdentifier, ArbilDataNode>();
egoSelectionPanel = new EgoSelectionPanel(imdiTable, graphPanel);
kinTermPanel = new KinTermTabPane(this, graphPanel.getkinTermGroups());
// kinTypeStringInput.setText(defaultString);
JPanel kinGraphPanel = new JPanel(new BorderLayout());
kinTypeHidePane = new HidePane(HidePane.HidePanePosition.top, 0);
IndexerParametersPanel indexerParametersPanel = new IndexerParametersPanel(this, graphPanel, tableCellDragHandler);
JPanel advancedPanel = new JPanel(new BorderLayout());
JScrollPane tableScrollPane = new JScrollPane(imdiTable);
advancedPanel.add(tableScrollPane, BorderLayout.CENTER);
//HidePane indexParamHidePane = new HidePane(HidePane.HidePanePosition.right, 0);
//advancedPanel.add(indexParamHidePane, BorderLayout.LINE_END);
HidePane tableHidePane = new HidePane(HidePane.HidePanePosition.bottom, 0);
KinDragTransferHandler dragTransferHandler = new KinDragTransferHandler(this);
graphPanel.setTransferHandler(dragTransferHandler);
egoSelectionPanel.setTransferHandler(dragTransferHandler);
EntitySearchPanel entitySearchPanel = new EntitySearchPanel(entityCollection, graphPanel, imdiTable);
entitySearchPanel.setTransferHandler(dragTransferHandler);
HidePane egoSelectionHidePane = new HidePane(HidePane.HidePanePosition.left, 0);
kinTermHidePane = new HidePane(HidePane.HidePanePosition.right, 0);
for (VisiblePanelSetting panelSetting : graphPanel.dataStoreSvg.getVisiblePanels()) {
switch (panelSetting.getPanelType()) {
case ArchiveLinker:
panelSetting.setTargetPanel(kinTermHidePane, new ArchiveEntityLinkerPanel(imdiTable, dragTransferHandler), "Archive Linker");
break;
case DiagramTree:
panelSetting.setTargetPanel(egoSelectionHidePane, egoSelectionPanel, "Diagram Tree");
break;
case EntitySearch:
panelSetting.setTargetPanel(egoSelectionHidePane, entitySearchPanel, "Search Entities");
break;
case IndexerSettings:
panelSetting.setTargetPanel(tableHidePane, indexerParametersPanel, "Indexer Parameters");
break;
case KinTerms:
panelSetting.setTargetPanel(kinTermHidePane, kinTermPanel, "Kin Terms");
break;
case KinTypeStrings:
panelSetting.setTargetPanel(kinTypeHidePane, new JScrollPane(kinTypeStringInput), "Kin Type Strings");
break;
case MetaData:
panelSetting.setTargetPanel(tableHidePane, advancedPanel, "Metadata");
break;
}
}
kinGraphPanel.add(kinTypeHidePane, BorderLayout.PAGE_START);
kinGraphPanel.add(egoSelectionHidePane, BorderLayout.LINE_START);
kinGraphPanel.add(graphPanel, BorderLayout.CENTER);
kinGraphPanel.add(kinTermHidePane, BorderLayout.LINE_END);
kinGraphPanel.add(tableHidePane, BorderLayout.PAGE_END);
this.add(kinGraphPanel);
entityIndex = new QueryParser(svgStoredEntities);
graphSorter = new GraphSorter();
kinTypeStringInput.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
synchronized (e) {
redrawIfKinTermsChanged();
}
}
});
}
public void redrawIfKinTermsChanged() {
if (kinTypeStringInput.hasChanges()) {
graphPanel.setKinTypeStrigs(kinTypeStringInput.getCurrentStrings());
drawGraph();
}
}
boolean graphThreadRunning = false;
boolean graphUpdateRequired = false;
public synchronized void drawGraph() {
graphUpdateRequired = true;
if (!graphThreadRunning) {
graphThreadRunning = true;
new Thread() {
@Override
public void run() {
// todo: there are probably other synchronisation issues to resolve here.
while (graphUpdateRequired) {
graphUpdateRequired = false;
try {
String[] kinTypeStrings = graphPanel.getKinTypeStrigs();
ParserHighlight[] parserHighlight = new ParserHighlight[kinTypeStrings.length];
progressBar.setValue(0);
progressBar.setVisible(true);
boolean isQuery = false;
if (!graphPanel.dataStoreSvg.egoEntities.isEmpty() || !graphPanel.dataStoreSvg.requiredEntities.isEmpty()) {
isQuery = true;
} else {
for (String currentLine : kinTypeStrings) {
if (currentLine.contains("=")) {
isQuery = true;
break;
}
}
}
if (isQuery) {
EntityData[] graphNodes = entityIndex.processKinTypeStrings(null, graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, kinTypeStrings, parserHighlight, graphPanel.getIndexParameters(), progressBar);
graphSorter.setEntitys(graphNodes);
// register interest Arbil updates and update the graph when data is edited in the table
registerCurrentNodes(graphSorter.getDataNodes());
graphPanel.drawNodes(graphSorter);
egoSelectionPanel.setTreeNodes(graphPanel.dataStoreSvg.egoEntities, graphPanel.dataStoreSvg.requiredEntities, graphSorter.getDataNodes());
} else {
KinTypeStringConverter graphData = new KinTypeStringConverter();
graphData.readKinTypes(kinTypeStrings, graphPanel.getkinTermGroups(), graphPanel.dataStoreSvg, parserHighlight);
graphPanel.drawNodes(graphData);
egoSelectionPanel.setTransientNodes(graphData.getDataNodes());
// KinDiagramPanel.this.doLayout();
}
kinTypeStringInput.highlightKinTerms(parserHighlight, kinTypeStrings);
// kinTypeStrings = graphPanel.getKinTypeStrigs();
} catch (EntityServiceException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to load all entities required", "Draw Graph");
}
progressBar.setVisible(false);
}
graphThreadRunning = false;
}
}.start();
}
}
// @Deprecated
// public void setDisplayNodes(String typeString, String[] egoIdentifierArray) {
// // todo: should this be replaced by the required nodes?
// if (kinTypeStringInput.getText().equals(defaultString)) {
// kinTypeStringInput.setText("");
// String kinTermContents = kinTypeStringInput.getText();
// for (String currentId : egoIdentifierArray) {
// kinTermContents = kinTermContents + typeString + "=[" + currentId + "]\n";
// kinTypeStringInput.setText(kinTermContents);
// graphPanel.setKinTypeStrigs(kinTypeStringInput.getText().split("\n"));
//// kinTypeStrings = graphPanel.getKinTypeStrigs();
// drawGraph();
public void setEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities = new HashSet<UniqueIdentifier>(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeEgoNodes(UniqueIdentifier[] egoIdentifierArray) {
// todo: this does not update the ego highlight on the graph and the trees.
graphPanel.dataStoreSvg.egoEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void addRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public void removeRequiredNodes(UniqueIdentifier[] egoIdentifierArray) {
graphPanel.dataStoreSvg.requiredEntities.removeAll(Arrays.asList(egoIdentifierArray));
drawGraph();
}
public boolean hasSaveFileName() {
return graphPanel.hasSaveFileName();
}
public File getFileName() {
return graphPanel.getFileName();
}
public boolean requiresSave() {
return graphPanel.requiresSave();
}
public void setRequiresSave() {
graphPanel.setRequiresSave();
}
public void saveToFile() {
graphPanel.saveToFile();
}
public void saveToFile(File saveFile) {
graphPanel.saveToFile(saveFile);
}
public void updateGraph() {
this.drawGraph();
}
public void exportKinTerms() {
kinTermPanel.getSelectedKinTermPanel().exportKinTerms();
}
public void hideShow() {
kinTermHidePane.toggleHiddenState();
}
public void importKinTerms() {
kinTermPanel.getSelectedKinTermPanel().importKinTerms();
}
public void addKinTermGroup() {
graphPanel.addKinTermGroup();
kinTermPanel.updateKinTerms(graphPanel.getkinTermGroups());
}
public VisiblePanelSetting[] getVisiblePanels() {
return graphPanel.dataStoreSvg.getVisiblePanels();
}
public void setPanelState(PanelType panelType, int panelWidth, boolean panelVisible) {
// todo: show / hide the requested panel
graphPanel.dataStoreSvg.setPanelState(panelType, panelWidth, panelVisible);
}
public void setSelectedKinTypeSting(String kinTypeStrings) {
kinTermPanel.setAddableKinTypeSting(kinTypeStrings);
}
public boolean isHidden() {
return kinTermHidePane.isHidden();
}
public EntityData[] getGraphEntities() {
return graphSorter.getDataNodes();
}
private void registerCurrentNodes(EntityData[] currentEntities) {
// todo: i think this is resolved but double check the issue where arbil nodes update frequency is too high and breaks basex
// todo: load the nodes in the KinDataNode when putting them in the table and pass on the reload requests here when they occur
// todo: replace the data node registering process.
// for (EntityData entityData : currentEntities) {
// ArbilDataNode arbilDataNode = null;
// if (!registeredArbilDataNode.containsKey(entityData.getUniqueIdentifier())) {
// try {
// String metadataPath = entityData.getEntityPath();
// if (metadataPath != null) {
// // todo: this should not load the arbil node only register an interest
//// and this needs to be tested
// arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNodeWithoutLoading(new URI(metadataPath));
// registeredArbilDataNode.put(entityData.getUniqueIdentifier(), arbilDataNode);
// arbilDataNode.registerContainer(this);
// // todo: keep track of registered nodes and remove the unrequired ones here
// } else {
// GuiHelper.linorgBugCatcher.logError(new Exception("Error getting path for: " + entityData.getUniqueIdentifier().getAttributeIdentifier() + " : " + entityData.getLabel()[0]));
// } catch (URISyntaxException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
// } else {
// arbilDataNode = registeredArbilDataNode.get(entityData.getUniqueIdentifier());
// if (arbilDataNode != null) {
// entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false);
}
public void entityRelationsChanged(UniqueIdentifier[] selectedIdentifiers) {
// this method does not need to update the database because the link changing process has already done that
// remove the stored graph locations of the selected ids
graphPanel.clearEntityLocations(selectedIdentifiers);
graphPanel.getIndexParameters().valuesChanged = true;
drawGraph();
}
public void dataNodeIconCleared(ArbilNode arbilNode) {
// todo: this needs to be updated to be multi threaded so users can link or save multiple nodes at once
boolean dataBaseRequiresUpdate = false;
boolean redrawRequired = false;
if (arbilNode instanceof ArbilDataNode) {
ArbilDataNode arbilDataNode = (ArbilDataNode) arbilNode;
// find the entity data for this arbil data node
for (EntityData entityData : graphSorter.getDataNodes()) {
try {
String entityPath = entityData.getEntityPath();
if (entityPath != null && arbilDataNode.getURI().equals(new URI(entityPath))) {
// check if the metadata has been changed
// todo: something here fails to act on multiple nodes that have changed (it is the db update that was missed)
if (entityData.metadataRequiresSave && !arbilDataNode.getNeedsSaveToDisk(false)) {
dataBaseRequiresUpdate = true;
redrawRequired = true;
}
// clear or set the needs save flag
entityData.metadataRequiresSave = arbilDataNode.getNeedsSaveToDisk(false);
if (entityData.metadataRequiresSave) {
redrawRequired = true;
}
}
} catch (URISyntaxException exception) {
GuiHelper.linorgBugCatcher.logError(exception);
}
}
if (dataBaseRequiresUpdate) {
entityCollection.updateDatabase(arbilDataNode.getURI());
graphPanel.getIndexParameters().valuesChanged = true;
}
}
if (redrawRequired) {
drawGraph();
}
}
public void dataNodeChildAdded(ArbilNode destination, ArbilNode newChildNode) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void dataNodeRemoved(ArbilNode adn) {
throw new UnsupportedOperationException("Not supported yet.");
}
} |
package nl.mpi.kinnate.ui.menu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
public class WindowMenu extends JMenu implements ActionListener {
AbstractDiagramManager diagramWindowManager;
public WindowMenu(AbstractDiagramManager diagramWindowManager, final Component parentComponent) {
this.setText("Window");
this.diagramWindowManager = diagramWindowManager;
this.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent evt) {
}
public void menuDeselected(MenuEvent evt) {
}
public void menuSelected(MenuEvent evt) {
initMenu(parentComponent);
}
});
}
private void initMenu(Component parentComponent) {
this.removeAll();
int diagramCount = diagramWindowManager.getAllDiagrams().length;
int selectedDiagramIndex = diagramWindowManager.getSavePanelIndex(parentComponent);
for (int diagramCounter = 0; diagramCounter < diagramCount; diagramCounter++) {
JCheckBoxMenuItem currentMenuItem = new JCheckBoxMenuItem(diagramWindowManager.getSavePanelTitle(diagramCounter));
currentMenuItem.setActionCommand(Integer.toString(diagramCounter));
currentMenuItem.addActionListener(this);
currentMenuItem.setSelected(diagramCounter == selectedDiagramIndex);
this.add(currentMenuItem);
}
}
public void actionPerformed(ActionEvent e) {
int diagramIndex = Integer.valueOf(e.getActionCommand());
diagramWindowManager.setSelectedDiagram(diagramIndex);
}
} |
package net.mgsx.kit.config;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map.Entry;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import com.badlogic.gdx.utils.Array;
import com.google.common.base.Predicate;
import net.mgsx.game.core.helpers.ArrayHelper;
import net.mgsx.game.core.helpers.ReflectionHelper;
import net.mgsx.game.core.meta.ClassRegistry;
public class ReflectionClassRegistry extends ClassRegistry
{
public static final String kitCore = "net.mgsx.game.core";
public static final String kitCorePlugin = "net.mgsx.game.plugins.core";
public static final String kitBehaviorTreePlugin = "net.mgsx.game.plugins.btree"; // XXX necessary to perform reflection on custom tasks ... maybe because of EntityLeafTask ...
public static final String kitPlugins = "net.mgsx.game.plugins";
public static final String behaviorTree = "com.badlogic.gdx.ai.btree";
private Reflections reflections;
public ReflectionClassRegistry(final String ...packages)
{
Collection<URL> urls = new ArrayList<URL>();
for(String url : packages){
urls.addAll(ClasspathHelper.getUrlsForPackagePrefix(url));
}
reflections = new Reflections(
new ConfigurationBuilder().filterInputsBy(new Predicate<String>() {
@Override
public boolean apply(String input) {
// executed in separate thread
boolean match = false;
for(String name : packages){
if(input.startsWith(name)){
match = true;
break;
}
}
return match;
}
})
.setUrls(urls)
.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));
}
@Override
public Array<Class> getSubTypesOf(Class type) {
return ArrayHelper.array(reflections.getSubTypesOf(type));
}
@Override
public Array<Class<?>> getTypesAnnotatedWith(Class<? extends Annotation> annotation) {
return ArrayHelper.array(reflections.getTypesAnnotatedWith(annotation));
}
@Override
public Array<Class<?>> getClasses() {
Array<Class<?>> r = new Array<Class<?>>();
for(Entry<String, String> entry : reflections.getStore().get(TypeAnnotationsScanner.class).entries()){
r.add(ReflectionHelper.forName(entry.getValue()));
}
return r;
}
} |
package com.songus.songus;
import android.app.Application;
import android.graphics.Typeface;
public class Songus extends Application {
/*
Global Fields Here
*/
public static Typeface roboto;
public static Typeface roboto_bold;
private static SongQueue songQueue;
@Override
public void onCreate() {
super.onCreate();
/*
Initialize here
*/
roboto = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
roboto_bold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
songQueue = new SongQueue();
}
/*
* Global Methods here.
*/
public SongQueue getSongQueue(){
return songQueue;
}
} |
package yuku.alkitab.base.widget;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import yuku.afw.App;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.afw.widget.EasyAdapter;
import yuku.alkitab.R;
import yuku.alkitab.base.ac.ColorSettingsActivity;
import yuku.alkitab.base.ac.FontManagerActivity;
import yuku.alkitab.base.util.FontManager;
public class TextAppearancePanel {
public static final String TAG = TextAppearancePanel.class.getSimpleName();
public interface Listener {
void onValueChanged();
}
final Activity activity;
final LayoutInflater inflater;
final FrameLayout parent;
final Listener listener;
final View content;
final int reqcodeGetFonts;
final int reqcodeCustomColors;
Spinner cbTypeface;
TextView lTextSize;
SeekBar sbTextSize;
TextView lLineSpacing;
SeekBar sbLineSpacing;
ToggleButton cBold;
Spinner cbColorTheme;
View bCustomColors;
TypefaceAdapter typefaceAdapter;
ColorThemeAdapter colorThemeAdapter;
boolean shown = false;
boolean initialColorThemeSelection = true;
public TextAppearancePanel(Activity activity, LayoutInflater inflater, FrameLayout parent, Listener listener, int reqcodeGetFonts, int reqcodeCustomColors) {
this.activity = activity;
this.inflater = inflater;
this.parent = parent;
this.listener = listener;
this.reqcodeGetFonts = reqcodeGetFonts;
this.reqcodeCustomColors = reqcodeCustomColors;
this.content = inflater.inflate(R.layout.panel_text_appearance, parent, false);
cbTypeface = V.get(content, R.id.cbTypeface);
cBold = V.get(content, R.id.cBold);
lTextSize = V.get(content, R.id.lTextSize);
sbTextSize = V.get(content, R.id.sbTextSize);
lLineSpacing = V.get(content, R.id.lLineSpacing);
sbLineSpacing = V.get(content, R.id.sbLineSpacing);
cbColorTheme = V.get(content, R.id.cbColorTheme);
bCustomColors = V.get(content, R.id.bCustomColors);
cbTypeface.setAdapter(typefaceAdapter = new TypefaceAdapter());
cbTypeface.setOnItemSelectedListener(cbTypeface_itemSelected);
sbTextSize.setOnSeekBarChangeListener(sbTextSize_seekBarChange);
sbLineSpacing.setOnSeekBarChangeListener(sbLineSpacing_seekBarChange);
cBold.setOnCheckedChangeListener(cBold_checkedChange);
cbColorTheme.setAdapter(colorThemeAdapter = new ColorThemeAdapter());
cbColorTheme.setOnItemSelectedListener(cbColorTheme_itemSelected);
bCustomColors.setOnClickListener(bCustomColors_click);
displayValues();
}
void displayValues() {
{
int selectedPosition = typefaceAdapter.getPositionByName(Preferences.getString(App.context.getString(R.string.pref_jenisHuruf_key)));
if (selectedPosition >= 0) {
cbTypeface.setSelection(selectedPosition);
}
}
boolean bold = Preferences.getBoolean(App.context.getString(R.string.pref_boldHuruf_key), false);
cBold.setChecked(bold);
float textSize = Preferences.getFloat(App.context.getString(R.string.pref_ukuranHuruf2_key), 17.f);
sbTextSize.setProgress((int) ((textSize - 2.f) * 2));
displayTextSizeText(textSize);
float lineSpacing = Preferences.getFloat(App.context.getString(R.string.pref_lineSpacingMult_key), 1.2f);
sbLineSpacing.setProgress(Math.round((lineSpacing - 1.f) * 20.f));
displayLineSpacingText(lineSpacing);
{
int[] currentColors = ColorThemes.getCurrentColors();
int selectedPosition = colorThemeAdapter.getPositionByColors(currentColors);
if (selectedPosition == -1) {
cbColorTheme.setSelection(colorThemeAdapter.getPositionOfCustomColors());
} else {
cbColorTheme.setSelection(selectedPosition);
}
colorThemeAdapter.notifyDataSetChanged();
}
}
public void show() {
if (shown) return;
parent.addView(content, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));
shown = true;
}
public void hide() {
if (!shown) return;
parent.removeView(content);
shown = false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == reqcodeGetFonts) {
typefaceAdapter.reload();
displayValues();
} else if (requestCode == reqcodeCustomColors) {
displayValues();
}
}
AdapterView.OnItemSelectedListener cbTypeface_itemSelected = new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
String name = typefaceAdapter.getNameByPosition(position);
if (name == null) {
activity.startActivityForResult(FontManagerActivity.createIntent(), reqcodeGetFonts);
} else {
Preferences.setString(App.context.getString(R.string.pref_jenisHuruf_key), name);
listener.onValueChanged();
}
}
@Override public void onNothingSelected(AdapterView<?> parent) {}
};
AdapterView.OnItemSelectedListener cbColorTheme_itemSelected = new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
if (initialColorThemeSelection) {
initialColorThemeSelection = false;
return;
}
if (position != colorThemeAdapter.getPositionOfCustomColors()) {
int[] colors = colorThemeAdapter.getColorsAtPosition(position);
ColorThemes.setCurrentColors(colors);
listener.onValueChanged();
colorThemeAdapter.notifyDataSetChanged();
} else {
// we are at the last item
}
}
@Override public void onNothingSelected(AdapterView<?> parent) {}
};
View.OnClickListener bCustomColors_click = new View.OnClickListener() {
@Override public void onClick(View v) {
activity.startActivityForResult(ColorSettingsActivity.createIntent(), reqcodeCustomColors);
}
};
SeekBar.OnSeekBarChangeListener sbTextSize_seekBarChange = new SeekBar.OnSeekBarChangeListener() {
@Override public void onStopTrackingTouch(SeekBar seekBar) {}
@Override public void onStartTrackingTouch(SeekBar seekBar) {}
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float textSize = progress * 0.5f + 2.f;
Preferences.setFloat(App.context.getString(R.string.pref_ukuranHuruf2_key), textSize);
displayTextSizeText(textSize);
listener.onValueChanged();
}
};
void displayTextSizeText(float textSize) {
lTextSize.setText(String.format("%.1f", textSize));
}
SeekBar.OnSeekBarChangeListener sbLineSpacing_seekBarChange = new SeekBar.OnSeekBarChangeListener() {
@Override public void onStopTrackingTouch(SeekBar seekBar) {}
@Override public void onStartTrackingTouch(SeekBar seekBar) {}
@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float lineSpacing = 1.f + progress * 0.05f;
Preferences.setFloat(App.context.getString(R.string.pref_lineSpacingMult_key), lineSpacing);
displayLineSpacingText(lineSpacing);
listener.onValueChanged();
}
};
void displayLineSpacingText(float lineSpacing) {
lLineSpacing.setText(String.format("%.2f", lineSpacing));
}
CompoundButton.OnCheckedChangeListener cBold_checkedChange = new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Preferences.setBoolean(App.context.getString(R.string.pref_boldHuruf_key), isChecked);
listener.onValueChanged();
}
};
class TypefaceAdapter extends EasyAdapter {
List<FontManager.FontEntry> fontEntries;
public TypefaceAdapter() {
reload();
}
public void reload() {
fontEntries = FontManager.getInstalledFonts();
notifyDataSetChanged();
}
@Override public int getCount() {
return 3 + fontEntries.size() + 1;
}
@Override public View newView(int position, ViewGroup parent) {
return inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
}
@Override public void bindView(View view, int position, ViewGroup parent) {
TextView text1 = V.get(view, android.R.id.text1);
if (position < 3) {
text1.setText(new String[] {"Sans-serif", "Serif", "Monospace"}[position]);
text1.setTypeface(new Typeface[] {Typeface.SANS_SERIF, Typeface.SERIF, Typeface.MONOSPACE}[position]);
} else if (position == getCount() - 1) {
text1.setText(App.context.getString(R.string.get_more_fonts));
text1.setTypeface(Typeface.DEFAULT);
} else {
int idx = position - 3;
text1.setText(fontEntries.get(idx).name);
text1.setTypeface(FontManager.typeface(fontEntries.get(idx).name));
}
}
public String getNameByPosition(int position) {
if (position < 3) {
return new String[] {"DEFAULT", "SERIF", "MONOSPACE"}[position];
} else if (position < getCount() - 1) {
int idx = position - 3;
return fontEntries.get(idx).name;
} else {
return null;
}
}
public int getPositionByName(String name) {
if ("DEFAULT".equals(name)) {
return 0;
} else if ("SERIF".equals(name)) {
return 1;
} else if ("MONOSPACE".equals(name)) {
return 2;
} else {
for (int i = 0; i < fontEntries.size(); i++) {
if (fontEntries.get(i).name.equals(name)) {
return i + 3;
}
}
}
return -1;
}
}
class ColorThemeAdapter extends EasyAdapter {
List<int[]> themes;
List<String> themeNames;
public ColorThemeAdapter() {
themes = new ArrayList<int[]>();
for (String themeString: activity.getResources().getStringArray(R.array.pref_temaWarna_value)) {
themes.add(ColorThemes.themeStringToColors(themeString));
}
themeNames = Arrays.asList(activity.getResources().getStringArray(R.array.pref_temaWarna_label));
}
@Override public int getCount() {
return themes.size() + 1;
}
@Override public View newView(int position, ViewGroup parent) {
return new MultiColorView(activity, null);
}
@Override public void bindView(View view, int position, ViewGroup parent) {
MultiColorView mcv = (MultiColorView) view;
mcv.setBgColor(0xff000000);
if (position == getPositionOfCustomColors()) {
mcv.setColors(ColorThemes.getCurrentColors());
} else {
mcv.setColors(themes.get(position));
}
LayoutParams lp = mcv.getLayoutParams();
if (lp == null) {
lp = new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 0);
}
lp.height = (int) (48 * mcv.getResources().getDisplayMetrics().density);
mcv.setLayoutParams(lp);
}
@Override public View newDropDownView(int position, ViewGroup parent) {
return inflater.inflate(android.R.layout.simple_list_item_single_choice, parent, false);
}
@Override public void bindDropDownView(View view, int position, ViewGroup parent) {
TextView text1 = (TextView) view;
if (position != getPositionOfCustomColors()) {
int colors[] = themes.get(position);
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append("" + (position+1));
sb.setSpan(new ForegroundColorSpan(colors[2]), 0, sb.length(), 0);
int sb_len = sb.length();
sb.append(" " + themeNames.get(position));
sb.setSpan(new ForegroundColorSpan(colors[0]), sb_len, sb.length(), 0);
text1.setText(sb);
text1.setBackgroundColor(colors[1]);
} else {
text1.setText(R.string.text_appearance_theme_custom);
text1.setBackgroundColor(0xffffffff);
}
}
public int[] getColorsAtPosition(int position) {
return themes.get(position);
}
public int getPositionByColors(int[] colors) {
for (int i = 0; i < themes.size(); i++) {
if (Arrays.equals(colors, themes.get(i))) {
return i;
}
}
return -1;
}
public int getPositionOfCustomColors() {
return themes.size();
}
}
} |
package yuku.alkitab.yes2.compress;
import java.io.IOException;
import yuku.alkitab.yes2.io.RandomInputStream;
import yuku.bintex.ValueMap;
import yuku.snappy.codec.Snappy;
public class SnappyInputStream extends RandomInputStream {
public final String TAG = SnappyInputStream.class.getSimpleName();
private final Snappy snappy;
private final long baseOffset;
private final int block_size;
private final int[] compressed_block_sizes;
private final int[] compressed_block_offsets;
private int current_block_index = 0;
private int current_block_skip = 0;
private byte[] compressed_buf;
private int uncompressed_block_index = -1;
private byte[] uncompressed_buf;
private int uncompressed_len = -1; // -1 means not initialized
public SnappyInputStream(RandomInputStream input, long baseOffset, int block_size, int[] compressed_block_sizes, int[] compressed_block_offsets) throws IOException {
super(input.getFile());
this.block_size = block_size;
this.snappy = new Snappy.Factory().newInstance();
this.baseOffset = baseOffset;
this.compressed_block_sizes = compressed_block_sizes;
this.compressed_block_offsets = compressed_block_offsets;
this.compressed_buf = new byte[snappy.maxCompressedLength(block_size)];
this.uncompressed_buf = new byte[block_size];
}
@Override public void seek(long n) throws IOException {
int offset = (int) n;
int block_index = offset / block_size;
int block_skip = offset - (block_index * block_size);
this.current_block_index = block_index;
this.current_block_skip = block_skip;
prepareBuffer();
}
private void prepareBuffer() throws IOException {
int block_index = current_block_index;
// if uncompressed_block_index is already equal to the requested block_index
// then we do not need to re-decompress again
if (uncompressed_block_index != block_index) {
super.seek(baseOffset + compressed_block_offsets[block_index]);
super.read(compressed_buf, 0, compressed_block_sizes[block_index]);
uncompressed_len = snappy.decompress(compressed_buf, 0, uncompressed_buf, 0, compressed_block_sizes[block_index]);
if (uncompressed_len < 0) {
throw new IOException("Error in decompressing: " + uncompressed_len);
}
uncompressed_block_index = block_index;
}
}
@Override public int read() throws IOException {
if (uncompressed_len == -1) {
prepareBuffer();
}
int can_read = uncompressed_len - current_block_skip;
if (can_read == 0) {
if (current_block_index >= compressed_block_sizes.length) {
return -1; // EOF
} else {
// need to move to the next block
current_block_index++;
current_block_skip = 0;
prepareBuffer();
}
}
int res = /* need to convert to uint8: */ 0xff & uncompressed_buf[current_block_skip];
current_block_skip++;
return res;
}
@Override public int read(byte[] buffer, int offset, int length) throws IOException {
if (uncompressed_len == -1) {
prepareBuffer();
}
int res = 0;
int want_read = length;
while (want_read > 0) {
int can_read = uncompressed_len - current_block_skip;
if (can_read == 0) {
if (current_block_index >= compressed_block_sizes.length) { // EOF
if (res == 0) return -1; // we didn't manage to read any
return res;
} else {
// need to move to the next block
current_block_index++;
current_block_skip = 0;
prepareBuffer();
can_read = uncompressed_len;
}
}
int will_read = want_read > can_read? can_read: want_read;
System.arraycopy(uncompressed_buf, current_block_skip, buffer, offset, will_read);
current_block_skip += will_read;
offset += will_read;
want_read -= will_read;
res += will_read;
}
return res;
}
@Override public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override public long getFilePointer() throws IOException {
return current_block_index * block_size + current_block_skip;
}
@Override public long skip(long n) throws IOException {
seek(getFilePointer() + n);
return n;
}
public static SnappyInputStream getInstanceFromAttributes(RandomInputStream input, ValueMap sectionAttributes, long sectionContentOffset) throws IOException {
int compressionVersion = sectionAttributes.getInt("compression.version", 0);
if (compressionVersion > 1) {
throw new IOException("Compression version " + compressionVersion + " is not supported");
}
ValueMap compressionInfo = sectionAttributes.getSimpleMap("compression.info");
int block_size = compressionInfo.getInt("block_size");
int[] compressed_block_sizes = compressionInfo.getIntArray("compressed_block_sizes");
int[] compressed_block_offsets = new int[compressed_block_sizes.length + 1];
{ // convert compressed_block_sizes into offsets
int c = 0;
for (int i = 0, len = compressed_block_sizes.length; i < len; i++) {
compressed_block_offsets[i] = c;
c += compressed_block_sizes[i];
}
compressed_block_offsets[compressed_block_sizes.length] = c;
}
return new SnappyInputStream(input, sectionContentOffset, block_size, compressed_block_sizes, compressed_block_offsets);
}
} |
package convwatch;
import java.io.File;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.lang.Double;
public class PerformanceContainer /* extends *//* implements */ {
private long m_nStartTime;
/*
simple helper functions to start/stop a timer, to know how long a process need in milliseconds
*/
public long getStartTime()
{
return System.currentTimeMillis();
}
public void setStartTime(long _nStartTime)
{
m_nStartTime = _nStartTime;
}
/*
return the time, which is done until last startTime()
*/
private long meanTime(long _nCurrentTimer)
{
if (_nCurrentTimer == 0)
{
GlobalLogWriter.get().println("Forgotten to initialise a start timer.");
return 0;
}
long nMeanTime = System.currentTimeMillis();
return nMeanTime - _nCurrentTimer;
}
/*
public long stopTimer()
{
if (m_nStartTime == 0)
{
System.out.println("Forgotten to initialise start timer.");
return 0;
}
long nStopTime = System.currentTimeMillis();
return nStopTime - m_nStartTime;
}
*/
final static int Load = 0;
final static int Store = 1;
final static int Print = 2;
final static int OfficeStart = 3;
final static int StoreAsPDF = 4;
private long m_nTime[];
private String m_sMSOfficeVersion;
public PerformanceContainer()
{
m_nTime = new long[5];
// @todo: is this need?
for (int i=0;i<5;i++)
{
m_nTime[i] = 0;
}
}
public void setTime(int _nIndex, long _nValue)
{
m_nTime[_nIndex] = _nValue;
}
public long getTime(int _nIndex)
{
return m_nTime[_nIndex];
}
public void startTime(int _nIndex)
{
m_nTime[_nIndex] = getStartTime();
}
public void stopTime(int _nIndex)
{
m_nTime[_nIndex] = meanTime(m_nTime[_nIndex]);
}
public String getMSOfficeVersion()
{
return m_sMSOfficeVersion;
}
public void print(FileWriter out) throws java.io.IOException
{
String ls = System.getProperty("line.separator");
out.write("loadtime=" + String.valueOf(m_nTime[ Load ]) + ls);
out.write("storetime=" + String.valueOf(m_nTime[ Store ]) + ls);
out.write("printtime=" + String.valueOf(m_nTime[ Print ]) + ls);
out.write("officestarttime=" + String.valueOf(m_nTime[ OfficeStart ]) + ls);
out.write("storeaspdftime=" + String.valueOf(m_nTime[ StoreAsPDF ]) + ls);
}
public static double stringToDouble(String _sStr)
{
double nValue = 0;
try
{
nValue = Double.parseDouble( _sStr );
}
catch (NumberFormatException e)
{
GlobalLogWriter.get().println("Can't convert string to double " + _sStr);
}
return nValue;
}
public static long secondsToMilliSeconds(double _nSeconds)
{
return (long)(_nSeconds * 1000.0);
}
/*
Helper function, which read some values from a given file
sample of wordinfofile
name=c:\doc-pool\wntmsci\samples\msoffice\word\LineSpacing.doc
WordVersion=11.0
WordStartTime=0.340490102767944
WordLoadTime=0.650935888290405
WordPrintTime=0.580835103988647
*/
public void readWordValuesFromFile(String sFilename)
{
File aFile = new File(sFilename);
if (! aFile.exists())
{
GlobalLogWriter.get().println("couldn't find file " + sFilename);
return;
}
RandomAccessFile aRandomAccessFile = null;
try
{
aRandomAccessFile = new RandomAccessFile(aFile,"r");
String sLine = "";
while (sLine != null)
{
sLine = aRandomAccessFile.readLine();
if ( (sLine != null) &&
(! (sLine.length() < 2) ) &&
(! sLine.startsWith("
{
if (sLine.startsWith("WordStartTime="))
{
String sTime = sLine.substring(14);
m_nTime[OfficeStart] = secondsToMilliSeconds(stringToDouble(sTime));
}
else if (sLine.startsWith("WordLoadTime="))
{
String sTime = sLine.substring(13);
m_nTime[Load] = secondsToMilliSeconds(stringToDouble(sTime));
}
else if (sLine.startsWith("WordPrintTime="))
{
String sTime = sLine.substring(14);
m_nTime[Print] = secondsToMilliSeconds(stringToDouble(sTime));
}
else if (sLine.startsWith("WordVersion="))
{
String sMSOfficeVersion = sLine.substring(12);
m_sMSOfficeVersion = "Word:" + sMSOfficeVersion;
}
else if (sLine.startsWith("ExcelVersion="))
{
String sMSOfficeVersion = sLine.substring(13);
m_sMSOfficeVersion = "Excel:" + sMSOfficeVersion;
}
else if (sLine.startsWith("PowerPointVersion="))
{
String sMSOfficeVersion = sLine.substring(18);
m_sMSOfficeVersion = "PowerPoint:" + sMSOfficeVersion;
}
}
}
}
catch (java.io.FileNotFoundException fne)
{
GlobalLogWriter.get().println("couldn't open file " + sFilename);
GlobalLogWriter.get().println("Message: " + fne.getMessage());
}
catch (java.io.IOException ie)
{
GlobalLogWriter.get().println("Exception while reading file " + sFilename);
GlobalLogWriter.get().println("Message: " + ie.getMessage());
}
try
{
aRandomAccessFile.close();
}
catch (java.io.IOException ie)
{
GlobalLogWriter.get().println("Couldn't close file " + sFilename);
GlobalLogWriter.get().println("Message: " + ie.getMessage());
}
}
public static void main(String[] args) {
/*
BorderRemover a = new BorderRemover();
try
{
a.createNewImageWithoutBorder(args[0], args[1]);
}
catch(java.io.IOException e)
{
System.out.println("Exception caught.");
}
*/
}
} |
package jmetest.renderer.loader;
import com.jme.app.SimpleGame;
import com.jme.scene.model.XMLparser.Converters.Md3ToJme;
import com.jme.scene.model.XMLparser.JmeBinaryReader;
import com.jme.scene.model.XMLparser.BinaryToXML;
import com.jme.scene.Node;
import com.jme.scene.state.TextureState;
import com.jme.util.TextureManager;
import com.jme.image.Texture;
import java.io.*;
import java.net.URL;
public class TestMd3JmeWrite extends SimpleGame{
public static void main(String[] args) {
TestMd3JmeWrite app=new TestMd3JmeWrite();
app.setDialogBehaviour(SimpleGame.FIRSTRUN_OR_NOCONFIGFILE_SHOW_PROPS_DIALOG);
app.start();
}
protected void simpleInitGame() {
Md3ToJme converter=new Md3ToJme();
BinaryToXML btx=new BinaryToXML();
URL laura=null;
laura=TestMd3JmeWrite.class.getClassLoader().getResource("jmetest/data/model/lara/lara_lower.md3");
URL tex=TestMd3JmeWrite.class.getClassLoader().getResource("jmetest/data/model/lara/default.bmp");
ByteArrayOutputStream BO=new ByteArrayOutputStream();
try {
converter.convert(laura.openStream(),BO);
// StringWriter SW=new StringWriter();
// btx.sendBinarytoXML(new ByteArrayInputStream(BO.toByteArray()),SW);
// System.out.println(SW);
JmeBinaryReader jbr=new JmeBinaryReader();
Node r=jbr.loadBinaryFormat(new ByteArrayInputStream(BO.toByteArray()));
TextureState ts=display.getRenderer().getTextureState();
ts.setTexture(TextureManager.loadTexture(tex,Texture.MM_LINEAR,Texture.FM_LINEAR,true));
ts.setEnabled(true);
r.setRenderState(ts);
// r.setLocalScale(.1f);
rootNode.attachChild(r);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package krunch17.launcher;
import edu.wpi.first.wpilibj.command.CommandGroup;
import krunch17.autonomous.AutonSettings;
import krunch17.intake.ExtendIntake;
import krunch17.intake.RollIn;
import krunch17.intake.StopRoller;
import krunch17.util.Wait;
/**
*
* @author Sebastian
*/
public class FireLauncherAutomated extends CommandGroup {
public FireLauncherAutomated() {
addSequential(new Wait(0.004));
addSequential(new ExtendIntake());
addSequential(new Wait(AutonSettings.EXTEND_INTAKE_DELAY + AutonSettings.FIRE_DELAY));
addSequential(new FireLauncher()); // Launcher will retract after fire
}
} |
package lama.sqlite3.gen;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import lama.QueryAdapter;
import lama.Randomly;
import lama.sqlite3.SQLite3Provider.SQLite3GlobalState;
public class SQLite3PragmaGenerator {
private enum Pragma {
APPLICATION_ID,
AUTO_VACUUM,
AUTOMATIC_INDEX,
BUSY_TIMEOUT,
CACHE_SIZE,
CACHE_SPILL_ENABLED,
CACHE_SPILL_SIZE,
/* CASE_SENSITIVE_LIKE */ CELL_SIZE_CHECK, CHECKPOINT_FULLSYNC, DEFAULT_CACHE_SIZE, DEFER_FOREIGN_KEY, /*ENCODING,*/
FOREIGN_KEYS, IGNORE_CHECK_CONSTRAINTS, INCREMENTAL_VACUUM, INTEGRITY_CHECK, JOURNAL_MODE, JOURNAL_SIZE_LIMIT,
/* LEGACY_ALTER_TABLE */ OPTIMIZE, LEGACY_FORMAT, LOCKING_MODE, MMAP_SIZE, RECURSIVE_TRIGGERS,
REVERSE_UNORDERED_SELECTS, SECURE_DELETE, SHRINK_MEMORY, SOFT_HEAP_LIMIT,
STATS,
/* TEMP_STORE, */ //
THREADS,
WAL_AUTOCHECKPOINT,
WAL_CHECKPOINT,
// WRITEABLE_SCHEMA
}
private final StringBuilder sb = new StringBuilder();
private final List<String> errors = new ArrayList<>();
public void createPragma(String pragmaName, Supplier<Object> supplier) {
boolean setSchema = Randomly.getBoolean();
boolean setValue = Randomly.getBoolean();
sb.append("PRAGMA ");
if (setSchema) {
sb.append(Randomly.fromOptions("main.", "temp."));
}
sb.append(pragmaName);
if (setValue) {
Object value = supplier.get();
if (value != null) {
sb.append(" = ");
sb.append(supplier.get());
}
}
}
public QueryAdapter insert(SQLite3GlobalState globalState) {
Randomly r = globalState.getRandomly();
Pragma p = Randomly.fromOptions(Pragma.values());
switch (p) {
case APPLICATION_ID:
createPragma("application_id", () -> Randomly.getNonCachedInteger());
break;
case AUTO_VACUUM:
createPragma("auto_vacuum", () -> Randomly.fromOptions("NONE", "FULL", "INCREMENTAL"));
break;
case AUTOMATIC_INDEX:
createPragma("automatic_index", () -> getRandomTextBoolean());
break;
case BUSY_TIMEOUT:
createPragma("busy_timeout", () -> {
if (Randomly.getBoolean()) {
return 0;
} else {
long value = Math.max(10000, Randomly.getNonCachedInteger());
return value;
}
});
break;
case CACHE_SIZE:
createPragma("cache_size", () -> {
if (Randomly.getBoolean()) {
return 0;
} else {
return Randomly.getNonCachedInteger();
}
});
break;
case CACHE_SPILL_ENABLED:
createPragma("cache_spill", () -> getRandomTextBoolean());
break;
case CACHE_SPILL_SIZE:
createPragma("cache_spill", () -> Randomly.getNonCachedInteger());
break;
case CELL_SIZE_CHECK:
createPragma("cell_size_check", () -> getRandomTextBoolean());
break;
case CHECKPOINT_FULLSYNC:
createPragma("checkpoint_fullfsync", () -> getRandomTextBoolean());
break;
case DEFAULT_CACHE_SIZE:
createPragma("default_cache_size", () -> r.getInteger());
break;
case DEFER_FOREIGN_KEY:
createPragma("defer_foreign_keys", () -> getRandomTextBoolean());
break;
// TODO: [SQLITE_ERROR] SQL error or missing database (attached databases must
// use the same text encoding as main database)
// case ENCODING:
// sb.append("PRAGMA main.encoding = \"");
// String encoding = Randomly.fromOptions("UTF-8", "UTF-16", "UTF-16be", "UTF-16le");
// sb.append(encoding);
// sb.append("\";\n");
// sb.append("PRAGMA temp.encoding = \"");
// sb.append(encoding);
// sb.append("\"");
// break;
case FOREIGN_KEYS:
createPragma("foreign_keys", () -> getRandomTextBoolean());
break;
case IGNORE_CHECK_CONSTRAINTS:
createPragma("ignore_check_constraints", () -> getRandomTextBoolean());
break;
case INCREMENTAL_VACUUM:
if (Randomly.getBoolean()) {
createPragma("incremental_vacuum", () -> null);
} else {
sb.append(String.format("PRAGMA incremental_vacuum(%d)", r.getInteger()));
}
break;
case INTEGRITY_CHECK:
errors.add("malformed JSON");
errors.add("JSON cannot hold BLOB values");
if (Randomly.getBoolean()) {
createPragma("integrity_check", () -> null);
} else {
sb.append(String.format("PRAGMA integrity_check(%d)", r.getInteger()));
}
break;
case JOURNAL_MODE:
// OFF is no longer generated, since it might corrupt the database upon failed
createPragma("journal_mode", () -> Randomly.fromOptions("DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL"));
errors.add("from within a transaction");
break;
case JOURNAL_SIZE_LIMIT:
createPragma("journal_size_limit", () -> {
if (Randomly.getBoolean()) {
return 0;
} else {
return Randomly.getNonCachedInteger();
}
});
break;
case LEGACY_FORMAT:
createPragma("legacy_file_format", () -> getRandomTextBoolean());
break;
case LOCKING_MODE:
createPragma("locking_mode", () -> Randomly.fromOptions("NORMAL", "EXCLUSIVE"));
break;
case MMAP_SIZE:
createPragma("mmap_size", () -> Randomly.getNonCachedInteger());
break;
case OPTIMIZE:
createPragma("optimize", () -> null);
break;
case RECURSIVE_TRIGGERS:
createPragma("recursive_triggers", () -> getRandomTextBoolean());
break;
case REVERSE_UNORDERED_SELECTS:
createPragma("reverse_unordered_selects", () -> getRandomTextBoolean());
break;
case SECURE_DELETE:
createPragma("secure_delete", () -> Randomly.fromOptions("true", "false", "FAST"));
break;
case SHRINK_MEMORY:
createPragma("shrink_memory", () -> null);
break;
case SOFT_HEAP_LIMIT:
createPragma("soft_heap_limit", () -> {
if (Randomly.getBoolean()) {
return 0;
} else {
return r.getPositiveInteger();
}
});
break;
case STATS:
createPragma("stats", () -> null);
break;
// case TEMP_STORE:
// createPragma("temp_store", () -> Randomly.fromOptions("DEFAULT", "FILE", "MEMORY"));
// break;
case THREADS:
createPragma("threads", () -> Randomly.getNonCachedInteger());
break;
case WAL_AUTOCHECKPOINT:
createPragma("wal_autocheckpoint", () -> Randomly.getNonCachedInteger());
break;
case WAL_CHECKPOINT:
sb.append("PRAGMA wal_checkpoint(");
sb.append(Randomly.fromOptions("PASSIVE", "FULL", "RESTART", "TRUNCATE"));
sb.append(")");
errors.add("database table is locked");
break;
// writeable schema can cause ALTER TABLE commands to result in a malformed schema
// case WRITEABLE_SCHEMA:
// createPragma("writable_schema", () -> Randomly.getBoolean());
// break;
default:
throw new AssertionError();
}
sb.append(";");
String pragmaString = sb.toString();
// errors.add("cannot change");
return new QueryAdapter(pragmaString, errors);
}
public static QueryAdapter insertPragma(SQLite3GlobalState globalState) throws SQLException {
return new SQLite3PragmaGenerator().insert(globalState);
}
private static String getRandomTextBoolean() {
return Randomly.fromOptions("true", "false");
}
} |
package net.somethingdreadful.MAL.sql;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MALSqlHelper extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "MAL.db";
private static final int DATABASE_VERSION = 7;
private static MALSqlHelper instance;
public static final String COLUMN_ID = "_id";
public static final String TABLE_ANIME = "anime";
public static final String TABLE_MANGA = "manga";
public static final String TABLE_FRIENDS = "friends";
public static final String TABLE_PROFILE = "profile";
private static final String CREATE_ANIME_TABLE = "create table "
+ TABLE_ANIME + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ "recordID integer UNIQUE, "
+ "recordName varchar, "
+ "recordType varchar, "
+ "imageUrl varchar, "
+ "recordStatus varchar, "
+ "myStatus varchar, "
+ "memberScore float, "
+ "myScore integer, "
+ "synopsis varchar, "
+ "episodesWatched integer, "
+ "episodesTotal integer, "
+ "dirty boolean DEFAULT false, "
+ "lastUpdate integer NOT NULL DEFAULT (strftime('%s','now'))"
+ ");";
private static final String CREATE_MANGA_TABLE = "create table "
+ TABLE_MANGA + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ "recordID integer UNIQUE, "
+ "recordName varchar, "
+ "recordType varchar, "
+ "imageUrl varchar, "
+ "recordStatus varchar, "
+ "myStatus varchar, "
+ "memberScore float, "
+ "myScore integer, "
+ "synopsis varchar, "
+ "chaptersRead integer, "
+ "chaptersTotal integer, "
+ "volumesRead integer, "
+ "volumesTotal integer, "
+ "dirty boolean DEFAULT false, "
+ "lastUpdate integer NOT NULL DEFAULT (strftime('%s','now'))"
+ ");";
private static final String CREATE_FRIENDS_TABLE = "create table "
+ TABLE_FRIENDS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ "username varchar UNIQUE, "
+ "avatar_url varchar, "
+ "last_online varchar, "
+ "friend_since varchar "
+ ");";
private static final String CREATE_PROFILE_TABLE = "create table "
+ TABLE_PROFILE + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ "username varchar UNIQUE, "
+ "avatar_url varchar, "
+ "birthday varchar, "
+ "location varchar, "
+ "website varchar, "
+ "comments integer, "
+ "forum_posts integer, "
+ "last_online varchar, "
+ "gender varchar, "
+ "join_date varchar, "
+ "access_rank varchar, "
+ "anime_list_views integer, "
+ "manga_list_views integer, "
+ "anime_time_days double, "
+ "anime_watching integer, "
+ "anime_completed integer, "
+ "anime_on_hold integer, "
+ "anime_dropped integer, "
+ "anime_plan_to_watch integer, "
+ "anime_total_entries integer, "
+ "manga_time_days double, "
+ "manga_reading integer, "
+ "manga_completed integer, "
+ "manga_on_hold integer, "
+ "manga_dropped integer, "
+ "manga_plan_to_read integer, "
+ "manga_total_entries integer "
+ ");";
//Since SQLite doesn't allow "dynamic" dates, we set the default timestamp an adequate distance in the
//past (1 December 1982) to make sure it will be in the past for update calculations. This should be okay,
//since we are going to update the column whenever we sync.
private static final String ADD_ANIME_SYNC_TIME = "ALTER TABLE "
+ TABLE_ANIME
+ " ADD COLUMN lastUpdate integer NOT NULL DEFAULT 407570400";
private static final String ADD_MANGA_SYNC_TIME = "ALTER TABLE "
+ TABLE_MANGA
+ " ADD COLUMN lastUpdate integer NOT NULL DEFAULT 407570400";
public MALSqlHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized MALSqlHelper getHelper(Context context) {
if (instance == null) {
instance = new MALSqlHelper(context);
}
return instance;
}
@Override
public String getDatabaseName() {
return DATABASE_NAME;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_ANIME_TABLE);
db.execSQL(CREATE_MANGA_TABLE);
db.execSQL(CREATE_FRIENDS_TABLE);
db.execSQL(CREATE_PROFILE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("MALX", "Upgrading database from version " + oldVersion + " to " + newVersion);
if ((oldVersion < 3)) {
db.execSQL(CREATE_MANGA_TABLE);
}
if (oldVersion < 4) {
db.execSQL(ADD_ANIME_SYNC_TIME);
db.execSQL(ADD_MANGA_SYNC_TIME);
}
if (oldVersion < 5) {
db.execSQL("create table temp_table as select * from " + TABLE_ANIME);
db.execSQL("drop table " + TABLE_ANIME);
db.execSQL(CREATE_ANIME_TABLE);
db.execSQL("insert into " + TABLE_ANIME + " select * from temp_table;");
db.execSQL("drop table temp_table;");
db.execSQL("create table temp_table as select * from " + TABLE_MANGA);
db.execSQL("drop table " + TABLE_MANGA);
db.execSQL(CREATE_MANGA_TABLE);
db.execSQL("insert into " + TABLE_MANGA + " select * from temp_table;");
db.execSQL("drop table temp_table;");
}
if (oldVersion < 6) {
db.execSQL("create table temp_table as select * from " + TABLE_FRIENDS);
db.execSQL("drop table " + TABLE_FRIENDS);
db.execSQL(CREATE_FRIENDS_TABLE);
db.execSQL("insert into " + TABLE_FRIENDS + " select * from temp_table;");
db.execSQL("drop table temp_table;");
db.execSQL("create table temp_table as select * from " + TABLE_PROFILE);
db.execSQL("drop table " + TABLE_PROFILE);
db.execSQL(CREATE_PROFILE_TABLE);
db.execSQL("insert into " + TABLE_PROFILE + " select * from temp_table;");
db.execSQL("drop table temp_table;");
}
if (oldVersion < 7) {
/*
* sadly SQLite does not have good alter table support, so the profile table needs to be
* recreated :(
*
* profile table changes:
*
* fix unnecessary anime_time_days(_d) and manga_time_days(_d) definitions: storing the same value
* with different field types is bad practice, better convert them when needed
*
* Update for unique declaration of recordID (as this is the anime/manga id returned by the API it should be unique anyway)
* and unique declaration of username in friends/profile table
* this gives us the ability to update easier because we can call SQLiteDatabase.replace() which inserts
* new records and updates existing records automatically
*/
// Delete anime_time_days_d and manga_time_days_d... so don't use * as column selector!
db.execSQL("create table temp_table as select " +
"_id, username, avatar_url, birthday, location, website, comments, forum_posts, last_online, gender, " +
"join_date, access_rank, anime_list_views, manga_list_views, anime_time_days, anime_watching, anime_completed," +
"anime_on_hold, anime_dropped, anime_plan_to_watch, anime_total_entries, manga_time_days, manga_reading, " +
"manga_completed, manga_on_hold, manga_dropped, manga_plan_to_read, manga_total_entries " +
"from " + TABLE_PROFILE);
db.execSQL("drop table " + TABLE_PROFILE);
db.execSQL(CREATE_PROFILE_TABLE);
db.execSQL("insert into " + TABLE_PROFILE + " select * from temp_table;");
db.execSQL("drop table temp_table;");
db.execSQL("create table temp_table as select * from " + TABLE_ANIME);
db.execSQL("drop table " + TABLE_ANIME);
db.execSQL(CREATE_ANIME_TABLE);
db.execSQL("insert into " + TABLE_ANIME + " select * from temp_table;");
db.execSQL("drop table temp_table;");
db.execSQL("create table temp_table as select * from " + TABLE_MANGA);
db.execSQL("drop table " + TABLE_MANGA);
db.execSQL(CREATE_MANGA_TABLE);
db.execSQL("insert into " + TABLE_MANGA + " select * from temp_table;");
db.execSQL("drop table temp_table;");
}
}
} |
package filter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import model.Model;
import model.TurboIssue;
import model.TurboLabel;
import model.TurboMilestone;
import model.TurboUser;
public class Predicate implements FilterExpression {
private final String name;
private final String content;
public Predicate(String name, String content) {
this.name = name;
this.content = content;
}
public Predicate() {
this.name = null;
this.content = null;
}
public boolean isSatisfiedBy(TurboIssue issue, Model model) {
if (name == null && content == null) return true;
switch (name) {
case "id":
return idSatisfies(issue);
case "title":
return titleSatisfies(issue);
case "milestone":
return milestoneSatisfies(issue);
case "parent":
return parentSatisfies(issue, model);
case "label":
return labelsSatisfy(issue);
case "assignee":
return assigneeSatisfies(issue);
case "state":
case "status":
return stateSatisfies(issue);
case "has":
return satisfiesHasConditions(issue);
default:
return false;
}
}
@Override
public void applyTo(TurboIssue issue, Model model) throws PredicateApplicationException {
assert !(name == null && content == null);
switch (name) {
case "title":
throw new PredicateApplicationException("Unnecessary filter: title cannot be changed by dragging");
case "milestone":
applyMilestone(issue, model);
break;
case "parent":
applyParent(issue, model);
break;
case "label":
applyLabel(issue, model);
break;
case "assignee":
applyAssignee(issue, model);
break;
case "state":
case "status":
applyState(issue);
break;
default:
break;
}
}
@Override
public boolean canBeAppliedToIssue() {
return true;
}
@Override
public List<String> getPredicateNames() {
return new ArrayList<String>(Arrays.asList(content));
}
@Override
public String toString() {
return name + "(" + content + ")";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Predicate other = (Predicate) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
private int parseIdString(String id) {
if (id.startsWith("
return Integer.parseInt(id.substring(1));
} else if (Character.isDigit(id.charAt(0))) {
return Integer.parseInt(id);
} else {
return -1;
}
}
private boolean idSatisfies(TurboIssue issue) {
return issue.getId() == parseIdString(content);
}
private boolean satisfiesHasConditions(TurboIssue issue) {
switch (content) {
case "label":
return issue.getLabels().size() > 0;
case "milestone":
return issue.getMilestone() != null;
case "assignee":
return issue.getAssignee() != null;
case "parent":
return issue.getParentIssue() != -1;
default:
return false;
}
}
private boolean stateSatisfies(TurboIssue issue) {
if (content.toLowerCase().contains("open")) {
return issue.getOpen();
} else if (content.toLowerCase().contains("closed")) {
return !issue.getOpen();
} else {
return false;
}
}
private boolean assigneeSatisfies(TurboIssue issue) {
if (issue.getAssignee() == null) return false;
return issue.getAssignee().getGithubName().toLowerCase().contains(content.toLowerCase())
|| (issue.getAssignee().getRealName() != null && issue.getAssignee().getRealName().toLowerCase().contains(content.toLowerCase()));
}
private boolean labelsSatisfy(TurboIssue issue) {
String group = "";
String labelName = content.toLowerCase();
if (content.contains(".")) {
if (content.length() == 1) {
// It's just a dot
return true;
}
int pos = content.indexOf('.');
group = content.substring(0, pos);
labelName = content.substring(pos+1);
}
// Both can't be empty
assert !(group.isEmpty() && labelName.isEmpty());
for (TurboLabel l : issue.getLabels()) {
if (labelName == null || l.getName().toLowerCase().contains(labelName)) {
if(l.getGroup() == null){
return group == null || group == "";
}
if (group == null || l.getGroup().toLowerCase().contains(group)) {
return true;
}
}
}
return false;
}
private boolean parentSatisfies(TurboIssue issue, Model model) {
String parent = content.toLowerCase();
int index = parseIdString(parent);
if (index != -1) {
return issue.getParentIssue() == index;
} else {
List<TurboIssue> actualParentInstances = model.getIssues().stream().filter(i -> (issue.getParentIssue() == i.getId())).collect(Collectors.toList());
for (int i=0; i<actualParentInstances.size(); i++) {
if (actualParentInstances.get(i).getTitle().toLowerCase().contains(parent)) {
return true;
}
}
return false;
}
}
private boolean milestoneSatisfies(TurboIssue issue) {
if (issue.getMilestone() == null) return false;
return issue.getMilestone().getTitle().toLowerCase().contains(content.toLowerCase());
}
private boolean titleSatisfies(TurboIssue issue) {
return issue.getTitle().toLowerCase().contains(content.toLowerCase());
}
private void applyMilestone(TurboIssue issue, Model model)
throws PredicateApplicationException {
// Find milestones containing the partial title
List<TurboMilestone> milestones = model.getMilestones().stream().filter(m -> m.getTitle().toLowerCase().contains(content.toLowerCase())).collect(Collectors.toList());
if (milestones.size() > 1) {
throw new PredicateApplicationException("Ambiguous filter: can apply any of the following milestones: " + milestones.toString());
} else {
issue.setMilestone(milestones.get(0));
}
}
private void applyParent(TurboIssue issue, Model model)
throws PredicateApplicationException {
String parent = content.toLowerCase();
int index = parseIdString(parent);
if (index != -1) {
issue.setParentIssue(index);
} else {
// Find parents containing the partial title
List<TurboIssue> parents = model.getIssues().stream().filter(i -> i.getTitle().toLowerCase().contains(parent.toLowerCase())).collect(Collectors.toList());
if (parents.size() > 1) {
throw new PredicateApplicationException("Ambiguous filter: can apply any of the following parents: " + parents.toString());
} else {
issue.setParentIssue(parents.get(0).getId());
}
}
}
private void applyLabel(TurboIssue issue, Model model)
throws PredicateApplicationException {
// Find labels containing the partial title
List<TurboLabel> labels = model.getLabels().stream().filter(l -> l.getName().toLowerCase().contains(content.toLowerCase())).collect(Collectors.toList());
if (labels.size() > 1) {
throw new PredicateApplicationException("Ambiguous filter: can apply any of the following labels: " + labels.toString());
} else {
issue.addLabel(labels.get(0));
}
}
private void applyAssignee(TurboIssue issue, Model model)
throws PredicateApplicationException {
// Find assignees containing the partial title
List<TurboUser> assignees = model.getCollaborators().stream().filter(c -> c.getGithubName().toLowerCase().contains(content.toLowerCase())).collect(Collectors.toList());
if (assignees.size() > 1) {
throw new PredicateApplicationException("Ambiguous filter: can apply any of the following assignees: " + assignees.toString());
} else {
issue.setAssignee(assignees.get(0));
}
}
private void applyState(TurboIssue issue) {
if (content.toLowerCase().contains("open")) {
issue.setOpen(true);
} else if (content.toLowerCase().contains("closed")) {
issue.setOpen(false);
}
}
} |
package algorithms.imageProcessing;
import algorithms.imageProcessing.util.MatrixUtil;
import java.awt.Color;
import java.security.SecureRandom;
import junit.framework.TestCase;
/**
*
* @author nichole
*/
public class ImageExtTest extends TestCase {
public void testInit() {
int w = 10;
int h = 10;
ImageExt img = new ImageExt(w, h);
assertNotNull(img);
int n = w * h;
assertTrue(img.getNPixels() == n);
}
public void testSetRadiusForPopulateOnDemand() {
// this also implicitly tests calculateColorIncludingNeighbors
int w = 5;
int h = 5;
int n = w * h;
ImageExt img = new ImageExt(w, h);
int count = 0;
for (int col = 0; col < w; col++) {
for (int row = 0; row < h; row++) {
count++;
img.setRGB(col, row, 100 + count, 110 + count, 120 + count);
}
}
img.setRadiusForPopulateOnDemand(5);
img.getCIEX(w/2, h/2);
for (int idx = 0; idx < n; idx++) {
assertTrue(img.getCIEX(idx) > 0.);
assertTrue(img.getCIEY(idx) > 0.);
assertTrue(img.getHue(idx) > 0.);
assertTrue(img.getSaturation(idx) > 0.);
assertTrue(img.getBrightness(idx) > 0.);
assertTrue(img.getLuma(idx) > 0.);
}
img = new ImageExt(w, h);
count = 0;
for (int col = 0; col < w; col++) {
for (int row = 0; row < h; row++) {
count++;
img.setRGB(col, row, 100 + count, 110 + count, 120 + count);
}
}
img.setRadiusForPopulateOnDemand(0);
int x = w/2;
int y = h/2;
img.getCIEX(x, y);
for (int col = 0; col < w; col++) {
for (int row = 0; row < h; row++) {
int idx = img.getInternalIndex(col, row);
assertTrue(img.getCIEX(idx) > 0.);
assertTrue(img.getCIEY(idx) > 0.);
assertTrue(img.getHue(idx) > 0.);
assertTrue(img.getSaturation(idx) > 0.);
assertTrue(img.getBrightness(idx) > 0.);
assertTrue(img.getLuma(idx) > 0.);
}
}
}
public void testIndexes() throws Exception {
int w = 5;
int h = 5;
int n = w * h;
ImageExt img = new ImageExt(w, h);
img.setRadiusForPopulateOnDemand(n);
int nTests = 100;
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
long seed = System.currentTimeMillis();
sr.setSeed(seed);
for (int i = 0; i < nTests; i++) {
int x = sr.nextInt(w);
int y = sr.nextInt(h);
int idx = img.getInternalIndex(x, y);
int col = img.getCol(idx);
int row = img.getRow(idx);
assertTrue(x == col);
assertTrue(y == row);
}
}
public void testGetters() throws Exception {
int w = 5;
int h = 5;
int n = w * h;
ImageExt img = new ImageExt(w, h);
img.setRadiusForPopulateOnDemand(n);
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
long seed = System.currentTimeMillis();
sr.setSeed(seed);
CIEChromaticity cieC = new CIEChromaticity();
for (int i = 0; i < 10; i++) {
int idx = sr.nextInt(n);
int r = sr.nextInt(255);
int g = sr.nextInt(255);
int b = sr.nextInt(255);
img.setRGB(idx, r, g, b);
assertTrue(img.getR(idx) == r);
assertTrue(img.getG(idx) == g);
assertTrue(img.getB(idx) == b);
}
for (int idx = 0; idx < img.getNPixels(); idx++) {
int x = img.getCol(idx);
int y = img.getRow(idx);
int r = img.getR(x, y);
int g = img.getG(x, y);
int b = img.getB(x, y);
float[] cieXY = cieC.rgbToXYChromaticity(r, g, b);
float[] hsb = new float[3];
Color.RGBtoHSB(r, g, b, hsb);
double[][] rgbToLumaMatrix = new double[3][];
rgbToLumaMatrix[0] = new double[]{0.256, 0.504, 0.098};
rgbToLumaMatrix[1] = new double[]{-0.148, -0.291, 0.439};
rgbToLumaMatrix[2] = new double[]{0.439, -0.368, -0.072};
double[] yuv = MatrixUtil.multiply(rgbToLumaMatrix,
new double[]{r, g, b});
assertTrue(Math.abs(img.getCIEX(x, y) - cieXY[0]) < 0.01);
assertTrue(Math.abs(img.getCIEX(idx) - cieXY[0]) < 0.01);
assertTrue(Math.abs(img.getCIEY(x, y) - cieXY[1]) < 0.01);
assertTrue(Math.abs(img.getCIEY(idx) - cieXY[1]) < 0.01);
assertTrue(Math.abs(img.getHue(x, y) - hsb[0]) < 0.01);
assertTrue(Math.abs(img.getHue(idx) - hsb[0]) < 0.01);
assertTrue(Math.abs(img.getSaturation(x, y) - hsb[1]) < 0.01);
assertTrue(Math.abs(img.getSaturation(idx) - hsb[1]) < 0.01);
assertTrue(Math.abs(img.getBrightness(x, y) - hsb[2]) < 0.01);
assertTrue(Math.abs(img.getBrightness(idx) - hsb[2]) < 0.01);
assertTrue(Math.abs(img.getLuma(x, y) - yuv[0]) < 0.01);
assertTrue(Math.abs(img.getLuma(idx) - yuv[0]) < 0.01);
}
}
public void testCalculateColorIncludingNeighbors() throws Exception {
int w = 5;
int h = 5;
int n = w * h;
ImageExt img = new ImageExt(w, h);
CIEChromaticity cieC = new CIEChromaticity();
for (int idx = 0; idx < n; idx++) {
int x = img.getCol(idx);
int y = img.getRow(idx);
int r = idx*1;
int g = idx*2;
int b = idx*1;
img.setRGB(x, y, r, g, b);
}
int neighborRadius = 1;
for (int idx = 0; idx < n; idx++) {
int x = img.getCol(idx);
int y = img.getRow(idx);
img.calculateColorIncludingNeighbors(idx, neighborRadius);
for (int col = (x - neighborRadius); col <= (x + neighborRadius);
col++) {
if ((col < 0) || (col > (w - 1))) {
continue;
}
for (int row = (y - neighborRadius); row <=
(y + neighborRadius); row++) {
if ((row < 0) || (row > (h - 1))) {
continue;
}
int index = img.getInternalIndex(col, row);
int expectedR = index*1;
int expectedG = index*2;
int expectedB = index*1;
float[] expectedCIEXY = cieC.rgbToXYChromaticity(
expectedR, expectedG, expectedB);
float[] expectedHSB = new float[3];
Color.RGBtoHSB(expectedR, expectedG, expectedB,
expectedHSB);
double[][] rgbToLumaMatrix = new double[3][];
rgbToLumaMatrix[0] = new double[]{0.256, 0.504, 0.098};
rgbToLumaMatrix[1] = new double[]{-0.148, -0.291, 0.439};
rgbToLumaMatrix[2] = new double[]{0.439, -0.368, -0.072};
double[] expectedYUV = MatrixUtil.multiply(rgbToLumaMatrix,
new double[]{expectedR, expectedG, expectedB});
assertTrue(Math.abs(img.getCIEX(index) - expectedCIEXY[0]) < 0.01);
assertTrue(Math.abs(img.getCIEY(index) - expectedCIEXY[1]) < 0.01);
assertTrue(Math.abs(img.getHue(index) - expectedHSB[0]) < 0.01);
assertTrue(Math.abs(img.getSaturation(index) - expectedHSB[1]) < 0.01);
assertTrue(Math.abs(img.getBrightness(index) - expectedHSB[2]) < 0.01);
assertTrue(Math.abs(img.getLuma(index) - expectedYUV[0]) < 0.01);
}
}
}
}
private ImageExt getImageExt0() {
int w = 5;
int h = 5;
int n = w * h;
ImageExt img = new ImageExt(w, h);
for (int idx = 0; idx < n; idx++) {
int x = img.getCol(idx);
int y = img.getRow(idx);
int r = idx*1;
int g = idx*2;
int b = idx*1;
img.setRGB(x, y, r, g, b);
}
for (int idx = 0; idx < n; idx++) {
img.calculateColor(idx);
}
return img;
}
public void testCopyImage() {
ImageExt img = getImageExt0();
Image img2 = img.copyImage();
assertTrue(img2 instanceof ImageExt);
ImageExt image2 = (ImageExt)img2;
assertTrue(image2.getNPixels() == img.getNPixels());
assertTrue(image2.getWidth() == img.getWidth());
assertTrue(image2.getHeight() == img.getHeight());
for (int idx = 0; idx < img.getNPixels(); idx++) {
assertTrue(image2.getR(idx) == img.getR(idx));
assertTrue(image2.getG(idx) == img.getG(idx));
assertTrue(image2.getB(idx) == img.getB(idx));
assertTrue(Math.abs(image2.getCIEX(idx) - img.getCIEX(idx)) < 0.01);
assertTrue(Math.abs(image2.getCIEY(idx) - img.getCIEY(idx)) < 0.01);
assertTrue(Math.abs(image2.getHue(idx) - img.getHue(idx)) < 0.01);
assertTrue(Math.abs(image2.getSaturation(idx) - img.getSaturation(idx)) < 0.01);
assertTrue(Math.abs(image2.getBrightness(idx) - img.getBrightness(idx)) < 0.01);
assertTrue(Math.abs(image2.getLuma(idx) - img.getLuma(idx)) < 0.01);
}
}
public void testResetTo() {
ImageExt img = getImageExt0();
ImageExt image2 = new ImageExt(img.getWidth(), img.getHeight());
image2.resetTo(img);
assertTrue(image2.getNPixels() == img.getNPixels());
assertTrue(image2.getWidth() == img.getWidth());
assertTrue(image2.getHeight() == img.getHeight());
for (int idx = 0; idx < img.getNPixels(); idx++) {
assertTrue(image2.getR(idx) == img.getR(idx));
assertTrue(image2.getG(idx) == img.getG(idx));
assertTrue(image2.getB(idx) == img.getB(idx));
assertTrue(Math.abs(image2.getCIEX(idx) - img.getCIEX(idx)) < 0.01);
assertTrue(Math.abs(image2.getCIEX(idx) - img.getCIEX(idx)) < 0.01);
assertTrue(Math.abs(image2.getHue(idx) - img.getHue(idx)) < 0.01);
assertTrue(Math.abs(image2.getSaturation(idx) - img.getSaturation(idx))
< 0.01);
assertTrue(Math.abs(image2.getBrightness(idx) - img.getBrightness(idx))
< 0.01);
assertTrue(Math.abs(image2.getLuma(idx) - img.getLuma(idx)) < 0.01);
}
}
} |
package com.ftdi.j2xx;
import android.os.SystemClock;
import android.util.Log;
import com.qualcomm.robotcore.util.TypeConversion;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class FT_Device
{
private static final String TAG = "FTDI_Device::";
D2xxManager.FtDeviceInfoListNode mDeviceInfoNode;
String mySerialNumber;
int mMotor1Encoder; // Simulate motor 1 encoder. Increment each write.
int mMotor2Encoder; // Simulate motor 2 encoder. Increment each write.
double mMotor1TotalError;
double mMotor2TotalError;
long mTimeInMilliseconds=0;
long mOldTimeInMilliseconds=0;
long mDeltaWriteTime=0;
protected final byte[] mCurrentStateBuffer = new byte[208];
private enum WriteStates {
READY_FOR_WRITE_COMMANDS,
READY_FOR_WRITE_DATA,
}
// Synchronized by 'this'
private WriteStates mWriteState = WriteStates.READY_FOR_WRITE_COMMANDS;
protected final Queue<CacheWriteRecord> readQueue = new ConcurrentLinkedQueue();
protected volatile boolean writeLocked = false;
public FT_Device(String serialNumber, String description)
{
int i;
this.mDeviceInfoNode = new D2xxManager.FtDeviceInfoListNode();
this.mDeviceInfoNode.serialNumber = serialNumber;
this.mDeviceInfoNode.description = description;
mMotor1Encoder = 0;
mMotor2Encoder = 0;
mMotor1TotalError = 0; // used in the RUN_TO_POSITION PID
mMotor2TotalError = 0;
}
public synchronized void close()
{
}
public int read(byte[] data, int length, long wait_ms)
{
int rc = 0;
Object localObject1;
String logString[];
if (length <= 0) {
return -2;
}
try
{
this.writeLocked = true;
if (!this.readQueue.isEmpty()) {
localObject1 = (CacheWriteRecord)this.readQueue.poll();
if (localObject1 == null)
return rc;
System.arraycopy(((CacheWriteRecord)localObject1).data, 0, data, 0, length);
rc = length;
if (length == 5) {
//Log.v("Legacy", "READ: Response Header (" + bufferToHexString(data,0,length) + ") len=" + length);
} else if (length == 3) {
//Log.v("Legacy", "READ: Response Header (" + bufferToHexString(data,0,length) + ") len=" + length);
} else if (length == 208) {
//Log.v("Legacy", "READ: Response Buffer S0 (" + bufferToHexString(data,16+4,20) + "...) len=" + length);
//Log.v("Legacy", "READ: Response Buffer FLAGS 0=" + bufferToHexString(data,0,3) + " 16=" + bufferToHexString(data,16,4) + "47=" + bufferToHexString(data,47,1));
}
}
} finally {
this.writeLocked = false;
}
return rc;
}
public int read(byte[] data, int length)
{
long l=0;
return read(data, length, l);
}
public int read(byte[] data)
{
long l=0;
return read(data, data.length,l);
}
public int write(byte[] data, int length)
{
return write(data, length, true);
}
public void queueUpForReadFromPhone(byte[] data) {
//while (this.writeLocked) Thread.yield();
this.readQueue.add(new CacheWriteRecord(data));
}
protected final byte[] writeCmd = { 85, -86, 0, 0, 0 };
protected final byte[] readCmd = { 85, -86, -128, 0, 0 };
protected final byte[] recSyncCmd3 = { 51, -52, 0, 0, 3};
protected final byte[] recSyncCmd0 = { 51, -52, -128, 0, 0};
protected final byte[] recSyncCmd208 = { 51, -52, -128, 0, (byte)208};
protected final byte[] controllerTypeLegacy = { 0, 77, 73}; // Controller type USBLegacyModule
public int write(byte[] data, int length, boolean wait)
{
int rc = 0;
if (length <= 0) {
return rc;
}
// Write Command
if (data[0] == writeCmd[0] && data[2] == writeCmd[2]) { // writeCmd
// If size is 208(0xd0) bytes then they are writing a full buffer of data to all ports.
// Note: the buffer we were giving in this case is 208+5 bytes because the "writeCmd" header is attached
if (data[4] == (byte)0xd0 ) {
//Log.v("Legacy", "WRITE: Write Header (" + bufferToHexString(data,0,5) + ") len=" + length);
queueUpForReadFromPhone(recSyncCmd0); // Reply we got your writeCmd
//Log.v("Legacy", "WRITE: Write Buffer S0 (" + bufferToHexString(data, 5+16+4, 20) + ") len=" + length);
//Log.v("Legacy", "WRITE: Write Buffer FLAGS 0=" + bufferToHexString(data,5+0,3) + " 16=" + bufferToHexString(data,5+16,4) + "47=" + bufferToHexString(data,5+47,1));
// Now, the reset of the buffer minus the header 5 bytes should be 208 (0xd0) bytes that need to be written to the connected devices
// Write the entire received buffer into the mCurrentState buffer so the android can see what we are up to
// Note: the buffer we were giving in this case is 208+5 bytes because the "writeCmd" header is attached
System.arraycopy(data, 5, mCurrentStateBuffer, 0, 208);
// Check delta time to see if we are too slow in our simulation.
// Baud rate was 250,000 with real USB port connected to module
// We are getting deltas of 31ms between each write call
mTimeInMilliseconds = SystemClock.uptimeMillis();
mDeltaWriteTime = mTimeInMilliseconds - mOldTimeInMilliseconds;
mOldTimeInMilliseconds = mTimeInMilliseconds;
Log.v("Legacy", "WRITE: Delta Time = " + mDeltaWriteTime);
// This is for Port P0 only. 16 is the base offset. Each port has 32 bytes.
// If I2C_ACTION is set, take some action
if (mCurrentStateBuffer[47] == (byte)0xff) { // Action flag
if ((mCurrentStateBuffer[16] & (byte)0x01) == (byte)0x01) { // I2C Mode
if ((mCurrentStateBuffer[16] & (byte)0x80) == (byte)0x80) { // Read mode
// just for fun, simulate reading the encoder from i2c.
// really just from the mMotor1Encoder class variable
// 4 bytes of header (r/w, i2c address, i2c register, i2c buffer len)
// +4 to get past the header, motor 1 encoder starts at 12 and is 4 bytes long
// See Tetrix Dc Motor Controller data sheet
mCurrentStateBuffer[16+4+12+0] = (byte)(mMotor1Encoder >> 24);
mCurrentStateBuffer[16+4+12+1] = (byte)(mMotor1Encoder >> 16);
mCurrentStateBuffer[16+4+12+2] = (byte)(mMotor1Encoder >> 8);
mCurrentStateBuffer[16+4+12+3] = (byte)(mMotor1Encoder >> 0);
mCurrentStateBuffer[16+4+16+0] = (byte)(mMotor2Encoder >> 24);
mCurrentStateBuffer[16+4+16+1] = (byte)(mMotor2Encoder >> 16);
mCurrentStateBuffer[16+4+16+2] = (byte)(mMotor2Encoder >> 8);
mCurrentStateBuffer[16+4+16+3] = (byte)(mMotor2Encoder >> 0);
} else { // Write mode
// Just for fun, simulate some of the motor modes
simulateWritesToMotor1();
simulateWritesToMotor2();
}
}
}
// Set the Port S0 ready bit in the global part of the Current State Buffer
mCurrentStateBuffer[3] = (byte)0xfe; // Port S0 ready
}
// Read Command
} else if (data[0] == readCmd[0] && data[2] == readCmd[2]) { // readCmd
if (data[4] == 3) { // Android asks for 3 bytes, initial query of device type
//Log.v("Legacy", "WRITE: Read Header (" + bufferToHexString(data,0,length) + ") len=" + length);
queueUpForReadFromPhone(recSyncCmd3); // Send receive sync, bytes to follow
queueUpForReadFromPhone(controllerTypeLegacy);
} else if (data[4] == (byte)208) { // Android asks for 208 bytes, full read of device
//Log.v("Legacy", "WRITE: Read Header (" + bufferToHexString(data,0,length) + ") len=" + length);
queueUpForReadFromPhone(recSyncCmd208); // Send receive sync, bytes to follow
queueUpForReadFromPhone(mCurrentStateBuffer);
}
}
rc = length;
return rc;
}
private void simulateWritesToMotor1() {
// Simulate writes to Motor 1
// Check for the 4 different states
switch ((mCurrentStateBuffer[16+4+4] & (byte)0x03)) {
case (byte)0x00: // Run with no encoder
// Check the motor power we just received and increment/decrement encoder
// For now just increment encoder by motor power
// Note: Float power = 0x80 (Negative Zero)
if ((mCurrentStateBuffer[16+4+5] != (byte)0x00) && (mCurrentStateBuffer[16+4+5] != (byte)0x80)) { // Motor 1 Power
mMotor1Encoder += mCurrentStateBuffer[16+4+5];
}
break;
case (byte)0x01: // Run with PID on encoder
break;
case (byte)0x02: // Run to position
double P = 0.5;
double I = 0.05;
int error = getMotor1TargetEncoder() - getMotor1CurrentEncoder();
mMotor1TotalError += error;
if (mMotor1TotalError > 2000) mMotor1TotalError = 2000;
if (mMotor1TotalError < -2000) mMotor1TotalError = -2000;
//Log.v("Legacy", "PID: " + error + " " + mMotor1TotalError);
int power = (int)(P*error) + (int)(mMotor1TotalError*I);
if (power > 100) power=100;
if (power < -100) power= -100;
mMotor1Encoder += power;
break;
case (byte)0x03: // Reset encoder
mMotor1Encoder = 0;
break;
}
}
private void simulateWritesToMotor2() {
// Simulate writes to Motor 2
// Check for the 4 different states
switch ((mCurrentStateBuffer[16+4+7] & (byte)0x03)) {
case (byte)0x00: // Run with no encoder
// Check the motor power we just received and increment/decrement encoder
// For now just increment encoder by motor power
// Note: Float power = 0x80 (Negative Zero)
if ((mCurrentStateBuffer[16+4+6] != (byte)0x00) && (mCurrentStateBuffer[16+4+6] != (byte)0x80)) { // Motor 2 Power
mMotor1Encoder += mCurrentStateBuffer[16+4+6];
}
break;
case (byte)0x01: // Run with PID on encoder
break;
case (byte)0x02: // Run to position
double P = 0.5;
double I = 0.05;
int error = getMotor2TargetEncoder() - getMotor2CurrentEncoder();
mMotor2TotalError += error;
if (mMotor2TotalError > 2000) mMotor2TotalError = 2000;
if (mMotor2TotalError < -2000) mMotor2TotalError = -2000;
//Log.v("Legacy", "PID: " + error + " " + mMotor2TotalError);
int power = (int)(P*error) + (int)(mMotor2TotalError*I);
if (power > 100) power=100;
if (power < -100) power= -100;
mMotor2Encoder += power;
break;
case (byte)0x03: // Reset encoder
mMotor2Encoder = 0;
break;
}
}
private int getMotor1CurrentEncoder() {
byte[] arrayOfByte1 = new byte[4];
System.arraycopy(mCurrentStateBuffer, 16+4+12, arrayOfByte1, 0, arrayOfByte1.length);
return TypeConversion.byteArrayToInt(arrayOfByte1);
}
private int getMotor2CurrentEncoder() {
byte[] arrayOfByte1 = new byte[4];
System.arraycopy(mCurrentStateBuffer, 16+4+16, arrayOfByte1, 0, arrayOfByte1.length);
return TypeConversion.byteArrayToInt(arrayOfByte1);
}
private int getMotor1TargetEncoder() {
byte[] arrayOfByte1 = new byte[4];
System.arraycopy(mCurrentStateBuffer, 16+4+0, arrayOfByte1, 0, arrayOfByte1.length);
return TypeConversion.byteArrayToInt(arrayOfByte1);
}
private int getMotor2TargetEncoder() {
byte[] arrayOfByte1 = new byte[4];
System.arraycopy(mCurrentStateBuffer, 16+4+8, arrayOfByte1, 0, arrayOfByte1.length);
return TypeConversion.byteArrayToInt(arrayOfByte1);
}
private String bufferToHexString(byte[] data, int start, int length) {
int i;
int myStop;
StringBuilder sb = new StringBuilder();
//byte [] subArray = Arrays.copyOfRange(a, 4, 6);
myStop = (length > data.length) ? data.length : length;
for (i=start; i<start+myStop; i++) {
sb.append(String.format("%02x ", data[i]));
}
return sb.toString();
}
public int write(byte[] data)
{
return write(data, data.length, true);
}
public boolean purge(byte flags)
{
return true;
}
public boolean setBaudRate(int baudRate)
{
return true;
}
public boolean setDataCharacteristics(byte dataBits, byte stopBits, byte parity)
{
return true;
}
public boolean setLatencyTimer(byte latency)
{
return true;
}
protected static class CacheWriteRecord {
public byte[] data;
public CacheWriteRecord(byte[] data) {
this.data = data;
}
}
} |
package com.ait.igenem;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ait.igenem.adapter.DynamicBlobRecyclerAdapter;
import com.ait.igenem.model.Blob;
import com.ait.igenem.model.Decision;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import butterknife.BindView;
import butterknife.ButterKnife;
//TODO: if you don't hit OK and just click "edit" for another blob. will only be saved locally, not in firebase
public class DecisionActivity extends AppCompatActivity implements PassDataDynamicBlobInterface {
@BindView(R.id.linearLayoutDecision)
LinearLayout linearLayoutDecision;
@BindView(R.id.btnNewBlob)
Button btnNewBlob;
@BindView(R.id.tvDecisionName)
TextView tvDecisionName;
@BindView(R.id.tvPercentPro)
TextView tvPercentPro;
//Editing blob
@BindView(R.id.editBlobLayout)
LinearLayout editBlobLayout;
@BindView(R.id.btnOkEditBlob)
Button btnOkEditBlob;
@BindView(R.id.btnCancelEdit)
Button btnCancelEdit;
@BindView(R.id.btnPlus)
Button btnPlus;
@BindView(R.id.btnMinus)
Button btnMinus;
@BindView(R.id.btnDeleteBlob)
Button btnDeleteBlob;
//For creating a new blob
@BindView(R.id.createBlobLayout)
LinearLayout createBlobLayout;
@BindView(R.id.btnDOkNewBlob)
Button btnOkNewBlob;
@BindView(R.id.etDBlobName)
EditText etBlobName;
@BindView(R.id.etDBlobRadius)
EditText etBlobRadius;
@BindView(R.id.cbDProCheckBox)
CheckBox cbProCheck;
//deleting decision
@BindView(R.id.btnDeleteDecision)
Button btnDeleteDecision;
//Setup RecyclerView
@BindView(R.id.recyclerDynamicBlob)
RecyclerView recyclerDynamicBlob;
DynamicBlobRecyclerAdapter dynamicBlobRecyclerAdapter;
private Decision decision;
private String decisionKey;
private String previousActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decision);
ButterKnife.bind(this);
previousActivity = getIntent().getStringExtra(ProfileActivity.KEY_PREVIOUS);
decision = (Decision) this.getIntent().getSerializableExtra(ProfileActivity.KEY_D);
decisionKey = this.getIntent().getStringExtra(ProfileActivity.KEY_D_KEY);
updateBackgroundColor();
setupDecisionUI();
setupFirebaseListener();
}
private void updateBackgroundColor() {
int decisionColor = decision.getColor();
Float percentColor = decision.getPercentPro();
float[] hsv = new float[3];
Color.colorToHSV(decisionColor, hsv);
hsv[1] = hsv[1] * percentColor;
linearLayoutDecision.setBackgroundColor(Color.HSVToColor(hsv));
recyclerDynamicBlob.setBackgroundColor(Color.HSVToColor(hsv));
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (previousActivity.equals("ProfileActivity")) {
Intent goProfileIntent = new Intent();
goProfileIntent.setClass(DecisionActivity.this, ProfileActivity.class);
startActivity(goProfileIntent);
} else if (previousActivity.equals("CreateDecision")) {
Intent goHomeIntent = new Intent();
goHomeIntent.setClass(DecisionActivity.this, HomeActivity.class);
//Clear entire back stack so when you click back from HomeActivity, the app exits.
goHomeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goHomeIntent);
}
}
private void setupFirebaseListener() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("decisions").child(decisionKey).child("blobs").orderByKey().
addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Blob newBlob = dataSnapshot.getValue(Blob.class);
dynamicBlobRecyclerAdapter.addBlob(newBlob, dataSnapshot.getKey());
recyclerDynamicBlob.scrollToPosition(0);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Blob changedBlob = dataSnapshot.getValue(Blob.class);
dynamicBlobRecyclerAdapter.updateBlob(changedBlob, dataSnapshot.getKey());
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
dynamicBlobRecyclerAdapter.removeBlobByKey(dataSnapshot.getKey());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setupDecisionUI() {
tvDecisionName.setText(decision.getName());
tvPercentPro.setText(String.valueOf(decision.getPercentPro()));
setupNewBlobButton();
setupDeleteDecisionButton();
setupOkayCreateBlobButton();
setupEditBlobListeners();
setupRecyclerView();
}
private void setupDeleteDecisionButton() {
btnDeleteDecision.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//delete from firebase
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).removeValue();
//Go back to profile page
Intent showProfileIntent = new Intent();
showProfileIntent.setClass(DecisionActivity.this, ProfileActivity.class);
startActivity(showProfileIntent);
finish();
}
});
}
private void setupRecyclerView() {
recyclerDynamicBlob.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager =
new LinearLayoutManager(this);
recyclerDynamicBlob.setLayoutManager(mLayoutManager);
dynamicBlobRecyclerAdapter = new DynamicBlobRecyclerAdapter((PassDataDynamicBlobInterface) this);
//callback, touchhelper?
recyclerDynamicBlob.setAdapter(dynamicBlobRecyclerAdapter);
}
private void setupEditBlobListeners() {
btnOkEditBlob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editBlobLayout.setVisibility(View.GONE);
}
});
btnCancelEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editBlobLayout.setVisibility(View.GONE);
}
});
}
private void setupOkayCreateBlobButton() {
btnOkNewBlob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (etBlobName.getText().toString().equals("")) {
etBlobName.setError(getString(R.string.enterBlobName));
}
//TODO: delete later. won't be setting a radius.
if (etBlobRadius.getText().toString().equals("")) {
etBlobRadius.setError(getString(R.string.enterBlobRadius));
} else {
// Add newBlob to Firebase, obtain key.
String key = FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("blobs").push().getKey();
Blob newBlob = new Blob(etBlobName.getText().toString(),
cbProCheck.isChecked(), Integer.parseInt(etBlobRadius.getText().toString()));
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("blobs").child(key).setValue(newBlob);
updateDecisionScoreNewBlob();
updateBackgroundColor();
resetCreateBlobLayout();
recyclerDynamicBlob.scrollToPosition(0);
}
}
});
}
private void updateDecisionScoreNewBlob() {
decision.updateScoreNewBlob(Integer.parseInt(etBlobRadius.getText().toString()),cbProCheck.isChecked());
tvPercentPro.setText(String.valueOf(decision.getPercentPro()));
updateScoreFirebase();
}
private void updateScoreFirebase() {
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("proScore").setValue(decision.getProScore());
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("totalScore").setValue(decision.getTotalScore());
}
private void resetCreateBlobLayout() {
createBlobLayout.setVisibility(View.GONE);
etBlobName.setText("");
etBlobRadius.setText("");
cbProCheck.setChecked(false);
}
private void setupNewBlobButton() {
btnNewBlob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editBlobLayout.setVisibility(View.GONE);
createBlobLayout.setVisibility(View.VISIBLE);
}
});
}
@Override
public void showEdit(Blob blobToEdit, int position) {
createBlobLayout.setVisibility(View.GONE);
editBlobLayout.setVisibility(View.VISIBLE);
//TODO: not sure if we need the blob and position
final int positionToEdit = position;
setupPlusListener(positionToEdit);
setupMinusListener(positionToEdit);
setupDeleteListener(positionToEdit);
setupOkEditListener(positionToEdit);
}
private void setupOkEditListener(final int positionToEdit) {
btnOkEditBlob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String key = dynamicBlobRecyclerAdapter.getBlobKey(positionToEdit);
Blob blob = dynamicBlobRecyclerAdapter.getBlob(positionToEdit);
updateBlobFirebase(blob, key);
updateScoreFirebase();
updateBackgroundColor();
editBlobLayout.setVisibility(View.GONE);
}
});
}
private void setupDeleteListener(final int positionToEdit) {
btnDeleteBlob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String key = dynamicBlobRecyclerAdapter.getBlobKey(positionToEdit);
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("blobs").child(key).removeValue();
updateDecisionScoreDeleteBlob(positionToEdit);
updateBackgroundColor();
editBlobLayout.setVisibility(View.GONE);
}
});
}
private void updateDecisionScoreDeleteBlob(int positionToEdit) {
Blob delBlob = dynamicBlobRecyclerAdapter.getBlob(positionToEdit);
decision.updateDecisionScoreDeleteBlob(delBlob.getRadius(), delBlob.isPro());
tvPercentPro.setText(String.valueOf(decision.getPercentPro()));
updateScoreFirebase();
}
private void setupMinusListener(final int positionToEdit) {
btnMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
decreaseRadius(positionToEdit);
}
});
}
private void setupPlusListener(final int positionToEdit) {
btnPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
increaseRadius(positionToEdit);
}
});
}
private void updateBlobFirebase(Blob updating, String key) {
FirebaseDatabase.getInstance().getReference().child("decisions").
child(decisionKey).child("blobs").child(key).setValue(updating);
}
public void increaseRadius(int positionToEdit) {
String key = dynamicBlobRecyclerAdapter.getBlobKey(positionToEdit);
Blob updating = dynamicBlobRecyclerAdapter.getBlob(positionToEdit);
updating.increaseRadius();
decision.increase(updating.isPro());
//this could be excessive and maybe combined into a field cry ugh
tvPercentPro.setText(String.valueOf(decision.getPercentPro()));
dynamicBlobRecyclerAdapter.updateBlob(updating, key);
}
public void decreaseRadius(int positionToEdit) {
String key = dynamicBlobRecyclerAdapter.getBlobKey(positionToEdit);
Blob updating = dynamicBlobRecyclerAdapter.getBlob(positionToEdit);
updating.decreaseRadius();
decision.decrease(updating.isPro());
//this could be excessive and maybe combined into a field cry ugh
tvPercentPro.setText(String.valueOf(decision.getPercentPro()));
dynamicBlobRecyclerAdapter.updateBlob(updating, key);
}
} |
package service;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Produces;
import ent.User;
@SessionScoped
public class UserProducer implements Serializable {
private char startName;
public UserProducer() {
startName = ' ';
}
@Produces
public @SessionScoped User createUser() {
final User user = new User();
final String name;
switch (startName) {
case 'c':
case 'C':
name = "Chomsky";
break;
case 'r':
case 'R':
name = "Rawls";
break;
default:
throw new IllegalStateException("Unknown start name: " + startName + ".");
}
user.setName(name);
return user;
}
public char getStartName() {
return startName;
}
public void setStartName(char startName) {
this.startName = startName;
}
} |
package grl.redis.users;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
public class HashSample {
public static void main(String[] args) {
String redisHost = System.getenv("REDIS_HOST");
Jedis redis = new Jedis(redisHost);
Map<String, String> map = new HashMap<>();
map.put("email", "user1@domain.com");
map.put("userid", "12356");
map.put("address", "1111 Main St. Houston TX, 77054");
map.put("phone", "555-124-5544");
// map hmset
redis.hmset("user.by.id." + map.get("userid"), map);
redis.set("user.id.by.email." + map.get("email"), map.get("userid"));
System.out.println("User stored: " + map.get("userid"));
// hgetall
System.out.println(
redis.hgetAll("user.by.id." + map.get("userid"))
);
map = new HashMap<>();
map.put("email", "user2@other.domain.com");
map.put("userid", "24567");
map.put("address", "1111 Main St. Houston TX, 77054");
map.put("phone", "555-124-5544");
redis.hmset("user.by.id." + map.get("userid"), map);
redis.set("user.id.by.email.", map.get("email"));
System.out.println("User stored: " + map.get("userid"));
System.out.println(
redis.hgetAll("user.by.id." + map.get("userid"))
);
// ID ID
String email = "user1@domain.com";
String userid = redis.get("user.id.by.email." + email);
if (userid != null) {
System.out.println(String.format(
"Found user by email: %s",
redis.hgetAll("user.by.id." + userid)
));
}
}
} |
package monitoring.impl;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import monitoring.impl.translators.OfflineTranslator;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import properties.Property;
import properties.competition.Soloist;
import properties.competition.translators.OfflineTranslator_SOLOIST_ONE;
import structure.impl.other.Verdict;
import structure.intf.QEA;
import util.ArrayUtil;
import exceptions.ShouldNotHappenException;
/**
* Content Handler that processes an XML document representing a trace of events
* and passes the events to the specified QEA monitor. The XML format is as
* follows:
*
* {@code
* <log>
<event>
<name>...</name>
<field>
<name>...</name>
<value>...</value>
</field>
<field>
</field>
</event>
<event>
</event>
</log>
* }
*
* @author Helena Cuenca
* @author Giles Reger
*/
public class XMLFileMonitor extends FileMonitor implements ContentHandler {
public static void main(String[] args) throws IOException,
ParserConfigurationException, SAXException {
XMLFileMonitor fileMonitor = new XMLFileMonitor("traces/Team1/B5.xml",
new Soloist().make(Property.SOLOIST_ONE),
new OfflineTranslator_SOLOIST_ONE());
System.out.println(fileMonitor.monitor());
}
/**
* Name of the event that is being processed
*/
private String eventName;
/**
* Number of events processed
*/
private int eventCount;
/**
* Array of field names for the current event
*/
private String[] fieldNames;
/**
* Array of field values for the current event
*/
private String[] fieldValues;
/**
* Count of fields for the current event
*/
private int fieldCount;
/**
* Maximum number of fields for any event in the XML document
*/
private final int MAX_FIELD_COUNT = 10;
/**
* Enumeration representing the possible stages of XML processing
*/
private enum Status {
START, INSIDE_EVENT, EXPECTING_EVENT_NAME, INSIDE_FIELD, EXPECTING_FIELD_NAME, EXPECTING_FIELD_VALUE
}
/**
* Stores the current processing status
*/
private Status status = Status.START;
/**
* Creates an XML file monitor for the specified trace and QEA property
*
* @param traceFileName
* Trace file name
* @param qea
* QEA property
* @throws FileNotFoundException
*/
public XMLFileMonitor(String traceFileName, QEA qea,
OfflineTranslator translator) throws FileNotFoundException {
super(traceFileName, qea, translator);
fieldNames = new String[MAX_FIELD_COUNT];
fieldValues = new String[MAX_FIELD_COUNT];
}
@Override
public Verdict monitor() throws IOException, ParserConfigurationException,
SAXException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(trace));
return translator.getMonitor().end();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
switch (qName) {
case "log":
break;
case "field":
status = Status.INSIDE_FIELD;
break;
case "event":
status = Status.INSIDE_EVENT;
fieldCount = 0;
break;
case "name":
if (status == Status.INSIDE_EVENT) {
status = Status.EXPECTING_EVENT_NAME;
} else {
status = Status.EXPECTING_FIELD_NAME;
}
break;
case "value":
status = Status.EXPECTING_FIELD_VALUE;
break;
default:
throw new ShouldNotHappenException("Unrecognised element: " + qName);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
switch (qName) {
case "name":
if (status == Status.EXPECTING_EVENT_NAME) {
status = Status.INSIDE_EVENT;
} else {
status = Status.INSIDE_FIELD;
}
break;
case "value":
status = Status.INSIDE_FIELD;
break;
case "field":
status = Status.INSIDE_EVENT;
break;
case "event":
eventCount++;
if (step() == Verdict.FAILURE) {
System.out.print("Failure on event #" + eventCount + ": "
+ eventName + "(");
for (int i = 0; i < fieldCount; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(fieldNames[i] + "=" + fieldValues[i]);
}
System.out.println(")");
}
break;
default:
break;
}
}
private Verdict step() {
// int event = translate(eventName);
if (fieldCount == 0) {
return translator.translateAndStep(eventName);
} else {
return translator.translateAndStep(eventName,
ArrayUtil.resize(fieldValues, fieldCount));
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
switch (status) {
case EXPECTING_EVENT_NAME:
eventName = new String(ch, start, length);
break;
case EXPECTING_FIELD_NAME:
fieldNames[fieldCount] = new String(ch, start, length);
break;
case EXPECTING_FIELD_VALUE:
fieldValues[fieldCount] = new String(ch, start, length);
fieldCount++;
break;
default:
break;
}
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
} |
package io.warp10.script;
import io.warp10.script.WarpScriptStack.Macro;
import io.warp10.script.functions.SNAPSHOT.Snapshotable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.io.output.ByteArrayOutputStream;
import com.google.common.base.Charsets;
/**
* Class containing various methods related to macros.
*/
public class MacroHelper {
private static final class MacroWrapper extends NamedWarpScriptFunction implements WarpScriptStackFunction, Snapshotable {
private final Macro macro;
public MacroWrapper(String name, Macro macro) {
super(name);
this.macro = macro;
}
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
stack.exec(this.macro);
return stack;
}
@Override
public String toString() {
if (null != getName()) {
return super.toString();
} else {
return this.macro.toString() + " " + WarpScriptLib.EVAL;
}
}
@Override
public String snapshot() {
return this.toString();
}
}
public static WarpScriptStackFunction wrap(String name, String mc2, boolean secure) {
if (mc2.startsWith("@")) {
return wrap(name, getResource(mc2.substring(1)), secure);
}
MemoryWarpScriptStack stack = new MemoryWarpScriptStack(null, null);
stack.maxLimits();
try {
stack.execMulti(mc2);
} catch (WarpScriptException wse) {
throw new RuntimeException(wse);
}
Object top = stack.pop();
if (!(top instanceof Macro)) {
throw new RuntimeException("WarpScript code did not leave a macro on top of the stack.");
}
((Macro) top).setSecure(secure);
return new MacroWrapper(name, (Macro) top);
}
public static WarpScriptStackFunction wrap(String mc2, boolean secure) {
return wrap(null, mc2, secure);
}
public static WarpScriptStackFunction wrap(String mc2) {
return wrap(null, mc2, false);
}
public static WarpScriptStackFunction wrap(String name, String mc2) {
return wrap(name, mc2, false);
}
public static WarpScriptStackFunction wrap(String name, InputStream in, boolean secure) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
while(true) {
int len = in.read(buf);
if (len < 0) {
break;
}
baos.write(buf, 0, len);
}
in.close();
String mc2 = new String(baos.toByteArray(), Charsets.UTF_8);
return wrap(name, mc2, secure);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public static WarpScriptStackFunction wrap(InputStream in, boolean secure) {
return wrap(null, in, secure);
}
public static WarpScriptStackFunction wrap(InputStream in) {
return wrap(null, in, false);
}
public static WarpScriptStackFunction wrap(String name, InputStream in) {
return wrap(name, in, false);
}
private static InputStream getResource(String path) {
InputStream in = MacroHelper.class.getResourceAsStream(path.startsWith("/") ? path : "/" + path);
if (null == in) {
throw new RuntimeException("Resource " + path + " was not found.");
}
return in;
}
} |
package to.etc.domui.dom.css;
import to.etc.domui.server.*;
import to.etc.domui.util.*;
public class CssBase {
private String m_cachedStyle;
/*-- CSS Background properties --*/
private BackgroundAttachment m_backgroundAttachment;
private String m_backgroundColor;
private String m_backgroundImage;
private String m_backgroundPosition;
private String m_backgroundRepeat;
/*-- CSS Border properties --*/
private int m_borderLeftWidth = -1;
private int m_borderRightWidth = -1;
private int m_borderTopWidth = -1;
private int m_borderBottomWidth = -1;
private String m_borderTopColor;
private String m_borderBottomColor;
private String m_borderLeftColor;
private String m_borderRightColor;
private String m_borderTopStyle;
private String m_borderBottomStyle;
private String m_borderLeftStyle;
private String m_borderRightStyle;
/*-- CSS Classification. --*/
private ClearType m_clear;
// private String m_cursor;
private DisplayType m_display;
private FloatType m_float;
private PositionType m_position;
private VisibilityType m_visibility;
/*-- CSS Dimension properties --*/
private String m_height;
private String m_lineHeight;
private String m_maxHeight;
private String m_maxWidth;
private String m_minHeight;
private String m_minWidth;
private String m_width;
/*-- CSS Font properties. --*/
private String m_fontFamily;
private String m_fontSize;
private String m_fontSizeAdjust;
private FontStyle m_fontStyle;
private FontVariant m_fontVariant;
private String m_fontWeight;
private String m_color;
/*-- Positioning --*/
private Overflow m_overflow;
private int m_zIndex = Integer.MIN_VALUE;
private String m_top;
private String m_bottom;
private String m_left;
private String m_right;
private TextAlign m_textAlign;
private VerticalAlignType m_verticalAlign;
/*-- CSS Margin properties --*/
private String m_marginLeft;
private String m_marginRight;
private String m_marginTop;
private String m_marginBottom;
private TextTransformType m_transform;
public String getCachedStyle() {
return m_cachedStyle;
}
public void setCachedStyle(final String cachedStyle) {
m_cachedStyle = cachedStyle;
}
/**
* Called as soon as a property of <i>this</i> object changes. This dirties this
* object.
*/
protected void changed() {
// FIXME Needs impl.
}
public BackgroundAttachment getBackgroundAttachment() {
return m_backgroundAttachment;
}
public void setBackgroundAttachment(final BackgroundAttachment backgroundAttachment) {
if(!DomUtil.isEqual(backgroundAttachment, m_backgroundAttachment))
changed();
m_backgroundAttachment = backgroundAttachment;
}
public String getBackgroundColor() {
return m_backgroundColor;
}
public void setBackgroundColor(final String backgroundColor) {
if(!DomUtil.isEqual(backgroundColor, m_backgroundColor))
changed();
m_backgroundColor = backgroundColor;
}
public String getBackgroundImage() {
return DomApplication.get().getThemedResourceRURL(m_backgroundImage);
// return m_backgroundImage;
}
public void setBackgroundImage(final String backgroundImage) {
if(!DomUtil.isEqual(backgroundImage, m_backgroundImage))
changed();
m_backgroundImage = backgroundImage;
}
public String getBackgroundPosition() {
return m_backgroundPosition;
}
public void setBackgroundPosition(final String backgroundPosition) {
if(!DomUtil.isEqual(backgroundPosition, m_backgroundPosition))
changed();
m_backgroundPosition = backgroundPosition;
}
public String getBackgroundRepeat() {
return m_backgroundRepeat;
}
public void setBackgroundRepeat(final String backgroundRepeat) {
if(!DomUtil.isEqual(backgroundRepeat, m_backgroundRepeat))
changed();
m_backgroundRepeat = backgroundRepeat;
}
public int getBorderLeftWidth() {
return m_borderLeftWidth;
}
public void setBorderLeftWidth(final int borderLeftWidth) {
if(borderLeftWidth != m_borderLeftWidth)
changed();
m_borderLeftWidth = borderLeftWidth;
}
public int getBorderRightWidth() {
return m_borderRightWidth;
}
public void setBorderRightWidth(final int borderRightWidth) {
if(m_borderRightWidth != borderRightWidth)
changed();
m_borderRightWidth = borderRightWidth;
}
public int getBorderTopWidth() {
return m_borderTopWidth;
}
public void setBorderTopWidth(final int borderTopWidth) {
if(m_borderTopWidth != borderTopWidth)
changed();
m_borderTopWidth = borderTopWidth;
}
public int getBorderBottomWidth() {
return m_borderBottomWidth;
}
public void setBorderBottomWidth(final int borderBottomWidth) {
if(m_borderBottomWidth != borderBottomWidth)
changed();
m_borderBottomWidth = borderBottomWidth;
}
public String getBorderTopColor() {
return m_borderTopColor;
}
public void setBorderTopColor(final String borderTopColor) {
if(!DomUtil.isEqual(borderTopColor, m_borderTopColor))
changed();
m_borderTopColor = borderTopColor;
}
public String getBorderBottomColor() {
return m_borderBottomColor;
}
public void setBorderBottomColor(final String borderBottomColor) {
if(!DomUtil.isEqual(borderBottomColor, m_borderBottomColor))
changed();
m_borderBottomColor = borderBottomColor;
}
public String getBorderLeftColor() {
return m_borderLeftColor;
}
public void setBorderLeftColor(final String borderLeftColor) {
if(!DomUtil.isEqual(borderLeftColor, m_borderLeftColor))
changed();
m_borderLeftColor = borderLeftColor;
}
public String getBorderRightColor() {
return m_borderRightColor;
}
public void setBorderRightColor(final String borderRightColor) {
if(!DomUtil.isEqual(borderRightColor, m_borderRightColor))
changed();
m_borderRightColor = borderRightColor;
}
public String getBorderTopStyle() {
return m_borderTopStyle;
}
public void setBorderTopStyle(final String borderTopStyle) {
if(!DomUtil.isEqual(borderTopStyle, m_borderTopStyle))
changed();
m_borderTopStyle = borderTopStyle;
}
public String getBorderBottomStyle() {
return m_borderBottomStyle;
}
public void setBorderBottomStyle(final String borderBottomStyle) {
if(!DomUtil.isEqual(borderBottomStyle, m_borderBottomStyle))
changed();
m_borderBottomStyle = borderBottomStyle;
}
public String getBorderLeftStyle() {
return m_borderLeftStyle;
}
public void setBorderLeftStyle(final String borderLeftStyle) {
if(!DomUtil.isEqual(borderLeftStyle, m_borderLeftStyle))
changed();
m_borderLeftStyle = borderLeftStyle;
}
public String getBorderRightStyle() {
return m_borderRightStyle;
}
public void setBorderRightStyle(final String borderRightStyle) {
if(!DomUtil.isEqual(borderRightStyle, m_borderRightStyle))
changed();
m_borderRightStyle = borderRightStyle;
}
/*-- Border shortcut calls. --*/
public void setBorderWidth(final int w) {
setBorderLeftWidth(w);
setBorderRightWidth(w);
setBorderTopWidth(w);
setBorderBottomWidth(w);
}
public void setBorderStyle(final String bs) {
setBorderLeftStyle(bs);
setBorderRightStyle(bs);
setBorderTopStyle(bs);
setBorderBottomStyle(bs);
}
public void setBorderColor(final String bs) {
setBorderLeftColor(bs);
setBorderRightColor(bs);
setBorderTopColor(bs);
setBorderBottomColor(bs);
}
public void setBorder(final int w) {
setBorderWidth(w);
}
public void setBorder(final int w, final String color, final String style) {
setBorderWidth(w);
setBorderColor(color);
setBorderStyle(style);
}
public ClearType getClear() {
return m_clear;
}
public void setClear(final ClearType clear) {
if(!DomUtil.isEqual(clear, m_clear))
changed();
m_clear = clear;
}
// public String getCursor() {
// return m_cursor;
// public void setCursor(final String cursor) {
// if(!DomUtil.isEqual(cursor, m_cursor))
// changed();
// m_cursor = cursor;
public DisplayType getDisplay() {
return m_display;
}
public void setDisplay(final DisplayType display) {
if(!DomUtil.isEqual(display, m_display))
changed();
m_display = display;
}
/**
* Used to switch the display attribute when it is switched by an effect.
* @param dt
* @return
*/
public boolean internalSetDisplay(final DisplayType dt) {
if(m_display == dt)
return false;
m_display = dt;
setCachedStyle(null);
return true;
}
public Overflow getOverflow() {
return m_overflow;
}
public void setOverflow(final Overflow overflow) {
if(m_overflow != overflow)
changed();
m_overflow = overflow;
}
public FloatType getFloat() {
return m_float;
}
public void setFloat(final FloatType f) {
if(m_float == f)
return;
changed();
m_float = f;
}
public PositionType getPosition() {
return m_position;
}
public void setPosition(final PositionType position) {
if(m_position == position)
return;
changed();
m_position = position;
}
public VisibilityType getVisibility() {
return m_visibility;
}
public void setVisibility(final VisibilityType visibility) {
if(m_visibility == visibility)
return;
changed();
m_visibility = visibility;
}
public String getHeight() {
return m_height;
}
public void setHeight(final String height) {
if(DomUtil.isEqual(height, m_height))
return;
changed();
m_height = height;
}
public String getLineHeight() {
return m_lineHeight;
}
public void setLineHeight(final String lineHeight) {
if(DomUtil.isEqual(m_lineHeight, lineHeight))
return;
changed();
m_lineHeight = lineHeight;
}
public String getMaxHeight() {
return m_maxHeight;
}
public void setMaxHeight(final String maxHeight) {
if(DomUtil.isEqual(m_maxHeight, maxHeight))
return;
changed();
m_maxHeight = maxHeight;
}
public String getMaxWidth() {
return m_maxWidth;
}
public void setMaxWidth(final String maxWidth) {
if(DomUtil.isEqual(m_maxWidth, maxWidth))
return;
changed();
m_maxWidth = maxWidth;
}
public String getMinHeight() {
return m_minHeight;
}
public void setMinHeight(final String minHeight) {
if(DomUtil.isEqual(m_minHeight, minHeight))
return;
changed();
m_minHeight = minHeight;
}
public String getMinWidth() {
return m_minWidth;
}
public void setMinWidth(final String minWidth) {
if(DomUtil.isEqual(m_minWidth, minWidth))
return;
changed();
m_minWidth = minWidth;
}
public String getWidth() {
return m_width;
}
public void setWidth(final String width) {
if(DomUtil.isEqual(m_width, width))
return;
changed();
m_width = width;
}
public String getFontFamily() {
return m_fontFamily;
}
public void setFontFamily(final String fontFamily) {
if(DomUtil.isEqual(m_fontFamily, fontFamily))
return;
changed();
m_fontFamily = fontFamily;
}
public String getFontSize() {
return m_fontSize;
}
public void setFontSize(final String fontSize) {
if(DomUtil.isEqual(m_fontSize, fontSize))
return;
changed();
m_fontSize = fontSize;
}
public String getFontSizeAdjust() {
return m_fontSizeAdjust;
}
public void setFontSizeAdjust(final String fontSizeAdjust) {
if(DomUtil.isEqual(m_fontSizeAdjust, fontSizeAdjust))
return;
changed();
m_fontSizeAdjust = fontSizeAdjust;
}
public FontStyle getFontStyle() {
return m_fontStyle;
}
public void setFontStyle(final FontStyle fontStyle) {
if(DomUtil.isEqual(m_fontStyle, fontStyle))
return;
changed();
m_fontStyle = fontStyle;
}
public FontVariant getFontVariant() {
return m_fontVariant;
}
public void setFontVariant(final FontVariant fontVariant) {
if(DomUtil.isEqual(m_fontVariant, fontVariant))
return;
changed();
m_fontVariant = fontVariant;
}
public String getFontWeight() {
return m_fontWeight;
}
public void setFontWeight(final String fontWeight) {
if(DomUtil.isEqual(m_fontWeight, fontWeight))
return;
changed();
m_fontWeight = fontWeight;
}
public int getZIndex() {
return m_zIndex;
}
public void setZIndex(final int index) {
if(m_zIndex != index)
changed();
m_zIndex = index;
}
public String getTop() {
return m_top;
}
public void setTop(final String top) {
if(DomUtil.isEqual(top, m_top))
return;
changed();
m_top = top;
}
public void setTop(int px) {
String s = Integer.toString(px) + "px";
setTop(s);
}
public String getBottom() {
return m_bottom;
}
public void setBottom(final String bottom) {
if(DomUtil.isEqual(bottom, m_bottom))
return;
changed();
m_bottom = bottom;
}
public void setBottom(int px) {
String s = Integer.toString(px) + "px";
setBottom(s);
}
public String getLeft() {
return m_left;
}
public void setLeft(final String left) {
if(DomUtil.isEqual(left, m_left))
return;
changed();
m_left = left;
}
public void setLeft(final int px) {
String s = Integer.toString(px) + "px";
setLeft(s);
}
public String getRight() {
return m_right;
}
public void setRight(final String right) {
if(DomUtil.isEqual(right, m_right))
return;
changed();
m_right = right;
}
public void setRight(final int px) {
String s = Integer.toString(px) + "px";
setRight(s);
}
public String getColor() {
return m_color;
}
public void setColor(final String color) {
if(DomUtil.isEqual(color, m_color))
return;
changed();
m_color = color;
}
public TextAlign getTextAlign() {
return m_textAlign;
}
public void setTextAlign(final TextAlign textAlign) {
if(m_textAlign == textAlign)
return;
changed();
m_textAlign = textAlign;
}
public VerticalAlignType getVerticalAlign() {
return m_verticalAlign;
}
public void setVerticalAlign(final VerticalAlignType verticalAlign) {
if(m_verticalAlign == verticalAlign)
return;
changed();
m_verticalAlign = verticalAlign;
}
public String getMarginLeft() {
return m_marginLeft;
}
public void setMarginLeft(String marginLeft) {
if(DomUtil.isEqual(m_marginLeft, marginLeft))
return;
changed();
m_marginLeft = marginLeft;
}
public String getMarginRight() {
return m_marginRight;
}
public void setMarginRight(String marginRight) {
if(DomUtil.isEqual(m_marginRight, marginRight))
return;
changed();
m_marginRight = marginRight;
}
public String getMarginTop() {
return m_marginTop;
}
public void setMarginTop(String marginTop) {
if(DomUtil.isEqual(m_marginTop, marginTop))
return;
changed();
m_marginTop = marginTop;
}
public String getMarginBottom() {
return m_marginBottom;
}
public void setMarginBottom(String marginBottom) {
if(DomUtil.isEqual(m_marginBottom, marginBottom))
return;
changed();
m_marginBottom = marginBottom;
}
public void setMargin(String... margin) {
switch(margin.length){
default:
throw new IllegalStateException("Margin must have 1..4 string parameters.");
case 1:
setMarginTop(margin[0]);
setMarginBottom(margin[0]);
setMarginLeft(margin[0]);
setMarginRight(margin[0]);
break;
case 2:
setMarginTop(margin[0]);
setMarginBottom(margin[0]);
setMarginLeft(margin[1]);
setMarginRight(margin[1]);
break;
case 3:
setMarginTop(margin[0]);
setMarginBottom(margin[2]);
setMarginLeft(margin[1]);
setMarginRight(margin[1]);
break;
case 4:
setMarginTop(margin[0]);
setMarginRight(margin[1]);
setMarginBottom(margin[2]);
setMarginLeft(margin[3]);
break;
}
}
public TextTransformType getTransform() {
return m_transform;
}
public void setTransform(TextTransformType transform) {
if(!DomUtil.isEqual(m_transform, transform))
changed();
m_transform = transform;
}
} |
import net.minecraft.src.*;
import net.minecraft.src.forge.*;
import net.minecraft.src.ic2.api.CropCard;
import java.io.*;
public class BerriesConfig {
public final Configuration config;
public final int cropid_vine;
public final int cropid_blackberry;
public final int cropid_raspberry;
public final int cropid_strawberry;
public final int cropid_blueberry;
public final int cropid_huckleberry;
public final ItemStack item_blackberry;
public final ItemStack item_raspberry;
public final ItemStack item_strawberry;
public final ItemStack item_blueberry;
public final ItemStack item_huckleberry;
public BerriesConfig(Configuration config) {
this.config = config;
try {
config.load();
} catch (RuntimeException e) {
e.printStackTrace();
}
cropid_vine = getInt("cropid.vine", 60);
cropid_blackberry = getInt("cropid.blackberry", 61);
cropid_raspberry = getInt("cropid.raspberry", 62);
cropid_strawberry = getInt("cropid.strawberry", 63);
cropid_blueberry = getInt("cropid.blueberry", 64);
cropid_huckleberry = getInt("cropid.huckleberry", 65);
item_blackberry = getItem("item.blackberry", 20000, 5);
item_raspberry = getItem("item.raspberry", 20000, 8);
item_strawberry = getItem("item.strawberry", 0, 0); // not in Trees++ TODO: new custom item
item_blueberry = getItem("item.blueberry", 20000, 7);
item_huckleberry = getItem("item.huckleberry", 20000, 6);
config.save();
}
public int getInt(String key, int defaultValue) {
return Integer.parseInt(config.getOrCreateIntProperty(key, Configuration.CATEGORY_GENERAL, defaultValue).value);
}
public ItemStack getItem(String key, int defaultID, int defaultDamage) {
int id = this.getInt(key, defaultID);
if (id == 0) {
return null;
}
int damage = this.getInt(key + ".damage", defaultDamage);
return new ItemStack(id, 1, damage);
}
public void registerCrops() {
if (cropid_vine != 0) new VineCrop(cropid_vine);
if (cropid_blackberry != 0 && item_blackberry != null) new BlackberryCrop(cropid_blackberry, item_blackberry);
if (cropid_raspberry != 0 && item_raspberry != null) new RaspberryCrop(cropid_raspberry, item_raspberry);
if (cropid_strawberry != 0 && item_strawberry != null) new StrawberryCrop(cropid_strawberry, item_strawberry);
if (cropid_blueberry != 0 && item_blueberry != null) new BlueberryCrop(cropid_blueberry, item_blueberry);
if (cropid_huckleberry != 0 && item_huckleberry != null) new HuckleberryCrop(cropid_huckleberry, item_huckleberry);
}
} |
package to.etc.domui.dom.html;
public class Select extends InputNodeContainer {
private boolean m_multiple;
private boolean m_disabled;
private int m_size;
private int m_selectedIndex;
public Select() {
super("select");
}
public Select(String... txt) {
this();
for(String s : txt) {
add(new SelectOption(s));
}
}
@Override
public void visit(INodeVisitor v) throws Exception {
v.visitSelect(this);
}
@Override
protected boolean canContain(NodeBase node) {
return node instanceof SelectOption;
}
public boolean isMultiple() {
return m_multiple;
}
public void setMultiple(boolean multiple) {
if(m_multiple == multiple)
return;
m_multiple = multiple;
changed();
}
public boolean isDisabled() {
return m_disabled;
}
public void setDisabled(boolean disabled) {
if(m_disabled == disabled)
return;
m_disabled = disabled;
changed();
}
public int getSize() {
return m_size;
}
public void setSize(int size) {
if(m_size == size)
return;
m_size = size;
changed();
}
@Override
public void setReadOnly(boolean readOnly) {
if(isReadOnly() == readOnly)
return;
changed();
super.setReadOnly(readOnly);
}
public SelectOption getOption(int ix) {
if(ix < 0 || ix >= getChildCount())
throw new ArrayIndexOutOfBoundsException("The option index " + ix + " is invalid, the #options is " + getChildCount());
return (SelectOption) getChild(ix);
}
@Override
public void acceptRequestParameter(String[] values) throws Exception {
String in = values[0];
SelectOption selo = (SelectOption) getPage().findNodeByID(in);
if(selo == null) {
m_selectedIndex = -1;
} else {
m_selectedIndex = findChildIndex(selo); // Must be found
}
for(int i = getChildCount(); --i >= 0;) {
getOption(i).setSelected(i == m_selectedIndex);
}
}
public void clearSelected() {
m_selectedIndex = -1;
for(int i = getChildCount(); --i >= 0;) {
getOption(i).setSelected(false);
}
}
public int getSelectedIndex() {
return m_selectedIndex;
}
public void setSelectedIndex(int ix) {
m_selectedIndex = ix;
for(int i = getChildCount(); --i >= 0;) {
getOption(i).setSelected(i == m_selectedIndex);
}
}
} |
// DataTools.java
package loci.common;
import java.io.File;
import java.io.IOException;
public final class DataTools {
// -- Constants --
// -- Static fields --
// -- Constructor --
private DataTools() { }
// -- Data reading --
/** Reads the contents of the given file into a string. */
public static String readFile(String id) throws IOException {
RandomAccessInputStream in = new RandomAccessInputStream(id);
long idLen = in.length();
if (idLen > Integer.MAX_VALUE) {
throw new IOException("File too large");
}
int len = (int) idLen;
String data = in.readString(len);
in.close();
return data;
}
// -- Word decoding - bytes to primitive types --
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a short. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array beyond the given
* offset to a short. If there are fewer than 2 bytes available
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(byte[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array byond the given
* offset to a short. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
short total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 2 bytes of a byte array byond the given
* offset to a short. If there are fewer than 2 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, int off, boolean little) {
return bytesToShort(bytes, off, 2, little);
}
/**
* Translates up to the first 2 bytes of a byte array to a short.
* If there are fewer than 2 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static short bytesToShort(short[] bytes, boolean little) {
return bytesToShort(bytes, 0, 2, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256 + bytes[ndx] :
(int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(byte[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to an int. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
int total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((int) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 4 bytes of a byte array beyond the given
* offset to an int. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to an int.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static int bytesToInt(short[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a float. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, int off, int len,
boolean little)
{
return Float.intBitsToFloat(bytesToInt(bytes, off, len, little));
}
/**
* Translates up to the first 4 bytes of a byte array beyond a given
* offset to a float. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, int off, boolean little) {
return bytesToFloat(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to a float.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(byte[] bytes, boolean little) {
return bytesToFloat(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond a given
* offset to a float. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, int off, int len,
boolean little)
{
return Float.intBitsToFloat(bytesToInt(bytes, off, len, little));
}
/**
* Translates up to the first 4 bytes of a byte array beyond a given
* offset to a float. If there are fewer than 4 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, int off, boolean little) {
return bytesToInt(bytes, off, 4, little);
}
/**
* Translates up to the first 4 bytes of a byte array to a float.
* If there are fewer than 4 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static float bytesToFloat(short[] bytes, boolean little) {
return bytesToInt(bytes, 0, 4, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= (bytes[ndx] < 0 ? 256L + bytes[ndx] :
(long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(byte[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a long. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, int len,
boolean little)
{
if (bytes.length - off < len) len = bytes.length - off;
long total = 0;
for (int i=0, ndx=off; i<len; i++, ndx++) {
total |= ((long) bytes[ndx]) << ((little ? i : len - i - 1) * 8);
}
return total;
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a long. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, int off, boolean little) {
return bytesToLong(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a long.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static long bytesToLong(short[] bytes, boolean little) {
return bytesToLong(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a double. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, int off, int len,
boolean little)
{
return Double.longBitsToDouble(bytesToLong(bytes, off, len, little));
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a double. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, int off,
boolean little)
{
return bytesToDouble(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a double.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(byte[] bytes, boolean little) {
return bytesToDouble(bytes, 0, 8, little);
}
/**
* Translates up to the first len bytes of a byte array beyond the given
* offset to a double. If there are fewer than len bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, int off, int len,
boolean little)
{
return Double.longBitsToDouble(bytesToLong(bytes, off, len, little));
}
/**
* Translates up to the first 8 bytes of a byte array beyond the given
* offset to a double. If there are fewer than 8 bytes available,
* the MSBs are all assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, int off,
boolean little)
{
return bytesToDouble(bytes, off, 8, little);
}
/**
* Translates up to the first 8 bytes of a byte array to a double.
* If there are fewer than 8 bytes available, the MSBs are all
* assumed to be zero (regardless of endianness).
*/
public static double bytesToDouble(short[] bytes, boolean little) {
return bytesToDouble(bytes, 0, 8, little);
}
/** Translates the given byte array into a String of hexadecimal digits. */
public static String bytesToHex(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<b.length; i++) {
String a = Integer.toHexString(b[i] & 0xff);
if (a.length() == 1) sb.append("0");
sb.append(a);
}
return sb.toString();
}
// -- Word decoding - primitive types to bytes --
/** Translates the short value into an array of two bytes. */
public static byte[] shortToBytes(short value, boolean little) {
byte[] v = new byte[2];
unpackBytes(value, v, 0, 2, little);
return v;
}
/** Translates the int value into an array of four bytes. */
public static byte[] intToBytes(int value, boolean little) {
byte[] v = new byte[4];
unpackBytes(value, v, 0, 4, little);
return v;
}
/** Translates the float value into an array of four bytes. */
public static byte[] floatToBytes(float value, boolean little) {
byte[] v = new byte[4];
unpackBytes(Float.floatToIntBits(value), v, 0, 4, little);
return v;
}
/** Translates the long value into an array of eight bytes. */
public static byte[] longToBytes(long value, boolean little) {
byte[] v = new byte[8];
unpackBytes(value, v, 0, 8, little);
return v;
}
/** Translates the double value into an array of eight bytes. */
public static byte[] doubleToBytes(double value, boolean little) {
byte[] v = new byte[8];
unpackBytes(Double.doubleToLongBits(value), v, 0, 8, little);
return v;
}
/** Translates an array of short values into an array of byte values. */
public static byte[] shortsToBytes(short[] values, boolean little) {
byte[] v = new byte[values.length * 2];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 2, 2, little);
}
return v;
}
/** Translates an array of int values into an array of byte values. */
public static byte[] intsToBytes(int[] values, boolean little) {
byte[] v = new byte[values.length * 4];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 4, 4, little);
}
return v;
}
/** Translates an array of float values into an array of byte values. */
public static byte[] floatsToBytes(float[] values, boolean little) {
byte[] v = new byte[values.length * 4];
for (int i=0; i<values.length; i++) {
unpackBytes(Float.floatToIntBits(values[i]), v, i * 4, 4, little);
}
return v;
}
/** Translates an array of long values into an array of byte values. */
public static byte[] longsToBytes(long[] values, boolean little) {
byte[] v = new byte[values.length * 8];
for (int i=0; i<values.length; i++) {
unpackBytes(values[i], v, i * 8, 8, little);
}
return v;
}
/** Translates an array of double values into an array of byte values. */
public static byte[] doublesToBytes(double[] values, boolean little) {
byte[] v = new byte[values.length * 8];
for (int i=0; i<values.length; i++) {
unpackBytes(Double.doubleToLongBits(values[i]), v, i * 8, 8, little);
}
return v;
}
/** @deprecated Use {@link #unpackBytes(long, byte[], int, int, boolean) */
public static void unpackShort(short value, byte[] buf, int ndx,
boolean little)
{
unpackBytes(value, buf, ndx, 2, little);
}
public static void unpackBytes(long value, byte[] buf, int ndx,
int nBytes, boolean little)
{
if (buf.length < ndx + nBytes) {
throw new IllegalArgumentException("Invalid indices: buf.length=" +
buf.length + ", ndx=" + ndx + ", nBytes=" + nBytes);
}
if (little) {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*i)) & 0xff);
}
}
else {
for (int i=0; i<nBytes; i++) {
buf[ndx + i] = (byte) ((value >> (8*(nBytes - i - 1))) & 0xff);
}
}
}
/**
* Convert a byte array to the appropriate primitive type array.
* @param b Byte array to convert.
* @param bpp Denotes the number of bytes in the returned primitive type
* (e.g. if bpp == 2, we should return an array of type short).
* @param fp If set and bpp == 4 or bpp == 8, then return floats or doubles.
* @param little Whether byte array is in little-endian order.
*/
public static Object makeDataArray(byte[] b, int bpp, boolean fp,
boolean little)
{
if (bpp == 1) {
return b;
}
else if (bpp == 2) {
short[] s = new short[b.length / 2];
for (int i=0; i<s.length; i++) {
s[i] = bytesToShort(b, i*2, 2, little);
}
return s;
}
else if (bpp == 4 && fp) {
float[] f = new float[b.length / 4];
for (int i=0; i<f.length; i++) {
f[i] = bytesToFloat(b, i * 4, 4, little);
}
return f;
}
else if (bpp == 4) {
int[] i = new int[b.length / 4];
for (int j=0; j<i.length; j++) {
i[j] = bytesToInt(b, j*4, 4, little);
}
return i;
}
else if (bpp == 8 && fp) {
double[] d = new double[b.length / 8];
for (int i=0; i<d.length; i++) {
d[i] = bytesToDouble(b, i * 8, 8, little);
}
return d;
}
else if (bpp == 8) {
long[] l = new long[b.length / 8];
for (int i=0; i<l.length; i++) {
l[i] = bytesToLong(b, i*8, 8, little);
}
return l;
}
return null;
}
/**
* @deprecated Use {@link #makeDataArray(byte[], int, boolean, boolean)}
* regardless of signedness.
*/
public static Object makeDataArray(byte[] b,
int bpp, boolean fp, boolean little, boolean signed)
{
return makeDataArray(b, bpp, fp, little);
}
// -- Byte swapping --
public static short swap(short x) {
return (short) ((x << 8) | ((x >> 8) & 0xFF));
}
public static char swap(char x) {
return (char) ((x << 8) | ((x >> 8) & 0xFF));
}
public static int swap(int x) {
return (int) ((swap((short) x) << 16) | (swap((short) (x >> 16)) & 0xFFFF));
}
public static long swap(long x) {
return (long) (((long) swap((int) x) << 32) |
((long) swap((int) (x >> 32)) & 0xFFFFFFFFL));
}
public static float swap(float x) {
return Float.intBitsToFloat(swap(Float.floatToIntBits(x)));
}
public static double swap(double x) {
return Double.longBitsToDouble(swap(Double.doubleToLongBits(x)));
}
// -- Strings --
/** Convert byte array to a hexadecimal string. */
public static String getHexString(byte[] b) {
StringBuffer sb = new StringBuffer();
for (int i=0; i<b.length; i++) {
String a = Integer.toHexString(b[i] & 0xff);
if (a.length() == 1) sb.append("0");
sb.append(a);
}
return sb.toString();
}
/** Remove null bytes from a string. */
public static String stripString(String toStrip) {
StringBuffer s = new StringBuffer();
for (int i=0; i<toStrip.length(); i++) {
if (toStrip.charAt(i) != 0) {
s.append(toStrip.charAt(i));
}
}
return s.toString().trim();
}
/** Check if two filenames have the same prefix. */
public static boolean samePrefix(String s1, String s2) {
if (s1 == null || s2 == null) return false;
int n1 = s1.indexOf(".");
int n2 = s2.indexOf(".");
if ((n1 == -1) || (n2 == -1)) return false;
int slash1 = s1.lastIndexOf(File.pathSeparator);
int slash2 = s2.lastIndexOf(File.pathSeparator);
String sub1 = s1.substring(slash1 + 1, n1);
String sub2 = s2.substring(slash2 + 1, n2);
return sub1.equals(sub2) || sub1.startsWith(sub2) || sub2.startsWith(sub1);
}
/** Remove unprintable characters from the given string. */
public static String sanitize(String s) {
if (s == null) return null;
StringBuffer buf = new StringBuffer(s);
for (int i=0; i<buf.length(); i++) {
char c = buf.charAt(i);
if (c != '\t' && c != '\n' && (c < ' ' || c > '~')) {
buf = buf.deleteCharAt(i
}
}
return buf.toString();
}
// -- Normalization --
/**
* Normalize the given float array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static float[] normalizeFloats(float[] data) {
float[] rtn = new float[data.length];
// determine the finite min and max values
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] == Float.POSITIVE_INFINITY ||
data[i] == Float.NEGATIVE_INFINITY)
{
continue;
}
if (data[i] < min) min = data[i];
if (data[i] > max) max = data[i];
}
// normalize infinity values
for (int i=0; i<data.length; i++) {
if (data[i] == Float.POSITIVE_INFINITY) data[i] = max;
else if (data[i] == Float.NEGATIVE_INFINITY) data[i] = min;
}
// now normalize; min => 0.0, max => 1.0
float range = max - min;
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / range;
}
return rtn;
}
/**
* Normalize the given double array so that the minimum value maps to 0.0
* and the maximum value maps to 1.0.
*/
public static double[] normalizeDoubles(double[] data) {
double[] rtn = new double[data.length];
// determine the finite min and max values
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int i=0; i<data.length; i++) {
if (data[i] == Double.POSITIVE_INFINITY ||
data[i] == Double.NEGATIVE_INFINITY)
{
continue;
}
if (data[i] < min) min = data[i];
if (data[i] > max) max = data[i];
}
// normalize infinity values
for (int i=0; i<data.length; i++) {
if (data[i] == Double.POSITIVE_INFINITY) data[i] = max;
else if (data[i] == Double.NEGATIVE_INFINITY) data[i] = min;
}
// now normalize; min => 0.0, max => 1.0
double range = max - min;
for (int i=0; i<rtn.length; i++) {
rtn[i] = (data[i] - min) / range;
}
return rtn;
}
// -- Array handling --
/** Returns true if the given value is contained in the given array. */
public static boolean containsValue(int[] array, int value) {
return indexOf(array, value) != -1;
}
/**
* Returns the index of the first occurrence of the given value in the given
* array. If the value is not in the array, returns -1.
*/
public static int indexOf(int[] array, int value) {
for (int i=0; i<array.length; i++) {
if (array[i] == value) return i;
}
return -1;
}
/**
* Returns the index of the first occurrence of the given value in the given
* Object array. If the value is not in the array, returns -1.
*/
public static int indexOf(Object[] array, Object value) {
for (int i=0; i<array.length; i++) {
if (value == null) {
if (array[i] == null) return i;
}
else if (value.equals(array[i])) return i;
}
return -1;
}
// -- Signed data conversion --
public static byte[] makeSigned(byte[] b) {
for (int i=0; i<b.length; i++) {
b[i] = (byte) (b[i] + 128);
}
return b;
}
public static short[] makeSigned(short[] s) {
for (int i=0; i<s.length; i++) {
s[i] = (short) (s[i] + 32768);
}
return s;
}
public static int[] makeSigned(int[] i) {
for (int j=0; j<i.length; j++) {
i[j] = (int) (i[j] + 2147483648L);
}
return i;
}
} |
// BF.java
package loci.plugins;
import ij.IJ;
import ij.ImagePlus;
import java.io.IOException;
import loci.formats.FormatException;
import loci.plugins.in.ImagePlusReader;
import loci.plugins.in.ImportProcess;
import loci.plugins.in.ImporterOptions;
import loci.plugins.in.ImporterPrompter;
public final class BF {
// -- Constructor --
private BF() { }
// -- Utility methods --
public static void debug(String msg) {
if (IJ.debugMode) IJ.log("LOCI: " + msg);
}
public static void status(boolean quiet, String msg) {
if (quiet) return;
IJ.showStatus(msg);
}
public static void warn(boolean quiet, String msg) {
if (quiet) return;
IJ.log("Warning: " + msg);
}
public static void progress(boolean quiet, int value, int max) {
if (quiet) return;
IJ.showProgress(value, max);
}
public static ImagePlus[] openImagePlus(String path)
throws FormatException, IOException
{
ImporterOptions options = new ImporterOptions();
options.setId(path);
return openImagePlus(options);
}
public static ImagePlus[] openImagePlus(ImporterOptions options)
throws FormatException, IOException
{
// TODO: Eliminate use of the ImporterPrompter. While no dialogs should
// appear due to the quiet and windowless flags, it would be cleaner to
// avoid piping everything through invisible GenericDialogs internally.
// However, we need to be sure all the Dialog classes are not performing
// any "side-effect" logic on the ImportProcess and/or ImporterOptions
// before we can make this change.
// Another downside might be that we could miss out on any other magic that
// ImageJ is performing (e.g., macro-related functionality), but further
// testing is warranted.
options.setQuiet(true); // NB: Only needed due to ImporterPrompter.
options.setWindowless(true); // NB: Only needed due to ImporterPrompter.
ImportProcess process = new ImportProcess(options);
new ImporterPrompter(process); // NB: Could eliminate this (see above).
if (!process.execute()) return null;
ImagePlusReader reader = new ImagePlusReader(process);
return reader.openImagePlus();
}
} |
package com.winterwell.web;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.RedirectException;
import com.winterwell.utils.FailureException;
import com.winterwell.utils.Printer;
import com.winterwell.utils.StrUtils;
import com.winterwell.utils.TodoException;
import com.winterwell.utils.Utils;
import com.winterwell.utils.WrappedException;
import com.winterwell.utils.containers.ArrayMap;
import com.winterwell.utils.containers.Containers;
import com.winterwell.utils.io.FileUtils;
import com.winterwell.utils.log.Log;
import com.winterwell.utils.web.Cooldown;
import com.winterwell.utils.web.WebUtils;
import com.winterwell.utils.web.WebUtils2;
import com.winterwell.web.data.XId;
import lgpl.haustein.Base64Encoder;
/**
* A pretend web browser. Stores cookies so it can step through sessions.
* <i>Not</i> thread safe.
*
* HTMLUnit is a much more complete version of this (it includes Javascript
* handling). Apache's HttpClient is a more complex version of this (more boilerplate but
* also more options).
*
* FIXME: SSL is currently hacked to disable any kind of certificate checks or
* man-in-the-middle detection. At the very least this should be optional.
*
* @author daniel
* @testedby {@link FakeBrowserTest}
*/
public class FakeBrowser {
static final int DEFAULT_TIMEOUT = 60000;
private static SSLContext INSECURE_SSL_CONTEXT;
static Pattern keyValue = Pattern
.compile("([^; \\t\\r\\n\\]]+)=([^; \\t\\r\\n\\]]+)");
public static final String MIME_TYPE_URLENCODED_FORM = "application/x-www-form-urlencoded";
boolean reqGzip = false;
/**
* Toggles the "Accept-Encoding" header to request gzip compression
* @param gzip
*/
public void setRequestGzip(boolean gzip) {
this.reqGzip = gzip;
if (gzip) {
// Add a "we take gzip here" marker
reqHeaders.put("Accept-Encoding", "gzip");
// + (gzip) to the user-agent
// This hack is for Google API See https://developers.google.com/discovery/v1/performance#gzip
String ua = getUserAgent();
if ( ! ua.contains("gzip")) {
ua += " (gzip)";
setUserAgent(ua);
}
} else {
// No gzip!
Object ae = reqHeaders.get("Accept-Encoding");
if ("gzip".equals(ae)) {
reqHeaders.remove("Accept-Encoding");
}
}
}
static final Pattern pInput = Pattern.compile("<input[^>]+>",
Pattern.DOTALL);
static final Pattern pName = Pattern.compile("name=['\"](.*?)['\"]",
Pattern.DOTALL);
static final Pattern pName2 = Pattern
.compile("name=(\\S+)", Pattern.DOTALL);
// TODO unit tests for these patterns
private static final Pattern pSrc = Pattern.compile("src=['\"](.+?)['\"]",
Pattern.DOTALL);
static final Pattern pValue = Pattern.compile("value=['\"](.*?)['\"]",
Pattern.DOTALL);
static final Pattern pValue2 = Pattern.compile("value=(\\S+)",
Pattern.DOTALL);
private static final int MAX_REDIRECTS = 10;
private static final String LOGTAG = "FakeBrowser";
/**
* Chrome v50
*/
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36";
/**
* Use this if you want to let servers know its FakeBrowser
*/
public static final String HONEST_USER_AGENT = "GoodLoopJavaBrowser";
static {
try {
INSECURE_SSL_CONTEXT = SSLContext.getInstance("SSL");
INSECURE_SSL_CONTEXT.init(null,
new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
} }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
} catch (KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
private int code;
private HttpURLConnection connection;
/**
* Map host to key/value pairs TODO this doesn't support deleting cookies,
* or proper domain/path handling
*/
private final Map<String, Map<String,String>> cookieJar = new HashMap();
private File downloadFile;
/**
* Request image and css files to look that bit more genuine.
*/
private boolean downloadImages = false;
/**
* response headers
*/
private Map<String, List<String>> headers;
/**
* If true (the default) binary data is ignored. If false, data is stored in
* {@link #downloadFile}
*/
private boolean ignoreBinaryFiles = true;
/**
* Store the last uri requested
*/
private String location;
/**
* Only allow 10 mb?!
* -1 => unlimited
*/
private long MAX_DOWNLOAD = 10 * 1024 * 1024;
String name;
private boolean parsePagesFlag;
String password;
/**
* Actually run JavaScript. Requires a DOM and is never going to be 100%
* compliant.
*/
private boolean runScripts = false;
/**
* If true, the web page/object will be saved to a file regardless of its
* type or the ignoreBinaryFiles setting.
*/
private boolean saveToFile;
/** Delay a second before posts? */
private final boolean slowPosts = false;
int timeOutMilliSecs = DEFAULT_TIMEOUT;
private File userDownloadFile;
private boolean followRedirects = true;
private boolean debug;
/**
* Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed.
* True by default.
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
private void disconnect() {
if (connection == null)
return;
// Do we also need to call close on the streams??
connection.disconnect();
connection = null;
}
public File getFile(String uri) {
// if (ignoreBinaryFiles) throw new
boolean oldSTF = saveToFile;
saveToFile = true;
try {
String p = getPage(uri);
if (p != null)
throw new IllegalArgumentException(uri + " returned text: " + p);
return downloadFile;
} finally {
saveToFile = oldSTF;
}
}
/**
* Extract the form fields from a page
*
* @param page
* @param formAction
* @return the key/value pairs from the form, or null if the form was not
* found
*/
public Map<String, String> getFormFields(String page, String formAction) {
Map<String, String> map = new HashMap<String, String>();
Pattern pForm = Pattern.compile("<form[^>]+action=." + formAction
+ ".+?</form>", Pattern.DOTALL);
String[] form = StrUtils.find(pForm, page);
if (form == null)
return null;
Matcher m = pInput.matcher(form[0]);
while (m.find()) {
String input = m.group();
String[] bits = StrUtils.find(pName, input);
String[] bits2 = StrUtils.find(pValue, input);
if (bits != null) {
map.put(bits[1], bits2 == null ? null : bits2[1]);
}
}
return map;
}
/**
* @param host e.g. "winterwell.com"
* @return cookie-to-value
*/
public Map<String,String> getHostCookies(String host) {
Map<String,String> cookies = cookieJar.get(host);
return cookies;
}
/**
* FIXME need to have two connection objects: one for pages, one for images,
* etc.
*
* @return The last url fetched. Note: If a redirect happens, then this is the redirected-to url!
*/
public String getLocation() {
return location;
}
/**
* Convenience for {@link #getPage(String, Map)} with no parameters.
*/
public String getPage(String uri) throws WrappedException {
return getPage(uri, null);
}
/**
*
* @param uri
* @param vars
* @return the web page as text, or null if binary data. The page will also
* be stored in the FakeBrowser object if parsing is switched on.
* @throws IORException
* if something goes wrong
*/
public String getPage(String uri, Map<String, String> vars) {
return getPage2(uri, vars, 0);
}
String getPage2(String uri, Map<String, String> vars, int depth) {
// e.g. 2 retries = 3 tries in total
int tries = Math.max(retryOnError + 1, 1);
Exception err = null;
for(int t=0; t<tries; t++) {
try {
assert uri != null : "URI is null!";
assert timeOutMilliSecs > 0 : "problem with timeOutMilliSecs";
// Build URI with query params
uri = WebUtils.addQueryParameters(uri, vars);
if (debug) {
Log.d("get", uri);
}
// Setup a connection
setupConnection(uri, timeOutMilliSecs);
location = uri;
// Open a connection and process response
String response = processResponse();
return response;
} catch (WebEx.Redirect e) {
return getPage3_redirect(uri, vars, depth, e);
} catch (Exception ex) {
// pause, unless that was our last try (in which case we'll exit the for loop and throw an exception)
if (t < tries-1) {
Utils.sleep(t*t*100);
}
err = ex;
} finally {
disconnect();
}
}
// fail if here (out of tries)
throw Utils.runtime(err);
}
private String getPage3_redirect(String uri, Map<String, String> vars, int depth, WebEx.Redirect e)
{
if ( ! followRedirects) {
throw e;
}
if (depth > MAX_REDIRECTS) {
// Give up (let's call it a 500 since it's the remote server's fault)
throw new WebEx.E50X(500, uri, "Too many redirects");
}
// Handle a redirect
String redirect = e.to;
URI r2 = WebUtils.resolveUri(uri, redirect);
redirect = r2.toString();
if (redirect.equals(uri)) {
throw new WebEx.E50X(500, uri, "Loopy redirect");
}
// Redirect
connection.disconnect();
connection = null;
return getPage2(redirect, vars, depth+1);
}
/**
* @param string
* @return
*/
public List<String> getResponseHeaders(String header) {
return headers.get(header);
}
public Map<String, List<String>> getResponseHeaders() {
return headers;
}
/**
* @return
* @throws IOException
*/
public int getStatus() throws IOException {
return code;
}
String requestMethod;
private String errorPage;
/**
* Fake a form POST.
*
* @param uri
* The uri to post to.
* @param vars
* The form variables to send. These are URL encoded before
* sending.
* @return The response from the server.
*/
public String post(String uri, Map<String, String> vars) {
String encodedData = WebUtils.urlEncode(vars);
return post(uri, MIME_TYPE_URLENCODED_FORM, encodedData);
}
/**
* @param uri
* The uri to post to.
* @param body
* This will be URL encoded before sending.
* @return The response from the server.
*/
public String post(String uri, String body) {
String encodedData = WebUtils.urlEncode(body);
return post(uri, MIME_TYPE_URLENCODED_FORM, encodedData);
}
/**
* TODO merge with {@link #post(String, Map)} if successful
*
* @param uri
* @param contentType e.g. FakeBrowser.MIME_TYPE_URLENCODED_FORM
* @param encodedPostBody
* ??
* @return
* @throws WrappedException of IOException
*/
public String post(String uri, String contentType, String encodedPostBody)
throws WrappedException
{
// People are never too fast
if (slowPosts) {
Utils.sleep(new Random().nextInt(750));
}
// uri = uri.replace("format", format.toString());
if (debug) {
String sheaders = StrUtils.join(Containers.apply(reqHeaders.keySet(), h -> {
Object v = reqHeaders.get(h);
return v==null? "" : " -H '"+h+": "+v+"'";
}), " ");
String postBody = WebUtils2.urlDecode(encodedPostBody);
String curl = StrUtils.compactWhitespace("curl -XPOST -d '"+postBody+"'"+sheaders+" '"+uri+"'");
Log.d(LOGTAG, curl);
}
try {
connection = setupConnection(uri, DEFAULT_TIMEOUT);
// Post out
connection.setDoOutput(true);
if (requestMethod==null) {
connection.setRequestMethod("POST");
}
if (contentType!=null) {
connection.setRequestProperty("Content-Type", contentType);
}
byte[] bytes = encodedPostBody.getBytes();
connection.setRequestProperty("Content-Length",
String.valueOf(bytes.length));
OutputStream os = connection.getOutputStream();
os.write(bytes);
FileUtils.close(os);
// Response
// TODO handle redirect, copy fetch code
return processResponse();
} catch (IOException ex) {
throw new WrappedException(ex);
} finally {
disconnect();
}
}
/**
*
* @param connection
* @return text or null if binary data. Binary data will be either ignored
* or stored in a file
* @throws IOException
*/
private String processResponse() throws IOException {
errorPage = null;
// Cookies
try {
updateCookies();
} catch(IllegalArgumentException ex) {
// First access of http headers -- can throw this due to a bug in Sun's connection handling
throw new IOException("Java bug fail: "+getLocation()+" "+ex);
} catch(NoSuchElementException ex) {
// WTF?
throw new IOException("Odd fail: "+getLocation()+" "+ex);
}
// Process error codes
processResponse2_errorCodes();
// data stream
headers = connection.getHeaderFields();
InputStream inStream = connection.getInputStream();
List<String> enc = headers.get("Content-Encoding");
if (enc!=null && ! enc.isEmpty() && enc.get(0).equalsIgnoreCase("gzip")) {
inStream = new GZIPInputStream(inStream);
}
// ...defend against giant files
if (MAX_DOWNLOAD>0) {
inStream = new LimitedInputStream(inStream, MAX_DOWNLOAD);
}
// Interpret as text by default
String type = "text";
// NB Alas some services e.g. protx do not provide a content-type
// header...
if (connection.getContentType() != null) {
type = connection.getContentType().trim().toLowerCase();
}
// Save to a file?
if (saveToFile || type.startsWith("image")) { // TODO video, audio, etc
processResponse2_binary(type, inStream);
return null;
}
// Normal Page
String response = FileUtils.read(inStream);
if (downloadImages) {
requestImages(connection.getURL(), response);
requestStyles(response);
}
return response;
}
private void processResponse2_binary(String type, InputStream inStream)
throws IOException {
if (ignoreBinaryFiles && !saveToFile)
return;
// Make a file...
String fileType = FileUtils.getType(getLocation());
// Chop out url vars
int i = fileType.indexOf('?');
if (i != -1) {
fileType = fileType.substring(0, i);
}
// Make safe
fileType = FileUtils.safeFilename(fileType, false);
// Shorten if long
if (fileType.length() > 4) {
fileType = fileType.substring(0, 4);
}
// .thing
if ( ! fileType.startsWith(".")) fileType = "."+fileType;
// too short? ie empty
if (fileType.length() < 2) {
fileType += "xx";
}
// Create (or use the previous/set value)
downloadFile = userDownloadFile;
if (downloadFile==null) {
downloadFile = File.createTempFile("download", fileType);
}
// Copy into file
FileUtils.copy(inStream, downloadFile);
}
@Override
public String toString() {
return "FakeBrowser[location="+getLocation()+"]";
}
private void processResponse2_errorCodes()
throws IOException {
// Code
try {
code = connection.getResponseCode();
} catch(IOException ex) {
if (ex.getMessage()==null || ! ex.getMessage().contains("http")) {
// include the url
throw new com.winterwell.utils.WrappedException("Error from "+connection.getURL().toString()+" - "+ex, ex);
}
throw ex;
}
// Location (which can be changed by redirects)
location = connection.getURL().toString();
// All good
if (code >= 200 && code < 300)
return;
// Process code
Map<String, List<String>> headers = connection.getHeaderFields();
// Redirect
if (code >= 300 && code < 400) {
List<String> locns = headers.get("Location");
if (locns!=null && locns.size() != 0 && locns.get(0)!=null)
throw new WebEx.Redirect(code, location, locns.get(0));
throw new IOException(code + " (redirect) "
+ Printer.toString(headers));
}
String errorMessage = Printer.toString(headers.get(null));
InputStream es = connection.getErrorStream();
if (es != null) {
try {
errorPage = FileUtils.read(es);
// allow for quite a bit of error 'cos it can be vital for debugging
errorMessage += StrUtils.ellipsize(WebUtils.stripTags(errorPage), 1500);
} catch(Exception ex) {
// ignore
}
}
// Client error
String url = connection.getURL().toString();
if (code >= 400 && code < 500) {
if (code==404) {
throw new WebEx.E404(url, errorMessage);
}
if (code==403) {
throw new WebEx.E403(url, errorMessage);
}
if (code==401) {
throw new WebEx.E401(url, errorMessage);
}
if (code==410) {
throw new WebEx.E410(url, errorMessage);
}
throw new WebEx.E40X(code, errorMessage+" "+url);
}
// Server error
if (code >= 500) {
throw new WebEx.E50X(code, url, "(server error): " + errorMessage);
}
throw new IOException(code + " (unrecognised error): " + errorMessage);
}
/**
* @return error-page from the last request, or null
* The error-page is sometimes a json blob with useful debug info.
*/
public String getErrorPage() {
return errorPage;
}
private void requestImages(URL base, String response) {
Matcher m = pSrc.matcher(response);
while (m.find()) {
String huh = m.group();
String huh2 = response.substring(m.start(), m.end() + 50);
String src = m.group(1);
URI srcUri = WebUtils.resolveUri(base.toString(), src);
// fetch and ignore
try {
getPage(srcUri.toString(), null);
} catch (Exception e) {
// ignore
}
}
}
private void requestStyles(String response) {
// TODO Auto-generated method stub
throw new TodoException();
}
/**
* Set basic authentication
* @param name Can be null (unusual but valid)
* @param password
* @return
*/
public FakeBrowser setAuthentication(String name, String password) {
this.name = name;
this.password = password;
return this;
}
/**
* Set a header for basic authentication login.
*/
private void setBasicAuthentication(URLConnection connection, String name,
String password) {
assert password != null;
String token = (name==null? "" : name) + ":" + password;
String encoding = Base64Encoder.encode(token);
encoding = encoding.replace("\r\n", "");
connection.setRequestProperty("Authorization", "Basic " + encoding);
}
private void setCookies(URLConnection connection) {
Map<String, String> cookies = getHostCookies(connection.getURL()
.getHost());
if (cookies == null)
return;
StringBuilder cList = new StringBuilder();
for (Map.Entry<String,String> c : cookies.entrySet()) {
cList.append(c.getKey());
cList.append('=');
cList.append(c.getValue());
cList.append("; ");
}
StrUtils.pop(cList, 1);
connection.setRequestProperty("Cookie", cList.toString());
}
public void setDownloadImages(boolean b) {
downloadImages = b;
}
/**
* If true (the default) binary data is ignored. If false, data is stored in
* {@link #downloadFile}
*/
public void setIgnoreBinaryFiles(boolean b) {
ignoreBinaryFiles = b;
}
/**
* max 10 mb by default. -1 for unlimited
*/
public void setMaxDownload(int mb) {
if (mb==-1) {
MAX_DOWNLOAD = -1; //unlimited
return;
}
assert mb > 0 : mb;
MAX_DOWNLOAD = mb * 1024L * 1024L;
}
/**
* Set the maximum amount of time to hold a connection for.
*
* @param milliSecs
*/
public void setTimeOut(long milliSecs) {
timeOutMilliSecs = (int) milliSecs;
}
Map<String,Object> reqHeaders = new ArrayMap(
// pretend to be modernish Firefox
"User-Agent", DEFAULT_USER_AGENT
);
private Proxy proxy;
public String getUserAgent() {
return (String) reqHeaders.get("User-Agent");
}
public FakeBrowser setUserAgent(String ua) {
reqHeaders.put("User-Agent", ua);
return this;
}
public void setRequestHeader(String header, Object value) {
reqHeaders.put(header, value);
}
Cooldown cooldown;
private int retryOnError;
/**
* Create a connection and set it up (authentication, cookies) - but do not
* open it
*
* @param uri
* @param timeOutMilliSecs
* @return
* @throws IOException
*/
HttpURLConnection setupConnection(String uri, int timeOutMilliSecs)
throws IOException
{
URL url = new URL(uri);
if (cooldown!=null) {
String host = url.getHost();
if (cooldown.isCoolingDown(new XId(host, "domain", false))) {
throw new WebEx.E50X(new FailureException("Pre-emptive fail: "+host+" is in Cooldown"));
}
}
assert connection == null : connection.getURL();
if (proxy==null) {
connection = (HttpURLConnection) url.openConnection();
} else {
connection = (HttpURLConnection) url.openConnection(proxy);
}
// GET or POST
if (requestMethod!=null) {
connection.setRequestMethod(requestMethod);
}
// HACK: Disable SSL certificate/hostname checks
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection sec = ((HttpsURLConnection) connection);
sec.setSSLSocketFactory(INSECURE_SSL_CONTEXT.getSocketFactory());
sec.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
// Authenticate?
if (password!=null) {
assert password != null;
setBasicAuthentication(connection, name, password);
}
// Set outgoing request headers
for(String h : reqHeaders.keySet()) {
Object v = reqHeaders.get(h);
if (v==null) continue;
connection.setRequestProperty(h, v.toString());
}
connection.setDoInput(true); // we always want input?
connection.setReadTimeout(timeOutMilliSecs);
connection.setInstanceFollowRedirects(false); // See bug 8293 -- our own handling seems to be better
// Set cookies!
setCookies(connection);
return connection;
}
void updateCookie(String host, String cookie) {
// TODO handle cookie expiry
Matcher m = keyValue.matcher(cookie);
boolean ok = m.find();
if (!ok)
return;
String k = m.group(1);
String v = m.group(2);
setCookie(host, k, v);
}
/**
* Set a "fake" cookie
* @param host
* @param cookieName
* @param cookieValue
*/
public void setCookie(String host, String cookieName, Object cookieValue) {
Map<String, String> hostJar = cookieJar.get(host);
if (hostJar==null) {
hostJar = new HashMap();
cookieJar.put(host, hostJar);
}
if (cookieValue==null || cookieValue.toString().isEmpty()) {
hostJar.remove(cookieName);
} else {
hostJar.put(cookieName, String.valueOf(cookieValue));
}
}
private void updateCookies() {
String host = connection.getURL().getHost();
Map<String, List<String>> headers = connection.getHeaderFields();
List<String> cookies = headers.get("Set-Cookie");
if (cookies == null)
return;
for (String cookie : cookies) {
updateCookie(host, cookie);
}
}
public void setSaveToFile(File file) {
userDownloadFile = file;
}
/**
* If true, output all get urls to Log
* @param debug
* @return this
*/
public FakeBrowser setDebug(boolean debug) {
this.debug = debug;
return this;
}
/**
* Set the request method. This will override the normal use of GET or POST,
* for all requests until it is reset to null.
* @param method Can be null for default behaviour.
* @return this
*/
public FakeBrowser setRequestMethod(String method) {
this.requestMethod = method;
return this;
}
/**
*
* @param proxy Can be null for no-proxy
*/
public void setProxy(Proxy proxy) {
this.proxy = proxy;
}
/**
*
* @param proxyIP Can be null for no-proxy
* @param port
*/
public void setProxy(String proxyIP, int port) {
if (proxyIP==null) {
proxy = null;
return;
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIP, port));
setProxy(proxy);
}
public void setCooldown(Cooldown cooldown) {
this.cooldown = cooldown;
}
public Cooldown getCooldown() {
return cooldown;
}
public FakeBrowser setAuthenticationByJWT(String token) {
setRequestHeader("Authorization", "Bearer "+token);
return this;
}
public void setRetryOnError(int retries) {
this.retryOnError = retries;
}
} |
package com.willcurrie;
import com.willcurrie.decoders.*;
import com.willcurrie.tlv.Tag;
import static com.willcurrie.decoders.Decoders.DOL;
import static com.willcurrie.decoders.PrimitiveDecoder.ASCII;
import static com.willcurrie.decoders.PrimitiveDecoder.BASE_10;
import static com.willcurrie.decoders.PrimitiveDecoder.HEX;
public class EmvTags {
public static final TagMetaData METADATA = new TagMetaData();
public static final Tag RECOGNISE_CARD_SUPPORTED_OPTIONS = newTag("DF8178", "recognise card supported options", HEX);
public static final Tag ASCII_CODE_TABLE_INDEX = newTag("DF8172", "ascii code table index", HEX);
public static final Tag BRAND_TABLE = newTag("FB", "brand table", HEX);
public static final Tag BRAND_TABLE_CHIP_FLAG = newTag("DF8173", "brand table chip flag", HEX);
public static final Tag BRAND_ID = newTag("DF5F", "BRAND_ID", HEX);
public static final Tag APPLICATION_SELECTION_INDICATOR = newTag("DF8175", "application selection indicator", HEX);
public static final Tag BRAND_ACCEPTED = newTag("DF8174", "brand accepted", HEX);
public static final Tag AID_TABLE_DOMESTIC_FLAG = newTag("DF9009", "aid table domestic flag", HEX);
public static final Tag NEXT_INDEX_IF_POS = newTag("DF9007", "next index if pos", HEX);
public static final Tag NEXT_INDEX_IF_NEG = newTag("DF9008", "next index if neg", HEX);
public static final Tag AID_TABLE = newTag("E5", "AID table", HEX);
public static final Tag POS_ENTRY_MODE = newTag("9F39", "pos entry mode", HEX);
public static final Tag TERMINAL_APPLICATION_VERSION_NUMBER = newTag("9F09", "terminal application version number", HEX);
public static final Tag DEFAULT_DDOL = newTag("DF5D", "Default DDOL", "Default DDOL", DOL);
public static final Tag TAC_DENIAL = newTag("DF57", "TAC denial", Decoders.TVR);
public static final Tag TAC_ONLINE = newTag("DF58", "TAC online", Decoders.TVR);
public static final Tag TAC_DEFAULT = newTag("DF56", "TAC default", Decoders.TVR);
public static final Tag TERMINAL_FLOOR_LIMIT = newTag("9F1B", "terminal floor limit", HEX);
public static final Tag TARGET_PERCENTAGE = newTag("DF5A", "target percentage", HEX);
public static final Tag MAX_TARGET_PERCENTAGE = newTag("DF5B", "max target percentage", HEX);
public static final Tag THRESHOLD_VALUE = newTag("DF5C", "threshold value", HEX);
public static final Tag FINAL_SELECT_INITIATE_TX = newTag("DF3A", "final select initiate tx", HEX);
// public static final Tag TRANSACTION_CURRENCY_CODE = newTag("5F2A", "transaction currency code", HEX);
public static final Tag TERMINAL_COUNTRY_CODE = newTag("9F1A", "terminal country code", HEX);
public static final Tag TRANSACTION_CURRENCY_EXPONENT = newTag("5F36", "transaction currency exponent", HEX);
public static final Tag MERCHANT_ID = newTag("9F16", "merchant id", ASCII);
public static final Tag MERCHANT_CATEGORY_CODE = newTag("9F15", "merchant category code", HEX);
public static final Tag TERMINAL_ID = newTag("9F1C", "terminal id", ASCII);
public static final Tag TERMINAL_CAPABILITIES = newTag("9F33", "terminal capabilities", HEX);
public static final Tag ADDITIONAL_TERMINAL_CAPABILITIES = newTag("9F40", "additional terminal capabilities", HEX);
public static final Tag TERMINAL_TYPE = newTag("9F35", "terminal type", HEX);
public static final Tag APPLICATION_ID = newTag("9F06", "application id", HEX);
public static final Tag TRANSACTION_DATE = newTag("9A", "transaction date", HEX);
public static final Tag TRANSACTION_TIME = newTag("9F21", "transaction time", HEX);
public static final Tag TRANSACTION_AMOUNT = newTag("DF50", "transaction amount", HEX);
public static final Tag OFFLINE_TOTAL_AMOUNT = newTag("DF52", "offline total amount", HEX);
public static final Tag TRANSACTION_TYPE = newTag("9C", "transaction type", HEX);
public static final Tag TRANSACTION_GROUP = newTag("E0", "transaction group", HEX);
public static final Tag TABLE_RECORD = newTag("EF", "table record", HEX);
public static final Tag CA_PUBLIC_KEY_MODULUS = newTag("DF53", "CA public key modulus", HEX);
public static final Tag CA_PUBLIC_KEY_EXPONENT = newTag("DF54", "CA public key exponent", HEX);
public static final Tag TRANSACTION_SEQUENCE_COUNTER = newTag("9F41", "transaction sequence counter", HEX);
public static final Tag AMOUNT_AUTHORIZED = newTag("9F02", "amount authorized", HEX);
public static final Tag AMOUNT_OTHER = newTag("9F03", "amount other", HEX);
public static final Tag APPLICATION_INTERCHANGE_PROFILE = newTag("82", "AIP", "Application Interchange Profile", Decoders.AIP);
public static final Tag APPLICATION_TRANSACTION_COUNTER = newTag("9F36", "application transaction counter", BASE_10);
public static final Tag APPLICATION_CRYPTOGRAM = newTag("9F26", "application cryptogram", HEX);
public static final Tag ISSUER_APPLICATION_DATA = newTag("9F10", "issuer application data", "issuer application data", new IssuerApplicationDataDecoder());
public static final Tag TERMINAL_CURRENCY_CODE = newTag("5F2A", "terminal currency code", Decoders.CURRENCY_CODE);
public static final Tag TERMINAL_SERIAL_NUMBER = newTag("9F1E", "terminal serial number", ASCII);
public static final Tag UNPREDICTABLE_NUMBER = newTag("9F37", "unpredictable number", HEX);
public static final Tag CVM_RESULTS = newTag("9F34", "CVM Results", "Cardholder Verification Results", Decoders.CVM_RESULTS);
public static final Tag CRYPTOGRAM_INFORMATION_DATA = newTag("9F27", "cryptogram information data", HEX);
public static final Tag HOST_INCIDENT_CODE = newTag("DF2E", "host incident code", HEX);
public static final Tag ISSUER_AUTHENTICATION_DATA = newTag("91", "issuer authentication data", HEX);
public static final Tag ISSUER_SCRIPT_TERMPLATE_1 = newTag("71", "issuer script termplate 1", HEX);
public static final Tag ISSUER_SCRIPT_TERMPLATE_2 = newTag("72", "issuer script termplate 2", HEX);
public static final Tag APPLICATION_LABEL = newTag("50", "application label", ASCII);
public static final Tag DEDICATED_FILE_NAME = newTag("84", "dedicated file name", HEX);
public static final Tag APPLICATION_PRIORITY_INDICATOR = newTag("87", "application priority indicator", HEX);
public static final Tag CA_PUBLIC_KEY_INDEX = newTag("8F", "ca public key index", HEX);
public static final Tag TRACK_2_EQUIVALENT_DATA = newTag("57", "track 2 equivalent data", HEX);
public static final Tag CARD_HOLDER_NAME = newTag("5F20", "card holder name", ASCII);
public static final Tag TRACK_1_DISCRETIONARY_DATA = newTag("9F1F", "track 1 discretionary data", ASCII);
public static final Tag TRACK_2_DISCRETIONARY_DATA = newTag("9F20", "track 2 discretionary data", HEX);
public static final Tag CARD_EXPIRY = newTag("5F24", "card expiry", HEX);
public static final Tag ISSUER_COUNTRY_CODE = newTag("5F28", "issuer country code", HEX);
public static final Tag PAN_SEQUENCE_NUMBER = newTag("5F34", "PAN sequence number", HEX);
public static final Tag PAN = newTag("5A", "PAN", HEX);
public static final Tag AUTHORISATION_RESPONSE_CODE = newTag("8A", "authorisation response code", ASCII);
public static final Tag TERMINAL_VERIFICATION_RESULTS = newTag("95", "TVR", "Terminal Verification Results", Decoders.TVR);
public static final Tag TSI = newTag("9B", "TSI", "Transaction Status Indicator", Decoders.TSI);
public static final Tag CVM_LIST = newTag("8E", "CVM List", "Cardholder Verification Method List", Decoders.CVM_LIST);
public static final Tag APPLICATION_CURRENCY_CODE = newTag("9F42", "application currency code", Decoders.CURRENCY_CODE);
public static final Tag TRANSACTION_CATEGORY_CODE = newTag("9F53", "transaction category code", ASCII);
public static final Tag FCI_TEMPLATE = newTag("6F", "FCI template", HEX);
public static final Tag FCI_PROPRIETARY_TEMPLATE = newTag("A5", "FCI proprietary template", HEX);
public static final Tag AFL = newTag("94", "AFL", "Application File Locator", Decoders.AFL);
public static final Tag APPLICATION_EFFECTIVE_DATE = newTag("5F25", "application effective date", HEX);
public static final Tag PDOL = newTag("9F38", "PDOL", "Processing DOL", DOL);
public static final Tag CDOL_1 = newTag("8C", "CDOL 1", "Data object list", DOL);
public static final Tag CDOL_2 = newTag("8D", "CDOL 1", "Data object list", DOL);
public static final Tag APPLICATION_USAGE_CONTROL = newTag("9F07", "application usage control", HEX);
public static final Tag CARD_APPLICATION_VERSION_NUMBER = newTag("9F08", "card application version number", HEX);
public static final Tag IAC_DEFAULT = newTag("9F0D", "IAC default", Decoders.TVR);
public static final Tag IAC_DENIAL = newTag("9F0E", "IAC denial", Decoders.TVR);
public static final Tag IAC_ONLINE = newTag("9F0F", "IAC online", Decoders.TVR);
public static final Tag SDA_TAG_LIST = newTag("9F4A", "SDA tag list", HEX);
public static final Tag ISSUER_PUBLIC_KEY_EXPONENT = newTag("9F32", "issuer public key exponent", HEX);
public static final Tag ISSUER_PUBLIC_KEY_REMAINDER = newTag("92", "issuer public key remainder", HEX);
public static final Tag ISSUER_PUBLIC_KEY_CERTIFICATE = newTag("90", "issuer public key certificate", HEX);
public static final Tag ICC_PUBLIC_KEY_EXPONENT = newTag("9F47", "ICC public key exponent", HEX);
public static final Tag ICC_PUBLIC_KEY_REMAINDER = newTag("9F48", "ICC public key remainder", HEX);
public static final Tag ICC_PIN_ENCIPHERMENT_PUBLIC_KEY = newTag("9F2D", "ICC pin encipherment public key", HEX);
public static final Tag ICC_PIN_ENCIPHERMENT_PUBLIC_KEY_EXPONENT = newTag("9F2E", "ICC pin encipherment public key exponent", HEX);
public static final Tag ICC_PIN_ENCIPHERMENT_PUBLIC_KEY_MODULUS = newTag("9F2F", "ICC pin encipherment public key modulus", HEX);
public static final Tag SIGNED_DYNAMIC_APPLICATION_DATA = newTag("9F4B", "signed dynamic application data", HEX);
public static final Tag RESPONSE_TEMPLATE = newTag("77", "response template", HEX);
public static final Tag PIN_TRY_COUNTER = newTag("9F17", "pin try counter", HEX);
public static final Tag SIGNED_STATIC_APPLICATION_DATA = newTag("93", "signed static application data", HEX);
public static final Tag ICC_PUBLIC_KEY_CERTIFICATE = newTag("9F46", "ICC public key certificate", HEX);
public static final Tag DATA_AUTHENTICATION_CODE = newTag("9F45", "data authentication code", HEX);
public static final Tag ICC_DYNAMIC_NUMBER = newTag("9F4C", "ICC dynamic number", HEX);
public static final Tag RESPONSE_TEMPLATE_2 = newTag("70", "response template", HEX);
public static final Tag FCI_DISCRETIONARY_DATA = newTag("BF0C", "FCI discretionary data", HEX);
public static final Tag SERVICE_CODE = newTag("5F30", "service code", HEX);
public static final Tag LANGUAGE_PREFERENCE = newTag("5F2D", "language preference", ASCII);
public static final Tag ISSUER_CODE_TABLE_INDEX = newTag("9F11", "issuer code table index", HEX);
public static final Tag APPLICATION_PREFERRED_NAME = newTag("9F12", "application preferred name", ASCII);
public static final Tag APPLICATION_CURRENCY_EXPONENT = newTag("9F44", "application currency exponent", HEX);
public static final Tag APPLICATION_REFERENCE_CURRENCY = newTag("9F3B", "application reference currency", HEX);
public static final Tag APPLICATION_REFERENCE_CURRENCY_EXPONENT = newTag("9F43", "application reference currency exponent", HEX);
public static final Tag DDOL = newTag("9F49", "DDOL", "dynamic data authentication DOL", DOL);
public static final Tag NON_TLV_RESPONSE_TEMPLATE = newTag("80", "Fixed response template", "Fixed response template", new ResponseFormat1Decoder());
private static Tag newTag(String hexString, String shortName, String longName, Decoder decoder) {
return newTag(METADATA, hexString, shortName, longName, decoder);
}
private static Tag newTag(String hexString, String longName, Decoder decoder) {
return newTag(METADATA, hexString, longName, longName, decoder);
}
private static Tag newTag(String hexString, String name, PrimitiveDecoder primitiveDecoder) {
return newTag(METADATA, hexString, name, primitiveDecoder);
}
protected static Tag newTag(TagMetaData metaData, String hexString, String shortName, String longName, Decoder decoder) {
Tag tag = Tag.fromHex(hexString);
metaData.put(tag, new TagInfo(shortName, longName, decoder, HEX));
return tag;
}
protected static Tag newTag(TagMetaData metaData, String hexString, String name, PrimitiveDecoder primitiveDecoder) {
Tag tag = Tag.fromHex(hexString);
metaData.put(tag, new TagInfo(name, null, Decoders.PRIMITIVE, primitiveDecoder));
return tag;
}
} |
package ucar.nc2.ui.table;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* A utility class offering various operations on JTables.
*
* @author cwardgar
*/
public abstract class TableUtils {
/**
* A listener that sets the preferred widths of a JTable's columns such that they're just big enough to display all
* of their contents without truncation.
*/
public static class ResizeColumnWidthsListener implements TableModelListener {
/**
* The default maximum number of table rows for which a full scan will be performed. If a table has more rows
* than this, only a partial scan will be done.
*/
public static final int DEFAULT_FULL_SCAN_CUTOFF = 10000;
private final JTable table;
private final int fullScanCutoff;
public ResizeColumnWidthsListener(JTable table) {
this(table, DEFAULT_FULL_SCAN_CUTOFF);
}
public ResizeColumnWidthsListener(JTable table, int fullScanCutoff) {
this.table = table;
this.fullScanCutoff = fullScanCutoff;
// Remove table as a listener. That way, we can control when it gets notified of events.
table.getModel().removeTableModelListener(table);
// Perform initial resize.
boolean doFullScan = table.getRowCount() <= fullScanCutoff;
TableUtils.resizeColumnWidths(table, doFullScan);
}
@Override public void tableChanged(TableModelEvent e) {
table.tableChanged(e); // table MUST be notified first.
// Do not cache the value of doFullScan; we need to reevaluate each time because the table model could
// have changed.
boolean doFullScan = table.getRowCount() <= fullScanCutoff;
TableUtils.resizeColumnWidths(table, doFullScan);
}
}
public static void resizeColumnWidths(JTable table, boolean doFullScan) {
for (int col = 0; col < table.getColumnCount(); ++col) {
int maxWidth = 0;
// Get header width.
TableColumn column = table.getColumnModel().getColumn(col);
TableCellRenderer headerRenderer = column.getHeaderRenderer();
if (headerRenderer == null) {
headerRenderer = table.getTableHeader().getDefaultRenderer();
}
Object headerValue = column.getHeaderValue();
Component headerRendererComp =
headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
maxWidth = Math.max(maxWidth, headerRendererComp.getPreferredSize().width);
// Get cell widths.
if (doFullScan) {
for (int row = 0; row < table.getRowCount(); ++row) {
maxWidth = Math.max(maxWidth, getCellWidth(table, row, col));
}
} else {
maxWidth = Math.max(maxWidth, getCellWidth(table, 0, col));
maxWidth = Math.max(maxWidth, getCellWidth(table, table.getRowCount() / 2, col));
maxWidth = Math.max(maxWidth, getCellWidth(table, table.getRowCount() - 1, col));
}
// For some reason, the calculation above gives a value that is 1 pixel too small.
// Maybe that's because of the cell divider line?
++maxWidth;
column.setPreferredWidth(maxWidth);
}
}
private static int getCellWidth(JTable table, int row, int col) {
TableCellRenderer cellRenderer = table.getCellRenderer(row, col);
Object value = table.getValueAt(row, col);
Component cellRendererComp =
cellRenderer.getTableCellRendererComponent(table, value, false, false, row, col);
return cellRendererComp.getPreferredSize().width;
}
public static void alignTable(JTable table, int alignment) {
// We don't want to set up completely new cell renderers: rather, we want to use the existing ones but just
// change their alignment.
for (int iCol = 0; iCol < table.getColumnCount(); ++iCol) {
TableColumn tableColumn = table.getColumnModel().getColumn(iCol);
TableCellRenderer headerRenderer = tableColumn.getHeaderRenderer();
if (headerRenderer == null) {
headerRenderer = table.getTableHeader().getDefaultRenderer();
}
tableColumn.setHeaderRenderer(new TableCellRendererAlignmentDecorator(headerRenderer, alignment));
TableCellRenderer cellRenderer = tableColumn.getCellRenderer();
if (cellRenderer == null) {
cellRenderer = table.getDefaultRenderer(table.getColumnClass(iCol));
}
tableColumn.setCellRenderer(new TableCellRendererAlignmentDecorator(cellRenderer, alignment));
}
}
private static class TableCellRendererAlignmentDecorator implements TableCellRenderer {
private final TableCellRenderer delegate;
private final int alignment;
private TableCellRendererAlignmentDecorator(TableCellRenderer delegate, int alignment) {
this.delegate = delegate;
this.alignment = alignment;
}
@Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cellRendererComp =
delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (cellRendererComp instanceof DefaultTableCellRenderer) {
JLabel cellLabel = (DefaultTableCellRenderer) cellRendererComp;
cellLabel.setHorizontalAlignment(alignment);
}
return cellRendererComp;
}
}
///////////////////////////////////// Test ResizeColumnWidthsListener /////////////////////////////////////
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int numRows = 1000000;
int numCols = 4;
DefaultTableModel model = new DefaultTableModel(numRows, 0);
for (int col = 0; col < numCols; ++col) {
addColumn(model);
}
JTable table = new JTable(model);
model.addTableModelListener(new ResizeColumnWidthsListener(table));
JButton minusButton = new JButton(new MinusAction(model));
JButton moveButton = new JButton(new MoveAction(table.getColumnModel()));
JButton plusButton = new JButton(new PlusAction(model));
JPanel buttonPanel = new JPanel();
buttonPanel.add(minusButton, BorderLayout.WEST);
buttonPanel.add(moveButton, BorderLayout.CENTER);
buttonPanel.add(plusButton, BorderLayout.EAST);
JFrame frame = new JFrame("Test ResizeColumnWidthsListener");
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
public static class MinusAction extends AbstractAction {
private final DefaultTableModel model;
public MinusAction(DefaultTableModel model) {
super("-");
this.model = model;
}
public void actionPerformed(ActionEvent e) {
if (model.getColumnCount() > 0) {
model.setColumnCount(model.getColumnCount() - 1);
}
}
}
public static class MoveAction extends AbstractAction {
private final TableColumnModel columnModel;
public MoveAction(TableColumnModel columnModel) {
super("Move");
this.columnModel = columnModel;
}
public void actionPerformed(ActionEvent e) {
if (columnModel.getColumnCount() > 0) {
columnModel.moveColumn(0, columnModel.getColumnCount() - 1);
}
}
}
public static class PlusAction extends AbstractAction {
private final DefaultTableModel model;
public PlusAction(DefaultTableModel model) {
super("+");
this.model = model;
}
public void actionPerformed(ActionEvent e) {
addColumn(model);
}
}
private static void addColumn(DefaultTableModel model) {
Object columnName = Integer.toString(model.getColumnCount());
Object[] columnData = genColumnData(model);
model.addColumn(columnName, columnData);
}
private static Object[] genColumnData(TableModel model) {
Object[] data = new Object[model.getRowCount()];
int cellValLen = (model.getColumnCount() + 1) * 8;
String cellVal = genString(cellValLen);
for (int row = 0; row < model.getRowCount(); ++row) {
data[row] = cellVal;
}
return data;
}
private static String genString(int len) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len; ++i) {
builder.append((char)('a' + i));
}
return builder.toString();
}
private TableUtils() { }
} |
package ru.stqa.pft.sandbox;
public class MyFirst {
public static void main(String[] args) {
hello("World");
hello("User");
hello("Alexei");
double l = 5;
System.out.println("Площадь Квадрата со сторойной " + l + " = " + area(l));
double a = 4;
double b = 6;
System.out.println("Площадь Прямоугольника со сторойнами " + a + " и " + b + " = " + area(a, b));
}
public static void hello(String somebody) {
System.out.println("Hello, " + somebody + "!");
}
public static double area(double l ){
return l * l;
}
public static double area(double a, double b ){
return a * b;
}
} |
package com.marverenic.music;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.SparseIntArray;
import android.view.View;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.marverenic.music.instances.Album;
import com.marverenic.music.instances.Artist;
import com.marverenic.music.instances.AutoPlaylist;
import com.marverenic.music.instances.Genre;
import com.marverenic.music.instances.Playlist;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.Prefs;
import com.marverenic.music.utils.Themes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Properties;
public class Library {
public static final String PLAY_COUNT_FILENAME = ".playcount";
public static final String PLAY_COUNT_FILE_COMMENT = "This file contains play count information for Jockey and should not be edited";
public static final int PERMISSION_REQUEST_ID = 0x01;
private static final String AUTO_PLAYLIST_EXTENSION = ".jpl";
private static final ArrayList<Playlist> playlistLib = new ArrayList<>();
private static final ArrayList<Song> songLib = new ArrayList<>();
private static final ArrayList<Artist> artistLib = new ArrayList<>();
private static final ArrayList<Album> albumLib = new ArrayList<>();
private static final ArrayList<Genre> genreLib = new ArrayList<>();
private static final SparseIntArray playCounts = new SparseIntArray();
private static final SparseIntArray skipCounts = new SparseIntArray();
private static final SparseIntArray playDates = new SparseIntArray();
private static final String[] songProjection = new String[]{
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.YEAR,
MediaStore.Audio.Media.DATE_ADDED,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.TRACK
};
private static final String[] artistProjection = new String[]{
MediaStore.Audio.Artists._ID,
MediaStore.Audio.Artists.ARTIST,
};
private static final String[] albumProjection = new String[]{
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.LAST_YEAR,
MediaStore.Audio.Albums.ALBUM_ART
};
private static final String[] playlistProjection = new String[]{
MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME
};
private static final String[] genreProjection = new String[]{
MediaStore.Audio.Genres._ID,
MediaStore.Audio.Genres.NAME
};
private static final String[] playlistEntryProjection = new String[]{
MediaStore.Audio.Playlists.Members.TITLE,
MediaStore.Audio.Playlists.Members.AUDIO_ID,
MediaStore.Audio.Playlists.Members.ARTIST,
MediaStore.Audio.Playlists.Members.ALBUM,
MediaStore.Audio.Playlists.Members.DURATION,
MediaStore.Audio.Playlists.Members.DATA,
MediaStore.Audio.Playlists.Members.YEAR,
MediaStore.Audio.Playlists.Members.DATE_ADDED,
MediaStore.Audio.Playlists.Members.ALBUM_ID,
MediaStore.Audio.Playlists.Members.ARTIST_ID
};
// LIBRARY LISTENERS
// Since it's important to know when the Library has entries added or removed so we can update
// the UI accordingly, associate listeners to receive callbacks for such events. These listeners
// will get called only when entries are added or removed -- not changed. This lets us do a lot
// of things on the UI like adding and removing playlists without having to create the associated
// Snackbars, AlertDialogs, etc. and is slightly cleaner than passing a callback as a parameter
// to methods that cause such changes since we don't have to instantiate a single-use Object.
private static final ArrayList<PlaylistChangeListener> PLAYLIST_LISTENERS = new ArrayList<>();
private static final ArrayList<LibraryRefreshListener> REFRESH_LISTENERS = new ArrayList<>();
public interface PlaylistChangeListener {
void onPlaylistRemoved(Playlist removed);
void onPlaylistAdded(Playlist added);
}
public interface LibraryRefreshListener {
void onLibraryRefreshed();
}
/**
* In certain cases like in {@link com.marverenic.music.fragments.PlaylistFragment}, editing the
* library can break a lot of things if not done carefully. (i.e. if
* {@link android.support.v7.widget.RecyclerView.Adapter#notifyDataSetChanged()} (or similar)
* isn't called after adding a playlist, then the UI process can throw an exception and crash)
*
* If this is the case, call this method to set a callback whenever the library gets updated
* (Not all library update calls will be relevant to the context, but better safe than sorry).
*
* <b>When using this method MAKE SURE TO CALL {@link Library#removePlaylistListener(PlaylistChangeListener)}
* WHEN THE ACTIVITY PAUSES -- OTHERWISE YOU WILL CAUSE A LEAK.</b>
*
* @param listener A {@link PlaylistChangeListener} to act as a callback
* when the library is changed in any way
*/
public static void addPlaylistListener(PlaylistChangeListener listener){
if (!PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.add(listener);
}
public static void addRefreshListener(LibraryRefreshListener listener) {
if (!REFRESH_LISTENERS.contains(listener)) REFRESH_LISTENERS.add(listener);
}
/**
* Remove a {@link PlaylistChangeListener} previously added to listen
* for library updates.
* @param listener A {@link PlaylistChangeListener} currently registered
* to recieve a callback when the library gets modified. If it's not already
* registered, then nothing will happen.
*/
public static void removePlaylistListener(PlaylistChangeListener listener){
if (PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.remove(listener);
}
public static void removeRefreshListener(LibraryRefreshListener listener) {
REFRESH_LISTENERS.remove(listener);
}
/**
* Private method for notifying registered {@link PlaylistChangeListener}s
* that the library has lost an entry. (Changing entries doesn't matter)
*/
private static void notifyPlaylistRemoved(Playlist removed){
for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistRemoved(removed);
}
/**
* Private method for notifying registered {@link PlaylistChangeListener}s
* that the library has gained an entry. (Changing entries doesn't matter)
*/
private static void notifyPlaylistAdded(Playlist added){
for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistAdded(added);
}
private static void notifyLibraryRefreshed() {
for (LibraryRefreshListener l : REFRESH_LISTENERS) l.onLibraryRefreshed();
}
@TargetApi(23)
public static boolean hasRWPermission(Context context){
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED
&& context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
@TargetApi(23)
public static void requestRWPermission(Activity activity){
activity.requestPermissions(
new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
PERMISSION_REQUEST_ID);
}
// LIBRARY BUILDING METHODS
public static void scanAll (final Activity activity){
if (hasRWPermission(activity)) {
resetAll();
setPlaylistLib(scanPlaylists(activity));
setSongLib(scanSongs(activity));
setArtistLib(scanArtists(activity));
setAlbumLib(scanAlbums(activity));
setGenreLib(scanGenres(activity));
sort();
notifyLibraryRefreshed();
// If the user permits it, log info about the size of their library
if (Prefs.allowAnalytics(activity)) {
int autoPlaylistCount = 0;
for (Playlist p : playlistLib) {
if (p instanceof AutoPlaylist) autoPlaylistCount++;
}
Answers.getInstance().logCustom(
new CustomEvent("Loaded library")
.putCustomAttribute("Playlist count", playlistLib.size())
.putCustomAttribute("Auto Playlist count", autoPlaylistCount)
.putCustomAttribute("Song count", songLib.size())
.putCustomAttribute("Artist count", artistLib.size())
.putCustomAttribute("Album count", albumLib.size())
.putCustomAttribute("Genre count", genreLib.size()));
}
}
else{
requestRWPermission(activity);
}
}
/**
* Scans the MediaStore for songs
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Song}s in the MediaStore
*/
public static ArrayList<Song> scanSongs (Context context){
ArrayList<Song> songs = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
songProjection,
MediaStore.Audio.Media.IS_MUSIC + "!= 0",
null,
MediaStore.Audio.Media.TITLE + " ASC");
if (cur == null) {
return songs;
}
final int titleIndex = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Media._ID);
final int artistIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
final int albumIndex = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
final int durationIndex = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
final int dataIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
final int yearIndex = cur.getColumnIndex(MediaStore.Audio.Media.YEAR);
final int dateIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED);
final int albumIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
final int artistIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Song s = new Song(
cur.getString(titleIndex),
cur.getInt(idIndex),
parseUnknown(cur.getString(artistIndex), context.getString(R.string.no_artist)),
cur.getString(albumIndex),
cur.getInt(durationIndex),
cur.getString(dataIndex),
cur.getInt(yearIndex),
cur.getInt(dateIndex),
cur.getInt(albumIdIndex),
cur.getInt(artistIdIndex));
s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK));
songs.add(s);
}
cur.close();
return songs;
}
/**
* Scans the MediaStore for artists
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Artist}s in the MediaStore
*/
public static ArrayList<Artist> scanArtists (Context context){
ArrayList<Artist> artists = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
artistProjection,
null,
null,
MediaStore.Audio.Artists.ARTIST + " ASC");
if (cur == null) {
return artists;
}
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Artists._ID);
final int artistIndex = cur.getColumnIndex(MediaStore.Audio.Artists.ARTIST);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
artists.add(new Artist(
cur.getInt(idIndex),
parseUnknown(
cur.getString(artistIndex),
context.getString(R.string.no_artist))));
}
cur.close();
return artists;
}
/**
* Scans the MediaStore for albums
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Album}s in the MediaStore
*/
public static ArrayList<Album> scanAlbums (Context context){
ArrayList<Album> albums = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
albumProjection,
null,
null,
MediaStore.Audio.Albums.ALBUM + " ASC");
if (cur == null) {
return albums;
}
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Albums._ID);
final int albumIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM);
final int artistIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST);
final int artistIdIndex = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID);
final int yearIndex = cur.getColumnIndex(MediaStore.Audio.Albums.LAST_YEAR);
final int artIndex = cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
albums.add(new Album(
cur.getInt(idIndex),
cur.getString(albumIndex),
cur.getInt(artistIdIndex),
parseUnknown(
cur.getString(artistIndex),
context.getString(R.string.no_artist)),
cur.getString(yearIndex),
cur.getString(artIndex)));
}
cur.close();
return albums;
}
/**
* Scans the MediaStore for playlists
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Playlist}s in the MediaStore
*/
public static ArrayList<Playlist> scanPlaylists (Context context){
ArrayList<Playlist> playlists = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
playlistProjection,
null,
null,
MediaStore.Audio.Playlists.NAME + " ASC");
if (cur == null) {
return playlists;
}
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Playlists._ID);
final int nameIndex = cur.getColumnIndex(MediaStore.Audio.Playlists.NAME);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
playlists.add(new Playlist(cur.getInt(idIndex), cur.getString(nameIndex)));
}
cur.close();
for (Playlist p : scanAutoPlaylists(context)) {
if (playlists.remove(p)) {
playlists.add(p);
} else {
// If AutoPlaylists have been deleted outside of Jockey, delete its configuration
//noinspection ResultOfMethodCallIgnored
new File(context.getExternalFilesDir(null) + "/" + p.playlistName + AUTO_PLAYLIST_EXTENSION)
.delete();
}
}
return playlists;
}
/**
* Scans storage for Auto Playlist configurations
* @param context {@link Context} to use to read files on the device
* @return An {@link ArrayList} with the loaded {@link AutoPlaylist}s
*/
public static ArrayList<AutoPlaylist> scanAutoPlaylists (Context context) {
ArrayList<AutoPlaylist> autoPlaylists = new ArrayList<>();
final Gson gson = new Gson();
try {
File externalFiles = new File(context.getExternalFilesDir(null) + "/");
if (!externalFiles.exists()) {
//noinspection ResultOfMethodCallIgnored
externalFiles.mkdirs();
}
String[] files = externalFiles.list();
for (String s : files) {
if (s.endsWith(AUTO_PLAYLIST_EXTENSION)) {
autoPlaylists.add(gson.fromJson(new FileReader(externalFiles + "/" + s), AutoPlaylist.class));
}
}
} catch (IOException e) {
Crashlytics.logException(e);
}
return autoPlaylists;
}
/**
* Scans the MediaStore for genres
* @param context {@link Context} to use to open a {@link Cursor}
* @return An {@link ArrayList} with the {@link Genre}s in the MediaStore
*/
public static ArrayList<Genre> scanGenres (Context context){
ArrayList<Genre> genres = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
genreProjection,
null,
null,
MediaStore.Audio.Genres.NAME + " ASC");
if (cur == null) {
return genres;
}
final int idIndex = cur.getColumnIndex(MediaStore.Audio.Genres._ID);
final int nameIndex = cur.getColumnIndex(MediaStore.Audio.Genres.NAME);
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
int thisGenreId = cur.getInt(idIndex);
String thisName = cur.getString(nameIndex);
if (thisName == null || thisName.equalsIgnoreCase("Unknown")){
genres.add(new Genre(-1, context.getString(R.string.unknown)));
} else {
genres.add(new Genre(thisGenreId,thisName));
// Associate all songs in this genre by setting the genreID field of each song in the genre
Cursor genreCur = context.getContentResolver().query(
MediaStore.Audio.Genres.Members.getContentUri("external", thisGenreId),
new String[]{MediaStore.Audio.Media._ID},
MediaStore.Audio.Media.IS_MUSIC + " != 0 ", null, null);
if (genreCur != null) {
genreCur.moveToFirst();
final int ID_INDEX = genreCur.getColumnIndex(MediaStore.Audio.Media._ID);
for (int j = 0; j < genreCur.getCount(); j++) {
genreCur.moveToPosition(j);
final Song s = findSongById(genreCur.getInt(ID_INDEX));
if (s != null) s.genreId = thisGenreId;
}
genreCur.close();
}
}
}
cur.close();
return genres;
}
/**
* Checks Strings from ContentResolvers and replaces the default unknown value of
* {@link MediaStore#UNKNOWN_STRING} with another String if needed
* @param value The value returned from the ContentResolver
* @param convertValue The value to replace unknown Strings with
* @return A String with localized unknown values if needed, otherwise the original value
*/
private static String parseUnknown(String value, String convertValue) {
if (value != null && value.equals(MediaStore.UNKNOWN_STRING)) {
return convertValue;
} else {
return value;
}
}
// LIBRARY STORAGE METHODS
/**
* Remove all library entries from memory
*/
public static void resetAll(){
playlistLib.clear();
songLib.clear();
artistLib.clear();
albumLib.clear();
genreLib.clear();
}
/**
* Replace the playlist library in memory with another one
* @param newLib The new playlist library
*/
public static void setPlaylistLib(ArrayList<Playlist> newLib){
playlistLib.clear();
playlistLib.addAll(newLib);
}
/**
* Replace the song library in memory with another one
* @param newLib The new song library
*/
public static void setSongLib(ArrayList<Song> newLib){
songLib.clear();
songLib.addAll(newLib);
}
/**
* Replace the album library in memory with another one
* @param newLib The new album library
*/
public static void setAlbumLib(ArrayList<Album> newLib){
albumLib.clear();
albumLib.addAll(newLib);
}
/**
* Replace the artist library in memory with another one
* @param newLib The new artist library
*/
public static void setArtistLib(ArrayList<Artist> newLib){
artistLib.clear();
artistLib.addAll(newLib);
}
/**
* Replace the genre library in memory with another one
* @param newLib The new genre library
*/
public static void setGenreLib(ArrayList<Genre> newLib){
genreLib.clear();
genreLib.addAll(newLib);
}
/**
* Sorts the libraries in memory using the default {@link Library} sort methods
*/
public static void sort (){
Collections.sort(songLib);
Collections.sort(albumLib);
Collections.sort(artistLib);
Collections.sort(playlistLib);
Collections.sort(genreLib);
}
/**
* @return true if the library is populated with any entries
*/
public static boolean isEmpty (){
return songLib.isEmpty() && albumLib.isEmpty() && artistLib.isEmpty() && playlistLib.isEmpty() && genreLib.isEmpty();
}
/**
* @return An {@link ArrayList} of {@link Playlist}s in the MediaStore
*/
public static ArrayList<Playlist> getPlaylists(){
return playlistLib;
}
/**
* @return An {@link ArrayList} of {@link Song}s in the MediaStore
*/
public static ArrayList<Song> getSongs(){
return songLib;
}
/**
* @return An {@link ArrayList} of {@link Album}s in the MediaStore
*/
public static ArrayList<Album> getAlbums(){
return albumLib;
}
/**
* @return An {@link ArrayList} of {@link Artist}s in the MediaStore
*/
public static ArrayList<Artist> getArtists(){
return artistLib;
}
/**
* @return An {@link ArrayList} of {@link Genre}s in the MediaStore
*/
public static ArrayList<Genre> getGenres(){
return genreLib;
}
// LIBRARY SEARCH METHODS
/**
* Finds a {@link Song} in the library based on its Id
* @param songId the MediaStore Id of the {@link Song}
* @return A {@link Song} with a matching Id
*/
public static Song findSongById (int songId){
for (Song s : songLib){
if (s.songId == songId){
return s;
}
}
return null;
}
/**
* Build an {@link ArrayList} of {@link Song}s from a list of id's. Doesn't require the library to be loaded
* @param songIDs The list of song ids to convert to {@link Song}s
* @param context The {@link Context} used to open a {@link Cursor}
* @return An {@link ArrayList} of {@link Song}s with ids matching those of the songIDs parameter
*/
public static ArrayList<Song> buildSongListFromIds (int[] songIDs, Context context){
ArrayList<Song> contents = new ArrayList<>();
if (songIDs.length == 0) return contents;
String query = MediaStore.Audio.Media._ID + " IN(?";
String[] ids = new String[songIDs.length];
ids[0] = Integer.toString(songIDs[0]);
for (int i = 1; i < songIDs.length; i++){
query += ",?";
ids[i] = Integer.toString(songIDs[i]);
}
query += ")";
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
songProjection,
query,
ids,
MediaStore.Audio.Media.TITLE + " ASC");
if (cur == null) {
return contents;
}
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
Song s = new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? context.getString(R.string.no_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)));
s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK));
contents.add(s);
}
cur.close();
// Sort the contents of the list so that it matches the order of the int array
ArrayList<Song> songs = new ArrayList<>();
Song dummy = new Song(null, 0, null, null, 0, null, 0, 0, 0, 0);
for (int i : songIDs){
dummy.songId = i;
// Because Songs are equal if their ids are equal, we can use a dummy song with the ID
// we want to find it in the list
songs.add(contents.get(contents.indexOf(dummy)));
}
return songs;
}
/**
* Finds a {@link Artist} in the library based on its Id
* @param artistId the MediaStore Id of the {@link Artist}
* @return A {@link Artist} with a matching Id
*/
public static Artist findArtistById (int artistId){
for (Artist a : artistLib){
if (a.artistId == artistId){
return a;
}
}
return null;
}
/**
* Finds a {@link Album} in a library based on its Id
* @param albumId the MediaStore Id of the {@link Album}
* @return A {@link Album} with a matching Id
*/
public static Album findAlbumById (int albumId){
// Returns the first Artist object in the library with a matching id
for (Album a : albumLib){
if (a.albumId == albumId){
return a;
}
}
return null;
}
/**
* Finds a {@link Genre} in a library based on its Id
* @param genreId the MediaStore Id of the {@link Genre}
* @return A {@link Genre} with a matching Id
*/
public static Genre findGenreById (int genreId){
// Returns the first Genre object in the library with a matching id
for (Genre g : genreLib){
if (g.genreId == genreId){
return g;
}
}
return null;
}
public static Artist findArtistByName (String artistName){
final String trimmedQuery = artistName.trim();
for (Artist a : artistLib){
if (a.artistName.equalsIgnoreCase(trimmedQuery))
return a;
}
return null;
}
// CONTENTS QUERY METHODS
/**
* Get a list of songs in a certain playlist
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the playlist
*/
public static ArrayList<Song> getPlaylistEntries (Context context, Playlist playlist){
if (playlist instanceof AutoPlaylist){
ArrayList<Song> entries = ((AutoPlaylist) playlist).generatePlaylist(context);
editPlaylist(context, playlist, entries);
return entries;
}
ArrayList<Song> songEntries = new ArrayList<>();
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
playlistEntryProjection,
MediaStore.Audio.Media.IS_MUSIC + " != 0", null, null);
if (cur == null) {
return songEntries;
}
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
songEntries.add(new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST_ID))));
}
cur.close();
return songEntries;
}
/**
* Get a list of songs on a certain album
* @param album The {@link Album} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the album
*/
public static ArrayList<Song> getAlbumEntries (Album album){
ArrayList<Song> songEntries = new ArrayList<>();
for (Song s : songLib){
if (s.albumId == album.albumId){
songEntries.add(s);
}
}
Collections.sort(songEntries, new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
return ((Integer) o1.trackNumber).compareTo(o2.trackNumber);
}
});
return songEntries;
}
/**
* Get a list of songs by a certain artist
* @param artist The {@link Artist} to get the entries of
* @return An {@link ArrayList} of {@link Song}s by the artist
*/
public static ArrayList<Song> getArtistSongEntries (Artist artist){
ArrayList<Song> songEntries = new ArrayList<>();
for(Song s : songLib){
if (s.artistId == artist.artistId){
songEntries.add(s);
}
}
return songEntries;
}
/**
* Get a list of albums by a certain artist
* @param artist The {@link Artist} to get the entries of
* @return An {@link ArrayList} of {@link Album}s by the artist
*/
public static ArrayList<Album> getArtistAlbumEntries (Artist artist){
ArrayList<Album> albumEntries = new ArrayList<>();
for (Album a : albumLib){
if (a.artistId == artist.artistId){
albumEntries.add(a);
}
}
return albumEntries;
}
/**
* Get a list of songs in a certain genre
* @param genre The {@link Genre} to get the entries of
* @return An {@link ArrayList} of {@link Song}s contained in the genre
*/
public static ArrayList<Song> getGenreEntries (Genre genre){
ArrayList<Song> songEntries = new ArrayList<>();
for(Song s : songLib){
if (s.genreId == genre.genreId){
songEntries.add(s);
}
}
return songEntries;
}
// PLAY COUNT READING & ACCESSING METHODS
public static void loadPlayCounts(Context context) {
playCounts.clear();
skipCounts.clear();
playDates.clear();
try {
Properties countProperties = openPlayCountFile(context);
Enumeration iterator = countProperties.propertyNames();
while (iterator.hasMoreElements()){
String key = (String) iterator.nextElement();
String value = countProperties.getProperty(key, "0,0");
final String[] originalValues = value.split(",");
int playCount = Integer.parseInt(originalValues[0]);
int skipCount = Integer.parseInt(originalValues[1]);
int playDate = 0;
if (originalValues.length > 2) {
playDate = Integer.parseInt(originalValues[2]);
}
playCounts.put(Integer.parseInt(key), playCount);
skipCounts.put(Integer.parseInt(key), skipCount);
playDates.put(Integer.parseInt(key), playDate);
}
}
catch (IOException e){
Crashlytics.logException(e);
}
}
/**
* Returns a readable {@link Properties} to be used with {@link Library#loadPlayCounts(Context)}
* @param context Used to read files from external storage
* @return A {@link Properties} object that has been initialized with values saved by
* {@link Player#logPlayCount(long, boolean)} and {@link Player#savePlayCountFile()}
* @throws IOException
*/
private static Properties openPlayCountFile(Context context) throws IOException{
File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME);
if (!file.exists()) //noinspection ResultOfMethodCallIgnored
file.createNewFile();
InputStream is = new FileInputStream(file);
Properties playCountHashtable;
try {
playCountHashtable = new Properties();
playCountHashtable.load(is);
}
finally {
is.close();
}
return playCountHashtable;
}
/**
* Returns the number of skips a song has. Note that you may need to call
* {@link Library#loadPlayCounts(Context)} in case the data has gone stale
* @param songId The {@link Song#songId} as written in the MediaStore
* @return The number of times a song has been skipped
*/
public static int getSkipCount (int songId){
return skipCounts.get(songId, 0);
}
/**
* Returns the number of plays a song has. Note that you may need to call
* {@link Library#loadPlayCounts(Context)} in case the data has gone stale
* @param songId The {@link Song#songId} as written in the MediaStore
* @return The number of times a song has been plays
*/
public static int getPlayCount (int songId){
return playCounts.get(songId, 0);
}
/**
* * Returns the last time a song was played with Jockey. Note that you may need to call
* {@link Library#loadPlayCounts(Context)} in case the data has gone stale
* @param songId The {@link Song#songId} as written in the MediaStore
* @return The last time a song was played given in seconds as a UTC timestamp
* (since midnight of January 1, 1970 UTC)
*/
public static int getPlayDate(int songId) {
return playDates.get(songId, 0);
}
// PLAYLIST WRITING METHODS
/**
* Add a new playlist to the MediaStore
* @param view A {@link View} to put a {@link Snackbar} in. Will also be used to get a {@link Context}.
* @param playlistName The name of the new playlist
* @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist
* @return The Playlist that was added to the library
*/
public static Playlist createPlaylist(final View view, final String playlistName, @Nullable final ArrayList<Song> songList){
final Context context = view.getContext();
String trimmedName = playlistName.trim();
setPlaylistLib(scanPlaylists(context));
String error = verifyPlaylistName(context, trimmedName);
if (error != null){
Snackbar
.make(
view,
error,
Snackbar.LENGTH_SHORT)
.show();
return null;
}
// Add the playlist to the MediaStore
final Playlist created = addPlaylist(context, trimmedName, songList);
Snackbar
.make(
view,
String.format(context.getResources().getString(R.string.message_created_playlist), playlistName),
Snackbar.LENGTH_LONG)
.setAction(
R.string.action_undo,
new View.OnClickListener() {
@Override
public void onClick(View v) {
deletePlaylist(context, created);
}
})
.show();
return created;
}
/**
* Test a playlist name to make sure it is valid when making a new playlist. Invalid playlist names
* are instance_empty or already exist in the MediaStore
* @param context A {@link Context} used to get localized Strings
* @param playlistName The playlist name that needs to be validated
* @return null if there is no error, or a {@link String} describing the error that can be
* presented to the user
*/
public static String verifyPlaylistName (final Context context, final String playlistName){
String trimmedName = playlistName.trim();
if (trimmedName.length() == 0){
return context.getResources().getString(R.string.error_hint_empty_playlist);
}
for (Playlist p : playlistLib){
if (p.playlistName.equalsIgnoreCase(trimmedName)){
return context.getResources().getString(R.string.error_hint_duplicate_playlist);
}
}
return null;
}
/**
* Removes a playlist from the MediaStore
* @param view A {@link View} to show a {@link Snackbar} and to get a {@link Context} used to edit the MediaStore
* @param playlist A {@link Playlist} which will be removed from the MediaStore
*/
public static void removePlaylist(final View view, final Playlist playlist){
final Context context = view.getContext();
final ArrayList<Song> entries = getPlaylistEntries(context, playlist);
deletePlaylist(context, playlist);
Snackbar
.make(
view,
String.format(context.getString(R.string.message_removed_playlist), playlist),
Snackbar.LENGTH_LONG)
.setAction(
context.getString(R.string.action_undo),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (playlist instanceof AutoPlaylist) {
createAutoPlaylist(context, (AutoPlaylist) playlist);
} else {
addPlaylist(context, playlist.playlistName, entries);
}
}
})
.show();
}
/**
* Replace the entries of a playlist in the MediaStore with a new {@link ArrayList} of {@link Song}s
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param newSongList An {@link ArrayList} of {@link Song}s to overwrite the list contained in the MediaStore
*/
public static void editPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> newSongList){
// Clear the playlist...
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.delete(uri, null, null);
// Then add all of the songs to it
ContentValues[] values = new ContentValues[newSongList.size()];
for (int i = 0; i < newSongList.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, newSongList.get(i).songId);
}
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
/**
* Rename a playlist in the MediaStore
* @param context A {@link Context} to open a {@link ContentResolver}
* @param playlistID The id of the {@link Playlist} to be renamed
* @param name The new name of the playlist
*/
public static void renamePlaylist(final Context context, final long playlistID, final String name) {
if (verifyPlaylistName(context, name) == null) {
ContentValues values = new ContentValues(1);
values.put(MediaStore.Audio.Playlists.NAME, name);
ContentResolver resolver = context.getContentResolver();
resolver.update(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
values,
MediaStore.Audio.Playlists._ID + "=?",
new String[]{Long.toString(playlistID)});
}
}
/**
* Append a song to the end of a playlist. Alerts the user about duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param song The {@link Song} to be added to the playlist in the MediaStore
*/
public static void addPlaylistEntry(final Context context, final Playlist playlist, final Song song){
// Public method to add a song to a playlist
// Checks the playlist for duplicate entries
if (getPlaylistEntries(context, playlist).contains(song)){
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, 1))
.setMessage(context.getString(R.string.playlist_confirm_duplicate, playlist, song))
.setPositiveButton(R.string.action_add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongToEndOfPlaylist(context, playlist, song);
}
})
.setNegativeButton(R.string.action_cancel, null)
.show();
Themes.themeAlertDialog(dialog);
}
else{
addSongToEndOfPlaylist(context, playlist, song);
}
}
/**
* Append a list of songs to the end of a playlist. Alerts the user about duplicates
* @param view A {@link View} to put a {@link android.support.design.widget.Snackbar} in. Will
* also be used to get a {@link Context}.
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore
*/
public static void addPlaylistEntries(final View view, final Playlist playlist, final ArrayList<Song> songs){
// Public method to add songs to a playlist
// Checks the playlist for duplicate entries
final Context context = view.getContext();
int duplicateCount = 0;
final ArrayList<Song> currentEntries = getPlaylistEntries(context, playlist);
final ArrayList<Song> newEntries = new ArrayList<>();
for (Song s : songs){
if (currentEntries.contains(s))duplicateCount++;
else newEntries.add(s);
}
if (duplicateCount > 0){
AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, duplicateCount));
if (duplicateCount == songs.size()) {
alert
.setMessage(context.getString(R.string.playlist_confirm_all_duplicates, duplicateCount))
.setPositiveButton(context.getResources().getQuantityText(R.plurals.playlist_positive_add_duplicates, duplicateCount), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(context.getString(R.string.action_undo), new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNeutralButton(context.getString(R.string.action_cancel), null);
}
else{
alert
.setMessage(context.getResources().getQuantityString(R.plurals.playlist_confirm_some_duplicates, duplicateCount, duplicateCount))
.setPositiveButton(R.string.action_add_new, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, newEntries);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNegativeButton(R.string.action_add_all, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
})
.setNeutralButton(R.string.action_cancel, null);
}
Themes.themeAlertDialog(alert.show());
}
else{
addSongsToEndOfPlaylist(context, playlist, songs);
Snackbar.make(
view,
context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName),
Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
Library.editPlaylist(
context,
playlist,
currentEntries);
}
}).show();
}
}
// MEDIA_STORE EDIT METHODS
// These methods only perform actions to the MediaStore. They do not validate inputs, and they
// do not display confirmation messages to the user.
/**
* Add a new playlist to the MediaStore and to the application's current library instance. Use
* this when making regular playlists.
* Outside of this class, use {@link Library#createPlaylist(View, String, ArrayList)} instead
* <b>This method DOES NOT validate inputs or display a confirmation message to the user</b>.
* @param context A {@link Context} used to edit the MediaStore
* @param playlistName The name of the new playlist
* @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist
* @return The Playlist that was added to the library
*/
private static Playlist addPlaylist(final Context context, final String playlistName,
@Nullable final ArrayList<Song> songList) {
final Playlist added = makePlaylist(context, playlistName, songList);
playlistLib.add(added);
Collections.sort(playlistLib);
notifyPlaylistAdded(added);
return added;
}
/**
* Internal logic for adding a playlist to the MediaStore only.
* @param context A {@link Context} used to edit the MediaStore
* @param playlistName The name of the new playlist
* @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist
* @return The Playlist that was added to the library
* @see Library#addPlaylist(Context, String, ArrayList) for playlist creation
* @see Library#createAutoPlaylist(Context, AutoPlaylist) for AutoPlaylist creation
*/
private static Playlist makePlaylist(final Context context, final String playlistName, @Nullable final ArrayList<Song> songList){
String trimmedName = playlistName.trim();
// Add the playlist to the MediaStore
ContentValues mInserts = new ContentValues();
mInserts.put(MediaStore.Audio.Playlists.NAME, trimmedName);
mInserts.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis());
mInserts.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis());
Uri newPlaylistUri = context.getContentResolver().insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mInserts);
if (newPlaylistUri == null) {
throw new RuntimeException("Content resolver insert returned null");
}
// Get the id of the new playlist
Cursor cursor = context.getContentResolver().query(
newPlaylistUri,
new String[] {MediaStore.Audio.Playlists._ID},
null, null, null);
if (cursor == null) {
throw new RuntimeException("Content resolver query returned null");
}
cursor.moveToFirst();
final Playlist playlist = new Playlist(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)), playlistName);
cursor.close();
// If we have a list of songs, associate it with the playlist
if(songList != null) {
ContentValues[] values = new ContentValues[songList.size()];
for (int i = 0; i < songList.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songList.get(i).songId);
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
return playlist;
}
/**
* Removes a playlist from the MediaStore
* @param context A {@link Context} to update the MediaStore
* @param playlist A {@link Playlist} whose matching playlist will be removed from the MediaStore
*/
public static void deletePlaylist(final Context context, final Playlist playlist){
// Remove the playlist from the MediaStore
context.getContentResolver().delete(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
MediaStore.Audio.Playlists._ID + "=?",
new String[]{playlist.playlistId + ""});
// If the playlist is an AutoPlaylist, make sure to delete its configuration
if (playlist instanceof AutoPlaylist) {
//noinspection ResultOfMethodCallIgnored
new File(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION).delete();
}
// Update the playlist library & resort it
playlistLib.clear();
setPlaylistLib(scanPlaylists(context));
Collections.sort(playlistLib);
notifyPlaylistRemoved(playlist);
}
/**
* Append a song to the end of a playlist. Doesn't check for duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param song The {@link Song} to be added to the playlist in the MediaStore
*/
private static void addSongToEndOfPlaylist (final Context context, final Playlist playlist, final Song song){
// Private method to add a song to a playlist
// This method does the actual operation to the MediaStore
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
null, null, null,
MediaStore.Audio.Playlists.Members.TRACK + " ASC");
if (cur == null) {
throw new RuntimeException("Content resolver query returned null");
}
long count = 0;
if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK));
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1);
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, song.songId);
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.insert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
/**
* Append a list of songs to the end of a playlist. Doesn't check for duplicates
* @param context A {@link Context} to open a {@link Cursor}
* @param playlist The {@link Playlist} to edit in the MediaStore
* @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore
*/
private static void addSongsToEndOfPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> songs){
// Private method to add a song to a playlist
// This method does the actual operation to the MediaStore
Cursor cur = context.getContentResolver().query(
MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId),
null, null, null,
MediaStore.Audio.Playlists.Members.TRACK + " ASC");
if (cur == null) {
throw new RuntimeException("Content resolver query returned null");
}
long count = 0;
if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK));
cur.close();
ContentValues[] values = new ContentValues[songs.size()];
for (int i = 0; i < songs.size(); i++) {
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(i).songId);
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId);
ContentResolver resolver = context.getContentResolver();
resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
}
// AUTO PLAYLIST EDIT METHODS
/**
* Add an {@link AutoPlaylist} to the library.
* @param playlist the AutoPlaylist to be added to the library. The configuration of this
* playlist will be saved so that it can be loaded when the library is next
* rescanned, and a "stale" copy with current entries will be written in the
* MediaStore so that other applications may access this playlist
*/
public static void createAutoPlaylist(Context context, AutoPlaylist playlist) {
try {
// Add the playlist to the MediaStore
Playlist p = makePlaylist(context, playlist.playlistName, playlist.generatePlaylist(context));
// Assign the auto playlist's ID to match the one in the MediaStore
playlist.playlistId = p.playlistId;
// Save the playlist configuration with GSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION);
playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class));
playlistWriter.close();
// Add the playlist to the library and resort the playlist library
playlistLib.add(playlist);
Collections.sort(playlistLib);
notifyPlaylistAdded(playlist);
} catch (IOException e) {
Crashlytics.logException(e);
}
}
public static void editAutoPlaylist(Context context, AutoPlaylist playlist) {
try {
// Save the playlist configuration with GSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION);
playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class));
playlistWriter.close();
// Edit the contents of this playlist in the MediaStore
editPlaylist(context, playlist, playlist.generatePlaylist(context));
// Remove the old index of this playlist, but keep the Object for reference.
// Since playlists are compared by Id's, this will remove the old index
AutoPlaylist oldReference =
(AutoPlaylist) playlistLib.remove(playlistLib.indexOf(playlist));
// If the user renamed the playlist, update it now
if (!oldReference.playlistName.equals(playlist.playlistName)) {
renamePlaylist(context, playlist.playlistId, playlist.playlistName);
// Delete the old config file so that it doesn't reappear on restart
//noinspection ResultOfMethodCallIgnored
new File(context.getExternalFilesDir(null) + "/" +
oldReference.playlistName + AUTO_PLAYLIST_EXTENSION).delete();
}
// Add the playlist again. This makes sure that if the values have been cloned before
// being changed that their values will be updated without having to rescan the
// entire library
playlistLib.add(playlist);
Collections.sort(playlistLib);
} catch (IOException e) {
Crashlytics.logException(e);
}
}
// Media file open method
/**
* Get a list of songs to play for a certain input file. If a song is passed as the file, then
* the list will include other songs in the same directory. If a playlist is passed as the file,
* then the playlist will be opened as a regular playlist.
*
* @param activity An {@link Activity} to use when building the list
* @param file The {@link File} which the list will be built around
* @param type The MIME type of the file being opened
* @param queue An {@link ArrayList} which will be populated with the {@link Song}s
* @return The position that this list should be started from
* @throws IOException
*/
public static int getSongListFromFile(Activity activity, File file, String type, final ArrayList<Song> queue) throws IOException{
// A somewhat convoluted method for getting a list of songs from a path
// Songs are put into the queue array list
// The integer returned is the position in this queue that corresponds to the requested song
if (isEmpty()){
// We depend on the library being scanned, so make sure it's scanned before we go any further
scanAll(activity);
}
// PLAYLISTS
if (type.equals("audio/x-mpegurl") || type.equals("audio/x-scpls") || type.equals("application/vnd.ms-wpl")){
// If a playlist was opened, try to find and play its entry from the MediaStore
Cursor cur = activity.getContentResolver().query(
MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Playlists.DATA + "=?",
new String[] {file.getPath()},
MediaStore.Audio.Playlists.NAME + " ASC");
if (cur == null) {
throw new RuntimeException("Content resolver query returned null");
}
// If the media store contains this playlist, play it like a regular playlist
if (cur.getCount() > 0){
cur.moveToFirst();
queue.addAll(getPlaylistEntries(activity, new Playlist(
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists._ID)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.NAME)))));
}
//TODO Attempt to manually read common playlist writing schemes
/*else{
// If the MediaStore doesn't contain this playlist, attempt to read it manually
Scanner sc = new Scanner(file);
ArrayList<String> lines = new ArrayList<>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
if (lines.size() > 0){
// Do stuff
}
}*/
cur.close();
// Return 0 to start at the beginning of the playlist
return 0;
}
// ALL OTHER TYPES OF MEDIA
else {
// If the file isn't a playlist, use a content resolver to find the song and play it
// Find all songs in the directory
Cursor cur = activity.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.DATA + " like ?",
new String[] {"%" + file.getParent() + "/%"},
MediaStore.Audio.Media.DATA + " ASC");
if (cur == null) {
throw new RuntimeException("Content resolver query returned null");
}
// Create song objects to match those in the music library
for (int i = 0; i < cur.getCount(); i++) {
cur.moveToPosition(i);
queue.add(new Song(
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)),
(cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)).equals(MediaStore.UNKNOWN_STRING))
? activity.getString(R.string.unknown_artist)
: cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)),
cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID))));
}
cur.close();
// Find the position of the song that should be played
for(int i = 0; i < queue.size(); i++){
if (queue.get(i).location.equals(file.getPath())) return i;
}
}
return 0;
}
} |
package wcdi.wcdiplayer;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.Comparator;
import wcdi.wcdiplayer.Items.SongObject;
import wcdi.wcdiplayer.widget.SongViewAdapter;
public class SongFragment extends ListFragment {
private static final String EXTRA_SERIALIZABLE_SONG_OBJECTS = "song_objects";
private SongViewAdapter mAdapter;
private OnSongClickListener mListener;
private ArrayList<SongObject> mSongObjectList;
public SongFragment() {
}
public static SongFragment newInstance(ArrayList<SongObject> songObjects) {
SongFragment fragment = new SongFragment();
Bundle args = new Bundle();
args.putSerializable(EXTRA_SERIALIZABLE_SONG_OBJECTS, songObjects);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
mAdapter = new SongViewAdapter(getActivity(), R.layout.song_list_item);
mSongObjectList = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_song, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
AbsListView mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListener.onSongClick(mSongObjectList, position);
}
});
if (mListView.getCount() == 0) {
mAdapter.addAll((ArrayList<SongObject>) getArguments().getSerializable(EXTRA_SERIALIZABLE_SONG_OBJECTS));
}
mAdapter.sort(new Comparator<SongObject>() {
@Override
public int compare(SongObject lhs, SongObject rhs) {
return lhs.mTrack - rhs.mTrack;
}
});
mSongObjectList = (ArrayList<SongObject>) mAdapter.getAll();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnSongClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnSongClickListener");
}
}
public interface OnSongClickListener {
void onSongClick(ArrayList<SongObject> mSongObjectList, int position);
}
} |
package org.xbill.DNS;
import java.io.*;
import java.util.*;
/**
* A cache of DNS records. The cache obeys TTLs, so items are purged after
* their validity period is complete. Negative answers are cached, to
* avoid repeated failed DNS queries. The credibility of each RRset is
* maintained, so that more credible records replace less credible records,
* and lookups can specify the minimum credibility of data they are requesting.
* @see RRset
* @see Credibility
*
* @author Brian Wellington
*/
public class Cache {
private interface Element {
public boolean expired();
public int compareCredibility(int cred);
public int getType();
}
private static int
limitExpire(long ttl, long maxttl) {
if (maxttl >= 0 && maxttl < ttl)
ttl = maxttl;
int expire = (int)((System.currentTimeMillis() / 1000) + ttl);
if (expire < 0 || expire > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return expire;
}
private static class CacheRRset extends RRset implements Element {
int credibility;
int expire;
public
CacheRRset(Record rec, int cred, long maxttl) {
super();
this.credibility = cred;
this.expire = limitExpire(rec.getTTL(), maxttl);
addRR(rec);
}
public
CacheRRset(RRset rrset, int cred, long maxttl) {
super(rrset);
this.credibility = cred;
this.expire = limitExpire(rrset.getTTL(), maxttl);
}
public final boolean
expired() {
int now = (int)(System.currentTimeMillis() / 1000);
return (now >= expire);
}
public final int
compareCredibility(int cred) {
return credibility - cred;
}
public String
toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append(" cl = ");
sb.append(credibility);
return sb.toString();
}
}
private static class NegativeElement implements Element {
int type;
Name name;
SOARecord soa;
int credibility;
int expire;
public
NegativeElement(Name name, int type, SOARecord soa, int cred,
long maxttl)
{
this.name = name;
this.type = type;
this.soa = soa;
long cttl = 0;
if (soa != null)
cttl = soa.getMinimum();
this.credibility = cred;
this.expire = limitExpire(cttl, maxttl);
}
public int
getType() {
return type;
}
public final boolean
expired() {
int now = (int)(System.currentTimeMillis() / 1000);
return (now >= expire);
}
public final int
compareCredibility(int cred) {
return credibility - cred;
}
public String
toString() {
StringBuffer sb = new StringBuffer();
if (type == 0)
sb.append("NXDOMAIN " + name);
else
sb.append("NXRRSET " + name + " " + Type.string(type));
sb.append(" cl = ");
sb.append(credibility);
return sb.toString();
}
}
private static class CacheMap extends LinkedHashMap {
private int maxsize = -1;
CacheMap(int maxsize) {
super(16, (float) 0.75, true);
this.maxsize = maxsize;
}
int
getMaxSize() {
return maxsize;
}
void
setMaxSize(int maxsize) {
/*
* Note that this doesn't shrink the size of the map if
* the maximum size is lowered, but it should shrink as
* entries expire.
*/
this.maxsize = maxsize;
}
protected boolean removeEldestEntry(Map.Entry eldest) {
return maxsize >= 0 && size() > maxsize;
}
}
private CacheMap data;
private int maxncache = -1;
private int maxcache = -1;
private int dclass;
private static final int defaultMaxEntries = 50000;
/**
* Creates an empty Cache
*
* @param dclass The DNS class of this cache
* @see DClass
*/
public
Cache(int dclass) {
this.dclass = dclass;
data = new CacheMap(defaultMaxEntries);
}
/**
* Creates an empty Cache
*
* @param dclass The DNS class of this cache
* @param cleanInterval unused
* @deprecated Use Cache(int) instead.
*/
public
Cache(int dclass, int cleanInterval) {
this(dclass);
}
/**
* Creates an empty Cache for class IN.
* @see DClass
*/
public
Cache() {
this(DClass.IN);
}
/**
* Creates a Cache which initially contains all records in the specified file.
*/
public
Cache(String file) throws IOException {
data = new CacheMap(defaultMaxEntries);
Master m = new Master(file);
Record record;
while ((record = m.nextRecord()) != null)
addRecord(record, Credibility.HINT, m);
}
private synchronized Object
exactName(Name name) {
return data.get(name);
}
private synchronized void
removeName(Name name) {
data.remove(name);
}
private synchronized Element []
allElements(Object types) {
if (types instanceof List) {
List typelist = (List) types;
int size = typelist.size();
return (Element []) typelist.toArray(new Element[size]);
} else {
Element set = (Element) types;
return new Element[] {set};
}
}
private synchronized Element
oneElement(Name name, Object types, int type, int minCred) {
Element found = null;
if (type == Type.ANY)
throw new IllegalArgumentException("oneElement(ANY)");
if (types instanceof List) {
List list = (List) types;
for (int i = 0; i < list.size(); i++) {
Element set = (Element) list.get(i);
if (set.getType() == type) {
found = set;
break;
}
}
} else {
Element set = (Element) types;
if (set.getType() == type)
found = set;
}
if (found == null)
return null;
if (found.expired()) {
removeElement(name, type);
return null;
}
if (found.compareCredibility(minCred) < 0)
return null;
return found;
}
private synchronized Element
findElement(Name name, int type, int minCred) {
Object types = exactName(name);
if (types == null)
return null;
return oneElement(name, types, type, minCred);
}
private synchronized void
addElement(Name name, Element element) {
Object types = data.get(name);
if (types == null) {
data.put(name, element);
return;
}
int type = element.getType();
if (types instanceof List) {
List list = (List) types;
for (int i = 0; i < list.size(); i++) {
Element elt = (Element) list.get(i);
if (elt.getType() == type) {
list.set(i, element);
return;
}
}
list.add(element);
} else {
Element elt = (Element) types;
if (elt.getType() == type)
data.put(name, element);
else {
LinkedList list = new LinkedList();
list.add(elt);
list.add(element);
data.put(name, list);
}
}
}
private synchronized void
removeElement(Name name, int type) {
Object types = data.get(name);
if (types == null) {
return;
}
if (types instanceof List) {
List list = (List) types;
for (int i = 0; i < list.size(); i++) {
Element elt = (Element) list.get(i);
if (elt.getType() == type) {
list.remove(i);
if (list.size() == 0)
data.remove(name);
return;
}
}
} else {
Element elt = (Element) types;
if (elt.getType() != type)
return;
data.remove(name);
}
}
/** Empties the Cache. */
public synchronized void
clearCache() {
data.clear();
}
/**
* Adds a record to the Cache.
* @param r The record to be added
* @param cred The credibility of the record
* @param o The source of the record (this could be a Message, for example)
* @see Record
*/
public synchronized void
addRecord(Record r, int cred, Object o) {
Name name = r.getName();
int type = r.getRRsetType();
if (!Type.isRR(type))
return;
Element element = findElement(name, type, cred);
if (element == null) {
CacheRRset crrset = new CacheRRset(r, cred, maxcache);
addRRset(crrset, cred);
} else if (element.compareCredibility(cred) == 0) {
if (element instanceof CacheRRset) {
CacheRRset crrset = (CacheRRset) element;
crrset.addRR(r);
}
}
}
/**
* Adds an RRset to the Cache.
* @param rrset The RRset to be added
* @param cred The credibility of these records
* @see RRset
*/
public synchronized void
addRRset(RRset rrset, int cred) {
long ttl = rrset.getTTL();
Name name = rrset.getName();
int type = rrset.getType();
Element element = findElement(name, type, 0);
if (ttl == 0) {
if (element != null && element.compareCredibility(cred) <= 0)
removeElement(name, type);
} else {
if (element != null && element.compareCredibility(cred) <= 0)
element = null;
if (element == null) {
CacheRRset crrset;
if (rrset instanceof CacheRRset)
crrset = (CacheRRset) rrset;
else
crrset = new CacheRRset(rrset, cred, maxcache);
addElement(name, crrset);
}
}
}
/**
* Adds a negative entry to the Cache.
* @param name The name of the negative entry
* @param type The type of the negative entry
* @param soa The SOA record to add to the negative cache entry, or null.
* The negative cache ttl is derived from the SOA.
* @param cred The credibility of the negative entry
*/
public synchronized void
addNegative(Name name, int type, SOARecord soa, int cred) {
long ttl = 0;
if (soa != null)
ttl = soa.getTTL();
Element element = findElement(name, type, 0);
if (ttl == 0) {
if (element != null && element.compareCredibility(cred) <= 0)
removeElement(name, type);
} else {
if (element != null && element.compareCredibility(cred) <= 0)
element = null;
if (element == null)
addElement(name, new NegativeElement(name, type,
soa, cred,
maxncache));
}
}
/**
* Finds all matching sets or something that causes the lookup to stop.
*/
protected synchronized SetResponse
lookup(Name name, int type, int minCred) {
int labels;
int tlabels;
Element element;
CacheRRset crrset;
Name tname;
Object types;
SetResponse sr;
labels = name.labels();
for (tlabels = labels; tlabels >= 1; tlabels
boolean isRoot = (tlabels == 1);
boolean isExact = (tlabels == labels);
if (isRoot)
tname = Name.root;
else if (isExact)
tname = name;
else
tname = new Name(name, labels - tlabels);
types = data.get(tname);
if (types == null)
continue;
/* If this is an ANY lookup, return everything. */
if (isExact && type == Type.ANY) {
sr = new SetResponse(SetResponse.SUCCESSFUL);
Element [] elements = allElements(types);
int added = 0;
for (int i = 0; i < elements.length; i++) {
element = elements[i];
if (element.expired()) {
removeElement(tname, element.getType());
continue;
}
if (!(element instanceof CacheRRset))
continue;
if (element.compareCredibility(minCred) < 0)
continue;
sr.addRRset((CacheRRset)element);
added++;
}
/* There were positive entries */
if (added > 0)
return sr;
}
/* Look for an NS */
element = oneElement(tname, types, Type.NS, minCred);
if (element != null && element instanceof CacheRRset)
return new SetResponse(SetResponse.DELEGATION,
(CacheRRset) element);
/*
* If this is the name, look for the actual type or a CNAME.
* Otherwise, look for a DNAME.
*/
if (isExact) {
element = oneElement(tname, types, type, minCred);
if (element != null &&
element instanceof CacheRRset)
{
sr = new SetResponse(SetResponse.SUCCESSFUL);
sr.addRRset((CacheRRset) element);
return sr;
} else if (element != null) {
sr = new SetResponse(SetResponse.NXRRSET);
return sr;
}
element = oneElement(tname, types, Type.CNAME, minCred);
if (element != null &&
element instanceof CacheRRset)
{
return new SetResponse(SetResponse.CNAME,
(CacheRRset) element);
}
} else {
element = oneElement(tname, types, Type.DNAME, minCred);
if (element != null &&
element instanceof CacheRRset)
{
return new SetResponse(SetResponse.DNAME,
(CacheRRset) element);
}
}
/* Check for the special NXDOMAIN element. */
if (isExact) {
element = oneElement(tname, types, 0, minCred);
if (element != null)
return SetResponse.ofType(SetResponse.NXDOMAIN);
}
}
return SetResponse.ofType(SetResponse.UNKNOWN);
}
/**
* Looks up Records in the Cache. This follows CNAMEs and handles negatively
* cached data.
* @param name The name to look up
* @param type The type to look up
* @param minCred The minimum acceptable credibility
* @return A SetResponse object
* @see SetResponse
* @see Credibility
*/
public SetResponse
lookupRecords(Name name, int type, int minCred) {
return lookup(name, type, minCred);
}
private RRset []
findRecords(Name name, int type, int minCred) {
SetResponse cr = lookupRecords(name, type, minCred);
if (cr.isSuccessful())
return cr.answers();
else
return null;
}
/**
* Looks up credible Records in the Cache (a wrapper around lookupRecords).
* Unlike lookupRecords, this given no indication of why failure occurred.
* @param name The name to look up
* @param type The type to look up
* @return An array of RRsets, or null
* @see Credibility
*/
public RRset []
findRecords(Name name, int type) {
return findRecords(name, type, Credibility.NORMAL);
}
/**
* Looks up Records in the Cache (a wrapper around lookupRecords). Unlike
* lookupRecords, this given no indication of why failure occurred.
* @param name The name to look up
* @param type The type to look up
* @return An array of RRsets, or null
* @see Credibility
*/
public RRset []
findAnyRecords(Name name, int type) {
return findRecords(name, type, Credibility.GLUE);
}
private final int
getCred(int section, boolean isAuth) {
if (section == Section.ANSWER) {
if (isAuth)
return Credibility.AUTH_ANSWER;
else
return Credibility.NONAUTH_ANSWER;
} else if (section == Section.AUTHORITY) {
if (isAuth)
return Credibility.AUTH_AUTHORITY;
else
return Credibility.NONAUTH_AUTHORITY;
} else if (section == Section.ADDITIONAL) {
return Credibility.ADDITIONAL;
} else
throw new IllegalArgumentException("getCred: invalid section");
}
private static void
markAdditional(RRset rrset, Set names) {
Record first = rrset.first();
if (first.getAdditionalName() == null)
return;
Iterator it = rrset.rrs();
while (it.hasNext()) {
Record r = (Record) it.next();
Name name = r.getAdditionalName();
if (name != null)
names.add(name);
}
}
/**
* Adds all data from a Message into the Cache. Each record is added with
* the appropriate credibility, and negative answers are cached as such.
* @param in The Message to be added
* @return A SetResponse that reflects what would be returned from a cache
* lookup, or null if nothing useful could be cached from the message.
* @see Message
*/
public SetResponse
addMessage(Message in) {
boolean isAuth = in.getHeader().getFlag(Flags.AA);
Record question = in.getQuestion();
Name qname;
Name curname;
int qtype;
int qclass;
int cred;
int rcode = in.getHeader().getRcode();
boolean haveAnswer = false;
boolean completed = false;
RRset [] answers, auth, addl;
SetResponse response = null;
boolean verbose = Options.check("verbosecache");
HashSet additionalNames;
if ((rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) ||
question == null)
return null;
qname = question.getName();
qtype = question.getType();
qclass = question.getDClass();
curname = qname;
additionalNames = new HashSet();
answers = in.getSectionRRsets(Section.ANSWER);
for (int i = 0; i < answers.length; i++) {
if (answers[i].getDClass() != qclass)
continue;
int type = answers[i].getType();
Name name = answers[i].getName();
cred = getCred(Section.ANSWER, isAuth);
if ((type == qtype || qtype == Type.ANY) &&
name.equals(curname))
{
addRRset(answers[i], cred);
completed = true;
haveAnswer = true;
if (curname == qname) {
if (response == null)
response = new SetResponse(
SetResponse.SUCCESSFUL);
response.addRRset(answers[i]);
}
markAdditional(answers[i], additionalNames);
} else if (type == Type.CNAME && name.equals(curname)) {
CNAMERecord cname;
addRRset(answers[i], cred);
if (curname == qname)
response = new SetResponse(SetResponse.CNAME,
answers[i]);
cname = (CNAMERecord) answers[i].first();
curname = cname.getTarget();
haveAnswer = true;
} else if (type == Type.DNAME && curname.subdomain(name)) {
DNAMERecord dname;
addRRset(answers[i], cred);
if (curname == qname)
response = new SetResponse(SetResponse.DNAME,
answers[i]);
dname = (DNAMERecord) answers[i].first();
try {
curname = curname.fromDNAME(dname);
}
catch (NameTooLongException e) {
break;
}
haveAnswer = true;
}
}
auth = in.getSectionRRsets(Section.AUTHORITY);
RRset soa = null, ns = null;
for (int i = 0; i < auth.length; i++) {
if (auth[i].getType() == Type.SOA &&
curname.subdomain(auth[i].getName()))
soa = auth[i];
else if (auth[i].getType() == Type.NS &&
curname.subdomain(auth[i].getName()))
ns = auth[i];
}
if (!completed) {
/* This is a negative response or a referral. */
int cachetype = (rcode == Rcode.NXDOMAIN) ? 0 : qtype;
if (soa != null || ns == null) {
/* Negative response */
cred = getCred(Section.AUTHORITY, isAuth);
SOARecord soarec = null;
if (soa != null)
soarec = (SOARecord) soa.first();
addNegative(curname, cachetype, soarec, cred);
if (response == null) {
int responseType;
if (rcode == Rcode.NXDOMAIN)
responseType = SetResponse.NXDOMAIN;
else
responseType = SetResponse.NXRRSET;
response = SetResponse.ofType(responseType);
}
/* NXT records are not cached yet. */
} else {
/* Referral response */
cred = getCred(Section.AUTHORITY, isAuth);
addRRset(ns, cred);
markAdditional(ns, additionalNames);
if (response == null)
response = new SetResponse(
SetResponse.DELEGATION,
ns);
}
} else if (rcode == Rcode.NOERROR && ns != null) {
/* Cache the NS set from a positive response. */
cred = getCred(Section.AUTHORITY, isAuth);
addRRset(ns, cred);
markAdditional(ns, additionalNames);
}
addl = in.getSectionRRsets(Section.ADDITIONAL);
for (int i = 0; i < addl.length; i++) {
int type = addl[i].getType();
if (type != Type.A && type != Type.AAAA && type != Type.A6)
continue;
Name name = addl[i].getName();
if (!additionalNames.contains(name))
continue;
cred = getCred(Section.ADDITIONAL, isAuth);
addRRset(addl[i], cred);
}
if (verbose)
System.out.println("addMessage: " + response);
return (response);
}
/**
* Flushes an RRset from the cache
* @param name The name of the records to be flushed
* @param type The type of the records to be flushed
* @see RRset
*/
public void
flushSet(Name name, int type) {
removeElement(name, type);
}
/**
* Flushes all RRsets with a given name from the cache
* @param name The name of the records to be flushed
* @see RRset
*/
public void
flushName(Name name) {
removeName(name);
}
/**
* Sets the maximum length of time that a negative response will be stored
* in this Cache. A negative value disables this feature (that is, sets
* no limit).
*/
public void
setMaxNCache(int seconds) {
maxncache = seconds;
}
/**
* Gets the maximum length of time that a negative response will be stored
* in this Cache. A negative value indicates no limit.
*/
public int
getMaxNCache() {
return maxncache;
}
/**
* Sets the maximum length of time that records will be stored in this
* Cache. A negative value disables this feature (that is, sets no limit).
*/
public void
setMaxCache(int seconds) {
maxcache = seconds;
}
/**
* Gets the maximum length of time that records will be stored
* in this Cache. A negative value indicates no limit.
*/
public int
getMaxCache() {
return maxcache;
}
/**
* Gets the current number of entries in the Cache, where an entry consists
* of all records with a specific Name.
*/
public int
getSize() {
return data.size();
}
/**
* Gets the maximum number of entries in the Cache, where an entry consists
* of all records with a specific Name. A negative value is treated as an
* infinite limit.
*/
public int
getMaxEntries() {
return data.getMaxSize();
}
/**
* Sets the maximum number of entries in the Cache, where an entry consists
* of all records with a specific Name. A negative value is treated as an
* infinite limit.
*
* Note that setting this to a value lower than the current number
* of entries will not cause the Cache to shrink immediately.
*
* The default maximum number of entries is 50000.
*
* @param entries The maximum number of entries in the Cache.
*/
public void
setMaxEntries(int entries) {
data.setMaxSize(entries);
}
/**
* Returns the DNS class of this cache.
*/
public int
getDClass() {
return dclass;
}
/**
* @deprecated Caches are no longer periodically cleaned.
*/
public void
setCleanInterval(int cleanInterval) {
}
/**
* Returns the contents of the Cache as a string.
*/
public String
toString() {
StringBuffer sb = new StringBuffer();
synchronized (this) {
Iterator it = data.values().iterator();
while (it.hasNext()) {
Element [] elements = allElements(it.next());
for (int i = 0; i < elements.length; i++) {
sb.append(elements[i]);
sb.append("\n");
}
}
}
return sb.toString();
}
} |
package ij.process;
public class Index {
/** create an index array of length numDims initialized to zeroes */
public static int[] create(int numDims)
{
return new int[numDims];
}
/** create an index array initialized to passed in values */
public static int[] create(int[] initialValues)
{
return initialValues.clone();
}
/** create an index array setting the first 2 dims to x & y and the remaining dims populated with passed in values */
public static int[] create(int x, int y, int[] planePosition)
{
if (x < 0)
throw new IllegalArgumentException("x value must be >= 0");
if (y < 0)
throw new IllegalArgumentException("y value must be >= 0");
int[] values = new int[planePosition.length + 2];
values[0] = x;
values[1] = y;
for (int i = 2; i < values.length; i++)
values[i] = planePosition[i-2];
return values;
}
public static boolean isValid(int[] position, int[] origin, int[] span)
{
for (int i = 0; i < position.length; i++)
{
if (position[i] < origin[i])
return false;
if (position[i] >= (origin[i] + span[i]))
return false;
}
return true;
}
// incrementing from left to right : not textbook but hacky way to get ImgLibProcessor::duplicate() working
public static void increment(int[] position, int[] origin, int[] span)
{
int i = 0;
position[i]++;
// if we're beyond end of this dimension
while (position[i] >= (origin[i] + span[i]))
{
// if this dim is the last then we've gone as far as we can go
if (i == position.length-1)
{
// return a value that isValid() will complain about
for (int j = 0; j < position.length; j++)
position[j] = origin[j] + span[j];
return;
}
// otherwise set our dim to its origin value and increment the dimension to our right
position[i] = origin[i];
position[i+1]++;
i++;
}
}
/*
// incrementing from right to left
public static void increment(int[] position, int[] origin, int[] span)
{
int i = position.length - 1;
position[i]++;
// if we're beyond end of this dimension
while (position[i] >= (origin[i] + span[i]))
{
// if this dim is the first then we've gone as far as we can go
if (i == 0)
{
// return a value that isValid() will complain about
for (int j = 0; j < position.length; j++)
position[j] = origin[j] + span[j];
return;
}
// otherwise set our dim to its origin value and increment the dimension to our left
position[i] = origin[i];
position[i-1]++;
i--;
}
}
*/
} |
package io.tetrapod.core;
import static io.tetrapod.protocol.core.CoreContract.*;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.ConnectException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Timer.Context;
import ch.qos.logback.classic.LoggerContext;
import io.netty.channel.socket.SocketChannel;
import io.tetrapod.core.pubsub.Publisher;
import io.tetrapod.core.pubsub.Topic;
import io.tetrapod.core.rpc.*;
import io.tetrapod.core.rpc.Error;
import io.tetrapod.core.utils.*;
import io.tetrapod.protocol.core.*;
public class DefaultService
implements Service, Fail.FailHandler, CoreContract.API, SessionFactory, EntityMessage.Handler, TetrapodContract.Cluster.API {
private static final Logger logger = LoggerFactory.getLogger(DefaultService.class);
protected final Set<Integer> dependencies = new HashSet<>();
public final Dispatcher dispatcher;
protected final Client clusterClient;
protected final Contract contract;
protected final ServiceCache services;
protected boolean terminated;
protected int entityId;
protected int parentId;
protected String token;
private int status;
public final String buildName;
protected final LogBuffer logBuffer;
protected SSLContext sslContext;
protected ServiceConnector serviceConnector;
protected final ServiceStats stats;
protected boolean startPaused;
public final SecureRandom random = new SecureRandom();
private final LinkedList<ServerAddress> clusterMembers = new LinkedList<>();
private final MessageHandlers messageHandlers = new MessageHandlers();
private final Publisher publisher = new Publisher(this);
public DefaultService() {
this(null);
}
public DefaultService(Contract mainContract) {
logBuffer = (LogBuffer) ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("ROOT").getAppender("BUFFER");
String m = getStartLoggingMessage();
logger.info(m);
Session.commsLog.info(m);
Fail.handler = this;
synchronized (this) {
status |= Core.STATUS_STARTING;
}
dispatcher = new Dispatcher();
clusterClient = new Client(this);
stats = new ServiceStats(this);
addContracts(new CoreContract());
addPeerContracts(new TetrapodContract());
addMessageHandler(new EntityMessage(), this);
addSubscriptionHandler(new TetrapodContract.Cluster(), this);
try {
if (Util.getProperty("tetrapod.tls", true)) {
sslContext = Util.createSSLContext(new FileInputStream(Util.getProperty("tetrapod.jks.file", "cfg/tetrapod.jks")),
Util.getProperty("tetrapod.jks.pwd", "4pod.dop4").toCharArray());
}
} catch (Exception e) {
fail(e);
}
if (getEntityType() != Core.TYPE_TETRAPOD) {
services = new ServiceCache();
addSubscriptionHandler(new TetrapodContract.Services(), services);
} else {
services = null;
}
Runtime.getRuntime().addShutdownHook(new Thread("Shutdown Hook") {
@Override
public void run() {
logger.info("Shutdown Hook");
if (!isShuttingDown()) {
shutdown(false);
}
}
});
String build = "Unknown";
try {
build = Util.readFileAsString(new File("build_name.txt"));
} catch (IOException e) {}
buildName = build;
checkHealth();
if (mainContract != null)
addContracts(mainContract);
this.contract = mainContract;
}
/**
* Returns a prefix for all exported metrics from this service.
*/
private String getMetricsPrefix() {
return Util.getProperty("devMode", "") + "." + Util.getProperty("product.name") + "." + Util.getHostName() + "."
+ getClass().getSimpleName();
}
public byte getEntityType() {
return Core.TYPE_SERVICE;
}
public synchronized int getStatus() {
return status;
}
@Override
public void messageEntity(EntityMessage m, MessageContext ctxA) {
SessionMessageContext ctx = (SessionMessageContext) ctxA;
if (ctx.session.getTheirEntityType() == Core.TYPE_TETRAPOD) {
synchronized (this) {
this.entityId = m.entityId;
}
ctx.session.setMyEntityId(m.entityId);
}
}
@Override
public void genericMessage(Message message, MessageContext ctx) {
logger.error("Unhandled message handler: {}", message.dump());
assert false;
}
// Service protocol
@Override
public void startNetwork(ServerAddress server, String token, Map<String, String> otherOpts) throws Exception {
this.token = token;
this.startPaused = otherOpts.get("paused").equals("true");
clusterMembers.addFirst(server);
connectToCluster(5);
}
/**
* Called after we've registered and dependencies are all available
*/
public void onReadyToServe() {}
private void onServiceRegistered() {
registerServiceInformation();
stats.publishTopic();
resetServiceConnector(true);
}
public boolean dependenciesReady() {
return services.checkDependencies(dependencies);
}
public boolean dependenciesReady(Set<Integer> deps) {
return services.checkDependencies(deps);
}
private final Object checkDependenciesLock = new Object();
public void checkDependencies() {
synchronized (checkDependenciesLock) {
if (!isShuttingDown() && isStartingUp()) {
logger.info("Checking Dependencies...");
if (dependenciesReady()) {
try {
if (startPaused) {
setStatus(Core.STATUS_PAUSED);
}
if (getEntityType() != Core.TYPE_TETRAPOD) {
AdminAuthToken.setSecret(Util.getProperty(AdminAuthToken.SHARED_SECRET_KEY));
}
onReadyToServe();
} catch (Throwable t) {
fail(t);
}
// ok, we're good to go
clearStatus(Core.STATUS_STARTING);
onStarted();
if (startPaused) {
onPaused();
startPaused = false; // only start paused once
}
} else {
dispatcher.dispatch(1, TimeUnit.SECONDS, () -> checkDependencies());
}
}
}
}
protected void resetServiceConnector(boolean start) {
logger.info("resetServiceConnector({})", start);
if (serviceConnector != null) {
serviceConnector.shutdown();
serviceConnector = null;
}
if (start) {
serviceConnector = new ServiceConnector(this, sslContext);
}
}
/**
* Periodically checks service health, updates metrics
*/
private void checkHealth() {
if (!isShuttingDown()) {
try {
if (dispatcher.workQueueSize.getCount() > 0) {
logger.warn("DISPATCHER QUEUE SIZE = {} ({} threads busy)", dispatcher.workQueueSize.getCount(),
dispatcher.getActiveThreads());
}
int status = 0;
if (logBuffer.hasErrors()) {
status |= Core.STATUS_ERRORS;
}
if (logBuffer.hasWarnings()) {
status |= Core.STATUS_WARNINGS;
}
synchronized (this) {
if (needsStatusUpdate) {
// if a status update previously failed, we try a hamfisted approach here to clobber-fix everything (except GONE state).
needsStatusUpdate = false;
sendDirectRequest(new ServiceStatusUpdateRequest(getStatus(), ~Core.STATUS_GONE)).handle(res -> {
if (res.isError()) {
needsStatusUpdate = true;
}
});
} else {
setStatus(status, Core.STATUS_ERRORS | Core.STATUS_WARNINGS);
}
}
} finally {
dispatcher.dispatch(1, TimeUnit.SECONDS, () -> checkHealth());
}
}
}
/**
* Called before shutting down. Default implementation is to do nothing. Subclasses are
* expecting to close any resources they opened (for example database connections or
* file handles).
*
* @param restarting true if we are shutting down in order to restart
*/
public void onShutdown(boolean restarting) {}
public void onPaused() {}
public void onPurged() {}
public void onReleaseExcess() {}
public void onRebalance() {}
public void onUnpaused() {}
public void onStarted() {}
public void shutdown(boolean restarting) {
setStatus(Core.STATUS_STOPPING);
try {
onShutdown(restarting);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
if (restarting) {
clusterClient.close();
dispatcher.shutdown();
setTerminated(true);
try {
Launcher.relaunch(getRelaunchToken());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
if (getEntityId() != 0 && clusterClient.getSession() != null) {
sendDirectRequest(new UnregisterRequest(getEntityId())).handle(res -> {
clusterClient.close();
dispatcher.shutdown();
setTerminated(true);
});
} else {
dispatcher.shutdown();
setTerminated(true);
}
}
// If JVM doesn't gracefully terminate after 1 minute, explicitly kill the process
final Thread hitman = new Thread(() -> {
Util.sleep(Util.ONE_MINUTE);
logger.warn("Service did not complete graceful termination. Force Killing JVM.");
final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Thread t : map.keySet()) {
logger.warn("{}", t);
}
System.exit(1);
}, "Hitman");
hitman.setDaemon(true);
hitman.start();
}
public ServiceCache getServiceCache() {
return services;
}
public Publisher getPublisher() {
return publisher;
}
protected String getRelaunchToken() {
return token;
}
/**
* Session factory for our session to our parent TetrapodService
*/
@Override
public Session makeSession(SocketChannel ch) {
final Session ses = new WireSession(ch, DefaultService.this);
ses.setMyEntityType(getEntityType());
ses.setTheirEntityType(Core.TYPE_TETRAPOD);
ses.addSessionListener(new Session.Listener() {
@Override
public void onSessionStop(Session ses) {
logger.info("Connection to tetrapod closed");
onDisconnectedFromCluster();
resetServiceConnector(false);
if (!isShuttingDown()) {
dispatcher.dispatch(3, TimeUnit.SECONDS, () -> connectToCluster(1));
}
publisher.resetTopics();
}
@Override
public void onSessionStart(Session ses) {
onConnectedToCluster();
}
});
return ses;
}
private void onConnectedToCluster() {
final Request req = new RegisterRequest(token, getContractId(), getShortName(), getStatus(), Util.getHostName(), buildName);
sendDirectRequest(req).handle(res -> {
if (res.isError()) {
logger.error("Unable to register: " + req.dump() + " ==> " + res);
clusterClient.close();
} else {
RegisterResponse r = (RegisterResponse) res;
entityId = r.entityId;
parentId = r.parentId;
token = r.token;
clusterClient.getSession().setMyEntityId(r.entityId);
clusterClient.getSession().setTheirEntityId(r.parentId);
clusterClient.getSession().setMyEntityType(getEntityType());
clusterClient.getSession().setTheirEntityType(Core.TYPE_TETRAPOD);
logger.info(String.format("%s My entityId is 0x%08X", clusterClient.getSession(), r.entityId));
onServiceRegistered();
}
});
}
public void onDisconnectedFromCluster() {
// override
}
public boolean isConnected() {
return clusterClient.isConnected();
}
protected void connectToCluster(final int retrySeconds) {
if (!isShuttingDown() && !clusterClient.isConnected()) {
synchronized (clusterMembers) {
final ServerAddress server = clusterMembers.poll();
if (server != null) {
try {
if (sslContext != null) {
clusterClient.enableTLS(sslContext);
}
clusterClient.connect(server.host, server.port, dispatcher).sync();
if (clusterClient.isConnected()) {
clusterMembers.addFirst(server);
return;
}
} catch (ConnectException e) {
logger.info(e.getMessage());
} catch (Throwable e) {
logger.error(e.getMessage(), e);
} finally {
clusterMembers.addLast(server);
}
}
}
// schedule a retry
dispatcher.dispatch(retrySeconds, TimeUnit.SECONDS, () -> connectToCluster(retrySeconds));
}
}
// subclass utils
protected void addContracts(Contract... contracts) {
for (Contract c : contracts) {
c.registerStructs();
}
}
protected void addPeerContracts(Contract... contracts) {
for (Contract c : contracts) {
c.registerPeerStructs();
}
}
public int getEntityId() {
return entityId;
}
protected int getParentId() {
return parentId;
}
public synchronized boolean isShuttingDown() {
return (status & Core.STATUS_STOPPING) != 0;
}
public synchronized boolean isPaused() {
return (status & Core.STATUS_PAUSED) != 0;
}
public synchronized boolean isStartingUp() {
return (status & Core.STATUS_STARTING) != 0;
}
public synchronized boolean isNominal() {
int nonRunning = Core.STATUS_STARTING | Core.STATUS_FAILED | Core.STATUS_BUSY | Core.STATUS_PAUSED | Core.STATUS_STOPPING;
return (status & nonRunning) == 0;
}
public synchronized boolean isTerminated() {
return terminated;
}
private synchronized void setTerminated(boolean val) {
logger.info("TERMINATED");
terminated = val;
}
/**
* Sets these status bits to true
*/
protected void setStatus(int bits) {
setStatus(bits, bits);
}
/**
* Clear these status bits
*/
protected void clearStatus(int bits) {
setStatus(0, bits);
}
private boolean needsStatusUpdate = false;
protected void setStatus(int bits, int mask) {
boolean changed = false;
synchronized (this) {
int status = (this.status & ~mask) | bits;
changed = this.status != status;
this.status = status;
}
if (changed && clusterClient.isConnected()) {
sendDirectRequest(new ServiceStatusUpdateRequest(bits, mask)).handle(res -> {
if (res.isError()) {
needsStatusUpdate = true;
}
});
}
}
@Override
public void fail(Throwable error) {
logger.error(error.getMessage(), error);
setStatus(Core.STATUS_FAILED);
onPaused();
}
@Override
public void fail(String reason) {
logger.error("FAIL: {}", reason);
setStatus(Core.STATUS_FAILED);
if (!isPaused()) {
onPaused();
}
}
/**
* Get a URL for this service's icon to display in the admin apps. Subclasses should
* override this to customize
*/
public String getServiceIcon() {
return "media/gear.gif";
}
/**
* Get any custom metadata for the service. Subclasses should override this to
* customize
*/
public String getServiceMetadata() {
return null;
}
/**
* Get any custom admin commands for the service to show in command menu of admin app.
* Subclasses should override this to customize
*/
public ServiceCommand[] getServiceCommands() {
return null;
}
public String getShortName() {
if (contract == null) {
return null;
}
return contract.getName();
}
protected String getFullName() {
if (contract == null) {
return null;
}
String s = contract.getClass().getCanonicalName();
return s.substring(0, s.length() - "Contract".length());
}
public long getAverageResponseTime() {
//return (long) dispatcher.requestTimes.getSnapshot().getMean() / 1000000L;
return Math.round(dispatcher.requestTimes.getOneMinuteRate());
}
/**
* Services can override this to provide a service specific counter for display in the
* admin app
*/
public long getCounter() {
return 0;
}
public long getNumRequestsHandled() {
return dispatcher.requestsHandledCounter.getCount();
}
public long getNumMessagesSent() {
return dispatcher.messagesSentCounter.getCount();
}
/**
* Dispatches a request to ourselves
*/
@Override
public Async dispatchRequest(final RequestHeader header, final Request req, final Session fromSession) {
final Async async = new Async(req, header, fromSession);
final ServiceAPI svc = getServiceHandler(header.contractId);
if (svc != null) {
final long start = System.nanoTime();
final Context context = dispatcher.requestTimes.time();
if (!dispatcher.dispatch(() -> {
final long dispatchTime = System.nanoTime();
Runnable onResult = () -> {
final long elapsed = System.nanoTime() - dispatchTime;
stats.recordRequest(header.fromId, req, elapsed, async.getErrorCode());
context.stop();
dispatcher.requestsHandledCounter.mark();
if (Util.nanosToMillis(elapsed) > 1000) {
logger.warn("Request took {} {} millis", req, Util.nanosToMillis(elapsed));
}
};
try {
if (Util.nanosToMillis(dispatchTime - start) > 2500) {
if ((getStatus() & Core.STATUS_OVERLOADED) == 0) {
logger.warn("Service is overloaded. Dispatch time is {}ms", Util.nanosToMillis(dispatchTime - start));
}
// If it took a while to get dispatched, so set STATUS_OVERLOADED flag as a back-pressure signal
setStatus(Core.STATUS_OVERLOADED);
} else {
clearStatus(Core.STATUS_OVERLOADED);
}
final RequestContext ctx = fromSession != null ? new SessionRequestContext(header, fromSession)
: new InternalRequestContext(header, new ResponseHandler() {
@Override
public void onResponse(Response res) {
try {
assert res != Response.PENDING;
onResult.run();
async.setResponse(res);
} catch (Throwable e) {
logger.error(e.getMessage(), e);
async.setResponse(new Error(ERROR_UNKNOWN));
}
}
});
Response res = req.securityCheck(ctx);
if (res == null) {
res = req.dispatch(svc, ctx);
}
if (res != null) {
if (res != Response.PENDING) {
async.setResponse(res);
}
} else {
async.setResponse(new Error(ERROR_UNKNOWN));
}
} catch (ErrorResponseException e) {
async.setResponse(new Error(e.errorCode));
} catch (Throwable e) {
logger.error(e.getMessage(), e);
async.setResponse(new Error(ERROR_UNKNOWN));
} finally {
if (async.getErrorCode() != -1) {
onResult.run();
}
}
}, Session.DEFAULT_OVERLOAD_THRESHOLD)) {
// too many items queued, full-force back-pressure
async.setResponse(new Error(ERROR_SERVICE_OVERLOADED));
setStatus(Core.STATUS_OVERLOADED);
}
} else {
logger.warn("{} No handler found for {}", this, header.dump());
async.setResponse(new Error(ERROR_UNKNOWN_REQUEST));
}
return async;
}
public Response sendPendingRequest(Request req, int toEntityId, PendingResponseHandler handler) {
if (serviceConnector != null) {
return serviceConnector.sendPendingRequest(req, toEntityId, handler);
}
return clusterClient.getSession().sendPendingRequest(req, toEntityId, (byte) 30, handler);
}
public Response sendPendingRequest(Request req, PendingResponseHandler handler) {
if (serviceConnector != null) {
return serviceConnector.sendPendingRequest(req, Core.UNADDRESSED, handler);
}
return clusterClient.getSession().sendPendingRequest(req, Core.UNADDRESSED, (byte) 30, handler);
}
public Response sendPendingDirectRequest(Request req, PendingResponseHandler handler) {
return clusterClient.getSession().sendPendingRequest(req, Core.DIRECT, (byte) 30, handler);
}
public void sendRequest(Request req, Async.IResponseHandler handler) {
sendRequest(req).handle(handler);
}
public Async sendRequest(Request req) {
if (serviceConnector != null) {
return serviceConnector.sendRequest(req, Core.UNADDRESSED);
}
return clusterClient.getSession().sendRequest(req, Core.UNADDRESSED, (byte) 30);
}
public Async sendRequest(Request req, int toEntityId) {
if (serviceConnector != null) {
return serviceConnector.sendRequest(req, toEntityId);
}
return clusterClient.getSession().sendRequest(req, toEntityId, (byte) 30);
}
public Async sendDirectRequest(Request req) {
return clusterClient.getSession().sendRequest(req, Core.DIRECT, (byte) 30);
}
public boolean isServiceExistant(int entityId) {
return services.isServiceExistant(entityId);
}
public void sendMessage(Message msg, int toEntityId) {
if (serviceConnector != null
&& (serviceConnector.hasService(toEntityId) || (services != null && services.isServiceExistant(toEntityId)))) {
serviceConnector.sendMessage(msg, toEntityId);
} else {
clusterClient.getSession().sendMessage(msg, toEntityId);
}
}
public void sendAltBroadcastMessage(Message msg, int altId) {
clusterClient.getSession().sendAltBroadcastMessage(msg, altId);
}
public boolean sendBroadcastMessage(Message msg, int toEntityId, int topicId) {
if (serviceConnector != null) {
return serviceConnector.sendBroadcastMessage(msg, toEntityId, topicId);
} else {
//clusterClient.getSession().sendTopicBroadcastMessage(msg, toEntityId, topicId);
return false;
}
}
public boolean sendPrivateMessage(Message msg, int toEntityId, int topicId) {
if (serviceConnector != null
&& (serviceConnector.hasService(toEntityId) || (services != null && services.isServiceExistant(toEntityId)))) {
return serviceConnector.sendMessage(msg, toEntityId);
} else {
clusterClient.getSession().sendMessage(msg, toEntityId);
return true;
}
}
public Topic publishTopic() {
return publisher.publish();
}
/**
* Subscribe an entity to the given topic. If once is true, tetrapod won't subscribe
* them a second time
*/
public void subscribe(int topicId, int entityId, boolean once) {
publisher.subscribe(topicId, entityId, once);
}
public void subscribe(int topicId, int entityId) {
subscribe(topicId, entityId, false);
}
public void unsubscribe(int topicId, int entityId) {
publisher.unsubscribe(topicId, entityId);
}
public void unpublish(int topicId) {
publisher.unpublish(topicId);
}
// Generic handlers for all request/subscriptions
@Override
public Response genericRequest(Request r, RequestContext ctx) {
logger.error("unhandled request " + r.dump());
return new Error(CoreContract.ERROR_UNKNOWN_REQUEST);
}
public void setDependencies(int... contractIds) {
for (int contractId : contractIds) {
dependencies.add(contractId);
}
}
// Session.Help implementation
@Override
public Dispatcher getDispatcher() {
return dispatcher;
}
public ServiceAPI getServiceHandler(int contractId) {
// this method allows us to have delegate objects that directly handle some contracts
return this;
}
@Override
public List<SubscriptionAPI> getMessageHandlers(int contractId, int structId) {
return messageHandlers.get(contractId, structId);
}
@Override
public int getContractId() {
return contract == null ? 0 : contract.getContractId();
}
public void addSubscriptionHandler(Contract sub, SubscriptionAPI handler) {
messageHandlers.add(sub, handler);
}
public void addMessageHandler(Message k, SubscriptionAPI handler) {
messageHandlers.add(k, handler);
}
@Override
public void messageClusterMember(ClusterMemberMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
clusterMembers.add(new ServerAddress(m.host, m.servicePort));
if (serviceConnector != null) {
serviceConnector.getDirectServiceInfo(m.entityId).considerConnecting();
}
}
@Override
public void messageClusterPropertyAdded(ClusterPropertyAddedMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
Util.setProperty(m.property.key, m.property.val);
}
@Override
public void messageClusterPropertyRemoved(ClusterPropertyRemovedMessage m, MessageContext ctx) {
logger.info("******** {}", m.dump());
Util.clearProperty(m.key);
}
@Override
public void messageClusterSynced(ClusterSyncedMessage m, MessageContext ctx) {
Metrics.init(getMetricsPrefix());
checkDependencies();
}
// private methods
protected void registerServiceInformation() {
if (contract != null) {
AddServiceInformationRequest asi = new AddServiceInformationRequest();
asi.info = new ContractDescription();
asi.info.contractId = contract.getContractId();
asi.info.version = contract.getContractVersion();
asi.info.routes = contract.getWebRoutes();
asi.info.structs = new ArrayList<>();
for (Structure s : contract.getRequests()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getResponses()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getMessages()) {
asi.info.structs.add(s.makeDescription());
}
for (Structure s : contract.getStructs()) {
asi.info.structs.add(s.makeDescription());
}
sendDirectRequest(asi).handle(ResponseHandler.LOGGER);
}
}
// Base service implementation
@Override
public Response requestPause(PauseRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
setStatus(Core.STATUS_PAUSED);
onPaused();
return Response.SUCCESS;
}
@Override
public Response requestPurge(PurgeRequest r, RequestContext ctx) {
onPurged();
return Response.SUCCESS;
}
@Override
public Response requestRebalance(RebalanceRequest r, RequestContext ctx) {
onRebalance();
return Response.SUCCESS;
}
@Override
public Response requestReleaseExcess(ReleaseExcessRequest r, RequestContext ctx) {
onReleaseExcess();
return Response.SUCCESS;
}
@Override
public Response requestUnpause(UnpauseRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
clearStatus(Core.STATUS_PAUSED);
onUnpaused();
return Response.SUCCESS;
}
@Override
public Response requestRestart(RestartRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
dispatcher.dispatch(() -> shutdown(true));
return Response.SUCCESS;
}
@Override
public Response requestShutdown(ShutdownRequest r, RequestContext ctx) {
// TODO: Check admin rights or macaroon
dispatcher.dispatch(() -> shutdown(false));
return Response.SUCCESS;
}
@Override
public Response requestServiceDetails(ServiceDetailsRequest r, RequestContext ctx) {
return new ServiceDetailsResponse(getServiceIcon(), getServiceMetadata(), getServiceCommands());
}
@Override
public Response requestServiceStatsSubscribe(ServiceStatsSubscribeRequest r, RequestContext ctx) {
stats.subscribe(ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceStatsUnsubscribe(ServiceStatsUnsubscribeRequest r, RequestContext ctx) {
stats.unsubscribe(ctx.header.fromId);
return Response.SUCCESS;
}
@Override
public Response requestServiceLogs(ServiceLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>();
long last = logBuffer.getItems(r.logId, logBuffer.convert(r.level), r.maxItems, list);
return new ServiceLogsResponse(last, list);
}
protected String getStartLoggingMessage() {
return "*** Start Service ***" + "\n *** Service name: " + Util.getProperty("APPNAME") + "\n *** Options: "
+ Launcher.getAllOpts()
+ "\n *** VM Args: " + ManagementFactory.getRuntimeMXBean().getInputArguments().toString();
}
@Override
public Response requestServiceErrorLogs(ServiceErrorLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
final List<ServiceLogEntry> list = new ArrayList<ServiceLogEntry>();
list.addAll(logBuffer.getErrors());
list.addAll(logBuffer.getWarnings());
Collections.sort(list, (e1, e2) -> ((Long) e1.timestamp).compareTo(e2.timestamp));
return new ServiceErrorLogsResponse(list);
}
@Override
public Response requestResetServiceErrorLogs(ResetServiceErrorLogsRequest r, RequestContext ctx) {
if (logBuffer == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
logBuffer.resetErrorLogs();
return Response.SUCCESS;
}
@Override
public Response requestSetCommsLogLevel(SetCommsLogLevelRequest r, RequestContext ctx) {
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("comms");
if (logger == null) {
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
logger.setLevel(ch.qos.logback.classic.Level.valueOf(r.level));
return Response.SUCCESS;
}
@Override
public Response requestWebAPI(WebAPIRequest r, RequestContext ctx) {
return Response.error(CoreContract.ERROR_UNKNOWN_REQUEST);
}
@Override
public Response requestDirectConnection(DirectConnectionRequest r, RequestContext ctx) {
if (serviceConnector != null) {
return serviceConnector.requestDirectConnection(r, ctx);
}
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
@Override
public Response requestValidateConnection(ValidateConnectionRequest r, RequestContext ctx) {
if (serviceConnector != null) {
return serviceConnector.requestValidateConnection(r, ctx);
}
return new Error(CoreContract.ERROR_NOT_CONFIGURED);
}
@Override
public Response requestDummy(DummyRequest r, RequestContext ctx) {
return Response.SUCCESS;
}
@Override
public Response requestHostInfo(HostInfoRequest r, RequestContext ctx) {
return new HostInfoResponse(Util.getHostName(), (byte) Metrics.getNumCores(), null);
}
@Override
public Response requestHostStats(HostStatsRequest r, RequestContext ctx) {
return new HostStatsResponse(Metrics.getLoadAverage(), Metrics.getFreeDiskSpace());
}
@Override
public Response requestServiceRequestStats(ServiceRequestStatsRequest r, RequestContext ctx) {
return stats.getRequestStats(r.domain, r.limit, r.minTime, r.sortBy);
}
} |
package com.thoughtworks.xstream;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.ConverterRegistry;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.LookAndFeelConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.extended.TextAttributeConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StatefulWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.AnnotationConfiguration;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.AttributeMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.LocalConversionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.SystemAttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
/**
* Simple facade to XStream library, a Java-XML serialization tool. <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>
* To create shorter XML, you can specify aliases for classes using the <code>alias()</code>
* method. For example, you can shorten all occurrences of element
* <code><com.blah.MyThing></code> to <code><my-thing></code> by registering an
* alias for the class.
* <p>
* <hr>
* <blockquote>
*
* <pre>
* xstream.alias("my-thing", MyThing.class);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>
* XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each
* of which acts as a strategy for converting a particular type of class to XML and back again. Out
* of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc)
* and collections (Map, List, Set, Properties, etc). For other objects reflection is used to
* serialize each field recursively.
* </p>
* <p/>
* <p>
* Extra converters can be registered using the <code>registerConverter()</code> method. Some
* non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended}
* package and you can create your own by implementing the
* {@link com.thoughtworks.xstream.converters.Converter} interface.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p>
* The converters can be registered with an explicit priority. By default they are registered with
* XStream.PRIORITY_NORMAL. Converters of same priority will be used in the reverse sequence
* they have been registered. The default converter, i.e. the converter which will be used if
* no other registered converter is suitable, can be registered with priority
* XStream.PRIORITY_VERY_LOW. XStream uses by default the
* {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the fallback
* converter.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new CustomDefaultConverter(), XStream.PRIORITY_VERY_LOW);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>
* XStream has support for object graphs; a deserialized object graph will keep references intact,
* including circular references.
* </p>
* <p/>
* <p>
* XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using
* <code>setMode()</code>:
* </p>
* <p/>
* <table border='1'>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML
* with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td>
* <td>Uses XPath absolute references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some scenarios, such as when using
* hand-written XML, this is easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object structure like a tree. Duplicate
* references are treated as two separate objects and circular references cause an exception. This
* is slightly faster and uses less memory than the other two modes.</td>
* </tr>
* </table>
* <h3>Thread safety</h3>
* <p>
* The XStream instance is thread-safe. That is, once the XStream instance has been created and
* configured, it may be shared across multiple threads allowing objects to be
* serialized/deserialized concurrently. <em>Note, that this only applies if annotations are not
* auto-detected on -the-fly.</em>
* </p>
* <h3>Implicit collections</h3>
* <p/>
* <p>
* To avoid the need for special tags for collections, you can define implicit collections using one
* of the <code>addImplicitCollection</code> methods.
* </p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
* @author Guilherme Silveira
*/
public class XStream {
// CAUTION: The sequence of the fields is intentional for an optimal XML output of a
// self-serialization!
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private ClassLoaderReference classLoaderReference;
private MarshallingStrategy marshallingStrategy;
private ConverterLookup converterLookup;
private ConverterRegistry converterRegistry;
private Mapper mapper;
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private SystemAttributeAliasingMapper systemAttributeAliasingMapper;
private AttributeMapper attributeMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private LocalConversionMapper localConversionMapper;
private AnnotationConfiguration annotationConfiguration;
private transient JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_RELATIVE_REFERENCES = 1003;
public static final int XPATH_ABSOLUTE_REFERENCES = 1004;
/**
* @deprecated since 1.2, use {@link #XPATH_RELATIVE_REFERENCES} or
* {@link #XPATH_ABSOLUTE_REFERENCES} instead.
*/
public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
private static final String ANNOTATION_MAPPER_TYPE = "com.thoughtworks.xstream.mapper.AnnotationMapper";
/**
* Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determine the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determine the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver) {
this(reflectionProvider, (Mapper)classMapper, driver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and
* register classAttributeIdentifier as alias
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver);
aliasAttribute(classAttributeIdentifier, "class");
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}.
*
* @throws InitializationException in case of an initialization problem
* @deprecated since 1.3, use {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, Mapper, ClassLoader)} instead
*/
public XStream(
ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
this(reflectionProvider, driver, new ClassLoaderReference(new CompositeClassLoader()), mapper, new DefaultConverterLookup(), null);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared
* {@link ClassLoader} to use.
*
* @throws InitializationException in case of an initialization problem
* @since 1.3
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) {
this(reflectionProvider, driver, classLoader, null);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}
* and the {@link ClassLoader} in use.
*
* <p>Note, if the class loader should be changed later again, you should provide a {@link ClassLoaderReference} as {@link ClassLoader} that is also
* use in the {@link Mapper} chain.</p>
*
* @throws InitializationException in case of an initialization problem
* @since 1.3
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) {
this(reflectionProvider, driver, classLoader, mapper, new DefaultConverterLookup(), null);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}, {@link ReflectionProvider}, a prepared {@link Mapper}
* and the {@link ClassLoader} in use and an own {@link ConverterRegistry}.
*
* <p>Note, if the class loader should be changed later again, you should provide a {@link ClassLoaderReference} as {@link ClassLoader} that is also
* use in the {@link Mapper} chain.</p>
*
* @throws InitializationException in case of an initialization problem
* @since 1.3
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver,
ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup,
ConverterRegistry converterRegistry) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = classLoader instanceof ClassLoaderReference ? (ClassLoaderReference)classLoader : new ClassLoaderReference(classLoader);
this.converterLookup = converterLookup;
this.converterRegistry = converterRegistry != null
? converterRegistry
: (converterLookup instanceof ConverterRegistry ? (ConverterRegistry)converterLookup : null);
this.mapper = mapper == null ? buildMapper() : mapper;
setupMappers();
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_RELATIVE_REFERENCES);
}
private Mapper buildMapper() {
Mapper mapper = new DefaultMapper(classLoaderReference);
if ( useXStream11XmlFriendlyMapper() ){
mapper = new XStream11XmlFriendlyMapper(mapper);
}
mapper = new DynamicProxyMapper(mapper);
mapper = new ClassAliasingMapper(mapper);
mapper = new FieldAliasingMapper(mapper);
mapper = new AttributeAliasingMapper(mapper);
mapper = new SystemAttributeAliasingMapper(mapper);
mapper = new ImplicitCollectionMapper(mapper);
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
mapper = new AttributeMapper(mapper, converterLookup);
if (JVM.is15()) {
mapper = buildMapperDynamically(
"com.thoughtworks.xstream.mapper.EnumMapper", new Class[]{Mapper.class},
new Object[]{mapper});
}
mapper = new LocalConversionMapper(mapper);
mapper = new ImmutableTypesMapper(mapper);
if (JVM.is15()) {
mapper = buildMapperDynamically(
ANNOTATION_MAPPER_TYPE,
new Class[]{Mapper.class, ConverterRegistry.class, ClassLoader.class, ReflectionProvider.class, JVM.class},
new Object[]{mapper, converterLookup, classLoaderReference, reflectionProvider, jvm});
}
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
private Mapper buildMapperDynamically(
String className, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
return (Mapper)constructor.newInstance(constructorParamValues);
} catch (Exception e) {
throw new InitializationException("Could not instantiate mapper : " + className, e);
}
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected boolean useXStream11XmlFriendlyMapper() {
return false;
}
private void setupMappers() {
classAliasingMapper = (ClassAliasingMapper)this.mapper
.lookupMapperOfType(ClassAliasingMapper.class);
fieldAliasingMapper = (FieldAliasingMapper)this.mapper
.lookupMapperOfType(FieldAliasingMapper.class);
attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class);
attributeAliasingMapper = (AttributeAliasingMapper)this.mapper
.lookupMapperOfType(AttributeAliasingMapper.class);
systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper
.lookupMapperOfType(SystemAttributeAliasingMapper.class);
implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper
.lookupMapperOfType(ImplicitCollectionMapper.class);
defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper
.lookupMapperOfType(DefaultImplementationsMapper.class);
immutableTypesMapper = (ImmutableTypesMapper)this.mapper
.lookupMapperOfType(ImmutableTypesMapper.class);
localConversionMapper = (LocalConversionMapper)this.mapper
.lookupMapperOfType(LocalConversionMapper.class);
annotationConfiguration = (AnnotationConfiguration)this.mapper
.lookupMapperOfType(AnnotationConfiguration.class);
}
protected void setupAliases() {
if (classAliasingMapper == null) {
return;
}
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
if (jvm.supportsAWT()) {
// Instantiating these two classes starts the AWT system, which is undesirable.
// Calling loadClass ensures a reference to the class is found but they are not
// instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("awt-text-attribute", jvm.loadClass("java.awt.font.TextAttribute"));
}
if (jvm.supportsSQL()) {
alias("sql-timestamp", jvm.loadClass("java.sql.Timestamp"));
alias("sql-time", jvm.loadClass("java.sql.Time"));
alias("sql-date", jvm.loadClass("java.sql.Date"));
}
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
if (JVM.is14()) {
alias("auth-subject", jvm.loadClass("javax.security.auth.Subject"));
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
aliasType("charset", jvm.loadClass("java.nio.charset.Charset"));
}
if (JVM.is15()) {
alias("duration", jvm.loadClass("javax.xml.datatype.Duration"));
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
alias("string-builder", jvm.loadClass("java.lang.StringBuilder"));
alias("uuid", jvm.loadClass("java.util.UUID"));
}
}
protected void setupDefaultImplementations() {
if (defaultImplementationsMapper == null) {
return;
}
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
final ReflectionConverter reflectionConverter =
new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
if(jvm.supportsSQL()) {
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
}
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
if(jvm.supportsAWT()) {
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL);
}
if(jvm.supportsSwing()) {
registerConverter(new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL);
}
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CharsetConverter",
PRIORITY_NORMAL, null, null);
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.DurationConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.basic.StringBuilderConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.basic.UUIDConverter", PRIORITY_NORMAL,
null, null);
}
registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL);
}
private void dynamicallyRegisterConverter(
String className, int priority, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
if (instance instanceof Converter) {
registerConverter((Converter)instance, priority);
} else if (instance instanceof SingleValueConverter) {
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instantiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
if (immutableTypesMapper == null) {
return;
}
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
if(jvm.supportsAWT()) {
addImmutableType(jvm.loadClass("java.awt.font.TextAttribute"));
}
if (JVM.is14()) {
// late bound types - allows XStream to be compiled on earlier JDKs
Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter");
addImmutableType(type);
}
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
* @throws XStreamException if the object cannot be serialized
*/
public String toXML(Object obj) {
Writer writer = new StringWriter();
toXML(obj, writer);
return writer.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
* The Writer will be flushed afterwards and in case of an exception.
* @throws XStreamException if the object cannot be serialized
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
try {
marshal(obj, writer);
} finally {
writer.flush();
}
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
* The OutputStream will be flushed afterwards and in case of an exception.
* @throws XStreamException if the object cannot be serialized
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
try {
marshal(obj, writer);
} finally {
writer.flush();
}
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
* @throws XStreamException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws XStreamException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String, populating the fields of the given root object
* instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter
* XStream will write directly into the raw memory area of the existing object. Use with care!
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader, populating the fields of the given root object
* instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter
* XStream will write directly into the raw memory area of the existing object. Use with care!
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream, populating the fields of the given root object
* instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter
* XStream will write directly into the raw memory area of the existing object. Use with care!
* @throws XStreamException if the object cannot be deserialized
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
* @throws XStreamException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML), populating the fields
* of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter
* XStream will write directly into the raw memory area of the existing object. Use with care!
* @throws XStreamException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to
* XStream creating a new instance. Note, that this is a special use case! With the ReflectionConverter
* XStream will write directly into the raw memory area of the existing object. Use with care!
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws XStreamException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a type to a shorter name to be used in XML elements.
* Any class that is assignable to this type will be aliased to the same name.
*
* @param name Short name
* @param type Type to be aliased
* @since 1.2
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void aliasType(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addTypeAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
* @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
/**
* Create an alias for a field name.
*
* @param alias the alias itself
* @param definedIn the type that declares the field
* @param fieldName the name of the field
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void aliasField(String alias, Class definedIn, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName);
}
/**
* Create an alias for an attribute
*
* @param alias the alias itself
* @param attributeName the name of the attribute
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(String alias, String attributeName) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName()
+ " available");
}
attributeAliasingMapper.addAliasFor(attributeName, alias);
}
/**
* Create an alias for a system attribute
*
* @param alias the alias itself
* @param systemAttributeName the name of the system attribute
* @throws InitializationException if no {@link SystemAttributeAliasingMapper} is available
* @since upcoming
*/
public void aliasSystemAttribute(String alias, String systemAttributeName) {
if (systemAttributeAliasingMapper == null) {
throw new InitializationException("No "
+ SystemAttributeAliasingMapper.class.getName()
+ " available");
}
systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias);
}
/**
* Create an alias for an attribute.
*
* @param definedIn the type where the attribute is defined
* @param attributeName the name of the attribute
* @param alias the alias itself
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
* @since 1.2.2
*/
public void aliasAttribute(Class definedIn, String attributeName, String alias) {
aliasField(alias, definedIn, attributeName);
useAttributeFor(definedIn, attributeName);
}
/**
* Use an attribute for a field or a specific type.
*
* @param fieldName the name of the field
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(String fieldName, Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(fieldName, type);
}
/**
* Use an attribute for a field declared in a specific type.
*
* @param fieldName the name of the field
* @param definedIn the Class containing such field
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2.2
*/
public void useAttributeFor(Class definedIn, String fieldName) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(definedIn, fieldName);
}
/**
* Use an attribute for an arbitrary type.
*
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an
* instance of this type, it will use the default implementation instead. For example,
* java.util.ArrayList is the default implementation of java.util.List.
*
* @param defaultImplementation
* @param ofType
* @throws InitializationException if no {@link DefaultImplementationsMapper} is available
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
if (defaultImplementationsMapper == null) {
throw new InitializationException("No "
+ DefaultImplementationsMapper.class.getName()
+ " available");
}
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
/**
* Add immutable types. The value of the instances of these types will always be written into
* the stream even if they appear multiple times.
* @throws InitializationException if no {@link ImmutableTypesMapper} is available
*/
public void addImmutableType(Class type) {
if (immutableTypesMapper == null) {
throw new InitializationException("No "
+ ImmutableTypesMapper.class.getName()
+ " available");
}
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
if (converterRegistry != null) {
converterRegistry.registerConverter(converter, priority);
}
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
if (converterRegistry != null) {
converterRegistry.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
}
/**
* Register a local {@link Converter} for a field.
*
* @param definedIn the class type the field is defined in
* @param fieldName the field name
* @param converter the converter to use
* @since 1.3
*/
public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) {
if (localConversionMapper == null) {
throw new InitializationException("No "
+ LocalConversionMapper.class.getName()
+ " available");
}
localConversionMapper.registerLocalConverter(definedIn, fieldName, converter);
}
/**
* Register a local {@link SingleValueConverter} for a field.
*
* @param definedIn the class type the field is defined in
* @param fieldName the field name
* @param converter the converter to use
* @since 1.3
*/
public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) {
registerLocalConverter(definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter));
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
if (mapper instanceof ClassMapper) {
return (ClassMapper)mapper;
} else {
return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(mapper, args);
}
});
}
}
/**
* Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
/**
* Retrieve the {@link ReflectionProvider} in use.
*
* @return the mapper
* @since 1.2.1
*/
public ReflectionProvider getReflectionProvider() {
return reflectionProvider;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_RELATIVE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.RELATIVE));
break;
case XPATH_ABSOLUTE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.ABSOLUTE));
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped XML tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be a
* concrete collection type or matching the default implementation type of the
* collection type.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, null);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be a
* concrete collection type or matching the default implementation type of the
* collection type.
* @param itemType type of the items to be part of this collection.
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by
* itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be a
* concrete collection type or matching the default implementation type of the
* collection type.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(
Class ownerType, String fieldName, String itemFieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
/**
* Create a DataHolder that can be used to pass data to the converters. The DataHolder is provided with a
* call to {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)} or
* {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}.
*
* @return a new {@link DataHolder}
*/
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer)
throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName)
throws IOException {
return createObjectOutputStream(hierarchicalStreamDriver.createWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.3
*/
public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException {
return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.3
*/
public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName)
throws IOException {
return createObjectOutputStream(hierarchicalStreamDriver.createWriter(out), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* Because an ObjectOutputStream can contain multiple items and XML only allows a single root
* node, the stream must be written inside an enclosing node.
* </p>
* <p>
* It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be
* incomplete.
* </p>
* <h3>Example</h3>
*
* <pre>
* ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();
* </pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(
final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
final StatefulWriter statefulWriter = new StatefulWriter(writer);
statefulWriter.startNode(rootNodeName, null);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, statefulWriter);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
statefulWriter.flush();
}
public void close() {
if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) {
statefulWriter.endNode();
statefulWriter.close();
}
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from an InputStream using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.3
*/
public ObjectInputStream createObjectInputStream(InputStream in) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(in));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
* <h3>Example</h3>
*
* <pre>
* ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();
* </pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority)
throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* Creating an XStream instance it will register for all kind of classes and types of the current JDK,
* but not for any 3rd party type. To ensure that all other types are loaded with your classloader,
* you should call this method as early as possible - or consider to provide the classloader directly
* in the constructor.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Retrieve the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized. To omit a field you must always provide the declaring
* type and not necessarily the type that is converted.
*
* @since 1.1.3
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void omitField(Class definedIn, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.omitField(definedIn, fieldName);
}
/**
* Process the annotations of the given types and configure the XStream.
*
* @param types the types with XStream annotations
* @since 1.3
*/
public void processAnnotations(final Class[] types) {
if (annotationConfiguration == null) {
throw new InitializationException("No " + ANNOTATION_MAPPER_TYPE + " available");
}
annotationConfiguration.processAnnotations(types);
}
/**
* Process the annotations of the given type and configure the XStream. A call of this method
* will automatically turn the auto-detection mode for annotations off.
*
* @param type the type with XStream annotations
* @since 1.3
*/
public void processAnnotations(final Class type) {
processAnnotations(new Class[]{type});
}
/**
* Set the auto-detection mode of the AnnotationMapper. Note that auto-detection implies that
* the XStream is configured while it is processing the XML steams. This is a potential concurrency
* problem. Also is it technically not possible to detect all class aliases at deserialization. You have
* been warned!
*
* @param mode <code>true</code> if annotations are auto-detected
* @since 1.3
*/
public void autodetectAnnotations(boolean mode) {
if (annotationConfiguration != null) {
annotationConfiguration.autodetectAnnotations(mode);
}
}
/**
* @deprecated since 1.3, use {@link InitializationException} instead
*/
public static class InitializationException extends XStreamException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
public InitializationException(String message) {
super(message);
}
}
private Object readResolve() {
jvm = new JVM();
return this;
}
} |
package com.thoughtworks.xstream;
import com.thoughtworks.xstream.alias.DefaultClassMapper;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.alias.DefaultElementMapper;
import com.thoughtworks.xstream.alias.ElementMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.basic.*;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.composite.ObjectWithFieldsConverter;
import com.thoughtworks.xstream.converters.lookup.DefaultConverterLookup;
import com.thoughtworks.xstream.objecttree.ObjectTree;
import com.thoughtworks.xstream.objecttree.reflection.ObjectFactory;
import com.thoughtworks.xstream.objecttree.reflection.ReflectionObjectGraph;
import com.thoughtworks.xstream.objecttree.reflection.SunReflectionObjectFactory;
import com.thoughtworks.xstream.xml.XMLReader;
import com.thoughtworks.xstream.xml.XMLReaderDriver;
import com.thoughtworks.xstream.xml.XMLWriter;
import com.thoughtworks.xstream.xml.dom.DomXMLReaderDriver;
import com.thoughtworks.xstream.xml.text.PrettyPrintXMLWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
public class XStream {
private ConverterLookup converterLookup = new DefaultConverterLookup();
private XMLReaderDriver xmlReaderDriver = new DomXMLReaderDriver();
private ClassMapper classMapper;
private ObjectFactory objectFactory;
public XStream() {
this(new SunReflectionObjectFactory(), new DefaultClassMapper(), new DefaultElementMapper());
}
public XStream(ObjectFactory objectFactory, ClassMapper classMapper, ElementMapper elementMapper) {
this.classMapper = classMapper;
this.objectFactory = objectFactory;
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("date", Date.class);
alias("map", Map.class, HashMap.class);
alias("list", List.class, ArrayList.class);
alias("set", Set.class, HashSet.class);
alias("linked-list", LinkedList.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
registerConverter(new ObjectWithFieldsConverter(classMapper,elementMapper));
registerConverter(new IntConverter());
registerConverter(new FloatConverter());
registerConverter(new DoubleConverter());
registerConverter(new LongConverter());
registerConverter(new ShortConverter());
registerConverter(new CharConverter());
registerConverter(new BooleanConverter());
registerConverter(new ByteConverter());
registerConverter(new StringConverter());
registerConverter(new StringBufferConverter());
registerConverter(new DateConverter());
registerConverter(new JavaClassConverter());
registerConverter(new ArrayConverter(classMapper));
registerConverter(new CollectionConverter(classMapper));
registerConverter(new MapConverter(classMapper));
}
public void alias(String elementName, Class type, Class defaultImplementation) {
classMapper.alias(elementName, type, defaultImplementation);
}
public void alias(String elementName, Class type) {
alias(elementName, type, type);
}
public String toXML(Object obj) {
Writer stringWriter = new StringWriter();
XMLWriter xmlWriter = new PrettyPrintXMLWriter(stringWriter);
toXML(obj, xmlWriter);
return stringWriter.toString();
}
public void toXML(Object obj, XMLWriter xmlWriter) {
ObjectTree objectGraph = new ReflectionObjectGraph(obj, objectFactory);
Converter rootConverter = converterLookup.lookupConverterForType(obj.getClass());
xmlWriter.startElement(classMapper.lookupName(obj.getClass()));
rootConverter.toXML(objectGraph, xmlWriter, converterLookup);
xmlWriter.endElement();
}
public Object fromXML(String xml) {
return fromXML(xmlReaderDriver.createReader(xml));
}
public Object fromXML(XMLReader xmlReader) {
Class type = classMapper.lookupType(xmlReader.name());
ObjectTree objectGraph = new ReflectionObjectGraph(type, objectFactory);
Converter rootConverter = converterLookup.lookupConverterForType(type);
rootConverter.fromXML(objectGraph, xmlReader, converterLookup, type);
return objectGraph.get();
}
public Object fromXML(XMLReader xmlReader, Object root) {
Class type = root.getClass();
ObjectTree objectGraph = new ReflectionObjectGraph(root, objectFactory);
Converter rootConverter = converterLookup.lookupConverterForType(type);
rootConverter.fromXML(objectGraph, xmlReader, converterLookup, type);
return objectGraph.get();
}
public void registerConverter(Converter converter) {
converterLookup.registerConverter(converter);
}
} |
package de.hpi.epc.validation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hpi.diagram.Diagram;
import de.hpi.diagram.DiagramEdge;
import de.hpi.diagram.DiagramNode;
import de.hpi.diagram.DiagramObject;
import de.hpi.petrinet.SyntaxChecker;
public class EPCSyntaxChecker implements SyntaxChecker {
private static final String NO_SOURCE = "Each edge must have a source";
private static final String NO_TARGET = "Each edge must have a target";
private static final String NOT_CONNECTED = "Node must be connected with edges";
private static final String NOT_CONNECTED_2 = "Node must be connected with more edges";
private static final String TOO_MANY_EDGES = "Node has too many connected edges";
private static final String NO_CORRECT_CONNECTOR = "Node is no correct conector";
private static final String MANY_STARTS = "There must be only one start event";
private static final String MANY_ENDS = "There must be only one end event";
private static final String FUNCTION_AFTER_OR = "There must be no functions after a splitting OR/XOR";
private static final String FUNCTION_AFTER_FUNCTION = "There must be no function after a function";
private static final String EVENT_AFTER_EVENT = "There must be no event after an event";
protected Diagram diagram;
protected Map<String,String> errors;
public EPCSyntaxChecker(Diagram diagram) {
this.diagram = diagram;
this.errors = new HashMap<String,String>();
}
public boolean checkSyntax() {
errors.clear();
if (diagram == null)
return false;
checkEdges();
checkNodes();
return errors.size() == 0;
}
public Map<String, String> getErrors() {
return errors;
}
protected void checkEdges() {
for (DiagramEdge edge: diagram.getEdges()) {
if (edge.getSource() == null)
addError(edge, NO_SOURCE);
if (edge.getTarget() == null)
addError(edge, NO_TARGET);
}
}
protected void checkNodes() {
List<DiagramNode> startEvents = new ArrayList<DiagramNode>();
List<DiagramNode> endEvents = new ArrayList<DiagramNode>();
for (DiagramNode node: diagram.getNodes()) {
int in = node.getIncomingEdges().size();
int out = node.getOutgoingEdges().size();
if (in == 0 && out == 0){
addError(node, NOT_CONNECTED);
}
else if ("Event".equals(node.getType())){
if (in == 1 && out == 0) endEvents.add(node);
else if (in == 0 && out == 1) startEvents.add(node);
else if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Event".equals(next.getType())) addError(next, EVENT_AFTER_EVENT);
}
}
else if (in == 0 || out == 0){
addError(node, NOT_CONNECTED_2);
}
else if ("Function".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())) addError(next, FUNCTION_AFTER_FUNCTION);
}
}
else if ("ProcessInterface".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
}
else if ("XorConnector".equals(node.getType()) || "OrConnector".equals(node.getType())){
if (in == 1 && out == 2){
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())){
addError(node, FUNCTION_AFTER_OR);
break;
}
}
} else if (in == 2 && out == 1){
// nothing todo
} else {
addError(node, NO_CORRECT_CONNECTOR);
}
}
else if ("AndConnector".equals(node.getType())){
if ( ! ( (in == 2 && out == 1) || (in == 1 && out == 2) ) ){
addError(node, NO_CORRECT_CONNECTOR);
}
}
}
if (startEvents.size() > 1){
for (DiagramNode n : startEvents){
addError(n, MANY_STARTS);
}
}
if (endEvents.size() > 1){
for (DiagramNode n : endEvents){
addError(n, MANY_ENDS);
}
}
}
protected void addError(DiagramObject obj, String errorCode) {
String key = obj.getResourceId();
String oldErrorCode = errors.get(key);
if (oldErrorCode != null && oldErrorCode.startsWith("Multiple Errors: ")){
errors.put(obj.getResourceId(), oldErrorCode+", "+errorCode);
} else if (oldErrorCode != null){
errors.put(obj.getResourceId(), "Multiple Errors: "+oldErrorCode+", "+errorCode);
} else {
errors.put(obj.getResourceId(), errorCode);
}
}
private List<DiagramNode>getNextEventsOrFunctions(List<DiagramEdge> edges){
List<DiagramEdge> newEdges = new ArrayList<DiagramEdge>();
List<DiagramNode> result = new ArrayList<DiagramNode>();
for (DiagramEdge edge : edges){
newEdges.add(edge);
}
return getNextEventsOrFunctions(newEdges, result);
}
private List<DiagramNode>getNextEventsOrFunctions(List<DiagramEdge> edges, List<DiagramNode> result){
List<DiagramEdge> newEdges = new ArrayList<DiagramEdge>();
for (DiagramEdge edge : edges){
if ("ControlFlow".equals(edge.getType())){
DiagramNode target = edge.getTarget();
if ("Function".equals(target.getType()) || "Event".equals(target.getType())){
result.add(target);
} else {
newEdges.addAll(target.getOutgoingEdges());
}
}
}
if (newEdges.size() > 0){
return getNextEventsOrFunctions(newEdges, result);
}
return result;
}
} |
package org.jboss.jca.as.rarinfo;
import org.jboss.jca.common.api.metadata.Defaults;
import org.jboss.jca.common.api.metadata.common.CommonAdminObject;
import org.jboss.jca.common.api.metadata.common.CommonPool;
import org.jboss.jca.common.api.metadata.common.TransactionSupportEnum;
import org.jboss.jca.common.api.metadata.common.v10.CommonConnDef;
import org.jboss.jca.common.api.metadata.ra.AdminObject;
import org.jboss.jca.common.api.metadata.ra.ConfigProperty;
import org.jboss.jca.common.api.metadata.ra.ConnectionDefinition;
import org.jboss.jca.common.api.metadata.ra.Connector;
import org.jboss.jca.common.api.metadata.ra.Connector.Version;
import org.jboss.jca.common.api.metadata.ra.MessageListener;
import org.jboss.jca.common.api.metadata.ra.RequiredConfigProperty;
import org.jboss.jca.common.api.metadata.ra.ResourceAdapter;
import org.jboss.jca.common.api.metadata.ra.ResourceAdapter1516;
import org.jboss.jca.common.api.metadata.ra.XsdString;
import org.jboss.jca.common.api.metadata.ra.ra10.ResourceAdapter10;
import org.jboss.jca.common.metadata.common.CommonAdminObjectImpl;
import org.jboss.jca.common.metadata.common.CommonPoolImpl;
import org.jboss.jca.common.metadata.common.CommonSecurityImpl;
import org.jboss.jca.common.metadata.common.CommonXaPoolImpl;
import org.jboss.jca.common.metadata.common.v10.CommonConnDefImpl;
import org.jboss.jca.common.metadata.ra.RaParser;
import org.jboss.jca.validator.Validation;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
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.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* rar info main class
*
* @author Jeff Zhang
*/
public class Main
{
/** Exit codes */
private static final int SUCCESS = 0;
private static final int ERROR = 1;
private static final int OTHER = 2;
private static final String REPORT_FILE = "-report.txt";
private static final String RAXML_FILE = "META-INF/ra.xml";
private static final String tempdir = System.getProperty("java.io.tmpdir");
private static final String subdir = "/jca/";
private static Set<Class<?>> validTypes;
private static final String ARGS_CP = "-classpath";
private static final String ARGS_STDOUT = "--stdout";
private static final String ARGS_OUT = "-o";
private static File root = null;
static
{
validTypes = new HashSet<Class<?>>();
validTypes.add(boolean.class);
validTypes.add(Boolean.class);
validTypes.add(byte.class);
validTypes.add(Byte.class);
validTypes.add(short.class);
validTypes.add(Short.class);
validTypes.add(int.class);
validTypes.add(Integer.class);
validTypes.add(long.class);
validTypes.add(Long.class);
validTypes.add(float.class);
validTypes.add(Float.class);
validTypes.add(double.class);
validTypes.add(Double.class);
validTypes.add(char.class);
validTypes.add(Character.class);
validTypes.add(String.class);
}
/**
* Main
* @param args args
*/
public static void main(String[] args)
{
final int argsLength = args.length;
PrintStream out = null;
try
{
if (argsLength < 1)
{
usage();
System.exit(OTHER);
}
String rarFile = "";
String[] cps = null;
boolean stdout = false;
String reportFile = "";
for (int i = 0; i < argsLength; i++)
{
String arg = args[i];
if (arg.equals(ARGS_CP))
{
cps = args[++i].split(System.getProperty("path.separator"));
}
else if (arg.equals(ARGS_STDOUT))
{
stdout = true;
}
else if (arg.equals(ARGS_OUT))
{
reportFile = args[++i];
}
else if (arg.endsWith("rar"))
{
rarFile = arg;
}
else
{
usage();
System.exit(OTHER);
}
}
ZipFile zipFile = new ZipFile(rarFile);
boolean hasRaXml = false;
boolean exsitNativeFile = false;
Connector connector = null;
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> xmls = new ArrayList<String>();
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements())
{
ZipEntry ze = (ZipEntry) zipEntries.nextElement();
String name = ze.getName();
names.add(name);
if (name.endsWith(".xml") && name.startsWith("META-INF") && !name.endsWith("pom.xml"))
xmls.add(name);
if (name.endsWith(".so") || name.endsWith(".a") || name.endsWith(".dll"))
exsitNativeFile = true;
if (name.equals(RAXML_FILE))
{
hasRaXml = true;
InputStream raIn = zipFile.getInputStream(ze);
RaParser parser = new RaParser();
connector = parser.parse(raIn);
raIn.close();
}
}
if (!hasRaXml)
{
System.out.println("JCA annotations aren't supported");
System.exit(OTHER);
}
if (connector == null)
{
System.out.println("can't parse ra.xml");
System.exit(OTHER);
}
URLClassLoader cl = loadClass(rarFile, cps);
if (stdout)
{
out = System.out;
}
else if (!reportFile.isEmpty())
{
out = new PrintStream(reportFile);
}
else
{
out = new PrintStream(rarFile.substring(0, rarFile.length() - 4) + REPORT_FILE);
}
out.println("Archive:\t" + rarFile);
String version;
String type = "";
ResourceAdapter ra;
boolean reauth = false;
if (connector.getVersion() == Version.V_10)
{
version = "1.0";
ra = connector.getResourceadapter();
type = "OutBound";
reauth = ((ResourceAdapter10)ra).getReauthenticationSupport();
}
else
{
if (connector.getVersion() == Version.V_15)
version = "1.5";
else
version = "1.6";
ResourceAdapter1516 ra1516 = (ResourceAdapter1516)connector.getResourceadapter();
ra = ra1516;
if (ra1516.getOutboundResourceadapter() != null)
{
reauth = ra1516.getOutboundResourceadapter().getReauthenticationSupport();
if (ra1516.getInboundResourceadapter() != null)
type = "Bidirectional";
else
type = "OutBound";
}
else
{
if (ra1516.getInboundResourceadapter() != null)
type = "InBound";
else
{
out.println("Rar file has problem");
System.exit(ERROR);
}
}
}
out.println("JCA version:\t" + version);
out.println("Type:\t\t" + type);
out.print("Reauth:\t\t");
if (reauth)
out.println("Yes");
else
out.println("No");
int systemExitCode = Validation.validate(new File(rarFile).toURI().toURL(), ".", cps);
String compliant;
if (systemExitCode == SUCCESS)
compliant = "Yes";
else
compliant = "No";
out.println("Compliant:\t" + compliant);
out.print("Native:\t\t");
if (exsitNativeFile)
out.println("Yes");
else
out.println("No");
Collections.sort(names);
out.println();
out.println("Structure:");
out.println("
for (String name : names)
{
out.println(name);
}
String classname = "";
Map<String, String> raConfigProperties = null;
TransactionSupportEnum transSupport = TransactionSupportEnum.NoTransaction;
List<CommonAdminObject> adminObjects = null;
List<CommonConnDef> connDefs = null;
CommonSecurityImpl secImpl = new CommonSecurityImpl("", "", true);
CommonPoolImpl poolImpl = new CommonPoolImpl(0, 10, Defaults.PREFILL, Defaults.USE_STRICT_MIN,
Defaults.FLUSH_STRATEGY);
CommonXaPoolImpl xaPoolImpl = new CommonXaPoolImpl(0, 10, Defaults.PREFILL, Defaults.USE_STRICT_MIN,
Defaults.FLUSH_STRATEGY, Defaults.IS_SAME_RM_OVERRIDE, Defaults.INTERLEAVING,
Defaults.PAD_XID, Defaults.WRAP_XA_RESOURCE, Defaults.NO_TX_SEPARATE_POOL);
if (connector.getVersion() != Version.V_10)
{
ResourceAdapter1516 ra1516 = (ResourceAdapter1516)ra;
if (ra1516.getResourceadapterClass() != null && !ra1516.getResourceadapterClass().equals(""))
{
out.println();
out.println("Resource-adapter:");
out.println("
out.println("Class: " + ra1516.getResourceadapterClass());
}
Map<String, String> introspected =
getIntrospectedProperties(ra1516.getResourceadapterClass(), cl);
if (ra1516.getConfigProperties() != null)
{
raConfigProperties = new HashMap<String, String>();
for (ConfigProperty cp : ra1516.getConfigProperties())
{
raConfigProperties.put(cp.getConfigPropertyName().toString(),
getValueString(cp.getConfigPropertyValue()));
removeIntrospectedValue(introspected, cp.getConfigPropertyName().toString());
out.println(" Config-property: " + cp.getConfigPropertyName() + " (" +
cp.getConfigPropertyType() + ")");
}
}
if (introspected != null && !introspected.isEmpty())
{
for (Map.Entry<String, String> entry : introspected.entrySet())
{
out.println(" Introspected Config-property: " + entry.getKey() + " (" +
entry.getValue() + ")");
}
}
if (introspected == null)
out.println(" Unable to resolve introspected config-property's");
int line = 0;
Set<String> sameClassnameSet = new HashSet<String>();
boolean needPrint = true;
if (ra1516.getOutboundResourceadapter() != null)
{
out.println();
out.println("Managed-connection-factory:");
out.println("
if (ra1516.getOutboundResourceadapter().getConnectionDefinitions() != null)
connDefs = new ArrayList<CommonConnDef>();
transSupport = ra1516.getOutboundResourceadapter().getTransactionSupport();
for (ConnectionDefinition mcf : ra1516.getOutboundResourceadapter().getConnectionDefinitions())
{
classname = mcf.getManagedConnectionFactoryClass().toString();
if (!sameClassnameSet.contains(classname))
{
sameClassnameSet.add(classname);
if (line != 0)
{
out.println();
}
line++;
out.println("Class: " + classname);
needPrint = true;
}
else
{
needPrint = false;
}
if (needPrint)
{
//ValidatingManagedConnectionFactory
try
{
out.print(" Validating: ");
Class<?> clazz = Class.forName(classname, true, cl);
if (hasInterface(clazz, "javax.resource.spi.ValidatingManagedConnectionFactory"))
{
out.println("Yes");
}
else
{
out.println("No");
}
}
catch (Throwable t)
{
// Nothing we can do
t.printStackTrace(System.err);
out.println("Unknown");
}
//CCI
String cfi = mcf.getConnectionFactoryInterface().toString();
try
{
out.print(" CCI: ");
Class<?> clazz = Class.forName(cfi, true, cl);
if (hasInterface(clazz, "javax.resource.cci.ConnectionFactory"))
{
out.println("Yes");
}
else
{
out.println("No");
}
}
catch (Throwable t)
{
// Nothing we can do
t.printStackTrace(System.err);
out.println("Unknown");
}
}
Map<String, String> configProperty = null;
if (mcf.getConfigProperties() != null)
configProperty = new HashMap<String, String>();
introspected = getIntrospectedProperties(classname, cl);
for (ConfigProperty cp : mcf.getConfigProperties())
{
configProperty.put(cp.getConfigPropertyName().toString(),
getValueString(cp.getConfigPropertyValue()));
removeIntrospectedValue(introspected, cp.getConfigPropertyName().toString());
if (needPrint)
out.println(" Config-property: " + cp.getConfigPropertyName() + " (" +
cp.getConfigPropertyType() + ")");
}
if (introspected != null && !introspected.isEmpty())
{
for (Map.Entry<String, String> entry : introspected.entrySet())
{
if (needPrint)
out.println(" Introspected Config-property: " + entry.getKey() + " (" +
entry.getValue() + ")");
}
}
if (introspected == null)
out.println(" Unable to resolve introspected config-property's");
String poolName = mcf.getConnectionInterface().toString().substring(
mcf.getConnectionInterface().toString().lastIndexOf('.') + 1);
CommonPool pool = null;
if (transSupport.equals(TransactionSupportEnum.XATransaction))
{
pool = xaPoolImpl;
}
else
{
pool = poolImpl;
}
CommonConnDefImpl connImpl = new CommonConnDefImpl(configProperty, classname,
"java:jboss/eis/" + poolName, poolName,
Defaults.ENABLED, Defaults.USE_JAVA_CONTEXT,
Defaults.USE_CCM,
pool, null, null, secImpl, null);
connDefs.add(connImpl);
}
}
line = 0;
sameClassnameSet.clear();
if (ra1516.getAdminObjects() != null && ra1516.getAdminObjects().size() > 0)
{
out.println();
out.println("Admin-object:");
out.println("
adminObjects = new ArrayList<CommonAdminObject>();
}
for (AdminObject ao : ra1516.getAdminObjects())
{
String aoClassname = ao.getAdminobjectClass().toString();
if (!sameClassnameSet.contains(aoClassname))
{
sameClassnameSet.add(aoClassname);
if (line != 0)
{
out.println();
}
line++;
out.println("Class: " + aoClassname);
needPrint = true;
}
else
{
needPrint = false;
}
String poolName = aoClassname.substring(aoClassname.lastIndexOf('.') + 1);
Map<String, String> configProperty = null;
if (ao.getConfigProperties() != null)
configProperty = new HashMap<String, String>();
introspected = getIntrospectedProperties(aoClassname, cl);
for (ConfigProperty cp : ao.getConfigProperties())
{
configProperty.put(cp.getConfigPropertyName().toString(),
getValueString(cp.getConfigPropertyValue()));
removeIntrospectedValue(introspected, cp.getConfigPropertyName().toString());
if (needPrint)
out.println(" Config-property: " + cp.getConfigPropertyName() + " (" +
cp.getConfigPropertyType() + ")");
}
if (introspected != null && !introspected.isEmpty())
{
for (Map.Entry<String, String> entry : introspected.entrySet())
{
if (needPrint)
out.println(" Introspected Config-property: " + entry.getKey() + " (" +
entry.getValue() + ")");
}
}
if (introspected == null)
out.println(" Unable to resolve introspected config-property's");
CommonAdminObjectImpl aoImpl = new CommonAdminObjectImpl(configProperty, aoClassname,
"java:jboss/eis/ao/" + poolName, poolName, Defaults.ENABLED, Defaults.USE_JAVA_CONTEXT);
adminObjects.add(aoImpl);
}
line = 0;
sameClassnameSet.clear();
if (ra1516.getInboundResourceadapter() != null &&
ra1516.getInboundResourceadapter().getMessageadapter() != null)
{
out.println();
out.println("Activation-spec:");
out.println("
for (MessageListener ml :
ra1516.getInboundResourceadapter().getMessageadapter().getMessagelisteners())
{
String asClassname = ml.getActivationspec().getActivationspecClass().toString();
if (!sameClassnameSet.contains(asClassname))
{
sameClassnameSet.add(asClassname);
if (line != 0)
{
out.println();
}
line++;
out.println("Class: " + asClassname);
introspected = getIntrospectedProperties(asClassname, cl);
if (ml.getActivationspec() != null &&
ml.getActivationspec().getRequiredConfigProperties() != null)
{
for (RequiredConfigProperty cp : ml.getActivationspec().getRequiredConfigProperties())
{
removeIntrospectedValue(introspected, cp.getConfigPropertyName().toString());
out.println(" Required-config-property: " + cp.getConfigPropertyName());
}
}
if (introspected != null && !introspected.isEmpty())
{
for (Map.Entry<String, String> entry : introspected.entrySet())
{
out.println(" Introspected Config-property: " + entry.getKey() + " (" +
entry.getValue() + ")");
}
}
if (introspected == null)
out.println(" Unable to resolve introspected config-property's");
}
}
}
}
else
{
out.println("Managed-connection-factory:");
out.println("
ResourceAdapter10 ra10 = (ResourceAdapter10)ra;
out.println("Class: " + ra10.getManagedConnectionFactoryClass());
classname = ra10.getManagedConnectionFactoryClass().toString();
transSupport = ra10.getTransactionSupport();
//ValidatingManagedConnectionFactory
try
{
Class<?> clazz = Class.forName(classname, true, cl);
out.print(" Validating: ");
if (hasInterface(clazz, "javax.resource.spi.ValidatingManagedConnectionFactory"))
{
out.println("Yes");
}
else
{
out.println("No");
}
}
catch (Exception e)
{
// Nothing we can do
}
Map<String, String> configProperty = null;
if (ra10.getConfigProperties() != null)
configProperty = new HashMap<String, String>();
Map<String, String> introspected =
getIntrospectedProperties(classname, cl);
for (ConfigProperty cp : ra10.getConfigProperties())
{
configProperty.put(cp.getConfigPropertyName().toString(),
getValueString(cp.getConfigPropertyValue()));
removeIntrospectedValue(introspected, cp.getConfigPropertyName().toString());
out.println(" Config-property: " + cp.getConfigPropertyName() + " (" +
cp.getConfigPropertyType() + ")");
}
if (introspected != null && !introspected.isEmpty())
{
for (Map.Entry<String, String> entry : introspected.entrySet())
{
out.println(" Introspected Config-property: " + entry.getKey() + " (" +
entry.getValue() + ")");
}
}
if (introspected == null)
out.println(" Unable to resolve introspected config-property's");
String poolName = classname.substring(classname.lastIndexOf('.') + 1);
CommonPool pool = null;
if (transSupport.equals(TransactionSupportEnum.XATransaction))
{
pool = xaPoolImpl;
}
else
{
pool = poolImpl;
}
CommonConnDefImpl connImpl = new CommonConnDefImpl(configProperty, classname,
"java:jboss/eis/" + poolName, poolName,
Defaults.ENABLED, Defaults.USE_JAVA_CONTEXT,
Defaults.USE_CCM,
pool, null, null, secImpl, null);
connDefs = new ArrayList<CommonConnDef>();
connDefs.add(connImpl);
}
RaImpl raImpl = new RaImpl(rarFile, transSupport, connDefs, adminObjects, raConfigProperties);
raImpl.buildResourceAdapterImpl();
outputXmlDesc(xmls, out);
outputRaDesc(raImpl, out);
System.out.println("Done.");
System.exit(SUCCESS);
}
catch (Throwable t)
{
System.err.println("Error: " + t.getMessage());
t.printStackTrace(System.err);
System.exit(ERROR);
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Exception ioe)
{
// Ignore
}
}
cleanupTempFiles();
}
}
private static void outputXmlDesc(ArrayList<String> xmls, PrintStream out) throws FileNotFoundException, IOException
{
for (String xmlfile : xmls)
{
out.println();
out.println(xmlfile + ":");
for (int i = 0; i <= xmlfile.length(); i++)
{
out.print("-");
}
out.println();
Reader in = null;
try
{
in = new FileReader(root.getAbsolutePath() + File.separator + xmlfile);
char[] buffer = new char[4096];
for (;;)
{
int nBytes = in.read(buffer);
if (nBytes <= 0)
break;
for (int i = 0; i < nBytes; i++)
{
if (buffer[i] != 13)
out.print(buffer[i]);
}
}
out.flush();
}
finally
{
try
{
if (in != null)
in.close();
}
catch (IOException ignore)
{
// Ignore
}
}
}
}
/**
* Output Resource Adapter XML description
*
* @param raImpl RaImpl
* @param out PrintStream
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws TransformerFactoryConfigurationError
* @throws TransformerConfigurationException
* @throws TransformerException
*/
private static void outputRaDesc(RaImpl raImpl, PrintStream out) throws ParserConfigurationException, SAXException,
IOException, TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
String raString = "<resource-adapters>" + raImpl.toString() + "</resource-adapters>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(raString)));
out.println();
out.println("Deployment descriptor:");
out.println("
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer serializer;
serializer = tfactory.newTransformer();
//Setup indenting to "pretty print"
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
serializer.transform(new DOMSource(doc), new StreamResult(out));
}
private static URLClassLoader loadClass(String rarFile, String[] classpath)
{
if (rarFile == null)
throw new IllegalArgumentException("Rar file name is null");
File destination = null;
try
{
File f = new File(rarFile);
//File root = null;
if (f.isFile())
{
destination = new File(tempdir, subdir);
root = extract(f, destination);
}
else
{
root = f;
}
// Create classloader
URL[] allurls;
URL[] urls = getUrls(root);
if (classpath != null && classpath.length > 0)
{
List<URL> listUrl = new ArrayList<URL>();
for (URL u : urls)
listUrl.add(u);
for (String jar : classpath)
{
if (jar.endsWith(".jar"))
listUrl.add(new File(jar).toURI().toURL());
}
allurls = listUrl.toArray(new URL[listUrl.size()]);
}
else
allurls = urls;
URLClassLoader cl = SecurityActions.createURLCLassLoader(allurls,
SecurityActions.getThreadContextClassLoader());
return cl;
}
catch (Throwable t)
{
// Nothing we can do
}
return null;
}
private static void cleanupTempFiles()
{
File destination = new File(tempdir, subdir);
if (destination != null)
{
try
{
recursiveDelete(destination);
}
catch (IOException ioe)
{
// Ignore
}
}
}
private static boolean hasInterface(Class<?> clazz, String interfaceName)
{
if (clazz.getName().equals(interfaceName))
return true;
for (Class<?> iface : clazz.getInterfaces())
{
if (iface.getName().equals(interfaceName))
{
return true;
}
else
{
return hasInterface(iface, interfaceName);
}
}
if (clazz.getSuperclass() != null)
{
return hasInterface(clazz.getSuperclass(), interfaceName);
}
return false;
}
/**
* Get the introspected properties for a class
* @param clz The fully qualified class name
* @param cl classloader
* @return The properties (name, type)
*/
private static Map<String, String> getIntrospectedProperties(String clz, URLClassLoader cl)
{
Map<String, String> result = null;
try
{
Class<?> c = Class.forName(clz, true, cl);
result = new TreeMap<String, String>();
Method[] methods = c.getMethods();
if (methods != null)
{
for (Method m : methods)
{
if (m.getName().startsWith("set") && m.getParameterTypes() != null && m.getParameterTypes().length == 1
&& isValidType(m.getParameterTypes()[0]))
{
String name = m.getName().substring(3);
if (name.length() == 1)
{
name = name.toLowerCase(Locale.US);
}
else
{
name = name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1);
}
String type = m.getParameterTypes()[0].getName();
result.put(name, type);
}
}
}
}
catch (Throwable t)
{
// Nothing we can do
t.printStackTrace(System.err);
}
return result;
}
/**
* Is valid type
* @param type The type
* @return True if valid; otherwise false
*/
private static boolean isValidType(Class<?> type)
{
return validTypes.contains(type);
}
/**
* Remove introspected value
* @param m The map
* @param name The name
*/
private static void removeIntrospectedValue(Map<String, String> m, String name)
{
if (m != null)
{
m.remove(name);
if (name.length() == 1)
{
name = name.toUpperCase(Locale.US);
}
else
{
name = name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1);
}
m.remove(name);
if (name.length() == 1)
{
name = name.toLowerCase(Locale.US);
}
else
{
name = name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1);
}
m.remove(name);
}
}
/**
* Get the URLs for the directory and all libraries located in the directory
* @param directory The directory
* @return The URLs
* @exception MalformedURLException MalformedURLException
* @exception IOException IOException
*/
private static URL[] getUrls(File directory) throws MalformedURLException, IOException
{
List<URL> list = new LinkedList<URL>();
if (directory.exists() && directory.isDirectory())
{
// Add directory
list.add(directory.toURI().toURL());
// Add the contents of the directory too
File[] jars = directory.listFiles(new FilenameFilter()
{
/**
* Accept
* @param dir The directory
* @param name The name
* @return True if accepts; otherwise false
*/
public boolean accept(File dir, String name)
{
return name.endsWith(".jar");
}
});
if (jars != null)
{
for (int j = 0; j < jars.length; j++)
{
list.add(jars[j].getCanonicalFile().toURI().toURL());
}
}
}
return list.toArray(new URL[list.size()]);
}
/**
* Extract a JAR type file
* @param file The file
* @param directory The directory where the file should be extracted
* @return The root of the extracted JAR file
* @exception IOException Thrown if an error occurs
*/
private static File extract(File file, File directory) throws IOException
{
if (file == null)
throw new IllegalArgumentException("File is null");
if (directory == null)
throw new IllegalArgumentException("Directory is null");
File target = new File(directory, file.getName());
if (target.exists())
recursiveDelete(target);
if (!target.mkdirs())
throw new IOException("Could not create " + target);
JarFile jar = new JarFile(file);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry je = entries.nextElement();
File copy = new File(target, je.getName());
if (!je.isDirectory())
{
InputStream in = null;
OutputStream out = null;
// Make sure that the directory is _really_ there
if (copy.getParentFile() != null && !copy.getParentFile().exists())
{
if (!copy.getParentFile().mkdirs())
throw new IOException("Could not create " + copy.getParentFile());
}
try
{
in = new BufferedInputStream(jar.getInputStream(je));
out = new BufferedOutputStream(new FileOutputStream(copy));
byte[] buffer = new byte[4096];
for (;;)
{
int nBytes = in.read(buffer);
if (nBytes <= 0)
break;
out.write(buffer, 0, nBytes);
}
out.flush();
}
finally
{
try
{
if (out != null)
out.close();
}
catch (IOException ignore)
{
// Ignore
}
try
{
if (in != null)
in.close();
}
catch (IOException ignore)
{
// Ignore
}
}
}
else
{
if (!copy.exists())
{
if (!copy.mkdirs())
throw new IOException("Could not create " + copy);
}
else
{
if (!copy.isDirectory())
throw new IOException(copy + " isn't a directory");
}
}
}
return target;
}
/**
* Recursive delete
* @param f The file handler
* @exception IOException Thrown if a file could not be deleted
*/
private static void recursiveDelete(File f) throws IOException
{
if (f != null && f.exists())
{
File[] files = f.listFiles();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
recursiveDelete(files[i]);
}
else
{
if (!files[i].delete())
throw new IOException("Could not delete " + files[i]);
}
}
}
if (!f.delete())
throw new IOException("Could not delete " + f);
}
}
/**
* get correct value string
* @param value xsdstring
* @return correct string
*/
private static String getValueString(XsdString value)
{
if (value == null || value == XsdString.NULL_XSDSTRING)
return "";
else
return value.toString();
}
/**
* Tool usage
*/
private static void usage()
{
System.out.println("Usage: ./rar-info.sh [-classpath <lib>[:<lib>]*] [--stdout] [-o <reportFile>] <file>");
}
} |
package de.qx.shaders;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.LocalFileHandleResolver;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.ArrayMap;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.util.Stack;
public class ShaderManager {
private final AssetManager assetManager;
private final ArrayMap<String, ShaderProgram> shaders;
private final ArrayMap<String, String> shaderPaths;
private final ArrayMap<String, FrameBuffer> frameBuffers;
private final Stack<FrameBuffer> activeFrameBuffers;
private final Camera screenCamera;
private final Mesh screenMesh;
private ShaderProgram currentShader;
private int currentTextureId;
public ShaderManager(AssetManager assetManager) {
this(assetManager, new ShaderLoader(new LocalFileHandleResolver()));
}
public ShaderManager(AssetManager assetManager, ShaderLoader shaderLoader) {
this.assetManager = assetManager;
assetManager.setLoader(ShaderProgram.class, shaderLoader);
shaders = new ArrayMap<>();
shaderPaths = new ArrayMap<>();
frameBuffers = new ArrayMap<>();
activeFrameBuffers = new Stack<>();
screenCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
screenMesh = new Mesh(true, 4, 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
new VertexAttribute(VertexAttributes.Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));
Vector3 vec0 = new Vector3(0, 0, 0);
screenCamera.unproject(vec0);
Vector3 vec1 = new Vector3(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), 0);
screenCamera.unproject(vec1);
screenMesh.setVertices(new float[]{
vec0.x, vec0.y, 0, 1, 1, 1, 1, 0, 1,
vec1.x, vec0.y, 0, 1, 1, 1, 1, 1, 1,
vec1.x, vec1.y, 0, 1, 1, 1, 1, 1, 0,
vec0.x, vec1.y, 0, 1, 1, 1, 1, 0, 0});
screenMesh.setIndices(new short[]{0, 1, 2, 2, 3, 0});
screenCamera.translate(0f, -1f, 0f);
screenCamera.update();
}
public void loadShader(String shaderName, String vertexShader, String fragmentShader) {
final String shaderPath = vertexShader + "+" + fragmentShader;
shaderPaths.put(shaderName, shaderPath);
assetManager.load(shaderPath, ShaderProgram.class);
}
public void begin(String shaderName) {
// check if we have a shader that has not been end()ed
if (currentShader != null) {
throw new IllegalArgumentException("Before calling begin() for a new shader please call end() for the current one!");
}
// check if we have a program for that name
ShaderProgram program = shaders.get(shaderName);
if (program == null) {
// check if we have loaded that shader program
// if not this line will through a runtime exception
program = assetManager.get(shaderPaths.get(shaderName), ShaderProgram.class);
shaders.put(shaderName, program);
}
currentTextureId = 0;
currentShader = program;
currentShader.begin();
}
public void end() {
currentShader.end();
currentShader = null;
}
public void createFrameBuffer(String frameBufferName) {
createFrameBuffer(frameBufferName, Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
public void createFrameBuffer(String frameBufferName, int width, int height) {
createFrameBuffer(frameBufferName, Pixmap.Format.RGBA8888, width, height);
}
public void createFrameBuffer(String frameBufferName, Pixmap.Format format, int width, int height) {
if (frameBuffers.containsKey(frameBufferName)) {
throw new IllegalArgumentException("A framebuffer with the name '" + frameBufferName + "' already exists");
}
FrameBuffer frameBuffer = new FrameBuffer(format, width, height, false, false);
frameBuffers.put(frameBufferName, frameBuffer);
}
public void beginFrameBuffer(String frameBufferName) {
final FrameBuffer frameBuffer = frameBuffers.get(frameBufferName);
frameBuffer.begin();
activeFrameBuffers.push(frameBuffer);
initInitialFrameBufferState(frameBuffer);
}
/**
* Sets the initial state when a FrameBuffer starts. Override to set your own state.
*
* @param frameBuffer the FrameBuffer for which the state is initialized
*/
protected void initInitialFrameBufferState(FrameBuffer frameBuffer) {
Gdx.graphics.getGL20().glViewport(0, 0, frameBuffer.getWidth(), frameBuffer.getHeight());
Gdx.graphics.getGL20().glClearColor(1f, 1f, 1f, 0f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.graphics.getGL20().glEnable(GL20.GL_TEXTURE_2D);
Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND);
Gdx.graphics.getGL20().glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
}
public void endFrameBuffer() {
if (activeFrameBuffers.empty()) {
throw new GdxRuntimeException("There is no active frame buffer that can be ended");
}
final FrameBuffer frameBuffer = activeFrameBuffers.pop();
frameBuffer.end();
}
/**
* Renders the given FrameBuffer to the screen using the current ShaderProgram
*
* @param frameBufferName name of the FrameBuffer to render
*/
public void renderFrameBuffer(String frameBufferName) {
renderFrameBuffer(frameBufferName, screenMesh);
}
/**
* Renders the given FrameBuffer onto a Mesh using the current ShaderProgram
*
* @param frameBufferName name of the FrameBuffer to render
* @param target Mesh to render onto
*/
public void renderFrameBuffer(String frameBufferName, Mesh target) {
if (currentShader == null) {
throw new GdxRuntimeException("Rendering the frame buffers needs an active shader");
}
FrameBuffer frameBuffer = frameBuffers.get(frameBufferName);
if (frameBuffer == null) {
throw new GdxRuntimeException("A framebuffer with the name '" + frameBufferName + "' could not be found");
}
frameBuffer.getColorBufferTexture().bind(0);
currentShader.setUniformMatrix("u_projTrans", screenCamera.combined);
currentShader.setUniformi("u_texture", 0);
target.render(currentShader, GL20.GL_TRIANGLES);
}
/**
* Return the FrameBuffer with the given name
*
* @param frameBufferName Name of the FrameBuffer to return
* @return a FrameBuffer or <b>null</b> if there is no such FrameBuffer
*/
public FrameBuffer getFrameBuffer(String frameBufferName) {
return frameBuffers.get(frameBufferName);
}
/**
* Returns the currently active shader.
*
* @return a valid ShaderProgram or <b>null</b>
*/
public ShaderProgram getCurrentShader() {
return currentShader;
}
public void setUniformMatrix(String uniformName, Matrix4 matrix) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniformMatrix(uniformName, matrix);
}
public void setUniformf(String uniformName, float value) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniformf(uniformName, value);
}
public void setUniform2fv(String uniformName, float[] values) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniform2fv(uniformName, values, 0, 2);
}
public void setUniformTexture(String uniformName, Texture texture) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
int textureId = ++currentTextureId;
texture.bind(textureId);
currentShader.setUniformi(uniformName, textureId);
}
/**
* ShaderManager needs to be disposed if not used anymore.
*/
public void dispose() {
for (String path : shaderPaths.values()) {
assetManager.unload(path);
}
shaderPaths.clear();
for (ShaderProgram program : shaders.values()) {
program.dispose();
}
shaders.clear();
screenMesh.dispose();
}
} |
package simpledb;
import java.util.NoSuchElementException;
import java.util.Set;
public class LogicalImputedScanNode extends ImputedPlan {
private final DbIterator physicalPlan;
private final int tableId;
private final String tableAlias;
public LogicalImputedScanNode(TransactionId tid, LogicalScanNode scan) throws ParsingException {
tableId = scan.t;
tableAlias = scan.alias;
/* Create a physical plan for the scan. */
try {
physicalPlan = new SeqScan(tid, scan.t, scan.alias);
} catch (NoSuchElementException e) {
throw new ParsingException("Unknown table " + scan.alias);
}
}
@Override
public Set<QualifiedName> getDirtySet() {
return DirtySet.ofBaseTable(tableId, tableAlias);
}
@Override
public DbIterator getPlan() {
return physicalPlan;
}
@Override
public double cost(double lossWeight) {
return (1 - lossWeight) * getTableStats().estimateScanCost();
}
@Override
public double cardinality() {
return getTableStats().totalTuples();
}
@Override
public TableStats getTableStats() {
return TableStats.getTableStats(Database.getCatalog().getTableName(tableId));
}
} |
package modules.admin;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Formatter;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import org.skyve.CORE;
import org.skyve.EXT;
import org.skyve.bizport.BizPortWorkbook;
import org.skyve.domain.Bean;
import org.skyve.domain.ChildBean;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.messages.DomainException;
import org.skyve.domain.messages.Message;
import org.skyve.domain.messages.SkyveException;
import org.skyve.domain.messages.UploadException;
import org.skyve.domain.messages.ValidationException;
import org.skyve.domain.types.DateOnly;
import org.skyve.domain.types.Decimal10;
import org.skyve.domain.types.Decimal2;
import org.skyve.domain.types.Decimal5;
import org.skyve.domain.types.converters.date.DD_MMM_YYYY;
import org.skyve.impl.bizport.StandardGenerator;
import org.skyve.impl.bizport.StandardLoader;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.Attribute;
import org.skyve.metadata.model.Persistent;
import org.skyve.metadata.model.document.Bizlet.DomainValue;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.module.Module;
import org.skyve.metadata.user.DocumentPermissionScope;
import org.skyve.metadata.user.User;
import org.skyve.persistence.AutoClosingIterable;
import org.skyve.persistence.DocumentQuery;
import org.skyve.persistence.DocumentQuery.AggregateFunction;
import org.skyve.persistence.Persistence;
import org.skyve.util.Binder;
import org.skyve.util.CommunicationUtil;
import org.skyve.util.Time;
import modules.admin.Group.GroupExtension;
import modules.admin.User.UserExtension;
import modules.admin.UserList.UserListUtil;
import modules.admin.UserProxy.UserProxyExtension;
import modules.admin.domain.Contact;
import modules.admin.domain.DocumentNumber;
import modules.admin.domain.Group;
import modules.admin.domain.UserProxy;
/**
* Utility methods applicable across application modules.
* <p>
* This class is provided as part of Skyve
*
* @author robert.brown
*
*/
public class ModulesUtil {
public static final long MEGABYTE = 1024L * 1024L;
/** comparator to allow sorting of domain values by code */
public static class DomainValueSortByCode implements Comparator<DomainValue> {
@Override
public int compare(DomainValue d1, DomainValue d2) {
return d1.getCode().compareTo(d2.getCode());
}
}
/** comparator to allow sorting of domain values by description */
public static class DomainValueSortByDescription implements Comparator<DomainValue> {
@Override
public int compare(DomainValue d1, DomainValue d2) {
return d1.getDescription().compareTo(d2.getDescription());
}
}
/** general types of time-based frequencies */
public static enum OccurenceFrequency {
OneOff, EverySecond, EveryMinute, Hourly, Daily, Weekly, Fortnightly, Monthly, Quarterly, HalfYearly, Yearly, Irregularly, DuringHolidays, NotDuringHolidays, WeekDays, Weekends;
}
public static final List<DomainValue> OCCURRENCE_FREQUENCIES = new ArrayList<>();
static {
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.OneOff.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Hourly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Daily.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString()));
OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString()));
}
/** subset of frequencies relevant for use as terms */
public static final List<DomainValue> TERM_FREQUENCIES = new ArrayList<>();
static {
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString()));
TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString()));
}
/** normal days of the week */
public static enum DayOfWeek {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
public static final List<DomainValue> WEEK_DAYS = new ArrayList<>();
static {
WEEK_DAYS.add(new DomainValue(DayOfWeek.Sunday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Monday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Tuesday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Wednesday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Thursday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Friday.toString()));
WEEK_DAYS.add(new DomainValue(DayOfWeek.Saturday.toString()));
}
/**
* Returns a calendar day of the week
*
* @param weekDay
* - the day of the week (DayOfWeek)
* @return - the day of the week as a Calendar.day (int)
*/
public static final int dayOfWeekToCalendar(DayOfWeek weekDay) {
int calendarDay = Calendar.MONDAY;
if (weekDay.equals(DayOfWeek.Monday)) {
calendarDay = Calendar.MONDAY;
}
if (weekDay.equals(DayOfWeek.Tuesday)) {
calendarDay = Calendar.TUESDAY;
}
if (weekDay.equals(DayOfWeek.Wednesday)) {
calendarDay = Calendar.WEDNESDAY;
}
if (weekDay.equals(DayOfWeek.Thursday)) {
calendarDay = Calendar.THURSDAY;
}
if (weekDay.equals(DayOfWeek.Friday)) {
calendarDay = Calendar.FRIDAY;
}
if (weekDay.equals(DayOfWeek.Saturday)) {
calendarDay = Calendar.SATURDAY;
}
if (weekDay.equals(DayOfWeek.Sunday)) {
calendarDay = Calendar.SUNDAY;
}
return calendarDay;
}
/**
* Returns a day of the week from a Calendar day
*
* @param calendarDay
* - the number of the day (int)
* @return - the DayOfWeek (DayOfWeek)
*/
public static final DayOfWeek calendarToDayOfWeek(int calendarDay) {
DayOfWeek weekDay = DayOfWeek.Monday;
if (calendarDay == Calendar.MONDAY) {
weekDay = DayOfWeek.Monday;
}
if (calendarDay == Calendar.TUESDAY) {
weekDay = DayOfWeek.Tuesday;
}
if (calendarDay == Calendar.WEDNESDAY) {
weekDay = DayOfWeek.Wednesday;
}
if (calendarDay == Calendar.THURSDAY) {
weekDay = DayOfWeek.Thursday;
}
if (calendarDay == Calendar.FRIDAY) {
weekDay = DayOfWeek.Friday;
}
if (calendarDay == Calendar.SATURDAY) {
weekDay = DayOfWeek.Saturday;
}
if (calendarDay == Calendar.SUNDAY) {
weekDay = DayOfWeek.Sunday;
}
return weekDay;
}
/** returns the number of days between day1 and day2 */
public static enum OccurrencePeriod {
Seconds, Minutes, Hours, Days, Weeks, Months, Years
}
public static final List<DomainValue> OCCURRENCE_PERIODS = new ArrayList<>();
static {
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Seconds.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Minutes.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Hours.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Days.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Weeks.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Months.toString()));
OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Years.toString()));
}
/**
* Returns the number of periods of specified frequency which occur in the
* calendar year.
*
* @param frequency
* - the specified frequency (OccurrenceFrequency)
* @return - the number of times the specified frequency occurs in a
* calendar year
*/
public static int annualFrequencyCount(OccurenceFrequency frequency) {
int periodCount = 1; // default period Count
if (frequency.equals(OccurenceFrequency.Daily)) {
// estimated
periodCount = 365;
} else if (frequency.equals(OccurenceFrequency.Weekly)) {
periodCount = 52;
} else if (frequency.equals(OccurenceFrequency.Fortnightly)) {
periodCount = 26;
} else if (frequency.equals(OccurenceFrequency.Monthly)) {
periodCount = 12;
} else if (frequency.equals(OccurenceFrequency.Quarterly)) {
periodCount = 4;
} else if (frequency.equals(OccurenceFrequency.HalfYearly)) {
periodCount = 2;
}
return periodCount;
}
/**
* Returns the number of periods which occur in a calendar year.
*
* @param period
* - the time period (OccurrencePeriod)
* @return - the number of times the period occurs within a calendar year
* (int)
*/
public static int annualPeriodCount(OccurrencePeriod period) {
int periodCount = 1; // default period Count
if (period.equals(OccurrencePeriod.Days)) {
// estimated
periodCount = 365;
} else if (period.equals(OccurrencePeriod.Weeks)) {
periodCount = 52;
} else if (period.equals(OccurrencePeriod.Months)) {
periodCount = 12;
} else if (period.equals(OccurrencePeriod.Years)) {
periodCount = 1;
}
return periodCount;
}
/**
* Adds a time frequency to a given date.
*
* @param frequency
* - the frequency to add
* @param date
* - the date to add to
* @param numberOfFrequencies
* - the number of frequencies to add
* @return - the resulting date
*/
public static final DateOnly addFrequency(OccurenceFrequency frequency, DateOnly date, int numberOfFrequencies) {
if (date != null) {
if (frequency.equals(OccurenceFrequency.OneOff)) {
return new DateOnly(date.getTime());
}
DateOnly newDate = new DateOnly(date.getTime());
Calendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
if (frequency.equals(OccurenceFrequency.Daily)) {
calendar.add(Calendar.DATE, numberOfFrequencies);
} else if (frequency.equals(OccurenceFrequency.Weekly)) {
calendar.add(Calendar.DATE, (numberOfFrequencies * 7));
} else if (frequency.equals(OccurenceFrequency.Fortnightly)) {
calendar.add(Calendar.DATE, (numberOfFrequencies * 14));
} else if (frequency.equals(OccurenceFrequency.Monthly)) {
calendar.add(Calendar.MONTH, numberOfFrequencies);
} else if (frequency.equals(OccurenceFrequency.Quarterly)) {
calendar.add(Calendar.MONTH, (numberOfFrequencies * 3));
} else if (frequency.equals(OccurenceFrequency.HalfYearly)) {
calendar.add(Calendar.MONTH, (numberOfFrequencies * 6));
} else if (frequency.equals(OccurenceFrequency.Yearly)) {
calendar.add(Calendar.YEAR, numberOfFrequencies);
}
newDate.setTime(calendar.getTime().getTime());
return newDate;
}
return null;
}
/**
* Returns the last day of the month in which the specified date occurs.
*
* @param date
* - the specified date
* @return - the date of the last day of the month in which the specified
* date occurs
*/
public static DateOnly lastDayOfMonth(DateOnly date) {
if (date != null) {
DateOnly newDate = new DateOnly(date.getTime());
Calendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
// last day of month is one day before 1st day of next month
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
newDate.setTime(calendar.getTime().getTime());
Time.addDays(newDate, -1);
return newDate;
}
return null;
}
/**
* Returns the last day of the year in which the specified date occurs.
*
* @param date
* - the specified date
* @return - the date of the last day of the year in which the specified
* date occurs
*/
public static DateOnly lastDayOfYear(DateOnly date) {
if (date != null) {
DateOnly newDate = new DateOnly(date.getTime());
Calendar calendar = new GregorianCalendar();
calendar.setTime(newDate);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
// last day of year is one day before 1st day of next year
calendar.add(Calendar.YEAR, 1);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, 1);
newDate.setTime(calendar.getTime().getTime());
Time.addDays(newDate, -1);
return newDate;
}
return null;
}
/**
* Returns the date of the first day of the month in which the specified
* date occurs.
*
* @param date
* - the specified date
* @return - the date of the first day of that month
*/
@SuppressWarnings("deprecation")
public static DateOnly firstDayOfMonth(DateOnly date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MONTH, date.getMonth());
calendar.set(Calendar.DATE, 1);
date.setTime(calendar.getTime().getTime());
return date;
}
/**
* Returns the date of the first day of the year in which the specified date
* occurs.
*
* @param date
* - the specified date
* @return - the date of the first day of that year
*/
public static DateOnly firstDayOfYear(DateOnly date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, 1);
date.setTime(calendar.getTime().getTime());
return date;
}
/**
* Returns the date which occurs after the specified date, given the number
* of days to add.
*
* @param date
* - the specified date
* @param daysToAdd
* - the number of days to add to that date
* @return - the resulting date
*/
public static DateOnly addDaysDateOnly(DateOnly date, int daysToAdd) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.setLenient(false);
// NB clear() does not work in JDK 1.3.1
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.add(Calendar.DAY_OF_WEEK, daysToAdd);
date.setTime(calendar.getTime().getTime());
return date;
}
@SuppressWarnings("deprecation")
public static String sqlFormatDateOnly(DateOnly theDate) {
String result = "";
if (theDate != null) {
String month = "0" + (theDate.getMonth() + 1);
month = month.substring(month.length() - 2);
String day = "0" + theDate.getDate();
day = day.substring(day.length() - 2);
result = "convert('" + (theDate.getYear() + 1900) + "-" + month + "-" + day + "', date) ";
}
return result;
}
/** Returns a TitleCase version of the String supplied */
public static String titleCase(String raw) {
String s = raw;
if (s != null) {
if (s.length() > 1) {
s = s.substring(0, 1).toUpperCase() + s.substring(1);
} else if (s.length() == 1) {
s = s.toUpperCase();
}
}
return s;
}
/** abbreviated forms of calendar months */
public static enum CalendarMonth {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}
public static final List<DomainValue> CALENDAR_MONTHS = new ArrayList<>();
static {
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JAN.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.FEB.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAR.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.APR.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAY.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUN.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUL.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.AUG.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.SEP.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.OCT.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.NOV.toString()));
CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.DEC.toString()));
}
/** conversion from month Name to calendar month (int) */
public static int calendarMonthNameToNumber(String monthName) {
if (CalendarMonth.JAN.toString().equals(monthName)) {
return 0;
} else if (CalendarMonth.FEB.toString().equals(monthName)) {
return 1;
} else if (CalendarMonth.MAR.toString().equals(monthName)) {
return 2;
} else if (CalendarMonth.APR.toString().equals(monthName)) {
return 3;
} else if (CalendarMonth.MAY.toString().equals(monthName)) {
return 4;
} else if (CalendarMonth.JUN.toString().equals(monthName)) {
return 5;
} else if (CalendarMonth.JUL.toString().equals(monthName)) {
return 6;
} else if (CalendarMonth.AUG.toString().equals(monthName)) {
return 7;
} else if (CalendarMonth.SEP.toString().equals(monthName)) {
return 8;
} else if (CalendarMonth.OCT.toString().equals(monthName)) {
return 9;
} else if (CalendarMonth.NOV.toString().equals(monthName)) {
return 10;
} else if (CalendarMonth.DEC.toString().equals(monthName)) {
return 11;
} else {
return 0;
}
}
/**
* Returns the current session/conversation user as an Admin module User
*
* @return The current {@link modules.admin.User.UserExtension}
*/
public static UserExtension currentAdminUser() {
UserExtension result = null;
try {
Persistence p = CORE.getPersistence();
result = p.retrieve(modules.admin.domain.User.MODULE_NAME,
modules.admin.domain.User.DOCUMENT_NAME,
p.getUser().getId());
}
catch (@SuppressWarnings("unused") Exception e) {
// do nothing
}
return result;
}
/**
* Creates a new admin User for a given contact
* - sets the new user name to be the contact email address
* - adds the specified group privileges to the user
* - sets their home Module (if provided)
* - sets an expired password (to force them to reset their password)
* - sets a password reset token that can be provided to the user to reset their password
* - optionally sends an invitation email
*
* @param contact the Contact to create the new User from
* @param groupName The name of the group
* @param homeModuleName
* @param sendInvitation
* @return
*/
public static UserExtension createAdminUserFromContactWithGroup(Contact contact, final String groupName,
final String homeModuleName, final boolean sendInvitation) {
if (contact == null) {
throw new DomainException("admin.modulesUtils.createAdminUserFromContactWithGroup.exception.contact");
}
if (groupName == null) {
throw new DomainException("admin.modulesUtils.createAdminUserFromContactWithGroup.exception.groupName");
}
// check if user already exists
DocumentQuery q = CORE.getPersistence().newDocumentQuery(modules.admin.domain.User.MODULE_NAME, modules.admin.domain.User.DOCUMENT_NAME);
q.getFilter().addEquals(modules.admin.domain.User.userNamePropertyName, contact.getEmail1());
q.setMaxResults(1);
User found = q.beanResult();
if (found != null) {
throw new DomainException("admin.modulesUtils.createAdminUserFromContactWithGroup.exception.duplicateUser");
}
// check the group exists
DocumentQuery qGroup = CORE.getPersistence().newDocumentQuery(Group.MODULE_NAME, Group.DOCUMENT_NAME);
qGroup.getFilter().addEquals(Group.namePropertyName, groupName);
qGroup.setMaxResults(1);
GroupExtension group = qGroup.beanResult();
if (group == null) {
throw new DomainException("admin.modulesUtils.createAdminUserFromContactWithGroup.exception.invalidGroup");
}
// check the home module name exists (Skyve will throw if it doesn't)
CORE.getCustomer().getModule(homeModuleName);
// save the contact to validate the contact and so that it can be referenced by the user
contact = CORE.getPersistence().save(contact);
final String token = UUID.randomUUID().toString() + Long.toString(System.currentTimeMillis());
// create a user - not with a generated password
UserExtension newUser = modules.admin.domain.User.newInstance();
newUser.setUserName(contact.getEmail1());
newUser.setPassword(EXT.hashPassword(token));
newUser.setPasswordExpired(Boolean.TRUE);
newUser.setPasswordResetToken(token);
newUser.setHomeModule(homeModuleName);
newUser.setContact(contact);
// assign group
newUser.getGroups().add(group);
newUser = CORE.getPersistence().save(newUser);
if (sendInvitation) {
try {
// send invitation email
CommunicationUtil.sendFailSafeSystemCommunication(UserListUtil.SYSTEM_USER_INVITATION,
UserListUtil.SYSTEM_USER_INVITATION_DEFAULT_SUBJECT,
UserListUtil.SYSTEM_USER_INVITATION_DEFAULT_BODY,
CommunicationUtil.ResponseMode.EXPLICIT, null, newUser);
} catch (Exception e) {
throw new DomainException("admin.modulesUtils.createAdminUserFromContactWithGroup.exception.invitation", e);
}
}
return newUser;
}
/**
* Returns the current session/conversation user as an Admin module UserProxy
*
* @return The current {@link modules.admin.domain.UserProxy}
*/
public static UserProxyExtension currentAdminUserProxy() {
UserProxyExtension result = null;
try {
Persistence p = CORE.getPersistence();
result = p.retrieve(UserProxy.MODULE_NAME, UserProxy.DOCUMENT_NAME, p.getUser().getId());
}
catch (@SuppressWarnings("unused") Exception e) {
// do nothing
}
return result;
}
public static Contact getCurrentUserContact() {
Persistence persistence = CORE.getPersistence();
User user = persistence.getUser();
Customer customer = user.getCustomer();
Module module = customer.getModule(Contact.MODULE_NAME);
Document document = module.getDocument(customer, Contact.DOCUMENT_NAME);
Contact contact = persistence.retrieve(document, user.getContactId());
return contact;
}
public static void addValidationError(ValidationException e, String fieldName, String messageString) {
Message vM = new Message(messageString);
vM.addBinding(fieldName);
e.getMessages().add(vM);
}
/**
* Returns a new document/sequence number for the given
* module.document.fieldName in a thread-safe way.
* <p>
* If no previous record is found in the DocumentNumber table, the method
* attempts to find the Maximum existing value currently extant in the field
* and increments that. Otherwise, the value returned is incremented and
* updated DocumentNumber value for the specified combination.
*
* @param prefix
* - if the sequence value has a known prefix before the number,
* eg INV0001 has a prefix of "INV"
* @param moduleName
* - the application module
* @param documentName
* - the application document
* @param fieldName
* - the fieldName/columnName in which the value is held
* @param numberLength
* - the minimum length of the number when specified as a string
* @return - the next sequence number
*/
public static String getNextDocumentNumber(String prefix, String moduleName, String documentName, String fieldName,
int numberLength) {
Persistence pers = CORE.getPersistence();
User user = pers.getUser();
Customer customer = user.getCustomer();
Module module = customer.getModule(DocumentNumber.MODULE_NAME);
Document document = module.getDocument(customer, DocumentNumber.DOCUMENT_NAME);
String nextNumber = "0";
String lastNumber = "0";
DocumentNumber dN = null;
try {
DocumentQuery qN = pers.newDocumentQuery(DocumentNumber.MODULE_NAME, DocumentNumber.DOCUMENT_NAME);
qN.getFilter().addEquals(DocumentNumber.moduleNamePropertyName, moduleName);
qN.getFilter().addEquals(DocumentNumber.documentNamePropertyName, documentName);
qN.getFilter().addEquals(DocumentNumber.sequenceNamePropertyName, fieldName);
//temporarily escalate access to the Document Number sequences
CORE.getPersistence().setDocumentPermissionScopes(DocumentPermissionScope.customer);
List<DocumentNumber> num = qN.beanResults();
CORE.getPersistence().resetDocumentPermissionScopes();
if (num.isEmpty()) {
// System.out.println("DOCUMENT NUMBER: No previous found - source from table");
// Check if sequence name is a field in that table
boolean isField = false;
for (Attribute attribute : document.getAttributes()) {
if (attribute.getName().equals(fieldName)) {
isField = true;
break;
}
}
if (isField) {
// first hit - go lookup max number from table
DocumentQuery query = pers.newDocumentQuery(moduleName, documentName);
query.addAggregateProjection(AggregateFunction.Max, fieldName, "MaxNumber");
List<Bean> beans = query.projectedResults();
if (!beans.isEmpty()) {
Object o = Binder.get(beans.get(0), "MaxNumber");
if (o instanceof Integer) {
lastNumber = ((Integer) Binder.get(beans.get(0), "MaxNumber")).toString();
} else {
lastNumber = (String) Binder.get(beans.get(0), "MaxNumber");
}
}
}
// create a new document number record
dN = DocumentNumber.newInstance();
dN.setModuleName(moduleName);
dN.setDocumentName(documentName);
dN.setSequenceName(fieldName);
} else {
// System.out.println("DOCUMENT NUMBER: Previous found");
dN = num.get(0);
dN = pers.retrieveAndLock(document, dN.getBizId()); // issue a row-level lock
lastNumber = dN.getDocumentNumber();
}
// just update from the document Number
nextNumber = incrementAlpha(prefix, lastNumber, numberLength);
dN.setDocumentNumber(nextNumber);
pers.preMerge(document, dN);
pers.upsertBeanTuple(dN);
pers.postMerge(document, dN);
} finally {
if (dN != null) {
pers.evictCached(dN);
}
}
// System.out.println("Next document number for " + moduleName + "." +
// documentName + "." + fieldName + " is " + nextNumber);
return nextNumber;
}
/**
* Wrapper for getNextDocumentNumber, specifically for numeric only
* sequences
*/
public static Integer getNextDocumentNumber(String moduleName, String documentName, String fieldName) {
return Integer.valueOf(Integer.parseInt(getNextDocumentNumber(null, moduleName, documentName, fieldName, 0)));
}
/**
* Wrapper for getNextDocumentNumber, specifically for long only
* sequences
*/
public static Long getNextLongDocumentNumber(String moduleName, String documentName, String fieldName) {
return Long.valueOf(Long.parseLong(getNextDocumentNumber(null, moduleName, documentName, fieldName, 0)));
}
/**
* Returns the next alpha value - ie A00A1 becomes A00A2 etc
*
* @param suppliedPrefix
* - if the sequence value has a known prefix before the number,
* eg INV0001 has a prefix of "INV"
* @param lastNumber
* - the number to increment
* @param numberLength
* - the minimum length of the number when specified as a string
*
* @return - the next number
*/
public static String incrementAlpha(String suppliedPrefix, String lastNumber, int numberLength) {
String newNumber = "";
String nonNumeric = lastNumber;
Integer value = Integer.valueOf(1);
String prefix;
if (suppliedPrefix != null) {
prefix = suppliedPrefix;
} else {
prefix = "";
}
if (lastNumber != null) {
String[] parts = (new StringBuilder(" ").append(lastNumber)).toString().split("\\D\\d+$");
// cater for alpha prefix
if (parts.length > 0 && parts[0].length() < lastNumber.length()) {
String numberPart = lastNumber.substring(parts[0].length(), lastNumber.length());
nonNumeric = lastNumber.substring(0, parts[0].length());
value = Integer.valueOf(Integer.parseInt(numberPart) + 1);
// cater for purely numeric prefix
} else if (prefix.matches("^\\d+$") && lastNumber.matches("^\\d+$") && !"0".equals(lastNumber)) {
int len = prefix.length();
value = Integer.valueOf(Integer.parseInt(lastNumber.substring(len)) + 1);
nonNumeric = prefix;
// cater for numeric only
} else if (lastNumber.matches("^\\d+$")) {
nonNumeric = prefix;
value = Integer.valueOf(Integer.parseInt(lastNumber) + 1);
}
} else {
nonNumeric = prefix;
}
// now put prefix and value together
int newLength = (nonNumeric.length() + value.toString().length() > numberLength
? nonNumeric.length() + value.toString().length() : numberLength);
StringBuilder sb = new StringBuilder(newLength + 1);
try (Formatter f = new Formatter(sb)) {
newNumber = nonNumeric
+ f.format(new StringBuilder("%1$").append(newLength - nonNumeric.length()).append("s").toString(),
value.toString()).toString().replace(" ", "0");
}
return newNumber;
}
private static final long PRIME = 4294967291L;
private static final long HALF_PRIME = PRIME / 2L;
public static long getUniqueQuadraticResidue(long incrementingNumber) {
long x = incrementingNumber + 1001; // for sufficient entropy
long residue = (x * x) % PRIME;
return (x <= HALF_PRIME) ? residue : (PRIME - residue);
}
/** returns a formatted string representing the condition */
public static String getConditionName(String conditionCode) {
String result = "is";
result += conditionCode.substring(0, 1).toUpperCase() + conditionCode.substring(1, conditionCode.length());
// System.out.println("GetConditionName " + result);
return result;
}
/** allows comparison where both terms being null evaluates as equality */
public static boolean bothNullOrEqual(Object object1, Object object2) {
boolean result = false;
if ((object1 == null && object2 == null) || (object1 != null && object2 != null && object1.equals(object2))) {
result = true;
}
return result;
}
/** type-specific coalesce */
public static String coalesce(Object val, String ifNullValue) {
return (val == null ? ifNullValue : val.toString());
}
/** type-specific coalesce */
public static String coalesce(String val, String ifNullValue) {
return (val == null ? ifNullValue : val);
}
/** type-specific coalesce */
public static Boolean coalesce(Boolean val, Boolean ifNullValue) {
return (val == null ? ifNullValue : val);
}
/** type-specific coalesce */
public static Integer coalesce(Integer val, Integer ifNullValue) {
return (val == null ? ifNullValue : val);
}
/** type-specific coalesce */
public static Decimal2 coalesce(Decimal2 val, Decimal2 ifNullValue) {
return (val == null ? ifNullValue : val);
}
/** returns null if zero - for reports or data import/export */
public static Decimal5 coalesce(Decimal5 val, Decimal5 ifNullValue) {
return (val == null ? ifNullValue : val);
}
/** returns null if zero - for reports or data import/export */
public static Decimal10 coalesce(Decimal10 val, Decimal10 ifNullValue) {
return (val == null ? ifNullValue : val);
}
/**
* Replaces the value found in the bean for the binding string provided,
* e.g. if the bean has a binding of contact.name, for which the
* displayNames of those bindings are Contact.FullName , then get the value
* of that binding from the bean provided.
*
* @param bean
* - the bean relevant for the binding
* @param replacementString
* - the string representing the displayName form of the binding
* @return - the value from the bean
* @throws Exception
* general Exception for metadata exception or string
* manipulation failure etc
*/
public static String replaceBindingsInString(Bean bean, String replacementString) throws Exception {
StringBuilder result = new StringBuilder(replacementString);
int openCurlyBraceIndex = result.indexOf("{");
// now replace contents of each curlyBraced expression if we can
while (openCurlyBraceIndex >= 0) {
int closedCurlyBraceIndex = result.indexOf("}");
String displayNameOfAttribute = result.substring(openCurlyBraceIndex + 1, closedCurlyBraceIndex);
Bean b = bean;
StringBuilder binding = new StringBuilder();
String[] attributes = displayNameOfAttribute.toString().split("\\.");
boolean found = false;
for (String a : attributes) {
// if the format string includes a sub-bean attribute, get the
// sub-bean
if (binding.toString().length() > 0) {
b = (Bean) Binder.get(bean, binding.toString());
}
// parent special case
if (a.equals("parent")) {
b = ((ChildBean<?>) bean).getParent();
}
// if the sub-bean isn't null, try to match the attribute
// because attributes in the format string might be optional
found = false;
if (b != null) {
User user = CORE.getPersistence().getUser();
Customer customer = user.getCustomer();
Module module = customer.getModule(b.getBizModule());
Document document = module.getDocument(customer, b.getBizDocument());
for (Attribute attribute : document.getAllAttributes()) {
if (attribute.getLocalisedDisplayName().equals(a)) {
found = true;
if (binding.toString().length() > 0) {
binding.append('.').append(attribute.getName());
} else {
binding.append(attribute.getName());
}
}
}
// check for non-attribute bindings
if (!found) {
try {
if (Binder.get(bean, a) != null) {
binding.append(a);
}
} catch (@SuppressWarnings("unused") Exception e) {
// do nothing
}
}
}
}
String term = "";
if (found) {
Object value = Binder.get(bean, binding.toString());
if (value instanceof DateOnly) {
DateOnly dValue = (DateOnly) value;
DD_MMM_YYYY convDate = new DD_MMM_YYYY();
term = convDate.toDisplayValue(dValue);
} else if (value instanceof Decimal2) {
term = value.toString();
} else if (value instanceof Decimal5) {
term = value.toString();
} else {
term = coalesce(value, "").toString();
}
}
// move along
String displayValue = ModulesUtil.coalesce(term, "");
result.replace(openCurlyBraceIndex, closedCurlyBraceIndex + 1, displayValue);
openCurlyBraceIndex = result.indexOf("{");
}
return result.toString();
}
/** simple concatenation with a delimiter */
public static String concatWithDelim(String delimiter, String... strings) {
StringBuilder sb = new StringBuilder();
String delim = coalesce(delimiter, " ");
for (String s : strings) {
if (coalesce(s, "").length() > 0) {
if (sb.toString().length() > 0) {
sb.append(delim);
}
sb.append(s);
}
}
return sb.toString();
}
/** short-hand enquoting of a string */
public static String enquote(String quoteSet, String s) {
String l = null;
String r = null;
if (quoteSet != null) {
l = quoteSet.substring(0, 1);
if (coalesce(quoteSet, "").length() > 1) {
r = quoteSet.substring(1);
}
}
return concatWithDelim("", l, concatWithDelim("", s, r));
}
/**
* Returns whether the user has access to the specified module
*
* @param moduleName
* @return
*/
public static boolean hasModule(String moduleName) {
boolean result = false;
User user = CORE.getPersistence().getUser();
Customer customer = user.getCustomer();
for (Module module : customer.getModules()) {
if (module.getName().equals(moduleName)) {
result = true;
break;
}
}
return result;
}
/**
* Generic bizport export method.
*
* @param moduleName
* - the module to be exported
* @param documentName
* - the document to be exported
* @param b
* - the top-level bean to export
* @return - the reference to the Bizportable
*/
public static BizPortWorkbook standardBeanBizExport(String modName, String docName, Bean b) {
String documentName = docName;
String moduleName = modName;
BizPortWorkbook result = EXT.newBizPortWorkbook(false);
if (b != null) {
moduleName = b.getBizModule();
documentName = b.getBizDocument();
}
Persistence persistence = CORE.getPersistence();
Customer customer = persistence.getUser().getCustomer();
Module module = customer.getModule(moduleName);
// Project
Document document = module.getDocument(customer, documentName);
StandardGenerator bgBean = EXT.newBizPortStandardGenerator(customer, document);
bgBean.generateStructure(result);
result.materialise();
// System.out.println("BIZPORTING PROJECT " );
DocumentQuery query = persistence.newDocumentQuery(moduleName, documentName);
if (b != null) {
// filter for this project if provided
query.getFilter().addEquals(Bean.DOCUMENT_ID, b.getBizId());
}
try (AutoClosingIterable<Bean> i = query.beanIterable()) {
bgBean.generateData(result, i);
}
catch (SkyveException e) {
throw e;
}
catch (Exception e) {
throw new DomainException(e);
}
return result;
}
public static void standardBeanBizImport(BizPortWorkbook workbook, UploadException problems) throws Exception {
final Persistence persistence = CORE.getPersistence();
final Customer customer = persistence.getUser().getCustomer();
StandardLoader loader = new StandardLoader(workbook, problems);
List<Bean> bs = loader.populate(persistence);
for (String key : loader.getBeanKeys()) {
Bean bean = loader.getBean(key);
Module module = customer.getModule(bean.getBizModule());
Document document = module.getDocument(customer, bean.getBizDocument());
try {
persistence.preMerge(document, bean);
} catch (DomainException e) {
loader.addError(customer, bean, e);
}
}
// throw if we have errors found
if (problems.hasErrors()) {
throw problems;
}
// do the insert as 1 operation, bugging out if we encounter any errors
PersistentBean pb = null;
try {
for (Bean b : bs) {
pb = (PersistentBean) b;
pb = persistence.save(pb);
}
} catch (DomainException e) {
if (pb != null) {
loader.addError(customer, pb, e);
}
throw problems;
}
}
/** short-hand way of finding a bean using a legacy key */
public static Bean lookupBean(String moduleName, String documentName, String propertyName, Object objValue) {
Persistence persistence = CORE.getPersistence();
DocumentQuery qBean = persistence.newDocumentQuery(moduleName, documentName);
qBean.getFilter().addEquals(propertyName, objValue);
List<Bean> beans = qBean.beanResults();
Bean bean = null;
if (!beans.isEmpty()) {
bean = beans.get(0);
} else {
System.out.println("Cannot find reference to " + objValue + " in document " + documentName);
}
return bean;
}
/**
* Returns the persistent table name for the specified module and document.
*/
public static String getPersistentIdentifier(final String moduleName, final String documentName) {
Customer customer = CORE.getCustomer();
Module module = customer.getModule(moduleName);
Document document = module.getDocument(customer, documentName);
Persistent p = document.getPersistent();
return p.getPersistentIdentifier();
}
/**
* Convenience method for returning autocomplete suggestions for a String attribute based on previous values
*
* @param moduleName
* @param documentName
* @param attributeName
* @param value
* @return
* @throws Exception
*/
public static List<String> getCompleteSuggestions(String moduleName, String documentName, String attributeName, String value) throws Exception {
DocumentQuery q = CORE.getPersistence().newDocumentQuery(moduleName, documentName);
if (value != null) {
q.getFilter().addLike(attributeName, value + "%");
}
q.addBoundProjection(attributeName, attributeName);
q.addBoundOrdering(attributeName);
q.setDistinct(true);
return q.scalarResults(String.class);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.